Fix TOC link references.
[org-mode/org-tableheadings.git] / lisp / org.el
blobadb5fb18d58a94f16d746417c6fd499138735c2a
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 '(choice (const nil) (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 '(choice (const nil) (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 vm-imap)
1771 (choice
1772 (const vm-visit-imap-folder)
1773 (const vm-visit-imap-folder-other-window)
1774 (const vm-visit-imap-folder-other-frame)))
1775 (cons (const gnus)
1776 (choice
1777 (const gnus)
1778 (const gnus-other-frame)
1779 (const org-gnus-no-new-news)))
1780 (cons (const file)
1781 (choice
1782 (const find-file)
1783 (const find-file-other-window)
1784 (const find-file-other-frame)))
1785 (cons (const wl)
1786 (choice
1787 (const wl)
1788 (const wl-other-frame)))))
1790 (defcustom org-display-internal-link-with-indirect-buffer nil
1791 "Non-nil means use indirect buffer to display infile links.
1792 Activating internal links (from one location in a file to another location
1793 in the same file) normally just jumps to the location. When the link is
1794 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1795 is displayed in
1796 another window. When this option is set, the other window actually displays
1797 an indirect buffer clone of the current buffer, to avoid any visibility
1798 changes to the current buffer."
1799 :group 'org-link-follow
1800 :type 'boolean)
1802 (defcustom org-open-non-existing-files nil
1803 "Non-nil means `org-open-file' will open non-existing files.
1804 When nil, an error will be generated.
1805 This variable applies only to external applications because they
1806 might choke on non-existing files. If the link is to a file that
1807 will be opened in Emacs, the variable is ignored."
1808 :group 'org-link-follow
1809 :type 'boolean)
1811 (defcustom org-open-directory-means-index-dot-org nil
1812 "Non-nil means a link to a directory really means to index.org.
1813 When nil, following a directory link will run dired or open a finder/explorer
1814 window on that directory."
1815 :group 'org-link-follow
1816 :type 'boolean)
1818 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1819 "Function and arguments to call for following mailto links.
1820 This is a list with the first element being a Lisp function, and the
1821 remaining elements being arguments to the function. In string arguments,
1822 %a will be replaced by the address, and %s will be replaced by the subject
1823 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1824 :group 'org-link-follow
1825 :type '(choice
1826 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1827 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1828 (const :tag "message-mail" (message-mail "%a" "%s"))
1829 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1831 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1832 "Non-nil means ask for confirmation before executing shell links.
1833 Shell links can be dangerous: just think about a link
1835 [[shell:rm -rf ~/*][Google Search]]
1837 This link would show up in your Org-mode document as \"Google Search\",
1838 but really it would remove your entire home directory.
1839 Therefore we advise against setting this variable to nil.
1840 Just change it to `y-or-n-p' if you want to confirm with a
1841 single keystroke rather than having to type \"yes\"."
1842 :group 'org-link-follow
1843 :type '(choice
1844 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1845 (const :tag "with y-or-n (faster)" y-or-n-p)
1846 (const :tag "no confirmation (dangerous)" nil)))
1847 (put 'org-confirm-shell-link-function
1848 'safe-local-variable
1849 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1851 (defcustom org-confirm-shell-link-not-regexp ""
1852 "A regexp to skip confirmation for shell links."
1853 :group 'org-link-follow
1854 :version "24.1"
1855 :type 'regexp)
1857 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1858 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1859 Elisp links can be dangerous: just think about a link
1861 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1863 This link would show up in your Org-mode document as \"Google Search\",
1864 but really it would remove your entire home directory.
1865 Therefore we advise against setting this variable to nil.
1866 Just change it to `y-or-n-p' if you want to confirm with a
1867 single keystroke rather than having to type \"yes\"."
1868 :group 'org-link-follow
1869 :type '(choice
1870 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1871 (const :tag "with y-or-n (faster)" y-or-n-p)
1872 (const :tag "no confirmation (dangerous)" nil)))
1873 (put 'org-confirm-shell-link-function
1874 'safe-local-variable
1875 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1877 (defcustom org-confirm-elisp-link-not-regexp ""
1878 "A regexp to skip confirmation for Elisp links."
1879 :group 'org-link-follow
1880 :version "24.1"
1881 :type 'regexp)
1883 (defconst org-file-apps-defaults-gnu
1884 '((remote . emacs)
1885 (system . mailcap)
1886 (t . mailcap))
1887 "Default file applications on a UNIX or GNU/Linux system.
1888 See `org-file-apps'.")
1890 (defconst org-file-apps-defaults-macosx
1891 '((remote . emacs)
1892 (t . "open %s")
1893 (system . "open %s")
1894 ("ps.gz" . "gv %s")
1895 ("eps.gz" . "gv %s")
1896 ("dvi" . "xdvi %s")
1897 ("fig" . "xfig %s"))
1898 "Default file applications on a MacOS X system.
1899 The system \"open\" is known as a default, but we use X11 applications
1900 for some files for which the OS does not have a good default.
1901 See `org-file-apps'.")
1903 (defconst org-file-apps-defaults-windowsnt
1904 (list
1905 '(remote . emacs)
1906 (cons t
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file))
1911 (cons 'system
1912 (list (if (featurep 'xemacs)
1913 'mswindows-shell-execute
1914 'w32-shell-execute)
1915 "open" 'file)))
1916 "Default file applications on a Windows NT system.
1917 The system \"open\" is used for most files.
1918 See `org-file-apps'.")
1920 (defcustom org-file-apps
1921 '((auto-mode . emacs)
1922 ("\\.mm\\'" . default)
1923 ("\\.x?html?\\'" . default)
1924 ("\\.pdf\\'" . default))
1925 "External applications for opening `file:path' items in a document.
1926 Org-mode uses system defaults for different file types, but
1927 you can use this variable to set the application for a given file
1928 extension. The entries in this list are cons cells where the car identifies
1929 files and the cdr the corresponding command. Possible values for the
1930 file identifier are
1931 \"string\" A string as a file identifier can be interpreted in different
1932 ways, depending on its contents:
1934 - Alphanumeric characters only:
1935 Match links with this file extension.
1936 Example: (\"pdf\" . \"evince %s\")
1937 to open PDFs with evince.
1939 - Regular expression: Match links where the
1940 filename matches the regexp. If you want to
1941 use groups here, use shy groups.
1943 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1944 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1945 to open *.html and *.xhtml with firefox.
1947 - Regular expression which contains (non-shy) groups:
1948 Match links where the whole link, including \"::\", and
1949 anything after that, matches the regexp.
1950 In a custom command string, %1, %2, etc. are replaced with
1951 the parts of the link that were matched by the groups.
1952 For backwards compatibility, if a command string is given
1953 that does not use any of the group matches, this case is
1954 handled identically to the second one (i.e. match against
1955 file name only).
1956 In a custom lisp form, you can access the group matches with
1957 (match-string n link).
1959 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1960 to open [[file:document.pdf::5]] with evince at page 5.
1962 `directory' Matches a directory
1963 `remote' Matches a remote file, accessible through tramp or efs.
1964 Remote files most likely should be visited through Emacs
1965 because external applications cannot handle such paths.
1966 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1967 so all files Emacs knows how to handle. Using this with
1968 command `emacs' will open most files in Emacs. Beware that this
1969 will also open html files inside Emacs, unless you add
1970 (\"html\" . default) to the list as well.
1971 t Default for files not matched by any of the other options.
1972 `system' The system command to open files, like `open' on Windows
1973 and Mac OS X, and mailcap under GNU/Linux. This is the command
1974 that will be selected if you call `C-c C-o' with a double
1975 \\[universal-argument] \\[universal-argument] prefix.
1977 Possible values for the command are:
1978 `emacs' The file will be visited by the current Emacs process.
1979 `default' Use the default application for this file type, which is the
1980 association for t in the list, most likely in the system-specific
1981 part.
1982 This can be used to overrule an unwanted setting in the
1983 system-specific variable.
1984 `system' Use the system command for opening files, like \"open\".
1985 This command is specified by the entry whose car is `system'.
1986 Most likely, the system-specific version of this variable
1987 does define this command, but you can overrule/replace it
1988 here.
1989 string A command to be executed by a shell; %s will be replaced
1990 by the path to the file.
1991 sexp A Lisp form which will be evaluated. The file path will
1992 be available in the Lisp variable `file'.
1993 For more examples, see the system specific constants
1994 `org-file-apps-defaults-macosx'
1995 `org-file-apps-defaults-windowsnt'
1996 `org-file-apps-defaults-gnu'."
1997 :group 'org-link-follow
1998 :type '(repeat
1999 (cons (choice :value ""
2000 (string :tag "Extension")
2001 (const :tag "System command to open files" system)
2002 (const :tag "Default for unrecognized files" t)
2003 (const :tag "Remote file" remote)
2004 (const :tag "Links to a directory" directory)
2005 (const :tag "Any files that have Emacs modes"
2006 auto-mode))
2007 (choice :value ""
2008 (const :tag "Visit with Emacs" emacs)
2009 (const :tag "Use default" default)
2010 (const :tag "Use the system command" system)
2011 (string :tag "Command")
2012 (sexp :tag "Lisp form")))))
2014 (defcustom org-doi-server-url "http://dx.doi.org/"
2015 "The URL of the DOI server."
2016 :type 'string
2017 :version "24.3"
2018 :group 'org-link-follow)
2020 (defgroup org-refile nil
2021 "Options concerning refiling entries in Org-mode."
2022 :tag "Org Refile"
2023 :group 'org)
2025 (defcustom org-directory "~/org"
2026 "Directory with org files.
2027 This is just a default location to look for Org files. There is no need
2028 at all to put your files into this directory. It is only used in the
2029 following situations:
2031 1. When a capture template specifies a target file that is not an
2032 absolute path. The path will then be interpreted relative to
2033 `org-directory'
2034 2. When a capture note is filed away in an interactive way (when exiting the
2035 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2036 with `org-directory' as the default path."
2037 :group 'org-refile
2038 :group 'org-remember
2039 :group 'org-capture
2040 :type 'directory)
2042 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2043 "Default target for storing notes.
2044 Used as a fall back file for org-remember.el and org-capture.el, for
2045 templates that do not specify a target file."
2046 :group 'org-refile
2047 :group 'org-remember
2048 :group 'org-capture
2049 :type '(choice
2050 (const :tag "Default from remember-data-file" nil)
2051 file))
2053 (defcustom org-goto-interface 'outline
2054 "The default interface to be used for `org-goto'.
2055 Allowed values are:
2056 outline The interface shows an outline of the relevant file
2057 and the correct heading is found by moving through
2058 the outline or by searching with incremental search.
2059 outline-path-completion Headlines in the current buffer are offered via
2060 completion. This is the interface also used by
2061 the refile command."
2062 :group 'org-refile
2063 :type '(choice
2064 (const :tag "Outline" outline)
2065 (const :tag "Outline-path-completion" outline-path-completion)))
2067 (defcustom org-goto-max-level 5
2068 "Maximum target level when running `org-goto' with refile interface."
2069 :group 'org-refile
2070 :type 'integer)
2072 (defcustom org-reverse-note-order nil
2073 "Non-nil means store new notes at the beginning of a file or entry.
2074 When nil, new notes will be filed to the end of a file or entry.
2075 This can also be a list with cons cells of regular expressions that
2076 are matched against file names, and values."
2077 :group 'org-remember
2078 :group 'org-capture
2079 :group 'org-refile
2080 :type '(choice
2081 (const :tag "Reverse always" t)
2082 (const :tag "Reverse never" nil)
2083 (repeat :tag "By file name regexp"
2084 (cons regexp boolean))))
2086 (defcustom org-log-refile nil
2087 "Information to record when a task is refiled.
2089 Possible values are:
2091 nil Don't add anything
2092 time Add a time stamp to the task
2093 note Prompt for a note and add it with template `org-log-note-headings'
2095 This option can also be set with on a per-file-basis with
2097 #+STARTUP: nologrefile
2098 #+STARTUP: logrefile
2099 #+STARTUP: lognoterefile
2101 You can have local logging settings for a subtree by setting the LOGGING
2102 property to one or more of these keywords.
2104 When bulk-refiling from the agenda, the value `note' is forbidden and
2105 will temporarily be changed to `time'."
2106 :group 'org-refile
2107 :group 'org-progress
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "No logging" nil)
2111 (const :tag "Record timestamp" time)
2112 (const :tag "Record timestamp with note." note)))
2114 (defcustom org-refile-targets nil
2115 "Targets for refiling entries with \\[org-refile].
2116 This is a list of cons cells. Each cell contains:
2117 - a specification of the files to be considered, either a list of files,
2118 or a symbol whose function or variable value will be used to retrieve
2119 a file name or a list of file names. If you use `org-agenda-files' for
2120 that, all agenda files will be scanned for targets. Nil means consider
2121 headings in the current buffer.
2122 - A specification of how to find candidate refile targets. This may be
2123 any of:
2124 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2125 This tag has to be present in all target headlines, inheritance will
2126 not be considered.
2127 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2128 todo keyword.
2129 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2130 headlines that are refiling targets.
2131 - a cons cell (:level . N). Any headline of level N is considered a target.
2132 Note that, when `org-odd-levels-only' is set, level corresponds to
2133 order in hierarchy, not to the number of stars.
2134 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2135 Note that, when `org-odd-levels-only' is set, level corresponds to
2136 order in hierarchy, not to the number of stars.
2138 Each element of this list generates a set of possible targets.
2139 The union of these sets is presented (with completion) to
2140 the user by `org-refile'.
2142 You can set the variable `org-refile-target-verify-function' to a function
2143 to verify each headline found by the simple criteria above.
2145 When this variable is nil, all top-level headlines in the current buffer
2146 are used, equivalent to the value `((nil . (:level . 1))'."
2147 :group 'org-refile
2148 :type '(repeat
2149 (cons
2150 (choice :value org-agenda-files
2151 (const :tag "All agenda files" org-agenda-files)
2152 (const :tag "Current buffer" nil)
2153 (function) (variable) (file))
2154 (choice :tag "Identify target headline by"
2155 (cons :tag "Specific tag" (const :value :tag) (string))
2156 (cons :tag "TODO keyword" (const :value :todo) (string))
2157 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2158 (cons :tag "Level number" (const :value :level) (integer))
2159 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2161 (defcustom org-refile-target-verify-function nil
2162 "Function to verify if the headline at point should be a refile target.
2163 The function will be called without arguments, with point at the
2164 beginning of the headline. It should return t and leave point
2165 where it is if the headline is a valid target for refiling.
2167 If the target should not be selected, the function must return nil.
2168 In addition to this, it may move point to a place from where the search
2169 should be continued. For example, the function may decide that the entire
2170 subtree of the current entry should be excluded and move point to the end
2171 of the subtree."
2172 :group 'org-refile
2173 :type '(choice
2174 (const nil)
2175 (function)))
2177 (defcustom org-refile-use-cache nil
2178 "Non-nil means cache refile targets to speed up the process.
2179 The cache for a particular file will be updated automatically when
2180 the buffer has been killed, or when any of the marker used for flagging
2181 refile targets no longer points at a live buffer.
2182 If you have added new entries to a buffer that might themselves be targets,
2183 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2184 find that easier, `C-u C-u C-u C-c C-w'."
2185 :group 'org-refile
2186 :version "24.1"
2187 :type 'boolean)
2189 (defcustom org-refile-use-outline-path nil
2190 "Non-nil means provide refile targets as paths.
2191 So a level 3 headline will be available as level1/level2/level3.
2193 When the value is `file', also include the file name (without directory)
2194 into the path. In this case, you can also stop the completion after
2195 the file name, to get entries inserted as top level in the file.
2197 When `full-file-path', include the full file path."
2198 :group 'org-refile
2199 :type '(choice
2200 (const :tag "Not" nil)
2201 (const :tag "Yes" t)
2202 (const :tag "Start with file name" file)
2203 (const :tag "Start with full file path" full-file-path)))
2205 (defcustom org-outline-path-complete-in-steps t
2206 "Non-nil means complete the outline path in hierarchical steps.
2207 When Org-mode uses the refile interface to select an outline path
2208 \(see variable `org-refile-use-outline-path'), the completion of
2209 the path can be done is a single go, or if can be done in steps down
2210 the headline hierarchy. Going in steps is probably the best if you
2211 do not use a special completion package like `ido' or `icicles'.
2212 However, when using these packages, going in one step can be very
2213 fast, while still showing the whole path to the entry."
2214 :group 'org-refile
2215 :type 'boolean)
2217 (defcustom org-refile-allow-creating-parent-nodes nil
2218 "Non-nil means allow to create new nodes as refile targets.
2219 New nodes are then created by adding \"/new node name\" to the completion
2220 of an existing node. When the value of this variable is `confirm',
2221 new node creation must be confirmed by the user (recommended)
2222 When nil, the completion must match an existing entry.
2224 Note that, if the new heading is not seen by the criteria
2225 listed in `org-refile-targets', multiple instances of the same
2226 heading would be created by trying again to file under the new
2227 heading."
2228 :group 'org-refile
2229 :type '(choice
2230 (const :tag "Never" nil)
2231 (const :tag "Always" t)
2232 (const :tag "Prompt for confirmation" confirm)))
2234 (defcustom org-refile-active-region-within-subtree nil
2235 "Non-nil means also refile active region within a subtree.
2237 By default `org-refile' doesn't allow refiling regions if they
2238 don't contain a set of subtrees, but it might be convenient to
2239 do so sometimes: in that case, the first line of the region is
2240 converted to a headline before refiling."
2241 :group 'org-refile
2242 :version "24.1"
2243 :type 'boolean)
2245 (defgroup org-todo nil
2246 "Options concerning TODO items in Org-mode."
2247 :tag "Org TODO"
2248 :group 'org)
2250 (defgroup org-progress nil
2251 "Options concerning Progress logging in Org-mode."
2252 :tag "Org Progress"
2253 :group 'org-time)
2255 (defvar org-todo-interpretation-widgets
2256 '((:tag "Sequence (cycling hits every state)" sequence)
2257 (:tag "Type (cycling directly to DONE)" type))
2258 "The available interpretation symbols for customizing `org-todo-keywords'.
2259 Interested libraries should add to this list.")
2261 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2262 "List of TODO entry keyword sequences and their interpretation.
2263 \\<org-mode-map>This is a list of sequences.
2265 Each sequence starts with a symbol, either `sequence' or `type',
2266 indicating if the keywords should be interpreted as a sequence of
2267 action steps, or as different types of TODO items. The first
2268 keywords are states requiring action - these states will select a headline
2269 for inclusion into the global TODO list Org-mode produces. If one of
2270 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2271 signify that no further action is necessary. If \"|\" is not found,
2272 the last keyword is treated as the only DONE state of the sequence.
2274 The command \\[org-todo] cycles an entry through these states, and one
2275 additional state where no keyword is present. For details about this
2276 cycling, see the manual.
2278 TODO keywords and interpretation can also be set on a per-file basis with
2279 the special #+SEQ_TODO and #+TYP_TODO lines.
2281 Each keyword can optionally specify a character for fast state selection
2282 \(in combination with the variable `org-use-fast-todo-selection')
2283 and specifiers for state change logging, using the same syntax that
2284 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2285 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2286 indicates to record a time stamp each time this state is selected.
2288 Each keyword may also specify if a timestamp or a note should be
2289 recorded when entering or leaving the state, by adding additional
2290 characters in the parenthesis after the keyword. This looks like this:
2291 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2292 record only the time of the state change. With X and Y being either
2293 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2294 Y when leaving the state if and only if the *target* state does not
2295 define X. You may omit any of the fast-selection key or X or /Y,
2296 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2298 For backward compatibility, this variable may also be just a list
2299 of keywords. In this case the interpretation (sequence or type) will be
2300 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2301 :group 'org-todo
2302 :group 'org-keywords
2303 :type '(choice
2304 (repeat :tag "Old syntax, just keywords"
2305 (string :tag "Keyword"))
2306 (repeat :tag "New syntax"
2307 (cons
2308 (choice
2309 :tag "Interpretation"
2310 ;;Quick and dirty way to see
2311 ;;`org-todo-interpretations'. This takes the
2312 ;;place of item arguments
2313 :convert-widget
2314 (lambda (widget)
2315 (widget-put widget
2316 :args (mapcar
2317 #'(lambda (x)
2318 (widget-convert
2319 (cons 'const x)))
2320 org-todo-interpretation-widgets))
2321 widget))
2322 (repeat
2323 (string :tag "Keyword"))))))
2325 (defvar org-todo-keywords-1 nil
2326 "All TODO and DONE keywords active in a buffer.")
2327 (make-variable-buffer-local 'org-todo-keywords-1)
2328 (defvar org-todo-keywords-for-agenda nil)
2329 (defvar org-done-keywords-for-agenda nil)
2330 (defvar org-drawers-for-agenda nil)
2331 (defvar org-todo-keyword-alist-for-agenda nil)
2332 (defvar org-tag-alist-for-agenda nil
2333 "Alist of all tags from all agenda files.")
2334 (defvar org-tag-groups-alist-for-agenda nil
2335 "Alist of all groups tags from all current agenda files.")
2336 (defvar org-tag-groups-alist nil)
2337 (make-variable-buffer-local 'org-tag-groups-alist)
2338 (defvar org-agenda-contributing-files nil)
2339 (defvar org-not-done-keywords nil)
2340 (make-variable-buffer-local 'org-not-done-keywords)
2341 (defvar org-done-keywords nil)
2342 (make-variable-buffer-local 'org-done-keywords)
2343 (defvar org-todo-heads nil)
2344 (make-variable-buffer-local 'org-todo-heads)
2345 (defvar org-todo-sets nil)
2346 (make-variable-buffer-local 'org-todo-sets)
2347 (defvar org-todo-log-states nil)
2348 (make-variable-buffer-local 'org-todo-log-states)
2349 (defvar org-todo-kwd-alist nil)
2350 (make-variable-buffer-local 'org-todo-kwd-alist)
2351 (defvar org-todo-key-alist nil)
2352 (make-variable-buffer-local 'org-todo-key-alist)
2353 (defvar org-todo-key-trigger nil)
2354 (make-variable-buffer-local 'org-todo-key-trigger)
2356 (defcustom org-todo-interpretation 'sequence
2357 "Controls how TODO keywords are interpreted.
2358 This variable is in principle obsolete and is only used for
2359 backward compatibility, if the interpretation of todo keywords is
2360 not given already in `org-todo-keywords'. See that variable for
2361 more information."
2362 :group 'org-todo
2363 :group 'org-keywords
2364 :type '(choice (const sequence)
2365 (const type)))
2367 (defcustom org-use-fast-todo-selection t
2368 "Non-nil means use the fast todo selection scheme with C-c C-t.
2369 This variable describes if and under what circumstances the cycling
2370 mechanism for TODO keywords will be replaced by a single-key, direct
2371 selection scheme.
2373 When nil, fast selection is never used.
2375 When the symbol `prefix', it will be used when `org-todo' is called
2376 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2377 `C-u t' in an agenda buffer.
2379 When t, fast selection is used by default. In this case, the prefix
2380 argument forces cycling instead.
2382 In all cases, the special interface is only used if access keys have
2383 actually been assigned by the user, i.e. if keywords in the configuration
2384 are followed by a letter in parenthesis, like TODO(t)."
2385 :group 'org-todo
2386 :type '(choice
2387 (const :tag "Never" nil)
2388 (const :tag "By default" t)
2389 (const :tag "Only with C-u C-c C-t" prefix)))
2391 (defcustom org-provide-todo-statistics t
2392 "Non-nil means update todo statistics after insert and toggle.
2393 ALL-HEADLINES means update todo statistics by including headlines
2394 with no TODO keyword as well, counting them as not done.
2395 A list of TODO keywords means the same, but skip keywords that are
2396 not in this list.
2398 When this is set, todo statistics is updated in the parent of the
2399 current entry each time a todo state is changed."
2400 :group 'org-todo
2401 :type '(choice
2402 (const :tag "Yes, only for TODO entries" t)
2403 (const :tag "Yes, including all entries" 'all-headlines)
2404 (repeat :tag "Yes, for TODOs in this list"
2405 (string :tag "TODO keyword"))
2406 (other :tag "No TODO statistics" nil)))
2408 (defcustom org-hierarchical-todo-statistics t
2409 "Non-nil means TODO statistics covers just direct children.
2410 When nil, all entries in the subtree are considered.
2411 This has only an effect if `org-provide-todo-statistics' is set.
2412 To set this to nil for only a single subtree, use a COOKIE_DATA
2413 property and include the word \"recursive\" into the value."
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-after-todo-state-change-hook nil
2418 "Hook which is run after the state of a TODO item was changed.
2419 The new state (a string with a TODO keyword, or nil) is available in the
2420 Lisp variable `org-state'."
2421 :group 'org-todo
2422 :type 'hook)
2424 (defvar org-blocker-hook nil
2425 "Hook for functions that are allowed to block a state change.
2427 Functions in this hook should not modify the buffer.
2428 Each function gets as its single argument a property list,
2429 see `org-trigger-hook' for more information about this list.
2431 If any of the functions in this hook returns nil, the state change
2432 is blocked.")
2434 (defvar org-trigger-hook nil
2435 "Hook for functions that are triggered by a state change.
2437 Each function gets as its single argument a property list with at
2438 least the following elements:
2440 (:type type-of-change :position pos-at-entry-start
2441 :from old-state :to new-state)
2443 Depending on the type, more properties may be present.
2445 This mechanism is currently implemented for:
2447 TODO state changes
2448 ------------------
2449 :type todo-state-change
2450 :from previous state (keyword as a string), or nil, or a symbol
2451 'todo' or 'done', to indicate the general type of state.
2452 :to new state, like in :from")
2454 (defcustom org-enforce-todo-dependencies nil
2455 "Non-nil means undone TODO entries will block switching the parent to DONE.
2456 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2457 be blocked if any prior sibling is not yet done.
2458 Finally, if the parent is blocked because of ordered siblings of its own,
2459 the child will also be blocked."
2460 :set (lambda (var val)
2461 (set var val)
2462 (if val
2463 (add-hook 'org-blocker-hook
2464 'org-block-todo-from-children-or-siblings-or-parent)
2465 (remove-hook 'org-blocker-hook
2466 'org-block-todo-from-children-or-siblings-or-parent)))
2467 :group 'org-todo
2468 :type 'boolean)
2470 (defcustom org-enforce-todo-checkbox-dependencies nil
2471 "Non-nil means unchecked boxes will block switching the parent to DONE.
2472 When this is nil, checkboxes have no influence on switching TODO states.
2473 When non-nil, you first need to check off all check boxes before the TODO
2474 entry can be switched to DONE.
2475 This variable needs to be set before org.el is loaded, and you need to
2476 restart Emacs after a change to make the change effective. The only way
2477 to change is while Emacs is running is through the customize interface."
2478 :set (lambda (var val)
2479 (set var val)
2480 (if val
2481 (add-hook 'org-blocker-hook
2482 'org-block-todo-from-checkboxes)
2483 (remove-hook 'org-blocker-hook
2484 'org-block-todo-from-checkboxes)))
2485 :group 'org-todo
2486 :type 'boolean)
2488 (defcustom org-treat-insert-todo-heading-as-state-change nil
2489 "Non-nil means inserting a TODO heading is treated as state change.
2490 So when the command \\[org-insert-todo-heading] is used, state change
2491 logging will apply if appropriate. When nil, the new TODO item will
2492 be inserted directly, and no logging will take place."
2493 :group 'org-todo
2494 :type 'boolean)
2496 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2497 "Non-nil means switching TODO states with S-cursor counts as state change.
2498 This is the default behavior. However, setting this to nil allows a
2499 convenient way to select a TODO state and bypass any logging associated
2500 with that."
2501 :group 'org-todo
2502 :type 'boolean)
2504 (defcustom org-todo-state-tags-triggers nil
2505 "Tag changes that should be triggered by TODO state changes.
2506 This is a list. Each entry is
2508 (state-change (tag . flag) .......)
2510 State-change can be a string with a state, and empty string to indicate the
2511 state that has no TODO keyword, or it can be one of the symbols `todo'
2512 or `done', meaning any not-done or done state, respectively."
2513 :group 'org-todo
2514 :group 'org-tags
2515 :type '(repeat
2516 (cons (choice :tag "When changing to"
2517 (const :tag "Not-done state" todo)
2518 (const :tag "Done state" done)
2519 (string :tag "State"))
2520 (repeat
2521 (cons :tag "Tag action"
2522 (string :tag "Tag")
2523 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2525 (defcustom org-log-done nil
2526 "Information to record when a task moves to the DONE state.
2528 Possible values are:
2530 nil Don't add anything, just change the keyword
2531 time Add a time stamp to the task
2532 note Prompt for a note and add it with template `org-log-note-headings'
2534 This option can also be set with on a per-file-basis with
2536 #+STARTUP: nologdone
2537 #+STARTUP: logdone
2538 #+STARTUP: lognotedone
2540 You can have local logging settings for a subtree by setting the LOGGING
2541 property to one or more of these keywords."
2542 :group 'org-todo
2543 :group 'org-progress
2544 :type '(choice
2545 (const :tag "No logging" nil)
2546 (const :tag "Record CLOSED timestamp" time)
2547 (const :tag "Record CLOSED timestamp with note." note)))
2549 ;; Normalize old uses of org-log-done.
2550 (cond
2551 ((eq org-log-done t) (setq org-log-done 'time))
2552 ((and (listp org-log-done) (memq 'done org-log-done))
2553 (setq org-log-done 'note)))
2555 (defcustom org-log-reschedule nil
2556 "Information to record when the scheduling date of a tasks is modified.
2558 Possible values are:
2560 nil Don't add anything, just change the date
2561 time Add a time stamp to the task
2562 note Prompt for a note and add it with template `org-log-note-headings'
2564 This option can also be set with on a per-file-basis with
2566 #+STARTUP: nologreschedule
2567 #+STARTUP: logreschedule
2568 #+STARTUP: lognotereschedule"
2569 :group 'org-todo
2570 :group 'org-progress
2571 :type '(choice
2572 (const :tag "No logging" nil)
2573 (const :tag "Record timestamp" time)
2574 (const :tag "Record timestamp with note." note)))
2576 (defcustom org-log-redeadline nil
2577 "Information to record when the deadline date of a tasks is modified.
2579 Possible values are:
2581 nil Don't add anything, just change the date
2582 time Add a time stamp to the task
2583 note Prompt for a note and add it with template `org-log-note-headings'
2585 This option can also be set with on a per-file-basis with
2587 #+STARTUP: nologredeadline
2588 #+STARTUP: logredeadline
2589 #+STARTUP: lognoteredeadline
2591 You can have local logging settings for a subtree by setting the LOGGING
2592 property to one or more of these keywords."
2593 :group 'org-todo
2594 :group 'org-progress
2595 :type '(choice
2596 (const :tag "No logging" nil)
2597 (const :tag "Record timestamp" time)
2598 (const :tag "Record timestamp with note." note)))
2600 (defcustom org-log-note-clock-out nil
2601 "Non-nil means record a note when clocking out of an item.
2602 This can also be configured on a per-file basis by adding one of
2603 the following lines anywhere in the buffer:
2605 #+STARTUP: lognoteclock-out
2606 #+STARTUP: nolognoteclock-out"
2607 :group 'org-todo
2608 :group 'org-progress
2609 :type 'boolean)
2611 (defcustom org-log-done-with-time t
2612 "Non-nil means the CLOSED time stamp will contain date and time.
2613 When nil, only the date will be recorded."
2614 :group 'org-progress
2615 :type 'boolean)
2617 (defcustom org-log-note-headings
2618 '((done . "CLOSING NOTE %t")
2619 (state . "State %-12s from %-12S %t")
2620 (note . "Note taken on %t")
2621 (reschedule . "Rescheduled from %S on %t")
2622 (delschedule . "Not scheduled, was %S on %t")
2623 (redeadline . "New deadline from %S on %t")
2624 (deldeadline . "Removed deadline, was %S on %t")
2625 (refile . "Refiled on %t")
2626 (clock-out . ""))
2627 "Headings for notes added to entries.
2628 The value is an alist, with the car being a symbol indicating the note
2629 context, and the cdr is the heading to be used. The heading may also be the
2630 empty string.
2631 %t in the heading will be replaced by a time stamp.
2632 %T will be an active time stamp instead the default inactive one
2633 %d will be replaced by a short-format time stamp.
2634 %D will be replaced by an active short-format time stamp.
2635 %s will be replaced by the new TODO state, in double quotes.
2636 %S will be replaced by the old TODO state, in double quotes.
2637 %u will be replaced by the user name.
2638 %U will be replaced by the full user name.
2640 In fact, it is not a good idea to change the `state' entry, because
2641 agenda log mode depends on the format of these entries."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type '(list :greedy t
2645 (cons (const :tag "Heading when closing an item" done) string)
2646 (cons (const :tag
2647 "Heading when changing todo state (todo sequence only)"
2648 state) string)
2649 (cons (const :tag "Heading when just taking a note" note) string)
2650 (cons (const :tag "Heading when clocking out" clock-out) string)
2651 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2652 (cons (const :tag "Heading when rescheduling" reschedule) string)
2653 (cons (const :tag "Heading when changing deadline" redeadline) string)
2654 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2655 (cons (const :tag "Heading when refiling" refile) string)))
2657 (unless (assq 'note org-log-note-headings)
2658 (push '(note . "%t") org-log-note-headings))
2660 (defcustom org-log-into-drawer nil
2661 "Non-nil means insert state change notes and time stamps into a drawer.
2662 When nil, state changes notes will be inserted after the headline and
2663 any scheduling and clock lines, but not inside a drawer.
2665 The value of this variable should be the name of the drawer to use.
2666 LOGBOOK is proposed as the default drawer for this purpose, you can
2667 also set this to a string to define the drawer of your choice.
2669 A value of t is also allowed, representing \"LOGBOOK\".
2671 A value of t or nil can also be set with on a per-file-basis with
2673 #+STARTUP: logdrawer
2674 #+STARTUP: nologdrawer
2676 If this variable is set, `org-log-state-notes-insert-after-drawers'
2677 will be ignored.
2679 You can set the property LOG_INTO_DRAWER to overrule this setting for
2680 a subtree."
2681 :group 'org-todo
2682 :group 'org-progress
2683 :type '(choice
2684 (const :tag "Not into a drawer" nil)
2685 (const :tag "LOGBOOK" t)
2686 (string :tag "Other")))
2688 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2690 (defun org-log-into-drawer ()
2691 "Return the value of `org-log-into-drawer', but let properties overrule.
2692 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2693 used instead of the default value."
2694 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2695 (cond
2696 ((not p) org-log-into-drawer)
2697 ((equal p "nil") nil)
2698 ((equal p "t") "LOGBOOK")
2699 (t p))))
2701 (defcustom org-log-state-notes-insert-after-drawers nil
2702 "Non-nil means insert state change notes after any drawers in entry.
2703 Only the drawers that *immediately* follow the headline and the
2704 deadline/scheduled line are skipped.
2705 When nil, insert notes right after the heading and perhaps the line
2706 with deadline/scheduling if present.
2708 This variable will have no effect if `org-log-into-drawer' is
2709 set."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type 'boolean)
2714 (defcustom org-log-states-order-reversed t
2715 "Non-nil means the latest state note will be directly after heading.
2716 When nil, the state change notes will be ordered according to time.
2718 This option can also be set with on a per-file-basis with
2720 #+STARTUP: logstatesreversed
2721 #+STARTUP: nologstatesreversed"
2722 :group 'org-todo
2723 :group 'org-progress
2724 :type 'boolean)
2726 (defcustom org-todo-repeat-to-state nil
2727 "The TODO state to which a repeater should return the repeating task.
2728 By default this is the first task in a TODO sequence, or the previous state
2729 in a TODO_TYP set. But you can specify another task here.
2730 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2731 :group 'org-todo
2732 :version "24.1"
2733 :type '(choice (const :tag "Head of sequence" nil)
2734 (string :tag "Specific state")))
2736 (defcustom org-log-repeat 'time
2737 "Non-nil means record moving through the DONE state when triggering repeat.
2738 An auto-repeating task is immediately switched back to TODO when
2739 marked DONE. If you are not logging state changes (by adding \"@\"
2740 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2741 record a closing note, there will be no record of the task moving
2742 through DONE. This variable forces taking a note anyway.
2744 nil Don't force a record
2745 time Record a time stamp
2746 note Prompt for a note and add it with template `org-log-note-headings'
2748 This option can also be set with on a per-file-basis with
2750 #+STARTUP: nologrepeat
2751 #+STARTUP: logrepeat
2752 #+STARTUP: lognoterepeat
2754 You can have local logging settings for a subtree by setting the LOGGING
2755 property to one or more of these keywords."
2756 :group 'org-todo
2757 :group 'org-progress
2758 :type '(choice
2759 (const :tag "Don't force a record" nil)
2760 (const :tag "Force recording the DONE state" time)
2761 (const :tag "Force recording a note with the DONE state" note)))
2764 (defgroup org-priorities nil
2765 "Priorities in Org-mode."
2766 :tag "Org Priorities"
2767 :group 'org-todo)
2769 (defcustom org-enable-priority-commands t
2770 "Non-nil means priority commands are active.
2771 When nil, these commands will be disabled, so that you never accidentally
2772 set a priority."
2773 :group 'org-priorities
2774 :type 'boolean)
2776 (defcustom org-highest-priority ?A
2777 "The highest priority of TODO items. A character like ?A, ?B etc.
2778 Must have a smaller ASCII number than `org-lowest-priority'."
2779 :group 'org-priorities
2780 :type 'character)
2782 (defcustom org-lowest-priority ?C
2783 "The lowest priority of TODO items. A character like ?A, ?B etc.
2784 Must have a larger ASCII number than `org-highest-priority'."
2785 :group 'org-priorities
2786 :type 'character)
2788 (defcustom org-default-priority ?B
2789 "The default priority of TODO items.
2790 This is the priority an item gets if no explicit priority is given.
2791 When starting to cycle on an empty priority the first step in the cycle
2792 depends on `org-priority-start-cycle-with-default'. The resulting first
2793 step priority must not exceed the range from `org-highest-priority' to
2794 `org-lowest-priority' which means that `org-default-priority' has to be
2795 in this range exclusive or inclusive the range boundaries. Else the
2796 first step refuses to set the default and the second will fall back
2797 to (depending on the command used) the highest or lowest priority."
2798 :group 'org-priorities
2799 :type 'character)
2801 (defcustom org-priority-start-cycle-with-default t
2802 "Non-nil means start with default priority when starting to cycle.
2803 When this is nil, the first step in the cycle will be (depending on the
2804 command used) one higher or lower than the default priority.
2805 See also `org-default-priority'."
2806 :group 'org-priorities
2807 :type 'boolean)
2809 (defcustom org-get-priority-function nil
2810 "Function to extract the priority from a string.
2811 The string is normally the headline. If this is nil Org computes the
2812 priority from the priority cookie like [#A] in the headline. It returns
2813 an integer, increasing by 1000 for each priority level.
2814 The user can set a different function here, which should take a string
2815 as an argument and return the numeric priority."
2816 :group 'org-priorities
2817 :version "24.1"
2818 :type '(choice
2819 (const nil)
2820 (function)))
2822 (defgroup org-time nil
2823 "Options concerning time stamps and deadlines in Org-mode."
2824 :tag "Org Time"
2825 :group 'org)
2827 (defcustom org-insert-labeled-timestamps-at-point nil
2828 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2829 When nil, these labeled time stamps are forces into the second line of an
2830 entry, just after the headline. When scheduling from the global TODO list,
2831 the time stamp will always be forced into the second line."
2832 :group 'org-time
2833 :type 'boolean)
2835 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2836 "Formats for `format-time-string' which are used for time stamps.
2837 It is not recommended to change this constant.")
2839 (defcustom org-time-stamp-rounding-minutes '(0 5)
2840 "Number of minutes to round time stamps to.
2841 These are two values, the first applies when first creating a time stamp.
2842 The second applies when changing it with the commands `S-up' and `S-down'.
2843 When changing the time stamp, this means that it will change in steps
2844 of N minutes, as given by the second value.
2846 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2847 numbers should be factors of 60, so for example 5, 10, 15.
2849 When this is larger than 1, you can still force an exact time stamp by using
2850 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2851 and by using a prefix arg to `S-up/down' to specify the exact number
2852 of minutes to shift."
2853 :group 'org-time
2854 :get #'(lambda (var) ; Make sure both elements are there
2855 (if (integerp (default-value var))
2856 (list (default-value var) 5)
2857 (default-value var)))
2858 :type '(list
2859 (integer :tag "when inserting times")
2860 (integer :tag "when modifying times")))
2862 ;; Normalize old customizations of this variable.
2863 (when (integerp org-time-stamp-rounding-minutes)
2864 (setq org-time-stamp-rounding-minutes
2865 (list org-time-stamp-rounding-minutes
2866 org-time-stamp-rounding-minutes)))
2868 (defcustom org-display-custom-times nil
2869 "Non-nil means overlay custom formats over all time stamps.
2870 The formats are defined through the variable `org-time-stamp-custom-formats'.
2871 To turn this on on a per-file basis, insert anywhere in the file:
2872 #+STARTUP: customtime"
2873 :group 'org-time
2874 :set 'set-default
2875 :type 'sexp)
2876 (make-variable-buffer-local 'org-display-custom-times)
2878 (defcustom org-time-stamp-custom-formats
2879 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2880 "Custom formats for time stamps. See `format-time-string' for the syntax.
2881 These are overlaid over the default ISO format if the variable
2882 `org-display-custom-times' is set. Time like %H:%M should be at the
2883 end of the second format. The custom formats are also honored by export
2884 commands, if custom time display is turned on at the time of export."
2885 :group 'org-time
2886 :type 'sexp)
2888 (defun org-time-stamp-format (&optional long inactive)
2889 "Get the right format for a time string."
2890 (let ((f (if long (cdr org-time-stamp-formats)
2891 (car org-time-stamp-formats))))
2892 (if inactive
2893 (concat "[" (substring f 1 -1) "]")
2894 f)))
2896 (defcustom org-time-clocksum-format
2897 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2898 "The format string used when creating CLOCKSUM lines.
2899 This is also used when Org mode generates a time duration.
2901 The value can be a single format string containing two
2902 %-sequences, which will be filled with the number of hours and
2903 minutes in that order.
2905 Alternatively, the value can be a plist associating any of the
2906 keys :years, :months, :weeks, :days, :hours or :minutes with
2907 format strings. The time duration is formatted using only the
2908 time components that are needed and concatenating the results.
2909 If a time unit in absent, it falls back to the next smallest
2910 unit.
2912 The keys :require-years, :require-months, :require-days,
2913 :require-weeks, :require-hours, :require-minutes are also
2914 meaningful. A non-nil value for these keys indicates that the
2915 corresponding time component should always be included, even if
2916 its value is 0.
2919 For example,
2921 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2922 :require-minutes t)
2924 means durations longer than a day will be expressed in days,
2925 hours and minutes, and durations less than a day will always be
2926 expressed in hours and minutes (even for durations less than an
2927 hour).
2929 The value
2931 \(:days \"%dd\" :minutes \"%dm\")
2933 means durations longer than a day will be expressed in days and
2934 minutes, and durations less than a day will be expressed entirely
2935 in minutes (even for durations longer than an hour)."
2936 :group 'org-time
2937 :group 'org-clock
2938 :version "24.4"
2939 :package-version '(Org . "8.0")
2940 :type '(choice (string :tag "Format string")
2941 (set :tag "Plist"
2942 (group :inline t (const :tag "Years" :years)
2943 (string :tag "Format string"))
2944 (group :inline t
2945 (const :tag "Always show years" :require-years)
2946 (const t))
2947 (group :inline t (const :tag "Months" :months)
2948 (string :tag "Format string"))
2949 (group :inline t
2950 (const :tag "Always show months" :require-months)
2951 (const t))
2952 (group :inline t (const :tag "Weeks" :weeks)
2953 (string :tag "Format string"))
2954 (group :inline t
2955 (const :tag "Always show weeks" :require-weeks)
2956 (const t))
2957 (group :inline t (const :tag "Days" :days)
2958 (string :tag "Format string"))
2959 (group :inline t
2960 (const :tag "Always show days" :require-days)
2961 (const t))
2962 (group :inline t (const :tag "Hours" :hours)
2963 (string :tag "Format string"))
2964 (group :inline t
2965 (const :tag "Always show hours" :require-hours)
2966 (const t))
2967 (group :inline t (const :tag "Minutes" :minutes)
2968 (string :tag "Format string"))
2969 (group :inline t
2970 (const :tag "Always show minutes" :require-minutes)
2971 (const t)))))
2973 (defcustom org-time-clocksum-use-fractional nil
2974 "When non-nil, \\[org-clock-display] uses fractional times.
2975 See `org-time-clocksum-format' for more on time clock formats."
2976 :group 'org-time
2977 :group 'org-clock
2978 :version "24.3"
2979 :type 'boolean)
2981 (defcustom org-time-clocksum-use-effort-durations nil
2982 "When non-nil, \\[org-clock-display] uses effort durations.
2983 E.g. by default, one day is considered to be a 8 hours effort,
2984 so a task that has been clocked for 16 hours will be displayed
2985 as during 2 days in the clock display or in the clocktable.
2987 See `org-effort-durations' on how to set effort durations
2988 and `org-time-clocksum-format' for more on time clock formats."
2989 :group 'org-time
2990 :group 'org-clock
2991 :version "24.4"
2992 :package-version '(Org . "8.0")
2993 :type 'boolean)
2995 (defcustom org-time-clocksum-fractional-format "%.2f"
2996 "The format string used when creating CLOCKSUM lines,
2997 or when Org mode generates a time duration, if
2998 `org-time-clocksum-use-fractional' is enabled.
3000 The value can be a single format string containing one
3001 %-sequence, which will be filled with the number of hours as
3002 a float.
3004 Alternatively, the value can be a plist associating any of the
3005 keys :years, :months, :weeks, :days, :hours or :minutes with
3006 a format string. The time duration is formatted using the
3007 largest time unit which gives a non-zero integer part. If all
3008 specified formats have zero integer part, the smallest time unit
3009 is used."
3010 :group 'org-time
3011 :type '(choice (string :tag "Format string")
3012 (set (group :inline t (const :tag "Years" :years)
3013 (string :tag "Format string"))
3014 (group :inline t (const :tag "Months" :months)
3015 (string :tag "Format string"))
3016 (group :inline t (const :tag "Weeks" :weeks)
3017 (string :tag "Format string"))
3018 (group :inline t (const :tag "Days" :days)
3019 (string :tag "Format string"))
3020 (group :inline t (const :tag "Hours" :hours)
3021 (string :tag "Format string"))
3022 (group :inline t (const :tag "Minutes" :minutes)
3023 (string :tag "Format string")))))
3025 (defcustom org-deadline-warning-days 14
3026 "Number of days before expiration during which a deadline becomes active.
3027 This variable governs the display in sparse trees and in the agenda.
3028 When 0 or negative, it means use this number (the absolute value of it)
3029 even if a deadline has a different individual lead time specified.
3031 Custom commands can set this variable in the options section."
3032 :group 'org-time
3033 :group 'org-agenda-daily/weekly
3034 :type 'integer)
3036 (defcustom org-scheduled-delay-days 0
3037 "Number of days before a scheduled item becomes active.
3038 This variable governs the display in sparse trees and in the agenda.
3039 The default value (i.e. 0) means: don't delay scheduled item.
3040 When negative, it means use this number (the absolute value of it)
3041 even if a scheduled item has a different individual delay time
3042 specified.
3044 Custom commands can set this variable in the options section."
3045 :group 'org-time
3046 :group 'org-agenda-daily/weekly
3047 :version "24.4"
3048 :package-version '(Org . "8.0")
3049 :type 'integer)
3051 (defcustom org-read-date-prefer-future t
3052 "Non-nil means assume future for incomplete date input from user.
3053 This affects the following situations:
3054 1. The user gives a month but not a year.
3055 For example, if it is April and you enter \"feb 2\", this will be read
3056 as Feb 2, *next* year. \"May 5\", however, will be this year.
3057 2. The user gives a day, but no month.
3058 For example, if today is the 15th, and you enter \"3\", Org-mode will
3059 read this as the third of *next* month. However, if you enter \"17\",
3060 it will be considered as *this* month.
3062 If you set this variable to the symbol `time', then also the following
3063 will work:
3065 3. If the user gives a time.
3066 If the time is before now, it will be interpreted as tomorrow.
3068 Currently none of this works for ISO week specifications.
3070 When this option is nil, the current day, month and year will always be
3071 used as defaults.
3073 See also `org-agenda-jump-prefer-future'."
3074 :group 'org-time
3075 :type '(choice
3076 (const :tag "Never" nil)
3077 (const :tag "Check month and day" t)
3078 (const :tag "Check month, day, and time" time)))
3080 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3081 "Should the agenda jump command prefer the future for incomplete dates?
3082 The default is to do the same as configured in `org-read-date-prefer-future'.
3083 But you can also set a deviating value here.
3084 This may t or nil, or the symbol `org-read-date-prefer-future'."
3085 :group 'org-agenda
3086 :group 'org-time
3087 :version "24.1"
3088 :type '(choice
3089 (const :tag "Use org-read-date-prefer-future"
3090 org-read-date-prefer-future)
3091 (const :tag "Never" nil)
3092 (const :tag "Always" t)))
3094 (defcustom org-read-date-force-compatible-dates t
3095 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3097 Depending on the system Emacs is running on, certain dates cannot
3098 be represented with the type used internally to represent time.
3099 Dates between 1970-1-1 and 2038-1-1 can always be represented
3100 correctly. Some systems allow for earlier dates, some for later,
3101 some for both. One way to find out it to insert any date into an
3102 Org buffer, putting the cursor on the year and hitting S-up and
3103 S-down to test the range.
3105 When this variable is set to t, the date/time prompt will not let
3106 you specify dates outside the 1970-2037 range, so it is certain that
3107 these dates will work in whatever version of Emacs you are
3108 running, and also that you can move a file from one Emacs implementation
3109 to another. WHenever Org is forcing the year for you, it will display
3110 a message and beep.
3112 When this variable is nil, Org will check if the date is
3113 representable in the specific Emacs implementation you are using.
3114 If not, it will force a year, usually the current year, and beep
3115 to remind you. Currently this setting is not recommended because
3116 the likelihood that you will open your Org files in an Emacs that
3117 has limited date range is not negligible.
3119 A workaround for this problem is to use diary sexp dates for time
3120 stamps outside of this range."
3121 :group 'org-time
3122 :version "24.1"
3123 :type 'boolean)
3125 (defcustom org-read-date-display-live t
3126 "Non-nil means display current interpretation of date prompt live.
3127 This display will be in an overlay, in the minibuffer."
3128 :group 'org-time
3129 :type 'boolean)
3131 (defcustom org-read-date-popup-calendar t
3132 "Non-nil means pop up a calendar when prompting for a date.
3133 In the calendar, the date can be selected with mouse-1. However, the
3134 minibuffer will also be active, and you can simply enter the date as well.
3135 When nil, only the minibuffer will be available."
3136 :group 'org-time
3137 :type 'boolean)
3138 (org-defvaralias 'org-popup-calendar-for-date-prompt
3139 'org-read-date-popup-calendar)
3141 (make-obsolete-variable
3142 'org-read-date-minibuffer-setup-hook
3143 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3144 (defcustom org-read-date-minibuffer-setup-hook nil
3145 "Hook to be used to set up keys for the date/time interface.
3146 Add key definitions to `minibuffer-local-map', which will be a
3147 temporary copy.
3149 WARNING: This option is obsolete, you should use
3150 `org-read-date-minibuffer-local-map' to set up keys."
3151 :group 'org-time
3152 :type 'hook)
3154 (defcustom org-extend-today-until 0
3155 "The hour when your day really ends. Must be an integer.
3156 This has influence for the following applications:
3157 - When switching the agenda to \"today\". It it is still earlier than
3158 the time given here, the day recognized as TODAY is actually yesterday.
3159 - When a date is read from the user and it is still before the time given
3160 here, the current date and time will be assumed to be yesterday, 23:59.
3161 Also, timestamps inserted in capture templates follow this rule.
3163 IMPORTANT: This is a feature whose implementation is and likely will
3164 remain incomplete. Really, it is only here because past midnight seems to
3165 be the favorite working time of John Wiegley :-)"
3166 :group 'org-time
3167 :type 'integer)
3169 (defcustom org-use-effective-time nil
3170 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3171 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3172 \"effective time\" of any timestamps between midnight and 8am will be
3173 23:59 of the previous day."
3174 :group 'org-time
3175 :version "24.1"
3176 :type 'boolean)
3178 (defcustom org-use-last-clock-out-time-as-effective-time nil
3179 "When non-nil, use the last clock out time for `org-todo'.
3180 Note that this option has precedence over the combined use of
3181 `org-use-effective-time' and `org-extend-today-until'."
3182 :group 'org-time
3183 :version "24.4"
3184 :package-version '(Org . "8.0")
3185 :type 'boolean)
3187 (defcustom org-edit-timestamp-down-means-later nil
3188 "Non-nil means S-down will increase the time in a time stamp.
3189 When nil, S-up will increase."
3190 :group 'org-time
3191 :type 'boolean)
3193 (defcustom org-calendar-follow-timestamp-change t
3194 "Non-nil means make the calendar window follow timestamp changes.
3195 When a timestamp is modified and the calendar window is visible, it will be
3196 moved to the new date."
3197 :group 'org-time
3198 :type 'boolean)
3200 (defgroup org-tags nil
3201 "Options concerning tags in Org-mode."
3202 :tag "Org Tags"
3203 :group 'org)
3205 (defcustom org-tag-alist nil
3206 "List of tags allowed in Org-mode files.
3207 When this list is nil, Org-mode will base TAG input on what is already in the
3208 buffer.
3209 The value of this variable is an alist, the car of each entry must be a
3210 keyword as a string, the cdr may be a character that is used to select
3211 that tag through the fast-tag-selection interface.
3212 See the manual for details."
3213 :group 'org-tags
3214 :type '(repeat
3215 (choice
3216 (cons (string :tag "Tag name")
3217 (character :tag "Access char"))
3218 (list :tag "Start radio group"
3219 (const :startgroup)
3220 (option (string :tag "Group description")))
3221 (list :tag "Group tags delimiter"
3222 (const :grouptags))
3223 (list :tag "End radio group"
3224 (const :endgroup)
3225 (option (string :tag "Group description")))
3226 (const :tag "New line" (:newline)))))
3228 (defcustom org-tag-persistent-alist nil
3229 "List of tags that will always appear in all Org-mode files.
3230 This is in addition to any in buffer settings or customizations
3231 of `org-tag-alist'.
3232 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3233 The value of this variable is an alist, the car of each entry must be a
3234 keyword as a string, the cdr may be a character that is used to select
3235 that tag through the fast-tag-selection interface.
3236 See the manual for details.
3237 To disable these tags on a per-file basis, insert anywhere in the file:
3238 #+STARTUP: noptag"
3239 :group 'org-tags
3240 :type '(repeat
3241 (choice
3242 (cons (string :tag "Tag name")
3243 (character :tag "Access char"))
3244 (const :tag "Start radio group" (:startgroup))
3245 (const :tag "Group tags delimiter" (:grouptags))
3246 (const :tag "End radio group" (:endgroup))
3247 (const :tag "New line" (:newline)))))
3249 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3250 "If non-nil, always offer completion for all tags of all agenda files.
3251 Instead of customizing this variable directly, you might want to
3252 set it locally for capture buffers, because there no list of
3253 tags in that file can be created dynamically (there are none).
3255 (add-hook 'org-capture-mode-hook
3256 (lambda ()
3257 (set (make-local-variable
3258 'org-complete-tags-always-offer-all-agenda-tags)
3259 t)))"
3260 :group 'org-tags
3261 :version "24.1"
3262 :type 'boolean)
3264 (defvar org-file-tags nil
3265 "List of tags that can be inherited by all entries in the file.
3266 The tags will be inherited if the variable `org-use-tag-inheritance'
3267 says they should be.
3268 This variable is populated from #+FILETAGS lines.")
3270 (defcustom org-use-fast-tag-selection 'auto
3271 "Non-nil means use fast tag selection scheme.
3272 This is a special interface to select and deselect tags with single keys.
3273 When nil, fast selection is never used.
3274 When the symbol `auto', fast selection is used if and only if selection
3275 characters for tags have been configured, either through the variable
3276 `org-tag-alist' or through a #+TAGS line in the buffer.
3277 When t, fast selection is always used and selection keys are assigned
3278 automatically if necessary."
3279 :group 'org-tags
3280 :type '(choice
3281 (const :tag "Always" t)
3282 (const :tag "Never" nil)
3283 (const :tag "When selection characters are configured" auto)))
3285 (defcustom org-fast-tag-selection-single-key nil
3286 "Non-nil means fast tag selection exits after first change.
3287 When nil, you have to press RET to exit it.
3288 During fast tag selection, you can toggle this flag with `C-c'.
3289 This variable can also have the value `expert'. In this case, the window
3290 displaying the tags menu is not even shown, until you press C-c again."
3291 :group 'org-tags
3292 :type '(choice
3293 (const :tag "No" nil)
3294 (const :tag "Yes" t)
3295 (const :tag "Expert" expert)))
3297 (defvar org-fast-tag-selection-include-todo nil
3298 "Non-nil means fast tags selection interface will also offer TODO states.
3299 This is an undocumented feature, you should not rely on it.")
3301 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3302 "The column to which tags should be indented in a headline.
3303 If this number is positive, it specifies the column. If it is negative,
3304 it means that the tags should be flushright to that column. For example,
3305 -80 works well for a normal 80 character screen.
3306 When 0, place tags directly after headline text, with only one space in
3307 between."
3308 :group 'org-tags
3309 :type 'integer)
3311 (defcustom org-auto-align-tags t
3312 "Non-nil keeps tags aligned when modifying headlines.
3313 Some operations (i.e. demoting) change the length of a headline and
3314 therefore shift the tags around. With this option turned on, after
3315 each such operation the tags are again aligned to `org-tags-column'."
3316 :group 'org-tags
3317 :type 'boolean)
3319 (defcustom org-use-tag-inheritance t
3320 "Non-nil means tags in levels apply also for sublevels.
3321 When nil, only the tags directly given in a specific line apply there.
3322 This may also be a list of tags that should be inherited, or a regexp that
3323 matches tags that should be inherited. Additional control is possible
3324 with the variable `org-tags-exclude-from-inheritance' which gives an
3325 explicit list of tags to be excluded from inheritance, even if the value of
3326 `org-use-tag-inheritance' would select it for inheritance.
3328 If this option is t, a match early-on in a tree can lead to a large
3329 number of matches in the subtree when constructing the agenda or creating
3330 a sparse tree. If you only want to see the first match in a tree during
3331 a search, check out the variable `org-tags-match-list-sublevels'."
3332 :group 'org-tags
3333 :type '(choice
3334 (const :tag "Not" nil)
3335 (const :tag "Always" t)
3336 (repeat :tag "Specific tags" (string :tag "Tag"))
3337 (regexp :tag "Tags matched by regexp")))
3339 (defcustom org-tags-exclude-from-inheritance nil
3340 "List of tags that should never be inherited.
3341 This is a way to exclude a few tags from inheritance. For way to do
3342 the opposite, to actively allow inheritance for selected tags,
3343 see the variable `org-use-tag-inheritance'."
3344 :group 'org-tags
3345 :type '(repeat (string :tag "Tag")))
3347 (defun org-tag-inherit-p (tag)
3348 "Check if TAG is one that should be inherited."
3349 (cond
3350 ((member tag org-tags-exclude-from-inheritance) nil)
3351 ((eq org-use-tag-inheritance t) t)
3352 ((not org-use-tag-inheritance) nil)
3353 ((stringp org-use-tag-inheritance)
3354 (string-match org-use-tag-inheritance tag))
3355 ((listp org-use-tag-inheritance)
3356 (member tag org-use-tag-inheritance))
3357 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3359 (defcustom org-tags-match-list-sublevels t
3360 "Non-nil means list also sublevels of headlines matching a search.
3361 This variable applies to tags/property searches, and also to stuck
3362 projects because this search is based on a tags match as well.
3364 When set to the symbol `indented', sublevels are indented with
3365 leading dots.
3367 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3368 the sublevels of a headline matching a tag search often also match
3369 the same search. Listing all of them can create very long lists.
3370 Setting this variable to nil causes subtrees of a match to be skipped.
3372 This variable is semi-obsolete and probably should always be true. It
3373 is better to limit inheritance to certain tags using the variables
3374 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3375 :group 'org-tags
3376 :type '(choice
3377 (const :tag "No, don't list them" nil)
3378 (const :tag "Yes, do list them" t)
3379 (const :tag "List them, indented with leading dots" indented)))
3381 (defcustom org-tags-sort-function nil
3382 "When set, tags are sorted using this function as a comparator."
3383 :group 'org-tags
3384 :type '(choice
3385 (const :tag "No sorting" nil)
3386 (const :tag "Alphabetical" string<)
3387 (const :tag "Reverse alphabetical" string>)
3388 (function :tag "Custom function" nil)))
3390 (defvar org-tags-history nil
3391 "History of minibuffer reads for tags.")
3392 (defvar org-last-tags-completion-table nil
3393 "The last used completion table for tags.")
3394 (defvar org-after-tags-change-hook nil
3395 "Hook that is run after the tags in a line have changed.")
3397 (defgroup org-properties nil
3398 "Options concerning properties in Org-mode."
3399 :tag "Org Properties"
3400 :group 'org)
3402 (defcustom org-property-format "%-10s %s"
3403 "How property key/value pairs should be formatted by `indent-line'.
3404 When `indent-line' hits a property definition, it will format the line
3405 according to this format, mainly to make sure that the values are
3406 lined-up with respect to each other."
3407 :group 'org-properties
3408 :type 'string)
3410 (defcustom org-properties-postprocess-alist nil
3411 "Alist of properties and functions to adjust inserted values.
3412 Elements of this alist must be of the form
3414 ([string] [function])
3416 where [string] must be a property name and [function] must be a
3417 lambda expression: this lambda expression must take one argument,
3418 the value to adjust, and return the new value as a string.
3420 For example, this element will allow the property \"Remaining\"
3421 to be updated wrt the relation between the \"Effort\" property
3422 and the clock summary:
3424 ((\"Remaining\" (lambda(value)
3425 (let ((clocksum (org-clock-sum-current-item))
3426 (effort (org-duration-string-to-minutes
3427 (org-entry-get (point) \"Effort\"))))
3428 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3429 :group 'org-properties
3430 :version "24.1"
3431 :type '(alist :key-type (string :tag "Property")
3432 :value-type (function :tag "Function")))
3434 (defcustom org-use-property-inheritance nil
3435 "Non-nil means properties apply also for sublevels.
3437 This setting is chiefly used during property searches. Turning it on can
3438 cause significant overhead when doing a search, which is why it is not
3439 on by default.
3441 When nil, only the properties directly given in the current entry count.
3442 When t, every property is inherited. The value may also be a list of
3443 properties that should have inheritance, or a regular expression matching
3444 properties that should be inherited.
3446 However, note that some special properties use inheritance under special
3447 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3448 and the properties ending in \"_ALL\" when they are used as descriptor
3449 for valid values of a property.
3451 Note for programmers:
3452 When querying an entry with `org-entry-get', you can control if inheritance
3453 should be used. By default, `org-entry-get' looks only at the local
3454 properties. You can request inheritance by setting the inherit argument
3455 to t (to force inheritance) or to `selective' (to respect the setting
3456 in this variable)."
3457 :group 'org-properties
3458 :type '(choice
3459 (const :tag "Not" nil)
3460 (const :tag "Always" t)
3461 (repeat :tag "Specific properties" (string :tag "Property"))
3462 (regexp :tag "Properties matched by regexp")))
3464 (defun org-property-inherit-p (property)
3465 "Check if PROPERTY is one that should be inherited."
3466 (cond
3467 ((eq org-use-property-inheritance t) t)
3468 ((not org-use-property-inheritance) nil)
3469 ((stringp org-use-property-inheritance)
3470 (string-match org-use-property-inheritance property))
3471 ((listp org-use-property-inheritance)
3472 (member property org-use-property-inheritance))
3473 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3475 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3476 "The default column format, if no other format has been defined.
3477 This variable can be set on the per-file basis by inserting a line
3479 #+COLUMNS: %25ITEM ....."
3480 :group 'org-properties
3481 :type 'string)
3483 (defcustom org-columns-ellipses ".."
3484 "The ellipses to be used when a field in column view is truncated.
3485 When this is the empty string, as many characters as possible are shown,
3486 but then there will be no visual indication that the field has been truncated.
3487 When this is a string of length N, the last N characters of a truncated
3488 field are replaced by this string. If the column is narrower than the
3489 ellipses string, only part of the ellipses string will be shown."
3490 :group 'org-properties
3491 :type 'string)
3493 (defcustom org-columns-modify-value-for-display-function nil
3494 "Function that modifies values for display in column view.
3495 For example, it can be used to cut out a certain part from a time stamp.
3496 The function must take 2 arguments:
3498 column-title The title of the column (*not* the property name)
3499 value The value that should be modified.
3501 The function should return the value that should be displayed,
3502 or nil if the normal value should be used."
3503 :group 'org-properties
3504 :type '(choice (const nil) (function)))
3506 (defcustom org-effort-property "Effort"
3507 "The property that is being used to keep track of effort estimates.
3508 Effort estimates given in this property need to have the format H:MM."
3509 :group 'org-properties
3510 :group 'org-progress
3511 :type '(string :tag "Property"))
3513 (defconst org-global-properties-fixed
3514 '(("VISIBILITY_ALL" . "folded children content all")
3515 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3516 "List of property/value pairs that can be inherited by any entry.
3518 These are fixed values, for the preset properties. The user variable
3519 that can be used to add to this list is `org-global-properties'.
3521 The entries in this list are cons cells where the car is a property
3522 name and cdr is a string with the value. If the value represents
3523 multiple items like an \"_ALL\" property, separate the items by
3524 spaces.")
3526 (defcustom org-global-properties nil
3527 "List of property/value pairs that can be inherited by any entry.
3529 This list will be combined with the constant `org-global-properties-fixed'.
3531 The entries in this list are cons cells where the car is a property
3532 name and cdr is a string with the value.
3534 You can set buffer-local values for the same purpose in the variable
3535 `org-file-properties' this by adding lines like
3537 #+PROPERTY: NAME VALUE"
3538 :group 'org-properties
3539 :type '(repeat
3540 (cons (string :tag "Property")
3541 (string :tag "Value"))))
3543 (defvar org-file-properties nil
3544 "List of property/value pairs that can be inherited by any entry.
3545 Valid for the current buffer.
3546 This variable is populated from #+PROPERTY lines.")
3547 (make-variable-buffer-local 'org-file-properties)
3549 (defgroup org-agenda nil
3550 "Options concerning agenda views in Org-mode."
3551 :tag "Org Agenda"
3552 :group 'org)
3554 (defvar org-category nil
3555 "Variable used by org files to set a category for agenda display.
3556 Such files should use a file variable to set it, for example
3558 # -*- mode: org; org-category: \"ELisp\"
3560 or contain a special line
3562 #+CATEGORY: ELisp
3564 If the file does not specify a category, then file's base name
3565 is used instead.")
3566 (make-variable-buffer-local 'org-category)
3567 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3569 (defcustom org-agenda-files nil
3570 "The files to be used for agenda display.
3571 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3572 \\[org-remove-file]. You can also use customize to edit the list.
3574 If an entry is a directory, all files in that directory that are matched by
3575 `org-agenda-file-regexp' will be part of the file list.
3577 If the value of the variable is not a list but a single file name, then
3578 the list of agenda files is actually stored and maintained in that file, one
3579 agenda file per line. In this file paths can be given relative to
3580 `org-directory'. Tilde expansion and environment variable substitution
3581 are also made."
3582 :group 'org-agenda
3583 :type '(choice
3584 (repeat :tag "List of files and directories" file)
3585 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3587 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3588 "Regular expression to match files for `org-agenda-files'.
3589 If any element in the list in that variable contains a directory instead
3590 of a normal file, all files in that directory that are matched by this
3591 regular expression will be included."
3592 :group 'org-agenda
3593 :type 'regexp)
3595 (defcustom org-agenda-text-search-extra-files nil
3596 "List of extra files to be searched by text search commands.
3597 These files will be searched in addition to the agenda files by the
3598 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3599 Note that these files will only be searched for text search commands,
3600 not for the other agenda views like todo lists, tag searches or the weekly
3601 agenda. This variable is intended to list notes and possibly archive files
3602 that should also be searched by these two commands.
3603 In fact, if the first element in the list is the symbol `agenda-archives',
3604 then all archive files of all agenda files will be added to the search
3605 scope."
3606 :group 'org-agenda
3607 :type '(set :greedy t
3608 (const :tag "Agenda Archives" agenda-archives)
3609 (repeat :inline t (file))))
3611 (org-defvaralias 'org-agenda-multi-occur-extra-files
3612 'org-agenda-text-search-extra-files)
3614 (defcustom org-agenda-skip-unavailable-files nil
3615 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3616 A nil value means to remove them, after a query, from the list."
3617 :group 'org-agenda
3618 :type 'boolean)
3620 (defcustom org-calendar-to-agenda-key [?c]
3621 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3622 The command `org-calendar-goto-agenda' will be bound to this key. The
3623 default is the character `c' because then `c' can be used to switch back and
3624 forth between agenda and calendar."
3625 :group 'org-agenda
3626 :type 'sexp)
3628 (defcustom org-calendar-insert-diary-entry-key [?i]
3629 "The key to be installed in `calendar-mode-map' for adding diary entries.
3630 This option is irrelevant until `org-agenda-diary-file' has been configured
3631 to point to an Org-mode file. When that is the case, the command
3632 `org-agenda-diary-entry' will be bound to the key given here, by default
3633 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3634 if you want to continue doing this, you need to change this to a different
3635 key."
3636 :group 'org-agenda
3637 :type 'sexp)
3639 (defcustom org-agenda-diary-file 'diary-file
3640 "File to which to add new entries with the `i' key in agenda and calendar.
3641 When this is the symbol `diary-file', the functionality in the Emacs
3642 calendar will be used to add entries to the `diary-file'. But when this
3643 points to a file, `org-agenda-diary-entry' will be used instead."
3644 :group 'org-agenda
3645 :type '(choice
3646 (const :tag "The standard Emacs diary file" diary-file)
3647 (file :tag "Special Org file diary entries")))
3649 (eval-after-load "calendar"
3650 '(progn
3651 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3652 'org-calendar-goto-agenda)
3653 (add-hook 'calendar-mode-hook
3654 (lambda ()
3655 (unless (eq org-agenda-diary-file 'diary-file)
3656 (define-key calendar-mode-map
3657 org-calendar-insert-diary-entry-key
3658 'org-agenda-diary-entry))))))
3660 (defgroup org-latex nil
3661 "Options for embedding LaTeX code into Org-mode."
3662 :tag "Org LaTeX"
3663 :group 'org)
3665 (defcustom org-format-latex-options
3666 '(:foreground default :background default :scale 1.0
3667 :html-foreground "Black" :html-background "Transparent"
3668 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3669 "Options for creating images from LaTeX fragments.
3670 This is a property list with the following properties:
3671 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3672 `default' means use the foreground of the default face.
3673 `auto' means use the foreground from the text face.
3674 :background the background color, or \"Transparent\".
3675 `default' means use the background of the default face.
3676 `auto' means use the background from the text face.
3677 :scale a scaling factor for the size of the images, to get more pixels
3678 :html-foreground, :html-background, :html-scale
3679 the same numbers for HTML export.
3680 :matchers a list indicating which matchers should be used to
3681 find LaTeX fragments. Valid members of this list are:
3682 \"begin\" find environments
3683 \"$1\" find single characters surrounded by $.$
3684 \"$\" find math expressions surrounded by $...$
3685 \"$$\" find math expressions surrounded by $$....$$
3686 \"\\(\" find math expressions surrounded by \\(...\\)
3687 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3688 :group 'org-latex
3689 :type 'plist)
3691 (defcustom org-format-latex-signal-error t
3692 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3693 When nil, just push out a message."
3694 :group 'org-latex
3695 :version "24.1"
3696 :type 'boolean)
3698 (defcustom org-latex-to-mathml-jar-file nil
3699 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3700 Use this to specify additional executable file say a jar file.
3702 When using MathToWeb as the converter, specify the full-path to
3703 your mathtoweb.jar file."
3704 :group 'org-latex
3705 :version "24.1"
3706 :type '(choice
3707 (const :tag "None" nil)
3708 (file :tag "JAR file" :must-match t)))
3710 (defcustom org-latex-to-mathml-convert-command nil
3711 "Command to convert LaTeX fragments to MathML.
3712 Replace format-specifiers in the command as noted below and use
3713 `shell-command' to convert LaTeX to MathML.
3714 %j: Executable file in fully expanded form as specified by
3715 `org-latex-to-mathml-jar-file'.
3716 %I: Input LaTeX file in fully expanded form
3717 %o: Output MathML file
3718 This command is used by `org-create-math-formula'.
3720 When using MathToWeb as the converter, set this to
3721 \"java -jar %j -unicode -force -df %o %I\"."
3722 :group 'org-latex
3723 :version "24.1"
3724 :type '(choice
3725 (const :tag "None" nil)
3726 (string :tag "\nShell command")))
3728 (defcustom org-latex-create-formula-image-program 'dvipng
3729 "Program to convert LaTeX fragments with.
3731 dvipng Process the LaTeX fragments to dvi file, then convert
3732 dvi files to png files using dvipng.
3733 This will also include processing of non-math environments.
3734 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3735 to convert pdf files to png files"
3736 :group 'org-latex
3737 :version "24.1"
3738 :type '(choice
3739 (const :tag "dvipng" dvipng)
3740 (const :tag "imagemagick" imagemagick)))
3742 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3743 "Path to store latex preview images.
3744 A relative path here creates many directories relative to the
3745 processed org files paths. An absolute path puts all preview
3746 images at the same place."
3747 :group 'org-latex
3748 :version "24.3"
3749 :type 'string)
3751 (defun org-format-latex-mathml-available-p ()
3752 "Return t if `org-latex-to-mathml-convert-command' is usable."
3753 (save-match-data
3754 (when (and (boundp 'org-latex-to-mathml-convert-command)
3755 org-latex-to-mathml-convert-command)
3756 (let ((executable (car (split-string
3757 org-latex-to-mathml-convert-command))))
3758 (when (executable-find executable)
3759 (if (string-match
3760 "%j" org-latex-to-mathml-convert-command)
3761 (file-readable-p org-latex-to-mathml-jar-file)
3762 t))))))
3764 (defcustom org-format-latex-header "\\documentclass{article}
3765 \\usepackage[usenames]{color}
3766 \\usepackage{amsmath}
3767 \\usepackage[mathscr]{eucal}
3768 \\pagestyle{empty} % do not remove
3769 \[PACKAGES]
3770 \[DEFAULT-PACKAGES]
3771 % The settings below are copied from fullpage.sty
3772 \\setlength{\\textwidth}{\\paperwidth}
3773 \\addtolength{\\textwidth}{-3cm}
3774 \\setlength{\\oddsidemargin}{1.5cm}
3775 \\addtolength{\\oddsidemargin}{-2.54cm}
3776 \\setlength{\\evensidemargin}{\\oddsidemargin}
3777 \\setlength{\\textheight}{\\paperheight}
3778 \\addtolength{\\textheight}{-\\headheight}
3779 \\addtolength{\\textheight}{-\\headsep}
3780 \\addtolength{\\textheight}{-\\footskip}
3781 \\addtolength{\\textheight}{-3cm}
3782 \\setlength{\\topmargin}{1.5cm}
3783 \\addtolength{\\topmargin}{-2.54cm}"
3784 "The document header used for processing LaTeX fragments.
3785 It is imperative that this header make sure that no page number
3786 appears on the page. The package defined in the variables
3787 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3788 will either replace the placeholder \"[PACKAGES]\" in this
3789 header, or they will be appended."
3790 :group 'org-latex
3791 :type 'string)
3793 (defun org-set-packages-alist (var val)
3794 "Set the packages alist and make sure it has 3 elements per entry."
3795 (set var (mapcar (lambda (x)
3796 (if (and (consp x) (= (length x) 2))
3797 (list (car x) (nth 1 x) t)
3799 val)))
3801 (defun org-get-packages-alist (var)
3802 "Get the packages alist and make sure it has 3 elements per entry."
3803 (mapcar (lambda (x)
3804 (if (and (consp x) (= (length x) 2))
3805 (list (car x) (nth 1 x) t)
3807 (default-value var)))
3809 (defcustom org-latex-default-packages-alist
3810 '(("AUTO" "inputenc" t)
3811 ("T1" "fontenc" t)
3812 ("" "fixltx2e" nil)
3813 ("" "graphicx" t)
3814 ("" "longtable" nil)
3815 ("" "float" nil)
3816 ("" "wrapfig" nil)
3817 ("" "soul" t)
3818 ("" "textcomp" t)
3819 ("" "marvosym" t)
3820 ("" "wasysym" t)
3821 ("" "latexsym" t)
3822 ("" "amssymb" t)
3823 ("" "amstext" nil)
3824 ("" "hyperref" nil)
3825 "\\tolerance=1000")
3826 "Alist of default packages to be inserted in the header.
3828 Change this only if one of the packages here causes an
3829 incompatibility with another package you are using.
3831 The packages in this list are needed by one part or another of
3832 Org mode to function properly:
3834 - inputenc, fontenc: for basic font and character selection
3835 - amstext: for subscript and superscript
3836 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3837 symbols used for interpreting the entities in `org-entities'.
3838 You can skip some of these packages if you don't use any of the
3839 symbols in it.
3840 - graphicx: for including images
3841 - float, wrapfig: for figure placement
3842 - longtable: for long tables
3843 - hyperref: for cross references
3845 Therefore you should not modify this variable unless you know
3846 what you are doing. The one reason to change it anyway is that
3847 you might be loading some other package that conflicts with one
3848 of the default packages. Each cell is of the format
3849 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3850 the package also needs to be included when compiling LaTeX
3851 snippets into images for inclusion into non-LaTeX output."
3852 :group 'org-latex
3853 :group 'org-export-latex
3854 :set 'org-set-packages-alist
3855 :get 'org-get-packages-alist
3856 :version "24.1"
3857 :type '(repeat
3858 (choice
3859 (list :tag "options/package pair"
3860 (string :tag "options")
3861 (string :tag "package")
3862 (boolean :tag "Snippet"))
3863 (string :tag "A line of LaTeX"))))
3865 (defcustom org-latex-packages-alist nil
3866 "Alist of packages to be inserted in every LaTeX header.
3868 These will be inserted after `org-latex-default-packages-alist'.
3869 Each cell is of the format:
3871 \(\"options\" \"package\" snippet-flag)
3873 SNIPPET-FLAG, when t, indicates that this package is also needed
3874 when turning LaTeX snippets into images for inclusion into
3875 non-LaTeX output.
3877 Make sure that you only list packages here which:
3879 - you want in every file
3880 - do not conflict with the setup in `org-format-latex-header'.
3881 - do not conflict with the default packages in
3882 `org-latex-default-packages-alist'."
3883 :group 'org-latex
3884 :group 'org-export-latex
3885 :set 'org-set-packages-alist
3886 :get 'org-get-packages-alist
3887 :type '(repeat
3888 (choice
3889 (list :tag "options/package pair"
3890 (string :tag "options")
3891 (string :tag "package")
3892 (boolean :tag "Snippet"))
3893 (string :tag "A line of LaTeX"))))
3895 (defgroup org-appearance nil
3896 "Settings for Org-mode appearance."
3897 :tag "Org Appearance"
3898 :group 'org)
3900 (defcustom org-level-color-stars-only nil
3901 "Non-nil means fontify only the stars in each headline.
3902 When nil, the entire headline is fontified.
3903 Changing it requires restart of `font-lock-mode' to become effective
3904 also in regions already fontified."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-hide-leading-stars nil
3909 "Non-nil means hide the first N-1 stars in a headline.
3910 This works by using the face `org-hide' for these stars. This
3911 face is white for a light background, and black for a dark
3912 background. You may have to customize the face `org-hide' to
3913 make this work.
3914 Changing it requires restart of `font-lock-mode' to become effective
3915 also in regions already fontified.
3916 You may also set this on a per-file basis by adding one of the following
3917 lines to the buffer:
3919 #+STARTUP: hidestars
3920 #+STARTUP: showstars"
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-hidden-keywords nil
3925 "List of symbols corresponding to keywords to be hidden the org buffer.
3926 For example, a value '(title) for this list will make the document's title
3927 appear in the buffer without the initial #+TITLE: keyword."
3928 :group 'org-appearance
3929 :version "24.1"
3930 :type '(set (const :tag "#+AUTHOR" author)
3931 (const :tag "#+DATE" date)
3932 (const :tag "#+EMAIL" email)
3933 (const :tag "#+TITLE" title)))
3935 (defcustom org-custom-properties nil
3936 "List of properties (as strings) with a special meaning.
3937 The default use of these custom properties is to let the user
3938 hide them with `org-toggle-custom-properties-visibility'."
3939 :group 'org-properties
3940 :group 'org-appearance
3941 :version "24.3"
3942 :type '(repeat (string :tag "Property Name")))
3944 (defcustom org-fontify-done-headline nil
3945 "Non-nil means change the face of a headline if it is marked DONE.
3946 Normally, only the TODO/DONE keyword indicates the state of a headline.
3947 When this is non-nil, the headline after the keyword is set to the
3948 `org-headline-done' as an additional indication."
3949 :group 'org-appearance
3950 :type 'boolean)
3952 (defcustom org-fontify-emphasized-text t
3953 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3954 Changing this variable requires a restart of Emacs to take effect."
3955 :group 'org-appearance
3956 :type 'boolean)
3958 (defcustom org-fontify-whole-heading-line nil
3959 "Non-nil means fontify the whole line for headings.
3960 This is useful when setting a background color for the
3961 org-level-* faces."
3962 :group 'org-appearance
3963 :type 'boolean)
3965 (defcustom org-highlight-latex-and-related nil
3966 "Non-nil means highlight LaTeX related syntax in the buffer.
3967 When non nil, the value should be a list containing any of the
3968 following symbols:
3969 `latex' Highlight LaTeX snippets and environments.
3970 `script' Highlight subscript and superscript.
3971 `entities' Highlight entities."
3972 :group 'org-appearance
3973 :version "24.4"
3974 :package-version '(Org . "8.0")
3975 :type '(choice
3976 (const :tag "No highlighting" nil)
3977 (set :greedy t :tag "Highlight"
3978 (const :tag "LaTeX snippets and environments" latex)
3979 (const :tag "Subscript and superscript" script)
3980 (const :tag "Entities" entities))))
3982 (defcustom org-hide-emphasis-markers nil
3983 "Non-nil mean font-lock should hide the emphasis marker characters."
3984 :group 'org-appearance
3985 :type 'boolean)
3987 (defcustom org-pretty-entities nil
3988 "Non-nil means show entities as UTF8 characters.
3989 When nil, the \\name form remains in the buffer."
3990 :group 'org-appearance
3991 :version "24.1"
3992 :type 'boolean)
3994 (defcustom org-pretty-entities-include-sub-superscripts t
3995 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3996 :group 'org-appearance
3997 :version "24.1"
3998 :type 'boolean)
4000 (defvar org-emph-re nil
4001 "Regular expression for matching emphasis.
4002 After a match, the match groups contain these elements:
4003 0 The match of the full regular expression, including the characters
4004 before and after the proper match
4005 1 The character before the proper match, or empty at beginning of line
4006 2 The proper match, including the leading and trailing markers
4007 3 The leading marker like * or /, indicating the type of highlighting
4008 4 The text between the emphasis markers, not including the markers
4009 5 The character after the match, empty at the end of a line")
4010 (defvar org-verbatim-re nil
4011 "Regular expression for matching verbatim text.")
4012 (defvar org-emphasis-regexp-components) ; defined just below
4013 (defvar org-emphasis-alist) ; defined just below
4014 (defun org-set-emph-re (var val)
4015 "Set variable and compute the emphasis regular expression."
4016 (set var val)
4017 (when (and (boundp 'org-emphasis-alist)
4018 (boundp 'org-emphasis-regexp-components)
4019 org-emphasis-alist org-emphasis-regexp-components)
4020 (let* ((e org-emphasis-regexp-components)
4021 (pre (car e))
4022 (post (nth 1 e))
4023 (border (nth 2 e))
4024 (body (nth 3 e))
4025 (nl (nth 4 e))
4026 (body1 (concat body "*?"))
4027 (markers (mapconcat 'car org-emphasis-alist ""))
4028 (vmarkers (mapconcat
4029 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4030 org-emphasis-alist "")))
4031 ;; make sure special characters appear at the right position in the class
4032 (if (string-match "\\^" markers)
4033 (setq markers (concat (replace-match "" t t markers) "^")))
4034 (if (string-match "-" markers)
4035 (setq markers (concat (replace-match "" t t markers) "-")))
4036 (if (string-match "\\^" vmarkers)
4037 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4038 (if (string-match "-" vmarkers)
4039 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4040 (if (> nl 0)
4041 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4042 (int-to-string nl) "\\}")))
4043 ;; Make the regexp
4044 (setq org-emph-re
4045 (concat "\\([" pre "]\\|^\\)"
4046 "\\("
4047 "\\([" markers "]\\)"
4048 "\\("
4049 "[^" border "]\\|"
4050 "[^" border "]"
4051 body1
4052 "[^" border "]"
4053 "\\)"
4054 "\\3\\)"
4055 "\\([" post "]\\|$\\)"))
4056 (setq org-verbatim-re
4057 (concat "\\([" pre "]\\|^\\)"
4058 "\\("
4059 "\\([" vmarkers "]\\)"
4060 "\\("
4061 "[^" border "]\\|"
4062 "[^" border "]"
4063 body1
4064 "[^" border "]"
4065 "\\)"
4066 "\\3\\)"
4067 "\\([" post "]\\|$\\)")))))
4069 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4070 ;; set this option proved cumbersome. See this message/thread:
4071 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4072 (defvar org-emphasis-regexp-components
4073 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4074 "Components used to build the regular expression for emphasis.
4075 This is a list with five entries. Terminology: In an emphasis string
4076 like \" *strong word* \", we call the initial space PREMATCH, the final
4077 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4078 and \"trong wor\" is the body. The different components in this variable
4079 specify what is allowed/forbidden in each part:
4081 pre Chars allowed as prematch. Beginning of line will be allowed too.
4082 post Chars allowed as postmatch. End of line will be allowed too.
4083 border The chars *forbidden* as border characters.
4084 body-regexp A regexp like \".\" to match a body character. Don't use
4085 non-shy groups here, and don't allow newline here.
4086 newline The maximum number of newlines allowed in an emphasis exp.
4088 You need to reload Org or to restart Emacs after customizing this.")
4090 (defcustom org-emphasis-alist
4091 `(("*" bold)
4092 ("/" italic)
4093 ("_" underline)
4094 ("=" org-code verbatim)
4095 ("~" org-verbatim verbatim)
4096 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4097 "Alist of characters and faces to emphasize text.
4098 Text starting and ending with a special character will be emphasized,
4099 for example *bold*, _underlined_ and /italic/. This variable sets the
4100 marker characters and the face to be used by font-lock for highlighting
4101 in Org-mode Emacs buffers.
4103 You need to reload Org or to restart Emacs after customizing this."
4104 :group 'org-appearance
4105 :set 'org-set-emph-re
4106 :version "24.4"
4107 :package-version '(Org . "8.0")
4108 :type '(repeat
4109 (list
4110 (string :tag "Marker character")
4111 (choice
4112 (face :tag "Font-lock-face")
4113 (plist :tag "Face property list"))
4114 (option (const verbatim)))))
4116 (defvar org-protecting-blocks
4117 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4118 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4119 This is needed for font-lock setup.")
4121 ;;; Miscellaneous options
4123 (defgroup org-completion nil
4124 "Completion in Org-mode."
4125 :tag "Org Completion"
4126 :group 'org)
4128 (defcustom org-completion-use-ido nil
4129 "Non-nil means use ido completion wherever possible.
4130 Note that `ido-mode' must be active for this variable to be relevant.
4131 If you decide to turn this variable on, you might well want to turn off
4132 `org-outline-path-complete-in-steps'.
4133 See also `org-completion-use-iswitchb'."
4134 :group 'org-completion
4135 :type 'boolean)
4137 (defcustom org-completion-use-iswitchb nil
4138 "Non-nil means use iswitchb completion wherever possible.
4139 Note that `iswitchb-mode' must be active for this variable to be relevant.
4140 If you decide to turn this variable on, you might well want to turn off
4141 `org-outline-path-complete-in-steps'.
4142 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4143 :group 'org-completion
4144 :type 'boolean)
4146 (defcustom org-completion-fallback-command 'hippie-expand
4147 "The expansion command called by \\[pcomplete] in normal context.
4148 Normal means, no org-mode-specific context."
4149 :group 'org-completion
4150 :type 'function)
4152 ;;; Functions and variables from their packages
4153 ;; Declared here to avoid compiler warnings
4155 ;; XEmacs only
4156 (defvar outline-mode-menu-heading)
4157 (defvar outline-mode-menu-show)
4158 (defvar outline-mode-menu-hide)
4159 (defvar zmacs-regions) ; XEmacs regions
4161 ;; Emacs only
4162 (defvar mark-active)
4164 ;; Various packages
4165 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4166 (declare-function calendar-forward-day "cal-move" (arg))
4167 (declare-function calendar-goto-date "cal-move" (date))
4168 (declare-function calendar-goto-today "cal-move" ())
4169 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4170 (defvar calc-embedded-close-formula)
4171 (defvar calc-embedded-open-formula)
4172 (declare-function cdlatex-tab "ext:cdlatex" ())
4173 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4174 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4175 (defvar font-lock-unfontify-region-function)
4176 (declare-function iswitchb-read-buffer "iswitchb"
4177 (prompt &optional default require-match start matches-set))
4178 (defvar iswitchb-temp-buflist)
4179 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4180 (defvar org-agenda-tags-todo-honor-ignore-options)
4181 (declare-function org-agenda-skip "org-agenda" ())
4182 (declare-function
4183 org-agenda-format-item "org-agenda"
4184 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4185 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4186 (declare-function org-agenda-change-all-lines "org-agenda"
4187 (newhead hdmarker &optional fixface just-this))
4188 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4189 (declare-function org-agenda-maybe-redo "org-agenda" ())
4190 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4191 (beg end))
4192 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4193 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4194 "org-agenda" (&optional end))
4195 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4196 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4197 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4198 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4199 (declare-function org-indent-mode "org-indent" (&optional arg))
4200 (declare-function parse-time-string "parse-time" (string))
4201 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4202 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4203 (defvar remember-data-file)
4204 (defvar texmathp-why)
4205 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4206 (declare-function table--at-cell-p "table" (position &optional object at-column))
4208 (defvar org-latex-regexps)
4210 ;;; Autoload and prepare some org modules
4212 ;; Some table stuff that needs to be defined here, because it is used
4213 ;; by the functions setting up org-mode or checking for table context.
4215 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4216 "Detect an org-type or table-type table.")
4217 (defconst org-table-line-regexp "^[ \t]*|"
4218 "Detect an org-type table line.")
4219 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4220 "Detect an org-type table line.")
4221 (defconst org-table-hline-regexp "^[ \t]*|-"
4222 "Detect an org-type table hline.")
4223 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4224 "Detect a table-type table hline.")
4225 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4226 "Detect the first line outside a table when searching from within it.
4227 This works for both table types.")
4229 ;; Autoload the functions in org-table.el that are needed by functions here.
4231 (eval-and-compile
4232 (org-autoload "org-table"
4233 '(org-table-begin org-table-blank-field org-table-end)))
4235 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4236 "Detect a #+TBLFM line.")
4238 ;;;###autoload
4239 (defun turn-on-orgtbl ()
4240 "Unconditionally turn on `orgtbl-mode'."
4241 (require 'org-table)
4242 (orgtbl-mode 1))
4244 (defun org-at-table-p (&optional table-type)
4245 "Return t if the cursor is inside an org-type table.
4246 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4247 (if org-enable-table-editor
4248 (save-excursion
4249 (beginning-of-line 1)
4250 (looking-at (if table-type org-table-any-line-regexp
4251 org-table-line-regexp)))
4252 nil))
4253 (defsubst org-table-p () (org-at-table-p))
4255 (defun org-at-table.el-p ()
4256 "Return t if and only if we are at a table.el table."
4257 (and (org-at-table-p 'any)
4258 (save-excursion
4259 (goto-char (org-table-begin 'any))
4260 (looking-at org-table1-hline-regexp))))
4262 (defun org-table-recognize-table.el ()
4263 "If there is a table.el table nearby, recognize it and move into it."
4264 (if org-table-tab-recognizes-table.el
4265 (if (org-at-table.el-p)
4266 (progn
4267 (beginning-of-line 1)
4268 (if (looking-at org-table-dataline-regexp)
4270 (if (looking-at org-table1-hline-regexp)
4271 (progn
4272 (beginning-of-line 2)
4273 (if (looking-at org-table-any-border-regexp)
4274 (beginning-of-line -1)))))
4275 (if (re-search-forward "|" (org-table-end t) t)
4276 (progn
4277 (require 'table)
4278 (if (table--at-cell-p (point))
4280 (message "recognizing table.el table...")
4281 (table-recognize-table)
4282 (message "recognizing table.el table...done")))
4283 (error "This should not happen"))
4285 nil)
4286 nil))
4288 (defun org-at-table-hline-p ()
4289 "Return t if the cursor is inside a hline in a table."
4290 (if org-enable-table-editor
4291 (save-excursion
4292 (beginning-of-line 1)
4293 (looking-at org-table-hline-regexp))
4294 nil))
4296 (defun org-table-map-tables (function &optional quietly)
4297 "Apply FUNCTION to the start of all tables in the buffer."
4298 (save-excursion
4299 (save-restriction
4300 (widen)
4301 (goto-char (point-min))
4302 (while (re-search-forward org-table-any-line-regexp nil t)
4303 (unless quietly
4304 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4305 (beginning-of-line 1)
4306 (when (and (looking-at org-table-line-regexp)
4307 ;; Exclude tables in src/example/verbatim/clocktable blocks
4308 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4309 (save-excursion (funcall function))
4310 (or (looking-at org-table-line-regexp)
4311 (forward-char 1)))
4312 (re-search-forward org-table-any-border-regexp nil 1))))
4313 (unless quietly (message "Mapping tables: done")))
4315 ;; Declare and autoload functions from ox.el and al.
4317 (declare-function org-export-get-environment "ox"
4318 (&optional backend subtreep ext-plist))
4319 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4321 ;; Declare and autoload functions from org-agenda.el
4323 (eval-and-compile
4324 (org-autoload "org-agenda"
4325 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4327 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4328 (declare-function org-clock-update-mode-line "org-clock" ())
4329 (declare-function org-resolve-clocks "org-clock"
4330 (&optional also-non-dangling-p prompt last-valid))
4332 (defun org-at-TBLFM-p (&optional pos)
4333 "Return t when point (or POS) is in #+TBLFM line."
4334 (save-excursion
4335 (let ((pos pos)))
4336 (goto-char (or pos (point)))
4337 (beginning-of-line 1)
4338 (looking-at org-TBLFM-regexp)))
4340 (defvar org-clock-start-time)
4341 (defvar org-clock-marker (make-marker)
4342 "Marker recording the last clock-in.")
4343 (defvar org-clock-hd-marker (make-marker)
4344 "Marker recording the last clock-in, but the headline position.")
4345 (defvar org-clock-heading ""
4346 "The heading of the current clock entry.")
4347 (defun org-clock-is-active ()
4348 "Return non-nil if clock is currently running.
4349 The return value is actually the clock marker."
4350 (marker-buffer org-clock-marker))
4352 (eval-and-compile
4353 (org-autoload "org-clock" '(org-clock-remove-overlays
4354 org-clock-update-time-maybe
4355 org-clocktable-shift)))
4357 (defun org-check-running-clock ()
4358 "Check if the current buffer contains the running clock.
4359 If yes, offer to stop it and to save the buffer with the changes."
4360 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4361 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4362 (buffer-name))))
4363 (org-clock-out)
4364 (when (y-or-n-p "Save changed buffer?")
4365 (save-buffer))))
4367 (defun org-clocktable-try-shift (dir n)
4368 "Check if this line starts a clock table, if yes, shift the time block."
4369 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4370 (org-clocktable-shift dir n)))
4372 ;;;###autoload
4373 (defun org-clock-persistence-insinuate ()
4374 "Set up hooks for clock persistence."
4375 (require 'org-clock)
4376 (add-hook 'org-mode-hook 'org-clock-load)
4377 (add-hook 'kill-emacs-hook 'org-clock-save))
4379 ;; Define the variable already here, to make sure we have it.
4380 (defvar org-indent-mode nil
4381 "Non-nil if Org-Indent mode is enabled.
4382 Use the command `org-indent-mode' to change this variable.")
4384 ;; Autoload archiving code
4385 ;; The stuff that is needed for cycling and tags has to be defined here.
4387 (defgroup org-archive nil
4388 "Options concerning archiving in Org-mode."
4389 :tag "Org Archive"
4390 :group 'org-structure)
4392 (defcustom org-archive-location "%s_archive::"
4393 "The location where subtrees should be archived.
4395 The value of this variable is a string, consisting of two parts,
4396 separated by a double-colon. The first part is a filename and
4397 the second part is a headline.
4399 When the filename is omitted, archiving happens in the same file.
4400 %s in the filename will be replaced by the current file
4401 name (without the directory part). Archiving to a different file
4402 is useful to keep archived entries from contributing to the
4403 Org-mode Agenda.
4405 The archived entries will be filed as subtrees of the specified
4406 headline. When the headline is omitted, the subtrees are simply
4407 filed away at the end of the file, as top-level entries. Also in
4408 the heading you can use %s to represent the file name, this can be
4409 useful when using the same archive for a number of different files.
4411 Here are a few examples:
4412 \"%s_archive::\"
4413 If the current file is Projects.org, archive in file
4414 Projects.org_archive, as top-level trees. This is the default.
4416 \"::* Archived Tasks\"
4417 Archive in the current file, under the top-level headline
4418 \"* Archived Tasks\".
4420 \"~/org/archive.org::\"
4421 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4423 \"~/org/archive.org::* From %s\"
4424 Archive in file ~/org/archive.org (absolute path), under headlines
4425 \"From FILENAME\" where file name is the current file name.
4427 \"~/org/datetree.org::datetree/* Finished Tasks\"
4428 The \"datetree/\" string is special, signifying to archive
4429 items to the datetree. Items are placed in either the CLOSED
4430 date of the item, or the current date if there is no CLOSED date.
4431 The heading will be a subentry to the current date. There doesn't
4432 need to be a heading, but there always needs to be a slash after
4433 datetree. For example, to store archived items directly in the
4434 datetree, use \"~/org/datetree.org::datetree/\".
4436 \"basement::** Finished Tasks\"
4437 Archive in file ./basement (relative path), as level 3 trees
4438 below the level 2 heading \"** Finished Tasks\".
4440 You may set this option on a per-file basis by adding to the buffer a
4441 line like
4443 #+ARCHIVE: basement::** Finished Tasks
4445 You may also define it locally for a subtree by setting an ARCHIVE property
4446 in the entry. If such a property is found in an entry, or anywhere up
4447 the hierarchy, it will be used."
4448 :group 'org-archive
4449 :type 'string)
4451 (defcustom org-archive-tag "ARCHIVE"
4452 "The tag that marks a subtree as archived.
4453 An archived subtree does not open during visibility cycling, and does
4454 not contribute to the agenda listings.
4455 After changing this, font-lock must be restarted in the relevant buffers to
4456 get the proper fontification."
4457 :group 'org-archive
4458 :group 'org-keywords
4459 :type 'string)
4461 (defcustom org-agenda-skip-archived-trees t
4462 "Non-nil means the agenda will skip any items located in archived trees.
4463 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4464 variable is no longer recommended, you should leave it at the value t.
4465 Instead, use the key `v' to cycle the archives-mode in the agenda."
4466 :group 'org-archive
4467 :group 'org-agenda-skip
4468 :type 'boolean)
4470 (defcustom org-columns-skip-archived-trees t
4471 "Non-nil means ignore archived trees when creating column view."
4472 :group 'org-archive
4473 :group 'org-properties
4474 :type 'boolean)
4476 (defcustom org-cycle-open-archived-trees nil
4477 "Non-nil means `org-cycle' will open archived trees.
4478 An archived tree is a tree marked with the tag ARCHIVE.
4479 When nil, archived trees will stay folded. You can still open them with
4480 normal outline commands like `show-all', but not with the cycling commands."
4481 :group 'org-archive
4482 :group 'org-cycle
4483 :type 'boolean)
4485 (defcustom org-sparse-tree-open-archived-trees nil
4486 "Non-nil means sparse tree construction shows matches in archived trees.
4487 When nil, matches in these trees are highlighted, but the trees are kept in
4488 collapsed state."
4489 :group 'org-archive
4490 :group 'org-sparse-trees
4491 :type 'boolean)
4493 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4494 "The default date type when building a sparse tree.
4495 When this is nil, a date is a scheduled or a deadline timestamp.
4496 Otherwise, these types are allowed:
4498 all: all timestamps
4499 active: only active timestamps (<...>)
4500 inactive: only inactive timestamps (<...)
4501 scheduled: only scheduled timestamps
4502 deadline: only deadline timestamps"
4503 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4504 (const :tag "All timestamps" all)
4505 (const :tag "Only active timestamps" active)
4506 (const :tag "Only inactive timestamps" inactive)
4507 (const :tag "Only scheduled timestamps" scheduled)
4508 (const :tag "Only deadline timestamps" deadline)
4509 (const :tag "Only closed timestamps" closed))
4510 :version "24.3"
4511 :group 'org-sparse-trees)
4513 (defun org-cycle-hide-archived-subtrees (state)
4514 "Re-hide all archived subtrees after a visibility state change."
4515 (when (and (not org-cycle-open-archived-trees)
4516 (not (memq state '(overview folded))))
4517 (save-excursion
4518 (let* ((globalp (memq state '(contents all)))
4519 (beg (if globalp (point-min) (point)))
4520 (end (if globalp (point-max) (org-end-of-subtree t))))
4521 (org-hide-archived-subtrees beg end)
4522 (goto-char beg)
4523 (if (looking-at (concat ".*:" org-archive-tag ":"))
4524 (message "%s" (substitute-command-keys
4525 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4527 (defun org-force-cycle-archived ()
4528 "Cycle subtree even if it is archived."
4529 (interactive)
4530 (setq this-command 'org-cycle)
4531 (let ((org-cycle-open-archived-trees t))
4532 (call-interactively 'org-cycle)))
4534 (defun org-hide-archived-subtrees (beg end)
4535 "Re-hide all archived subtrees after a visibility state change."
4536 (save-excursion
4537 (let* ((re (concat ":" org-archive-tag ":")))
4538 (goto-char beg)
4539 (while (re-search-forward re end t)
4540 (when (org-at-heading-p)
4541 (org-flag-subtree t)
4542 (org-end-of-subtree t))))))
4544 (declare-function outline-end-of-heading "outline" ())
4545 (declare-function outline-flag-region "outline" (from to flag))
4546 (defun org-flag-subtree (flag)
4547 (save-excursion
4548 (org-back-to-heading t)
4549 (outline-end-of-heading)
4550 (outline-flag-region (point)
4551 (progn (org-end-of-subtree t) (point))
4552 flag)))
4554 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4556 (eval-and-compile
4557 (org-autoload "org-archive"
4558 '(org-add-archive-files)))
4560 ;; Autoload Column View Code
4562 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4563 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4564 (declare-function org-columns-compute "org-colview" (property))
4566 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4567 '(org-columns-number-to-string
4568 org-columns-get-format-and-top-level
4569 org-columns-compute
4570 org-columns-remove-overlays))
4572 ;; Autoload ID code
4574 (declare-function org-id-store-link "org-id")
4575 (declare-function org-id-locations-load "org-id")
4576 (declare-function org-id-locations-save "org-id")
4577 (defvar org-id-track-globally)
4578 (org-autoload "org-id"
4579 '(org-id-new
4580 org-id-copy
4581 org-id-get-with-outline-path-completion
4582 org-id-get-with-outline-drilling))
4584 ;;; Variables for pre-computed regular expressions, all buffer local
4586 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4587 "Matches first line of a hidden block.")
4588 (make-variable-buffer-local 'org-drawer-regexp)
4589 (defvar org-todo-regexp nil
4590 "Matches any of the TODO state keywords.")
4591 (make-variable-buffer-local 'org-todo-regexp)
4592 (defvar org-not-done-regexp nil
4593 "Matches any of the TODO state keywords except the last one.")
4594 (make-variable-buffer-local 'org-not-done-regexp)
4595 (defvar org-not-done-heading-regexp nil
4596 "Matches a TODO headline that is not done.")
4597 (make-variable-buffer-local 'org-not-done-regexp)
4598 (defvar org-todo-line-regexp nil
4599 "Matches a headline and puts TODO state into group 2 if present.")
4600 (make-variable-buffer-local 'org-todo-line-regexp)
4601 (defvar org-complex-heading-regexp nil
4602 "Matches a headline and puts everything into groups:
4603 group 1: the stars
4604 group 2: The todo keyword, maybe
4605 group 3: Priority cookie
4606 group 4: True headline
4607 group 5: Tags")
4608 (make-variable-buffer-local 'org-complex-heading-regexp)
4609 (defvar org-complex-heading-regexp-format nil
4610 "Printf format to make regexp to match an exact headline.
4611 This regexp will match the headline of any node which has the
4612 exact headline text that is put into the format, but may have any
4613 TODO state, priority and tags.")
4614 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4615 (defvar org-todo-line-tags-regexp nil
4616 "Matches a headline and puts TODO state into group 2 if present.
4617 Also put tags into group 4 if tags are present.")
4618 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4619 (defvar org-ds-keyword-length 12
4620 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4621 (make-variable-buffer-local 'org-ds-keyword-length)
4622 (defvar org-deadline-regexp nil
4623 "Matches the DEADLINE keyword.")
4624 (make-variable-buffer-local 'org-deadline-regexp)
4625 (defvar org-deadline-time-regexp nil
4626 "Matches the DEADLINE keyword together with a time stamp.")
4627 (make-variable-buffer-local 'org-deadline-time-regexp)
4628 (defvar org-deadline-time-hour-regexp nil
4629 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4630 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4631 (defvar org-deadline-line-regexp nil
4632 "Matches the DEADLINE keyword and the rest of the line.")
4633 (make-variable-buffer-local 'org-deadline-line-regexp)
4634 (defvar org-scheduled-regexp nil
4635 "Matches the SCHEDULED keyword.")
4636 (make-variable-buffer-local 'org-scheduled-regexp)
4637 (defvar org-scheduled-time-regexp nil
4638 "Matches the SCHEDULED keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-scheduled-time-regexp)
4640 (defvar org-scheduled-time-hour-regexp nil
4641 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4642 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4643 (defvar org-closed-time-regexp nil
4644 "Matches the CLOSED keyword together with a time stamp.")
4645 (make-variable-buffer-local 'org-closed-time-regexp)
4647 (defvar org-keyword-time-regexp nil
4648 "Matches any of the 4 keywords, together with the time stamp.")
4649 (make-variable-buffer-local 'org-keyword-time-regexp)
4650 (defvar org-keyword-time-not-clock-regexp nil
4651 "Matches any of the 3 keywords, together with the time stamp.")
4652 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4653 (defvar org-maybe-keyword-time-regexp nil
4654 "Matches a timestamp, possibly preceded by a keyword.")
4655 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4656 (defvar org-all-time-keywords nil
4657 "List of time keywords.")
4658 (make-variable-buffer-local 'org-all-time-keywords)
4660 (defconst org-plain-time-of-day-regexp
4661 (concat
4662 "\\(\\<[012]?[0-9]"
4663 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4664 "\\(--?"
4665 "\\(\\<[012]?[0-9]"
4666 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4667 "\\)?")
4668 "Regular expression to match a plain time or time range.
4669 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4670 groups carry important information:
4671 0 the full match
4672 1 the first time, range or not
4673 8 the second time, if it is a range.")
4675 (defconst org-plain-time-extension-regexp
4676 (concat
4677 "\\(\\<[012]?[0-9]"
4678 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4679 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4680 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4681 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4682 groups carry important information:
4683 0 the full match
4684 7 hours of duration
4685 9 minutes of duration")
4687 (defconst org-stamp-time-of-day-regexp
4688 (concat
4689 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4690 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4691 "\\(--?"
4692 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4693 "Regular expression to match a timestamp time or time range.
4694 After a match, the following groups carry important information:
4695 0 the full match
4696 1 date plus weekday, for back referencing to make sure both times are on the same day
4697 2 the first time, range or not
4698 4 the second time, if it is a range.")
4700 (defconst org-startup-options
4701 '(("fold" org-startup-folded t)
4702 ("overview" org-startup-folded t)
4703 ("nofold" org-startup-folded nil)
4704 ("showall" org-startup-folded nil)
4705 ("showeverything" org-startup-folded showeverything)
4706 ("content" org-startup-folded content)
4707 ("indent" org-startup-indented t)
4708 ("noindent" org-startup-indented nil)
4709 ("hidestars" org-hide-leading-stars t)
4710 ("showstars" org-hide-leading-stars nil)
4711 ("odd" org-odd-levels-only t)
4712 ("oddeven" org-odd-levels-only nil)
4713 ("align" org-startup-align-all-tables t)
4714 ("noalign" org-startup-align-all-tables nil)
4715 ("inlineimages" org-startup-with-inline-images t)
4716 ("noinlineimages" org-startup-with-inline-images nil)
4717 ("latexpreview" org-startup-with-latex-preview t)
4718 ("nolatexpreview" org-startup-with-latex-preview nil)
4719 ("customtime" org-display-custom-times t)
4720 ("logdone" org-log-done time)
4721 ("lognotedone" org-log-done note)
4722 ("nologdone" org-log-done nil)
4723 ("lognoteclock-out" org-log-note-clock-out t)
4724 ("nolognoteclock-out" org-log-note-clock-out nil)
4725 ("logrepeat" org-log-repeat state)
4726 ("lognoterepeat" org-log-repeat note)
4727 ("logdrawer" org-log-into-drawer t)
4728 ("nologdrawer" org-log-into-drawer nil)
4729 ("logstatesreversed" org-log-states-order-reversed t)
4730 ("nologstatesreversed" org-log-states-order-reversed nil)
4731 ("nologrepeat" org-log-repeat nil)
4732 ("logreschedule" org-log-reschedule time)
4733 ("lognotereschedule" org-log-reschedule note)
4734 ("nologreschedule" org-log-reschedule nil)
4735 ("logredeadline" org-log-redeadline time)
4736 ("lognoteredeadline" org-log-redeadline note)
4737 ("nologredeadline" org-log-redeadline nil)
4738 ("logrefile" org-log-refile time)
4739 ("lognoterefile" org-log-refile note)
4740 ("nologrefile" org-log-refile nil)
4741 ("fninline" org-footnote-define-inline t)
4742 ("nofninline" org-footnote-define-inline nil)
4743 ("fnlocal" org-footnote-section nil)
4744 ("fnauto" org-footnote-auto-label t)
4745 ("fnprompt" org-footnote-auto-label nil)
4746 ("fnconfirm" org-footnote-auto-label confirm)
4747 ("fnplain" org-footnote-auto-label plain)
4748 ("fnadjust" org-footnote-auto-adjust t)
4749 ("nofnadjust" org-footnote-auto-adjust nil)
4750 ("constcgs" constants-unit-system cgs)
4751 ("constSI" constants-unit-system SI)
4752 ("noptag" org-tag-persistent-alist nil)
4753 ("hideblocks" org-hide-block-startup t)
4754 ("nohideblocks" org-hide-block-startup nil)
4755 ("beamer" org-startup-with-beamer-mode t)
4756 ("entitiespretty" org-pretty-entities t)
4757 ("entitiesplain" org-pretty-entities nil))
4758 "Variable associated with STARTUP options for org-mode.
4759 Each element is a list of three items: the startup options (as written
4760 in the #+STARTUP line), the corresponding variable, and the value to set
4761 this variable to if the option is found. An optional forth element PUSH
4762 means to push this value onto the list in the variable.")
4764 (defun org-update-property-plist (key val props)
4765 "Update PROPS with KEY and VAL."
4766 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4767 (key (if appending (substring key 0 (- (length key) 1)) key))
4768 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4769 (previous (cdr (assoc key props))))
4770 (if appending
4771 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4772 (cons (cons key val) remainder))))
4774 (defconst org-block-regexp
4775 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4776 "Regular expression for hiding blocks.")
4777 (defconst org-heading-keyword-regexp-format
4778 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4779 "Printf format for a regexp matching a headline with some keyword.
4780 This regexp will match the headline of any node which has the
4781 exact keyword that is put into the format. The keyword isn't in
4782 any group by default, but the stars and the body are.")
4783 (defconst org-heading-keyword-maybe-regexp-format
4784 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4785 "Printf format for a regexp matching a headline, possibly with some keyword.
4786 This regexp can match any headline with the specified keyword, or
4787 without a keyword. The keyword isn't in any group by default,
4788 but the stars and the body are.")
4790 (defcustom org-group-tags t
4791 "When non-nil (the default), use group tags.
4792 This can be turned on/off through `org-toggle-tags-groups'."
4793 :group 'org-tags
4794 :group 'org-startup
4795 :type 'boolean)
4797 (defun org-toggle-tags-groups ()
4798 "Toggle support for group tags.
4799 Support for group tags is controlled by the option
4800 `org-group-tags', which is non-nil by default."
4801 (interactive)
4802 (setq org-group-tags (not org-group-tags))
4803 (cond ((and (derived-mode-p 'org-agenda-mode)
4804 org-group-tags)
4805 (org-agenda-redo))
4806 ((derived-mode-p 'org-mode)
4807 (let ((org-inhibit-startup t)) (org-mode))))
4808 (message "Groups tags support has been turned %s"
4809 (if org-group-tags "on" "off")))
4811 (defun org-set-regexps-and-options-for-tags ()
4812 "Precompute regular expressions used for tags in the current buffer."
4813 (when (derived-mode-p 'org-mode)
4814 (org-set-local 'org-file-tags nil)
4815 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4816 (splitre "[ \t]+")
4817 (start 0)
4818 tags ftags key value)
4819 (save-excursion
4820 (save-restriction
4821 (widen)
4822 (goto-char (point-min))
4823 (while (re-search-forward re nil t)
4824 (setq key (upcase (org-match-string-no-properties 1))
4825 value (org-match-string-no-properties 2))
4826 (if (stringp value) (setq value (org-trim value)))
4827 (cond
4828 ((equal key "TAGS")
4829 (setq tags (append tags (if tags '("\\n") nil)
4830 (org-split-string value splitre))))
4831 ((equal key "FILETAGS")
4832 (when (string-match "\\S-" value)
4833 (setq ftags
4834 (append
4835 ftags
4836 (apply 'append
4837 (mapcar (lambda (x) (org-split-string x ":"))
4838 (org-split-string value)))))))))))
4839 ;; Process the file tags.
4840 (and ftags (org-set-local 'org-file-tags
4841 (mapcar 'org-add-prop-inherited ftags)))
4842 (org-set-local 'org-tag-groups-alist nil)
4843 ;; Process the tags.
4844 ;; FIXME
4845 (when tags
4846 (let (e tgs g)
4847 (while (setq e (pop tags))
4848 (cond
4849 ((equal e "{")
4850 (progn (push '(:startgroup) tgs)
4851 (when (equal (nth 1 tags) ":")
4852 (push (list (replace-regexp-in-string
4853 "(.+)$" "" (nth 0 tags)))
4854 org-tag-groups-alist)
4855 (setq g 0))))
4856 ((equal e ":") (push '(:grouptags) tgs))
4857 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4858 ((equal e "\\n") (push '(:newline) tgs))
4859 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4860 (push (cons (match-string 1 e)
4861 (string-to-char (match-string 2 e))) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist)
4865 (list (match-string 1 e)))))
4866 (if g (setq g (1+ g))))
4867 (t (push (list e) tgs)
4868 (if (and g (> g 0))
4869 (setcar org-tag-groups-alist
4870 (append (car org-tag-groups-alist) (list e))))
4871 (if g (setq g (1+ g))))))
4872 (org-set-local 'org-tag-alist nil)
4873 (while (setq e (pop tgs))
4874 (or (and (stringp (car e))
4875 (assoc (car e) org-tag-alist))
4876 (push e org-tag-alist)))
4877 ;; Return a list with tag variables
4878 (list org-file-tags org-tag-alist org-tag-groups-alist))))))
4880 (defun org-set-regexps-and-options ()
4881 "Precompute regular expressions used in the current buffer."
4882 (when (derived-mode-p 'org-mode)
4883 (org-set-local 'org-todo-kwd-alist nil)
4884 (org-set-local 'org-todo-key-alist nil)
4885 (org-set-local 'org-todo-key-trigger nil)
4886 (org-set-local 'org-todo-keywords-1 nil)
4887 (org-set-local 'org-done-keywords nil)
4888 (org-set-local 'org-todo-heads nil)
4889 (org-set-local 'org-todo-sets nil)
4890 (org-set-local 'org-todo-log-states nil)
4891 (org-set-local 'org-file-properties nil)
4892 (let ((re (org-make-options-regexp
4893 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4894 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4895 "SETUPFILE" "OPTIONS")
4896 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4897 (splitre "[ \t]+")
4898 (scripts org-use-sub-superscripts)
4899 kwds kws0 kwsa key log value cat arch const links hw dws
4900 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4901 (start 0))
4902 (save-excursion
4903 (save-restriction
4904 (widen)
4905 (goto-char (point-min))
4906 (while
4907 (or (and
4908 ext-setup-or-nil
4909 (let (ret)
4910 (with-temp-buffer
4911 (insert ext-setup-or-nil)
4912 (let ((major-mode 'org-mode))
4913 (setq ret (save-match-data
4914 (org-set-regexps-and-options-for-tags)))))
4915 ;; Append setupfile tags to existing tags
4916 (setq org-file-tags
4917 (delq nil (append org-file-tags (nth 0 ret)))
4918 org-tag-alist
4919 (delq nil (append org-tag-alist (nth 1 ret)))
4920 org-tag-groups-alist
4921 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4922 (and ext-setup-or-nil
4923 (string-match re ext-setup-or-nil start)
4924 (setq start (match-end 0)))
4925 (and (setq ext-setup-or-nil nil start 0)
4926 (re-search-forward re nil t)))
4927 (setq key (upcase (match-string 1 ext-setup-or-nil))
4928 value (org-match-string-no-properties 2 ext-setup-or-nil))
4929 (if (stringp value) (setq value (org-trim value)))
4930 (cond
4931 ((equal key "CATEGORY")
4932 (setq cat value))
4933 ((member key '("SEQ_TODO" "TODO"))
4934 (push (cons 'sequence (org-split-string value splitre)) kwds))
4935 ((equal key "TYP_TODO")
4936 (push (cons 'type (org-split-string value splitre)) kwds))
4937 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4938 ;; general TODO-like setup
4939 (push (cons (intern (downcase (match-string 1 key)))
4940 (org-split-string value splitre)) kwds))
4941 ((equal key "COLUMNS")
4942 (org-set-local 'org-columns-default-format value))
4943 ((equal key "LINK")
4944 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4945 (push (cons (match-string 1 value)
4946 (org-trim (match-string 2 value)))
4947 links)))
4948 ((equal key "PRIORITIES")
4949 (setq prio (org-split-string value " +")))
4950 ((equal key "PROPERTY")
4951 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4952 (setq props (org-update-property-plist (match-string 1 value)
4953 (match-string 2 value)
4954 props))))
4955 ((equal key "DRAWERS")
4956 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4957 ((equal key "CONSTANTS")
4958 (org-table-set-constants))
4959 ((equal key "STARTUP")
4960 (let ((opts (org-split-string value splitre))
4961 l var val)
4962 (while (setq l (pop opts))
4963 (when (setq l (assoc l org-startup-options))
4964 (setq var (nth 1 l) val (nth 2 l))
4965 (if (not (nth 3 l))
4966 (set (make-local-variable var) val)
4967 (if (not (listp (symbol-value var)))
4968 (set (make-local-variable var) nil))
4969 (set (make-local-variable var) (symbol-value var))
4970 (add-to-list var val))))))
4971 ((equal key "ARCHIVE")
4972 (setq arch value)
4973 (remove-text-properties 0 (length arch)
4974 '(face t fontified t) arch))
4975 ((equal key "OPTIONS")
4976 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4977 (setq scripts (read (match-string 2 value)))))
4978 ((and (equal key "SETUPFILE")
4979 ;; Prevent checking in Gnus messages
4980 (not buffer-read-only))
4981 (setq setup-contents (org-file-contents
4982 (expand-file-name
4983 (org-remove-double-quotes value))
4984 'noerror))
4985 (if (not ext-setup-or-nil)
4986 (setq ext-setup-or-nil setup-contents start 0)
4987 (setq ext-setup-or-nil
4988 (concat (substring ext-setup-or-nil 0 start)
4989 "\n" setup-contents "\n"
4990 (substring ext-setup-or-nil start)))))))
4991 ;; search for property blocks
4992 (goto-char (point-min))
4993 (while (re-search-forward org-block-regexp nil t)
4994 (when (equal "PROPERTY" (upcase (match-string 1)))
4995 (setq value (replace-regexp-in-string
4996 "[\n\r]" " " (match-string 4)))
4997 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4998 (setq props (org-update-property-plist (match-string 1 value)
4999 (match-string 2 value)
5000 props)))))))
5001 (org-set-local 'org-use-sub-superscripts scripts)
5002 (when cat
5003 (org-set-local 'org-category (intern cat))
5004 (push (cons "CATEGORY" cat) props))
5005 (when prio
5006 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5007 (setq prio (mapcar 'string-to-char prio))
5008 (org-set-local 'org-highest-priority (nth 0 prio))
5009 (org-set-local 'org-lowest-priority (nth 1 prio))
5010 (org-set-local 'org-default-priority (nth 2 prio)))
5011 (and props (org-set-local 'org-file-properties (nreverse props)))
5012 (and drawers (org-set-local 'org-drawers drawers))
5013 (and arch (org-set-local 'org-archive-location arch))
5014 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5015 ;; Process the TODO keywords
5016 (unless kwds
5017 ;; Use the global values as if they had been given locally.
5018 (setq kwds (default-value 'org-todo-keywords))
5019 (if (stringp (car kwds))
5020 (setq kwds (list (cons org-todo-interpretation
5021 (default-value 'org-todo-keywords)))))
5022 (setq kwds (reverse kwds)))
5023 (setq kwds (nreverse kwds))
5024 (let (inter kws kw)
5025 (while (setq kws (pop kwds))
5026 (let ((kws (or
5027 (run-hook-with-args-until-success
5028 'org-todo-setup-filter-hook kws)
5029 kws)))
5030 (setq inter (pop kws) sep (member "|" kws)
5031 kws0 (delete "|" (copy-sequence kws))
5032 kwsa nil
5033 kws1 (mapcar
5034 (lambda (x)
5035 ;; 1 2
5036 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5037 (progn
5038 (setq kw (match-string 1 x)
5039 key (and (match-end 2) (match-string 2 x))
5040 log (org-extract-log-state-settings x))
5041 (push (cons kw (and key (string-to-char key))) kwsa)
5042 (and log (push log org-todo-log-states))
5044 (error "Invalid TODO keyword %s" x)))
5045 kws0)
5046 kwsa (if kwsa (append '((:startgroup))
5047 (nreverse kwsa)
5048 '((:endgroup))))
5049 hw (car kws1)
5050 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5051 tail (list inter hw (car dws) (org-last dws))))
5052 (add-to-list 'org-todo-heads hw 'append)
5053 (push kws1 org-todo-sets)
5054 (setq org-done-keywords (append org-done-keywords dws nil))
5055 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5056 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5057 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5058 (setq org-todo-sets (nreverse org-todo-sets)
5059 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5060 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5061 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5062 ;; Compute the regular expressions and other local variables.
5063 ;; Using `org-outline-regexp-bol' would complicate them much,
5064 ;; because of the fixed white space at the end of that string.
5065 (if (not org-done-keywords)
5066 (setq org-done-keywords (and org-todo-keywords-1
5067 (list (org-last org-todo-keywords-1)))))
5068 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5069 (length org-scheduled-string)
5070 (length org-clock-string)
5071 (length org-closed-string)))
5072 org-drawer-regexp
5073 (concat "^[ \t]*:\\("
5074 (mapconcat 'regexp-quote org-drawers "\\|")
5075 "\\):[ \t]*$")
5076 org-not-done-keywords
5077 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5078 org-todo-regexp
5079 (concat "\\("
5080 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5081 "\\)")
5082 org-not-done-regexp
5083 (concat "\\("
5084 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5085 "\\)")
5086 org-not-done-heading-regexp
5087 (format org-heading-keyword-regexp-format org-not-done-regexp)
5088 org-todo-line-regexp
5089 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5090 org-complex-heading-regexp
5091 (concat "^\\(\\*+\\)"
5092 "\\(?: +" org-todo-regexp "\\)?"
5093 "\\(?: +\\(\\[#.\\]\\)\\)?"
5094 "\\(?: +\\(.*?\\)\\)??"
5095 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5096 "[ \t]*$")
5097 org-complex-heading-regexp-format
5098 (concat "^\\(\\*+\\)"
5099 "\\(?: +" org-todo-regexp "\\)?"
5100 "\\(?: +\\(\\[#.\\]\\)\\)?"
5101 "\\(?: +"
5102 ;; Stats cookies can be stuck to body.
5103 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5104 "\\(%s\\)"
5105 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5106 "\\)"
5107 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5108 "[ \t]*$")
5109 org-todo-line-tags-regexp
5110 (concat "^\\(\\*+\\)"
5111 "\\(?: +" org-todo-regexp "\\)?"
5112 "\\(?: +\\(.*?\\)\\)??"
5113 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5114 "[ \t]*$")
5115 org-deadline-regexp (concat "\\<" org-deadline-string)
5116 org-deadline-time-regexp
5117 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5118 org-deadline-time-hour-regexp
5119 (concat "\\<" org-deadline-string
5120 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5121 org-deadline-line-regexp
5122 (concat "\\<\\(" org-deadline-string "\\).*")
5123 org-scheduled-regexp
5124 (concat "\\<" org-scheduled-string)
5125 org-scheduled-time-regexp
5126 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5127 org-scheduled-time-hour-regexp
5128 (concat "\\<" org-scheduled-string
5129 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5130 org-closed-time-regexp
5131 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5132 org-keyword-time-regexp
5133 (concat "\\<\\(" org-scheduled-string
5134 "\\|" org-deadline-string
5135 "\\|" org-closed-string
5136 "\\|" org-clock-string "\\)"
5137 " *[[<]\\([^]>]+\\)[]>]")
5138 org-keyword-time-not-clock-regexp
5139 (concat "\\<\\(" org-scheduled-string
5140 "\\|" org-deadline-string
5141 "\\|" org-closed-string
5142 "\\)"
5143 " *[[<]\\([^]>]+\\)[]>]")
5144 org-maybe-keyword-time-regexp
5145 (concat "\\(\\<\\(" org-scheduled-string
5146 "\\|" org-deadline-string
5147 "\\|" org-closed-string
5148 "\\|" org-clock-string "\\)\\)?"
5149 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5150 org-all-time-keywords
5151 (mapcar (lambda (w) (substring w 0 -1))
5152 (list org-scheduled-string org-deadline-string
5153 org-clock-string org-closed-string)))
5154 (org-compute-latex-and-related-regexp)
5155 (org-set-font-lock-defaults))))
5157 (defun org-file-contents (file &optional noerror)
5158 "Return the contents of FILE, as a string."
5159 (if (or (not file)
5160 (not (file-readable-p file)))
5161 (if noerror
5162 (message "Cannot read file \"%s\"" file)
5163 (error "Cannot read file \"%s\"" file))
5164 (with-temp-buffer
5165 (insert-file-contents file)
5166 (buffer-string))))
5168 (defun org-extract-log-state-settings (x)
5169 "Extract the log state setting from a TODO keyword string.
5170 This will extract info from a string like \"WAIT(w@/!)\"."
5171 (let (kw key log1 log2)
5172 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5173 (setq kw (match-string 1 x)
5174 key (and (match-end 2) (match-string 2 x))
5175 log1 (and (match-end 3) (match-string 3 x))
5176 log2 (and (match-end 4) (match-string 4 x)))
5177 (and (or log1 log2)
5178 (list kw
5179 (and log1 (if (equal log1 "!") 'time 'note))
5180 (and log2 (if (equal log2 "!") 'time 'note)))))))
5182 (defun org-remove-keyword-keys (list)
5183 "Remove a pair of parenthesis at the end of each string in LIST."
5184 (mapcar (lambda (x)
5185 (if (string-match "(.*)$" x)
5186 (substring x 0 (match-beginning 0))
5188 list))
5190 (defun org-assign-fast-keys (alist)
5191 "Assign fast keys to a keyword-key alist.
5192 Respect keys that are already there."
5193 (let (new e (alt ?0))
5194 (while (setq e (pop alist))
5195 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5196 (cdr e)) ;; Key already assigned.
5197 (push e new)
5198 (let ((clist (string-to-list (downcase (car e))))
5199 (used (append new alist)))
5200 (when (= (car clist) ?@)
5201 (pop clist))
5202 (while (and clist (rassoc (car clist) used))
5203 (pop clist))
5204 (unless clist
5205 (while (rassoc alt used)
5206 (incf alt)))
5207 (push (cons (car e) (or (car clist) alt)) new))))
5208 (nreverse new)))
5210 ;;; Some variables used in various places
5212 (defvar org-window-configuration nil
5213 "Used in various places to store a window configuration.")
5214 (defvar org-selected-window nil
5215 "Used in various places to store a window configuration.")
5216 (defvar org-finish-function nil
5217 "Function to be called when `C-c C-c' is used.
5218 This is for getting out of special buffers like capture.")
5221 ;; FIXME: Occasionally check by commenting these, to make sure
5222 ;; no other functions uses these, forgetting to let-bind them.
5223 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5224 (defvar org-last-state)
5225 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5227 ;; Defined somewhere in this file, but used before definition.
5228 (defvar org-entities) ;; defined in org-entities.el
5229 (defvar org-struct-menu)
5230 (defvar org-org-menu)
5231 (defvar org-tbl-menu)
5233 ;;;; Define the Org-mode
5235 ;; We use a before-change function to check if a table might need
5236 ;; an update.
5237 (defvar org-table-may-need-update t
5238 "Indicates that a table might need an update.
5239 This variable is set by `org-before-change-function'.
5240 `org-table-align' sets it back to nil.")
5241 (defun org-before-change-function (beg end)
5242 "Every change indicates that a table might need an update."
5243 (setq org-table-may-need-update t))
5244 (defvar org-mode-map)
5245 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5246 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5247 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5248 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5249 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5250 (defvar org-table-buffer-is-an nil)
5252 (defvar bidi-paragraph-direction)
5253 (defvar buffer-face-mode-face)
5255 (require 'outline)
5256 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5257 (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"))
5258 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5260 ;; Other stuff we need.
5261 (require 'time-date)
5262 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5263 (require 'easymenu)
5264 (require 'overlay)
5266 ;; (require 'org-macs) moved higher up in the file before it is first used
5267 (require 'org-entities)
5268 ;; (require 'org-compat) moved higher up in the file before it is first used
5269 (require 'org-faces)
5270 (require 'org-list)
5271 (require 'org-pcomplete)
5272 (require 'org-src)
5273 (require 'org-footnote)
5274 (require 'org-macro)
5276 ;; babel
5277 (require 'ob)
5279 ;;;###autoload
5280 (define-derived-mode org-mode outline-mode "Org"
5281 "Outline-based notes management and organizer, alias
5282 \"Carsten's outline-mode for keeping track of everything.\"
5284 Org-mode develops organizational tasks around a NOTES file which
5285 contains information about projects as plain text. Org-mode is
5286 implemented on top of outline-mode, which is ideal to keep the content
5287 of large files well structured. It supports ToDo items, deadlines and
5288 time stamps, which magically appear in the diary listing of the Emacs
5289 calendar. Tables are easily created with a built-in table editor.
5290 Plain text URL-like links connect to websites, emails (VM), Usenet
5291 messages (Gnus), BBDB entries, and any files related to the project.
5292 For printing and sharing of notes, an Org-mode file (or a part of it)
5293 can be exported as a structured ASCII or HTML file.
5295 The following commands are available:
5297 \\{org-mode-map}"
5299 ;; Get rid of Outline menus, they are not needed
5300 ;; Need to do this here because define-derived-mode sets up
5301 ;; the keymap so late. Still, it is a waste to call this each time
5302 ;; we switch another buffer into org-mode.
5303 (if (featurep 'xemacs)
5304 (when (boundp 'outline-mode-menu-heading)
5305 ;; Assume this is Greg's port, it uses easymenu
5306 (easy-menu-remove outline-mode-menu-heading)
5307 (easy-menu-remove outline-mode-menu-show)
5308 (easy-menu-remove outline-mode-menu-hide))
5309 (define-key org-mode-map [menu-bar headings] 'undefined)
5310 (define-key org-mode-map [menu-bar hide] 'undefined)
5311 (define-key org-mode-map [menu-bar show] 'undefined))
5313 (org-load-modules-maybe)
5314 (easy-menu-add org-org-menu)
5315 (easy-menu-add org-tbl-menu)
5316 (org-install-agenda-files-menu)
5317 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5318 (add-to-invisibility-spec '(org-cwidth))
5319 (add-to-invisibility-spec '(org-hide-block . t))
5320 (when (featurep 'xemacs)
5321 (org-set-local 'line-move-ignore-invisible t))
5322 (org-set-local 'outline-regexp org-outline-regexp)
5323 (org-set-local 'outline-level 'org-outline-level)
5324 (setq bidi-paragraph-direction 'left-to-right)
5325 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5326 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5327 (when (and org-ellipsis
5328 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5329 (fboundp 'make-glyph-code))
5330 (unless org-display-table
5331 (setq org-display-table (make-display-table)))
5332 (set-display-table-slot
5333 org-display-table 4
5334 (vconcat (mapcar
5335 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5336 org-ellipsis)))
5337 (if (stringp org-ellipsis) org-ellipsis "..."))))
5338 (setq buffer-display-table org-display-table))
5339 (org-set-regexps-and-options-for-tags)
5340 (org-set-regexps-and-options)
5341 (when (and org-tag-faces (not org-tags-special-faces-re))
5342 ;; tag faces set outside customize.... force initialization.
5343 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5344 ;; Calc embedded
5345 (org-set-local 'calc-embedded-open-mode "# ")
5346 ;; Modify a few syntax entries
5347 (modify-syntax-entry ?@ "w")
5348 (modify-syntax-entry ?\" "\"")
5349 (if org-startup-truncated (setq truncate-lines t))
5350 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5351 (org-set-local 'font-lock-unfontify-region-function
5352 'org-unfontify-region)
5353 ;; Activate before-change-function
5354 (org-set-local 'org-table-may-need-update t)
5355 (org-add-hook 'before-change-functions 'org-before-change-function nil
5356 'local)
5357 ;; Check for running clock before killing a buffer
5358 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5359 ;; Initialize macros templates.
5360 (org-macro-initialize-templates)
5361 ;; Initialize radio targets.
5362 (org-update-radio-target-regexp)
5363 ;; Indentation.
5364 (org-set-local 'indent-line-function 'org-indent-line)
5365 (org-set-local 'indent-region-function 'org-indent-region)
5366 ;; Filling and auto-filling.
5367 (org-setup-filling)
5368 ;; Comments.
5369 (org-setup-comments-handling)
5370 ;; Beginning/end of defun
5371 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5372 (org-set-local 'end-of-defun-function 'org-forward-element)
5373 ;; Next error for sparse trees
5374 (org-set-local 'next-error-function 'org-occur-next-match)
5375 ;; Make sure dependence stuff works reliably, even for users who set it
5376 ;; too late :-(
5377 (if org-enforce-todo-dependencies
5378 (add-hook 'org-blocker-hook
5379 'org-block-todo-from-children-or-siblings-or-parent)
5380 (remove-hook 'org-blocker-hook
5381 'org-block-todo-from-children-or-siblings-or-parent))
5382 (if org-enforce-todo-checkbox-dependencies
5383 (add-hook 'org-blocker-hook
5384 'org-block-todo-from-checkboxes)
5385 (remove-hook 'org-blocker-hook
5386 'org-block-todo-from-checkboxes))
5388 ;; Align options lines
5389 (org-set-local
5390 'align-mode-rules-list
5391 '((org-in-buffer-settings
5392 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5393 (modes . '(org-mode)))))
5395 ;; Imenu
5396 (org-set-local 'imenu-create-index-function
5397 'org-imenu-get-tree)
5399 ;; Make isearch reveal context
5400 (if (or (featurep 'xemacs)
5401 (not (boundp 'outline-isearch-open-invisible-function)))
5402 ;; Emacs 21 and XEmacs make use of the hook
5403 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5404 ;; Emacs 22 deals with this through a special variable
5405 (org-set-local 'outline-isearch-open-invisible-function
5406 (lambda (&rest ignore) (org-show-context 'isearch)))
5407 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5409 ;; Setup the pcomplete hooks
5410 (set (make-local-variable 'pcomplete-command-completion-function)
5411 'org-pcomplete-initial)
5412 (set (make-local-variable 'pcomplete-command-name-function)
5413 'org-command-at-point)
5414 (set (make-local-variable 'pcomplete-default-completion-function)
5415 'ignore)
5416 (set (make-local-variable 'pcomplete-parse-arguments-function)
5417 'org-parse-arguments)
5418 (set (make-local-variable 'pcomplete-termination-string) "")
5419 (when (>= emacs-major-version 23)
5420 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5422 ;; If empty file that did not turn on org-mode automatically, make it to.
5423 (if (and org-insert-mode-line-in-empty-file
5424 (org-called-interactively-p 'any)
5425 (= (point-min) (point-max)))
5426 (insert "# -*- mode: org -*-\n\n"))
5427 (unless org-inhibit-startup
5428 (org-unmodified
5429 (and org-startup-with-beamer-mode (org-beamer-mode))
5430 (when org-startup-align-all-tables
5431 (org-table-map-tables 'org-table-align 'quietly))
5432 (when org-startup-with-inline-images
5433 (org-display-inline-images))
5434 (when org-startup-with-latex-preview
5435 (org-preview-latex-fragment))
5436 (unless org-inhibit-startup-visibility-stuff
5437 (org-set-startup-visibility))))
5438 ;; Try to set org-hide correctly
5439 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5441 ;; Update `customize-package-emacs-version-alist'
5442 (add-to-list 'customize-package-emacs-version-alist
5443 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5444 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5445 ("8.0" . "24.4")))
5447 (defvar org-mode-transpose-word-syntax-table
5448 (let ((st (make-syntax-table)))
5449 (mapc (lambda(c) (modify-syntax-entry
5450 (string-to-char (car c)) "w p" st))
5451 org-emphasis-alist)
5452 st))
5454 (when (fboundp 'abbrev-table-put)
5455 (abbrev-table-put org-mode-abbrev-table
5456 :parents (list text-mode-abbrev-table)))
5458 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5460 (defsubst org-fix-ellipsis-at-bol ()
5461 (save-excursion (goto-char (window-start)) (recenter 0)))
5463 (defun org-find-invisible-foreground ()
5464 (let ((candidates (remove
5465 "unspecified-bg"
5466 (nconc
5467 (list (face-background 'default)
5468 (face-background 'org-default))
5469 (mapcar
5470 (lambda (alist)
5471 (when (boundp alist)
5472 (cdr (assoc 'background-color (symbol-value alist)))))
5473 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5474 (list (face-foreground 'org-hide))))))
5475 (car (remove nil candidates))))
5477 (defun org-current-time (&optional rounding-minutes past)
5478 "Current time, possibly rounded to ROUNDING-MINUTES.
5479 When ROUNDING-MINUTES is not an integer, fall back on the car of
5480 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5481 the rounding returns a past time."
5482 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5483 (car org-time-stamp-rounding-minutes)))
5484 (time (decode-time)) res)
5485 (if (< r 1)
5486 (current-time)
5487 (setq res
5488 (apply 'encode-time
5489 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5490 (nthcdr 2 time))))
5491 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5492 (seconds-to-time (- (org-float-time res) (* r 60)))
5493 res))))
5495 (defun org-today ()
5496 "Return today date, considering `org-extend-today-until'."
5497 (time-to-days
5498 (time-subtract (current-time)
5499 (list 0 (* 3600 org-extend-today-until) 0))))
5501 ;;;; Font-Lock stuff, including the activators
5503 (defvar org-mouse-map (make-sparse-keymap))
5504 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5505 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5506 (when org-mouse-1-follows-link
5507 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5508 (when org-tab-follows-link
5509 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5510 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5512 (require 'font-lock)
5514 (defconst org-non-link-chars "]\t\n\r<>")
5515 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5516 "shell" "elisp" "doi" "message"))
5517 (defvar org-link-types-re nil
5518 "Matches a link that has a url-like prefix like \"http:\"")
5519 (defvar org-link-re-with-space nil
5520 "Matches a link with spaces, optional angular brackets around it.")
5521 (defvar org-link-re-with-space2 nil
5522 "Matches a link with spaces, optional angular brackets around it.")
5523 (defvar org-link-re-with-space3 nil
5524 "Matches a link with spaces, only for internal part in bracket links.")
5525 (defvar org-angle-link-re nil
5526 "Matches link with angular brackets, spaces are allowed.")
5527 (defvar org-plain-link-re nil
5528 "Matches plain link, without spaces.")
5529 (defvar org-bracket-link-regexp nil
5530 "Matches a link in double brackets.")
5531 (defvar org-bracket-link-analytic-regexp nil
5532 "Regular expression used to analyze links.
5533 Here is what the match groups contain after a match:
5534 1: http:
5535 2: http
5536 3: path
5537 4: [desc]
5538 5: desc")
5539 (defvar org-bracket-link-analytic-regexp++ nil
5540 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5541 (defvar org-any-link-re nil
5542 "Regular expression matching any link.")
5544 (defconst org-match-sexp-depth 3
5545 "Number of stacked braces for sub/superscript matching.")
5547 (defun org-create-multibrace-regexp (left right n)
5548 "Create a regular expression which will match a balanced sexp.
5549 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5550 as single character strings.
5551 The regexp returned will match the entire expression including the
5552 delimiters. It will also define a single group which contains the
5553 match except for the outermost delimiters. The maximum depth of
5554 stacked delimiters is N. Escaping delimiters is not possible."
5555 (let* ((nothing (concat "[^" left right "]*?"))
5556 (or "\\|")
5557 (re nothing)
5558 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5559 (while (> n 1)
5560 (setq n (1- n)
5561 re (concat re or next)
5562 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5563 (concat left "\\(" re "\\)" right)))
5565 (defvar org-match-substring-regexp
5566 (concat
5567 "\\(\\S-\\)\\([_^]\\)\\("
5568 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5569 "\\|"
5570 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5571 "\\|"
5572 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5573 "The regular expression matching a sub- or superscript.")
5575 (defvar org-match-substring-with-braces-regexp
5576 (concat
5577 "\\(\\S-\\)\\([_^]\\)\\("
5578 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5579 "\\)")
5580 "The regular expression matching a sub- or superscript, forcing braces.")
5582 (defun org-make-link-regexps ()
5583 "Update the link regular expressions.
5584 This should be called after the variable `org-link-types' has changed."
5585 (setq org-link-types-re
5586 (concat
5587 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5588 org-link-re-with-space
5589 (concat
5590 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5591 "\\([^" org-non-link-chars " ]"
5592 "[^" org-non-link-chars "]*"
5593 "[^" org-non-link-chars " ]\\)>?")
5594 org-link-re-with-space2
5595 (concat
5596 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5597 "\\([^" org-non-link-chars " ]"
5598 "[^\t\n\r]*"
5599 "[^" org-non-link-chars " ]\\)>?")
5600 org-link-re-with-space3
5601 (concat
5602 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5603 "\\([^" org-non-link-chars " ]"
5604 "[^\t\n\r]*\\)")
5605 org-angle-link-re
5606 (concat
5607 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5608 "\\([^" org-non-link-chars " ]"
5609 "[^" org-non-link-chars "]*"
5610 "\\)>")
5611 org-plain-link-re
5612 (concat
5613 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5614 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5615 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5616 org-bracket-link-regexp
5617 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5618 org-bracket-link-analytic-regexp
5619 (concat
5620 "\\[\\["
5621 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5622 "\\([^]]+\\)"
5623 "\\]"
5624 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5625 "\\]")
5626 org-bracket-link-analytic-regexp++
5627 (concat
5628 "\\[\\["
5629 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5630 "\\([^]]+\\)"
5631 "\\]"
5632 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5633 "\\]")
5634 org-any-link-re
5635 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5636 org-angle-link-re "\\)\\|\\("
5637 org-plain-link-re "\\)")))
5639 (org-make-link-regexps)
5641 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5642 "Regular expression for fast time stamp matching.")
5643 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5644 "Regular expression for fast time stamp matching.")
5645 (defconst org-ts-regexp0
5646 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5647 "Regular expression matching time strings for analysis.
5648 This one does not require the space after the date, so it can be used
5649 on a string that terminates immediately after the date.")
5650 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5651 "Regular expression matching time strings for analysis.")
5652 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5653 "Regular expression matching time stamps, with groups.")
5654 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5655 "Regular expression matching time stamps (also [..]), with groups.")
5656 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5657 "Regular expression matching a time stamp range.")
5658 (defconst org-tr-regexp-both
5659 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5660 "Regular expression matching a time stamp range.")
5661 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5662 org-ts-regexp "\\)?")
5663 "Regular expression matching a time stamp or time stamp range.")
5664 (defconst org-tsr-regexp-both
5665 (concat org-ts-regexp-both "\\(--?-?"
5666 org-ts-regexp-both "\\)?")
5667 "Regular expression matching a time stamp or time stamp range.
5668 The time stamps may be either active or inactive.")
5670 (defvar org-emph-face nil)
5672 (defun org-do-emphasis-faces (limit)
5673 "Run through the buffer and add overlays to emphasized strings."
5674 (let (rtn a)
5675 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5676 (if (not (= (char-after (match-beginning 3))
5677 (char-after (match-beginning 4))))
5678 (progn
5679 (setq rtn t)
5680 (setq a (assoc (match-string 3) org-emphasis-alist))
5681 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5682 'face
5683 (nth 1 a))
5684 (and (nth 4 a)
5685 (org-remove-flyspell-overlays-in
5686 (match-beginning 0) (match-end 0)))
5687 (add-text-properties (match-beginning 2) (match-end 2)
5688 '(font-lock-multiline t org-emphasis t))
5689 (when org-hide-emphasis-markers
5690 (add-text-properties (match-end 4) (match-beginning 5)
5691 '(invisible org-link))
5692 (add-text-properties (match-beginning 3) (match-end 3)
5693 '(invisible org-link)))))
5694 (backward-char 1))
5695 rtn))
5697 (defun org-emphasize (&optional char)
5698 "Insert or change an emphasis, i.e. a font like bold or italic.
5699 If there is an active region, change that region to a new emphasis.
5700 If there is no region, just insert the marker characters and position
5701 the cursor between them.
5702 CHAR should be the marker character. If it is a space, it means to
5703 remove the emphasis of the selected region.
5704 If CHAR is not given (for example in an interactive call) it will be
5705 prompted for."
5706 (interactive)
5707 (let ((erc org-emphasis-regexp-components)
5708 (prompt "")
5709 (string "") beg end move c s)
5710 (if (org-region-active-p)
5711 (setq beg (region-beginning) end (region-end)
5712 string (buffer-substring beg end))
5713 (setq move t))
5715 (unless char
5716 (message "Emphasis marker or tag: [%s]"
5717 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5718 (setq char (read-char-exclusive)))
5719 (if (equal char ?\ )
5720 (setq s "" move nil)
5721 (unless (assoc (char-to-string char) org-emphasis-alist)
5722 (user-error "No such emphasis marker: \"%c\"" char))
5723 (setq s (char-to-string char)))
5724 (while (and (> (length string) 1)
5725 (equal (substring string 0 1) (substring string -1))
5726 (assoc (substring string 0 1) org-emphasis-alist))
5727 (setq string (substring string 1 -1)))
5728 (setq string (concat s string s))
5729 (if beg (delete-region beg end))
5730 (unless (or (bolp)
5731 (string-match (concat "[" (nth 0 erc) "\n]")
5732 (char-to-string (char-before (point)))))
5733 (insert " "))
5734 (unless (or (eobp)
5735 (string-match (concat "[" (nth 1 erc) "\n]")
5736 (char-to-string (char-after (point)))))
5737 (insert " ") (backward-char 1))
5738 (insert string)
5739 (and move (backward-char 1))))
5741 (defconst org-nonsticky-props
5742 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5744 (defsubst org-rear-nonsticky-at (pos)
5745 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5747 (defun org-activate-plain-links (limit)
5748 "Run through the buffer and add overlays to links."
5749 (let (f hl)
5750 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5751 (not (org-in-src-block-p)))
5752 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5753 (setq f (get-text-property (match-beginning 0) 'face))
5754 (setq hl (org-match-string-no-properties 0))
5755 (if (or (eq f 'org-tag)
5756 (and (listp f) (memq 'org-tag f)))
5758 (add-text-properties (match-beginning 0) (match-end 0)
5759 (list 'mouse-face 'highlight
5760 'face 'org-link
5761 'htmlize-link `(:uri ,hl)
5762 'keymap org-mouse-map))
5763 (org-rear-nonsticky-at (match-end 0)))
5764 t)))
5766 (defun org-activate-code (limit)
5767 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5768 (progn
5769 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5770 (remove-text-properties (match-beginning 0) (match-end 0)
5771 '(display t invisible t intangible t))
5772 t)))
5774 (defcustom org-src-fontify-natively nil
5775 "When non-nil, fontify code in code blocks."
5776 :type 'boolean
5777 :version "24.1"
5778 :group 'org-appearance
5779 :group 'org-babel)
5781 (defcustom org-allow-promoting-top-level-subtree nil
5782 "When non-nil, allow promoting a top level subtree.
5783 The leading star of the top level headline will be replaced
5784 by a #."
5785 :type 'boolean
5786 :version "24.1"
5787 :group 'org-appearance)
5789 (defun org-fontify-meta-lines-and-blocks (limit)
5790 (condition-case nil
5791 (org-fontify-meta-lines-and-blocks-1 limit)
5792 (error (message "org-mode fontification error"))))
5794 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5795 "Fontify #+ lines and blocks."
5796 (let ((case-fold-search t))
5797 (if (re-search-forward
5798 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5799 limit t)
5800 (let ((beg (match-beginning 0))
5801 (block-start (match-end 0))
5802 (block-end nil)
5803 (lang (match-string 7))
5804 (beg1 (line-beginning-position 2))
5805 (dc1 (downcase (match-string 2)))
5806 (dc3 (downcase (match-string 3)))
5807 end end1 quoting block-type ovl)
5808 (cond
5809 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5810 ;; a single line of backend-specific content
5811 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5812 (remove-text-properties (match-beginning 0) (match-end 0)
5813 '(display t invisible t intangible t))
5814 (add-text-properties (match-beginning 1) (match-end 3)
5815 '(font-lock-fontified t face org-meta-line))
5816 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5817 '(font-lock-fontified t face org-block))
5818 ; for backend-specific code
5820 ((and (match-end 4) (equal dc3 "+begin"))
5821 ;; Truly a block
5822 (setq block-type (downcase (match-string 5))
5823 quoting (member block-type org-protecting-blocks))
5824 (when (re-search-forward
5825 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5826 nil t) ;; on purpose, we look further than LIMIT
5827 (setq end (min (point-max) (match-end 0))
5828 end1 (min (point-max) (1- (match-beginning 0))))
5829 (setq block-end (match-beginning 0))
5830 (when quoting
5831 (remove-text-properties beg end
5832 '(display t invisible t intangible t)))
5833 (add-text-properties
5834 beg end
5835 '(font-lock-fontified t font-lock-multiline t))
5836 (add-text-properties beg beg1 '(face org-meta-line))
5837 (add-text-properties end1 (min (point-max) (1+ end))
5838 '(face org-meta-line)) ; for end_src
5839 (cond
5840 ((and lang (not (string= lang "")) org-src-fontify-natively)
5841 (org-src-font-lock-fontify-block lang block-start block-end)
5842 ;; remove old background overlays
5843 (mapc (lambda (ov)
5844 (if (eq (overlay-get ov 'face) 'org-block-background)
5845 (delete-overlay ov)))
5846 (overlays-at (/ (+ beg1 block-end) 2)))
5847 ;; add a background overlay
5848 (setq ovl (make-overlay beg1 block-end))
5849 (overlay-put ovl 'face 'org-block-background)
5850 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5851 (quoting
5852 (add-text-properties beg1 (min (point-max) (1+ end1))
5853 '(face org-block))) ; end of source block
5854 ((not org-fontify-quote-and-verse-blocks))
5855 ((string= block-type "quote")
5856 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5857 ((string= block-type "verse")
5858 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5859 (add-text-properties beg beg1 '(face org-block-begin-line))
5860 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5861 '(face org-block-end-line))
5863 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5864 (add-text-properties
5865 beg (match-end 3)
5866 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5867 '(font-lock-fontified t invisible t)
5868 '(font-lock-fontified t face org-document-info-keyword)))
5869 (add-text-properties
5870 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5871 (if (string-equal dc1 "+title:")
5872 '(font-lock-fontified t face org-document-title)
5873 '(font-lock-fontified t face org-document-info))))
5874 ((or (equal dc1 "+results")
5875 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5876 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5877 "+call:" "+header:" "+headers:" "+name:"))
5878 (and (match-end 4) (equal dc3 "+attr")))
5879 (add-text-properties
5880 beg (match-end 0)
5881 '(font-lock-fontified t face org-meta-line))
5883 ((member dc3 '(" " ""))
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face font-lock-comment-face)))
5887 ((not (member (char-after beg) '(?\ ?\t)))
5888 ;; just any other in-buffer setting, but not indented
5889 (add-text-properties
5890 beg (match-end 0)
5891 '(font-lock-fontified t face org-meta-line))
5893 (t nil))))))
5895 (defun org-activate-angle-links (limit)
5896 "Run through the buffer and add overlays to links."
5897 (if (and (re-search-forward org-angle-link-re limit t)
5898 (not (org-in-src-block-p)))
5899 (progn
5900 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5901 (add-text-properties (match-beginning 0) (match-end 0)
5902 (list 'mouse-face 'highlight
5903 'keymap org-mouse-map))
5904 (org-rear-nonsticky-at (match-end 0))
5905 t)))
5907 (defun org-activate-footnote-links (limit)
5908 "Run through the buffer and add overlays to footnotes."
5909 (let ((fn (org-footnote-next-reference-or-definition limit)))
5910 (when fn
5911 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5912 (org-remove-flyspell-overlays-in beg end)
5913 (add-text-properties beg end
5914 (list 'mouse-face 'highlight
5915 'keymap org-mouse-map
5916 'help-echo
5917 (if (= (point-at-bol) beg)
5918 "Footnote definition"
5919 "Footnote reference")
5920 'font-lock-fontified t
5921 'font-lock-multiline t
5922 'face 'org-footnote))))))
5924 (defun org-activate-bracket-links (limit)
5925 "Run through the buffer and add overlays to bracketed links."
5926 (if (and (re-search-forward org-bracket-link-regexp limit t)
5927 (not (org-in-src-block-p)))
5928 (let* ((hl (org-match-string-no-properties 1))
5929 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5930 (ip (org-maybe-intangible
5931 (list 'invisible 'org-link
5932 'keymap org-mouse-map 'mouse-face 'highlight
5933 'font-lock-multiline t 'help-echo help
5934 'htmlize-link `(:uri ,hl))))
5935 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5936 'font-lock-multiline t 'help-echo help
5937 'htmlize-link `(:uri ,hl))))
5938 ;; We need to remove the invisible property here. Table narrowing
5939 ;; may have made some of this invisible.
5940 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5941 (remove-text-properties (match-beginning 0) (match-end 0)
5942 '(invisible nil))
5943 (if (match-end 3)
5944 (progn
5945 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5946 (org-rear-nonsticky-at (match-beginning 3))
5947 (add-text-properties (match-beginning 3) (match-end 3) vp)
5948 (org-rear-nonsticky-at (match-end 3))
5949 (add-text-properties (match-end 3) (match-end 0) ip)
5950 (org-rear-nonsticky-at (match-end 0)))
5951 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5952 (org-rear-nonsticky-at (match-beginning 1))
5953 (add-text-properties (match-beginning 1) (match-end 1) vp)
5954 (org-rear-nonsticky-at (match-end 1))
5955 (add-text-properties (match-end 1) (match-end 0) ip)
5956 (org-rear-nonsticky-at (match-end 0)))
5957 t)))
5959 (defun org-activate-dates (limit)
5960 "Run through the buffer and add overlays to dates."
5961 (if (and (re-search-forward org-tsr-regexp-both limit t)
5962 (not (equal (char-before (match-beginning 0)) 91)))
5963 (progn
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (add-text-properties (match-beginning 0) (match-end 0)
5966 (list 'mouse-face 'highlight
5967 'keymap org-mouse-map))
5968 (org-rear-nonsticky-at (match-end 0))
5969 (when org-display-custom-times
5970 (if (match-end 3)
5971 (org-display-custom-time (match-beginning 3) (match-end 3)))
5972 (org-display-custom-time (match-beginning 1) (match-end 1)))
5973 t)))
5975 (defvar org-target-link-regexp nil
5976 "Regular expression matching radio targets in plain text.")
5977 (make-variable-buffer-local 'org-target-link-regexp)
5978 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5979 "Regular expression matching a link target.")
5980 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5981 "Regular expression matching a radio target.")
5982 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5983 "Regular expression matching any target.")
5985 (defun org-activate-target-links (limit)
5986 "Run through the buffer and add overlays to target matches."
5987 (when org-target-link-regexp
5988 (let ((case-fold-search t))
5989 (if (re-search-forward org-target-link-regexp limit t)
5990 (progn
5991 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (add-text-properties (match-beginning 0) (match-end 0)
5993 (list 'mouse-face 'highlight
5994 'keymap org-mouse-map
5995 'help-echo "Radio target link"
5996 'org-linked-text t))
5997 (org-rear-nonsticky-at (match-end 0))
5998 t)))))
6000 (defun org-update-radio-target-regexp ()
6001 "Find all radio targets in this file and update the regular expression."
6002 (interactive)
6003 (when (memq 'radio org-activate-links)
6004 (setq org-target-link-regexp
6005 (org-make-target-link-regexp (org-all-targets 'radio)))
6006 (org-restart-font-lock)))
6008 (defun org-hide-wide-columns (limit)
6009 (let (s e)
6010 (setq s (text-property-any (point) (or limit (point-max))
6011 'org-cwidth t))
6012 (when s
6013 (setq e (next-single-property-change s 'org-cwidth))
6014 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6015 (goto-char e)
6016 t)))
6018 (defvar org-latex-and-related-regexp nil
6019 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6020 (defvar org-match-substring-regexp)
6021 (defvar org-match-substring-with-braces-regexp)
6023 (defun org-compute-latex-and-related-regexp ()
6024 "Compute regular expression for LaTeX, entities and sub/superscript.
6025 Result depends on variable `org-highlight-latex-and-related'."
6026 (org-set-local
6027 'org-latex-and-related-regexp
6028 (let* ((re-sub
6029 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6030 ((eq org-use-sub-superscripts '{})
6031 (list org-match-substring-with-braces-regexp))
6032 (org-use-sub-superscripts (list org-match-substring-regexp))))
6033 (re-latex
6034 (when (memq 'latex org-highlight-latex-and-related)
6035 (let ((matchers (plist-get org-format-latex-options :matchers)))
6036 (delq nil
6037 (mapcar (lambda (x)
6038 (and (member (car x) matchers) (nth 1 x)))
6039 org-latex-regexps)))))
6040 (re-entities
6041 (when (memq 'entities org-highlight-latex-and-related)
6042 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6043 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6045 (defun org-do-latex-and-related (limit)
6046 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6047 LIMIT bounds the search for syntax to highlight. Stop at first
6048 highlighted object, if any. Return t if some highlighting was
6049 done, nil otherwise."
6050 (when (org-string-nw-p org-latex-and-related-regexp)
6051 (catch 'found
6052 (while (re-search-forward org-latex-and-related-regexp limit t)
6053 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6054 'face))
6055 '(org-code org-verbatim underline))
6056 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6057 '(?_ ?^))
6059 0)))
6060 (font-lock-prepend-text-property
6061 (+ offset (match-beginning 0)) (match-end 0)
6062 'face 'org-latex-and-related)
6063 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6064 '(font-lock-multiline t)))
6065 (throw 'found t)))
6066 nil)))
6068 (defun org-restart-font-lock ()
6069 "Restart `font-lock-mode', to force refontification."
6070 (when (and (boundp 'font-lock-mode) font-lock-mode)
6071 (font-lock-mode -1)
6072 (font-lock-mode 1)))
6074 (defun org-all-targets (&optional radio)
6075 "Return a list of all targets in this file.
6076 When optional argument RADIO is non-nil, only find radio
6077 targets."
6078 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6079 (save-excursion
6080 (goto-char (point-min))
6081 (while (re-search-forward re nil t)
6082 ;; Make sure point is really within the object.
6083 (backward-char)
6084 (let ((obj (org-element-context)))
6085 (when (memq (org-element-type obj) '(radio-target target))
6086 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6087 rtn)))
6089 (defun org-make-target-link-regexp (targets)
6090 "Make regular expression matching all strings in TARGETS.
6091 The regular expression finds the targets also if there is a line break
6092 between words."
6093 (and targets
6094 (concat
6095 "\\<\\("
6096 (mapconcat
6097 (lambda (x)
6098 (setq x (regexp-quote x))
6099 (while (string-match " +" x)
6100 (setq x (replace-match "\\s-+" t t x)))
6102 targets
6103 "\\|")
6104 "\\)\\>")))
6106 (defun org-activate-tags (limit)
6107 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6108 (progn
6109 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6110 (add-text-properties (match-beginning 1) (match-end 1)
6111 (list 'mouse-face 'highlight
6112 'keymap org-mouse-map))
6113 (org-rear-nonsticky-at (match-end 1))
6114 t)))
6116 (defun org-outline-level ()
6117 "Compute the outline level of the heading at point.
6118 If this is called at a normal headline, the level is the number of stars.
6119 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6120 (save-excursion
6121 (if (not (condition-case nil
6122 (org-back-to-heading t)
6123 (error nil)))
6125 (looking-at org-outline-regexp)
6126 (1- (- (match-end 0) (match-beginning 0))))))
6128 (defvar org-font-lock-keywords nil)
6130 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6131 "Regular expression matching a property line.")
6133 (defvar org-font-lock-hook nil
6134 "Functions to be called for special font lock stuff.")
6136 (defvar org-font-lock-set-keywords-hook nil
6137 "Functions that can manipulate `org-font-lock-extra-keywords'.
6138 This is called after `org-font-lock-extra-keywords' is defined, but before
6139 it is installed to be used by font lock. This can be useful if something
6140 needs to be inserted at a specific position in the font-lock sequence.")
6142 (defun org-font-lock-hook (limit)
6143 "Run `org-font-lock-hook' within LIMIT."
6144 (run-hook-with-args 'org-font-lock-hook limit))
6146 (defun org-set-font-lock-defaults ()
6147 "Set font lock defaults for the current buffer."
6148 (let* ((em org-fontify-emphasized-text)
6149 (lk org-activate-links)
6150 (org-font-lock-extra-keywords
6151 (list
6152 ;; Call the hook
6153 '(org-font-lock-hook)
6154 ;; Headlines
6155 `(,(if org-fontify-whole-heading-line
6156 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6157 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6158 (1 (org-get-level-face 1))
6159 (2 (org-get-level-face 2))
6160 (3 (org-get-level-face 3)))
6161 ;; Table lines
6162 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6163 (1 'org-table t))
6164 ;; Table internals
6165 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6166 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6167 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6168 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6169 ;; Drawers
6170 (list org-drawer-regexp '(0 'org-special-keyword t))
6171 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6172 ;; Properties
6173 (list org-property-re
6174 '(1 'org-special-keyword t)
6175 '(3 'org-property-value t))
6176 ;; Links
6177 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6178 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6179 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6180 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6181 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6182 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6183 (if (memq 'footnote lk) '(org-activate-footnote-links))
6184 ;; Targets.
6185 (list org-any-target-regexp '(0 'org-target t))
6186 ;; Diary sexps.
6187 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6188 ;; Macro
6189 '("{{{.+}}}" (0 'org-macro t))
6190 '(org-hide-wide-columns (0 nil append))
6191 ;; TODO keyword
6192 (list (format org-heading-keyword-regexp-format
6193 org-todo-regexp)
6194 '(2 (org-get-todo-face 2) t))
6195 ;; DONE
6196 (if org-fontify-done-headline
6197 (list (format org-heading-keyword-regexp-format
6198 (concat
6199 "\\(?:"
6200 (mapconcat 'regexp-quote org-done-keywords "\\|")
6201 "\\)"))
6202 '(2 'org-headline-done t))
6203 nil)
6204 ;; Priorities
6205 '(org-font-lock-add-priority-faces)
6206 ;; Tags
6207 '(org-font-lock-add-tag-faces)
6208 ;; Tags groups
6209 (if (and org-group-tags org-tag-groups-alist)
6210 (list (concat org-outline-regexp-bol ".+\\(:"
6211 (regexp-opt (mapcar 'car org-tag-groups-alist))
6212 ":\\).*$")
6213 '(1 'org-tag-group prepend)))
6214 ;; Special keywords
6215 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6216 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6217 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6218 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6219 ;; Emphasis
6220 (if em
6221 (if (featurep 'xemacs)
6222 '(org-do-emphasis-faces (0 nil append))
6223 '(org-do-emphasis-faces)))
6224 ;; Checkboxes
6225 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6226 1 'org-checkbox prepend)
6227 (if (cdr (assq 'checkbox org-list-automatic-rules))
6228 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6229 (0 (org-get-checkbox-statistics-face) t)))
6230 ;; Description list items
6231 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6232 1 'org-list-dt prepend)
6233 ;; ARCHIVEd headings
6234 (list (concat
6235 org-outline-regexp-bol
6236 "\\(.*:" org-archive-tag ":.*\\)")
6237 '(1 'org-archived prepend))
6238 ;; Specials
6239 '(org-do-latex-and-related)
6240 '(org-fontify-entities)
6241 '(org-raise-scripts)
6242 ;; Code
6243 '(org-activate-code (1 'org-code t))
6244 ;; COMMENT
6245 (list (format org-heading-keyword-regexp-format
6246 (concat "\\("
6247 org-comment-string "\\|" org-quote-string
6248 "\\)"))
6249 '(2 'org-special-keyword t))
6250 ;; Blocks and meta lines
6251 '(org-fontify-meta-lines-and-blocks))))
6252 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6253 (run-hooks 'org-font-lock-set-keywords-hook)
6254 ;; Now set the full font-lock-keywords
6255 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6256 (org-set-local 'font-lock-defaults
6257 '(org-font-lock-keywords t nil nil backward-paragraph))
6258 (kill-local-variable 'font-lock-keywords) nil))
6260 (defun org-toggle-pretty-entities ()
6261 "Toggle the composition display of entities as UTF8 characters."
6262 (interactive)
6263 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6264 (org-restart-font-lock)
6265 (if org-pretty-entities
6266 (message "Entities are now displayed as UTF8 characters")
6267 (save-restriction
6268 (widen)
6269 (org-decompose-region (point-min) (point-max))
6270 (message "Entities are now displayed as plain text"))))
6272 (defvar org-custom-properties-overlays nil
6273 "List of overlays used for custom properties.")
6274 (make-variable-buffer-local 'org-custom-properties-overlays)
6276 (defun org-toggle-custom-properties-visibility ()
6277 "Display or hide properties in `org-custom-properties'."
6278 (interactive)
6279 (if org-custom-properties-overlays
6280 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6281 (setq org-custom-properties-overlays nil))
6282 (unless (not org-custom-properties)
6283 (save-excursion
6284 (save-restriction
6285 (widen)
6286 (goto-char (point-min))
6287 (while (re-search-forward org-property-re nil t)
6288 (mapc (lambda(p)
6289 (when (equal p (substring (match-string 1) 1 -1))
6290 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6291 (overlay-put o 'invisible t)
6292 (overlay-put o 'org-custom-property t)
6293 (push o org-custom-properties-overlays))))
6294 org-custom-properties)))))))
6296 (defun org-fontify-entities (limit)
6297 "Find an entity to fontify."
6298 (let (ee)
6299 (when org-pretty-entities
6300 (catch 'match
6301 (while (re-search-forward
6302 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6303 limit t)
6304 (if (and (not (org-in-indented-comment-line))
6305 (setq ee (org-entity-get (match-string 1)))
6306 (= (length (nth 6 ee)) 1))
6307 (let*
6308 ((end (if (equal (match-string 2) "{}")
6309 (match-end 2)
6310 (match-end 1))))
6311 (add-text-properties
6312 (match-beginning 0) end
6313 (list 'font-lock-fontified t))
6314 (compose-region (match-beginning 0) end
6315 (nth 6 ee) nil)
6316 (backward-char 1)
6317 (throw 'match t))))
6318 nil))))
6320 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6321 "Fontify string S like in Org-mode."
6322 (with-temp-buffer
6323 (insert s)
6324 (let ((org-odd-levels-only odd-levels))
6325 (org-mode)
6326 (font-lock-fontify-buffer)
6327 (buffer-string))))
6329 (defvar org-m nil)
6330 (defvar org-l nil)
6331 (defvar org-f nil)
6332 (defun org-get-level-face (n)
6333 "Get the right face for match N in font-lock matching of headlines."
6334 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6335 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6336 (if org-cycle-level-faces
6337 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6338 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6339 (cond
6340 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6341 ((eq n 2) org-f)
6342 (t (if org-level-color-stars-only nil org-f))))
6345 (defun org-get-todo-face (kwd)
6346 "Get the right face for a TODO keyword KWD.
6347 If KWD is a number, get the corresponding match group."
6348 (if (numberp kwd) (setq kwd (match-string kwd)))
6349 (or (org-face-from-face-or-color
6350 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6351 (and (member kwd org-done-keywords) 'org-done)
6352 'org-todo))
6354 (defun org-face-from-face-or-color (context inherit face-or-color)
6355 "Create a face list that inherits INHERIT, but sets the foreground color.
6356 When FACE-OR-COLOR is not a string, just return it."
6357 (if (stringp face-or-color)
6358 (list :inherit inherit
6359 (cdr (assoc context org-faces-easy-properties))
6360 face-or-color)
6361 face-or-color))
6363 (defun org-font-lock-add-tag-faces (limit)
6364 "Add the special tag faces."
6365 (when (and org-tag-faces org-tags-special-faces-re)
6366 (while (re-search-forward org-tags-special-faces-re limit t)
6367 (add-text-properties (match-beginning 1) (match-end 1)
6368 (list 'face (org-get-tag-face 1)
6369 'font-lock-fontified t))
6370 (backward-char 1))))
6372 (defun org-font-lock-add-priority-faces (limit)
6373 "Add the special priority faces."
6374 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6375 (when (save-match-data (org-at-heading-p))
6376 (add-text-properties
6377 (match-beginning 0) (match-end 0)
6378 (list 'face (or (org-face-from-face-or-color
6379 'priority 'org-priority
6380 (cdr (assoc (char-after (match-beginning 1))
6381 org-priority-faces)))
6382 'org-priority)
6383 'font-lock-fontified t)))))
6385 (defun org-get-tag-face (kwd)
6386 "Get the right face for a TODO keyword KWD.
6387 If KWD is a number, get the corresponding match group."
6388 (if (numberp kwd) (setq kwd (match-string kwd)))
6389 (or (org-face-from-face-or-color
6390 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6391 'org-tag))
6393 (defun org-unfontify-region (beg end &optional maybe_loudly)
6394 "Remove fontification and activation overlays from links."
6395 (font-lock-default-unfontify-region beg end)
6396 (let* ((buffer-undo-list t)
6397 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6398 (inhibit-modification-hooks t)
6399 deactivate-mark buffer-file-name buffer-file-truename)
6400 (org-decompose-region beg end)
6401 (remove-text-properties beg end
6402 '(mouse-face t keymap t org-linked-text t
6403 invisible t intangible t
6404 org-no-flyspell t org-emphasis t))
6405 (org-remove-font-lock-display-properties beg end)))
6407 (defconst org-script-display '(((raise -0.3) (height 0.7))
6408 ((raise 0.3) (height 0.7))
6409 ((raise -0.5))
6410 ((raise 0.5)))
6411 "Display properties for showing superscripts and subscripts.")
6413 (defun org-remove-font-lock-display-properties (beg end)
6414 "Remove specific display properties that have been added by font lock.
6415 The will remove the raise properties that are used to show superscripts
6416 and subscripts."
6417 (let (next prop)
6418 (while (< beg end)
6419 (setq next (next-single-property-change beg 'display nil end)
6420 prop (get-text-property beg 'display))
6421 (if (member prop org-script-display)
6422 (put-text-property beg next 'display nil))
6423 (setq beg next))))
6425 (defun org-raise-scripts (limit)
6426 "Add raise properties to sub/superscripts."
6427 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6428 (if (re-search-forward
6429 (if (eq org-use-sub-superscripts t)
6430 org-match-substring-regexp
6431 org-match-substring-with-braces-regexp)
6432 limit t)
6433 (let* ((pos (point)) table-p comment-p
6434 (mpos (match-beginning 3))
6435 (emph-p (get-text-property mpos 'org-emphasis))
6436 (link-p (get-text-property mpos 'mouse-face))
6437 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6438 (goto-char (point-at-bol))
6439 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6440 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6441 (goto-char pos)
6442 ;; Handle a_b^c
6443 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6444 (if (or comment-p emph-p link-p keyw-p)
6446 (put-text-property (match-beginning 3) (match-end 0)
6447 'display
6448 (if (equal (char-after (match-beginning 2)) ?^)
6449 (nth (if table-p 3 1) org-script-display)
6450 (nth (if table-p 2 0) org-script-display)))
6451 (add-text-properties (match-beginning 2) (match-end 2)
6452 (list 'invisible t
6453 'org-dwidth t 'org-dwidth-n 1))
6454 (if (and (eq (char-after (match-beginning 3)) ?{)
6455 (eq (char-before (match-end 3)) ?}))
6456 (progn
6457 (add-text-properties
6458 (match-beginning 3) (1+ (match-beginning 3))
6459 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6460 (add-text-properties
6461 (1- (match-end 3)) (match-end 3)
6462 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6463 t)))))
6465 ;;;; Visibility cycling, including org-goto and indirect buffer
6467 ;;; Cycling
6469 (defvar org-cycle-global-status nil)
6470 (make-variable-buffer-local 'org-cycle-global-status)
6471 (put 'org-cycle-global-status 'org-state t)
6472 (defvar org-cycle-subtree-status nil)
6473 (make-variable-buffer-local 'org-cycle-subtree-status)
6474 (put 'org-cycle-subtree-status 'org-state t)
6476 (defvar org-inlinetask-min-level)
6478 ;;;###autoload
6479 (defun org-cycle (&optional arg)
6480 "TAB-action and visibility cycling for Org-mode.
6482 This is the command invoked in Org-mode by the TAB key. Its main purpose
6483 is outline visibility cycling, but it also invokes other actions
6484 in special contexts.
6486 - When this function is called with a prefix argument, rotate the entire
6487 buffer through 3 states (global cycling)
6488 1. OVERVIEW: Show only top-level headlines.
6489 2. CONTENTS: Show all headlines of all levels, but no body text.
6490 3. SHOW ALL: Show everything.
6491 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6492 determined by the variable `org-startup-folded', and by any VISIBILITY
6493 properties in the buffer.
6494 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6495 including any drawers.
6497 - When inside a table, re-align the table and move to the next field.
6499 - When point is at the beginning of a headline, rotate the subtree started
6500 by this line through 3 different states (local cycling)
6501 1. FOLDED: Only the main headline is shown.
6502 2. CHILDREN: The main headline and the direct children are shown.
6503 From this state, you can move to one of the children
6504 and zoom in further.
6505 3. SUBTREE: Show the entire subtree, including body text.
6506 If there is no subtree, switch directly from CHILDREN to FOLDED.
6508 - When point is at the beginning of an empty headline and the variable
6509 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6510 of the headline by demoting and promoting it to likely levels. This
6511 speeds up creation document structure by pressing TAB once or several
6512 times right after creating a new headline.
6514 - When there is a numeric prefix, go up to a heading with level ARG, do
6515 a `show-subtree' and return to the previous cursor position. If ARG
6516 is negative, go up that many levels.
6518 - When point is not at the beginning of a headline, execute the global
6519 binding for TAB, which is re-indenting the line. See the option
6520 `org-cycle-emulate-tab' for details.
6522 - Special case: if point is at the beginning of the buffer and there is
6523 no headline in line 1, this function will act as if called with prefix arg
6524 (C-u TAB, same as S-TAB) also when called without prefix arg.
6525 But only if also the variable `org-cycle-global-at-bob' is t."
6526 (interactive "P")
6527 (org-load-modules-maybe)
6528 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6529 (and org-cycle-level-after-item/entry-creation
6530 (or (org-cycle-level)
6531 (org-cycle-item-indentation))))
6532 (let* (message-log-max ; Don't populate the *Messages* buffer
6533 (limit-level
6534 (or org-cycle-max-level
6535 (and (boundp 'org-inlinetask-min-level)
6536 org-inlinetask-min-level
6537 (1- org-inlinetask-min-level))))
6538 (nstars (and limit-level
6539 (if org-odd-levels-only
6540 (and limit-level (1- (* limit-level 2)))
6541 limit-level)))
6542 (org-outline-regexp
6543 (if (not (derived-mode-p 'org-mode))
6544 outline-regexp
6545 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6546 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6547 (not (looking-at org-outline-regexp))))
6548 (org-cycle-hook
6549 (if bob-special
6550 (delq 'org-optimize-window-after-visibility-change
6551 (copy-sequence org-cycle-hook))
6552 org-cycle-hook))
6553 (pos (point)))
6555 (if (or bob-special (equal arg '(4)))
6556 ;; special case: use global cycling
6557 (setq arg t))
6559 (cond
6561 ((equal arg '(16))
6562 (setq last-command 'dummy)
6563 (org-set-startup-visibility)
6564 (message "Startup visibility, plus VISIBILITY properties"))
6566 ((equal arg '(64))
6567 (show-all)
6568 (message "Entire buffer visible, including drawers"))
6570 ;; Table: enter it or move to the next field.
6571 ((org-at-table-p 'any)
6572 (if (org-at-table.el-p)
6573 (message "Use C-c ' to edit table.el tables")
6574 (if arg (org-table-edit-field t)
6575 (org-table-justify-field-maybe)
6576 (call-interactively 'org-table-next-field))))
6578 ((run-hook-with-args-until-success
6579 'org-tab-after-check-for-table-hook))
6581 ;; Global cycling: delegate to `org-cycle-internal-global'.
6582 ((eq arg t) (org-cycle-internal-global))
6584 ;; Drawers: delegate to `org-flag-drawer'.
6585 ((and org-drawers org-drawer-regexp
6586 (save-excursion
6587 (beginning-of-line 1)
6588 (looking-at org-drawer-regexp)))
6589 (org-flag-drawer ; toggle block visibility
6590 (not (get-char-property (match-end 0) 'invisible))))
6592 ;; Show-subtree, ARG levels up from here.
6593 ((integerp arg)
6594 (save-excursion
6595 (org-back-to-heading)
6596 (outline-up-heading (if (< arg 0) (- arg)
6597 (- (funcall outline-level) arg)))
6598 (org-show-subtree)))
6600 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6601 ((and (featurep 'org-inlinetask)
6602 (org-inlinetask-at-task-p)
6603 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6604 (org-inlinetask-toggle-visibility))
6606 ((org-try-cdlatex-tab))
6608 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6609 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6610 (save-excursion (beginning-of-line 1)
6611 (looking-at org-outline-regexp)))
6612 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6613 (org-cycle-internal-local))
6615 ;; From there: TAB emulation and template completion.
6616 (buffer-read-only (org-back-to-heading))
6618 ((run-hook-with-args-until-success
6619 'org-tab-after-check-for-cycling-hook))
6621 ((org-try-structure-completion))
6623 ((run-hook-with-args-until-success
6624 'org-tab-before-tab-emulation-hook))
6626 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6627 (or (not (bolp))
6628 (not (looking-at org-outline-regexp))))
6629 (call-interactively (global-key-binding "\t")))
6631 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6632 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6633 (or (and (eq org-cycle-emulate-tab 'white)
6634 (= (match-end 0) (point-at-eol)))
6635 (and (eq org-cycle-emulate-tab 'whitestart)
6636 (>= (match-end 0) pos))))
6638 (eq org-cycle-emulate-tab t))
6639 (call-interactively (global-key-binding "\t")))
6641 (t (save-excursion
6642 (org-back-to-heading)
6643 (org-cycle)))))))
6645 (defun org-cycle-internal-global ()
6646 "Do the global cycling action."
6647 ;; Hack to avoid display of messages for .org attachments in Gnus
6648 (let (message-log-max ; Don't populate the *Messages* buffer
6649 (ga (string-match "\\*fontification" (buffer-name))))
6650 (cond
6651 ((and (eq last-command this-command)
6652 (eq org-cycle-global-status 'overview))
6653 ;; We just created the overview - now do table of contents
6654 ;; This can be slow in very large buffers, so indicate action
6655 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6656 (unless ga (message "CONTENTS..."))
6657 (org-content)
6658 (unless ga (message "CONTENTS...done"))
6659 (setq org-cycle-global-status 'contents)
6660 (run-hook-with-args 'org-cycle-hook 'contents))
6662 ((and (eq last-command this-command)
6663 (eq org-cycle-global-status 'contents))
6664 ;; We just showed the table of contents - now show everything
6665 (run-hook-with-args 'org-pre-cycle-hook 'all)
6666 (show-all)
6667 (unless ga (message "SHOW ALL"))
6668 (setq org-cycle-global-status 'all)
6669 (run-hook-with-args 'org-cycle-hook 'all))
6672 ;; Default action: go to overview
6673 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6674 (org-overview)
6675 (unless ga (message "OVERVIEW"))
6676 (setq org-cycle-global-status 'overview)
6677 (run-hook-with-args 'org-cycle-hook 'overview)))))
6679 (defun org-cycle-internal-local ()
6680 "Do the local cycling action."
6681 (let (message-log-max ; Don't populate the *Messages* buffer
6682 (goal-column 0) eoh eol eos has-children children-skipped struct)
6683 ;; First, determine end of headline (EOH), end of subtree or item
6684 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6685 (save-excursion
6686 (if (org-at-item-p)
6687 (progn
6688 (beginning-of-line)
6689 (setq struct (org-list-struct))
6690 (setq eoh (point-at-eol))
6691 (setq eos (org-list-get-item-end-before-blank (point) struct))
6692 (setq has-children (org-list-has-child-p (point) struct)))
6693 (org-back-to-heading)
6694 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6695 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6696 (setq has-children
6697 (or (save-excursion
6698 (let ((level (funcall outline-level)))
6699 (outline-next-heading)
6700 (and (org-at-heading-p t)
6701 (> (funcall outline-level) level))))
6702 (save-excursion
6703 (org-list-search-forward (org-item-beginning-re) eos t)))))
6704 ;; Determine end invisible part of buffer (EOL)
6705 (beginning-of-line 2)
6706 ;; XEmacs doesn't have `next-single-char-property-change'
6707 (if (featurep 'xemacs)
6708 (while (and (not (eobp)) ;; this is like `next-line'
6709 (get-char-property (1- (point)) 'invisible))
6710 (beginning-of-line 2))
6711 (while (and (not (eobp)) ;; this is like `next-line'
6712 (get-char-property (1- (point)) 'invisible))
6713 (goto-char (next-single-char-property-change (point) 'invisible))
6714 (and (eolp) (beginning-of-line 2))))
6715 (setq eol (point)))
6716 ;; Find out what to do next and set `this-command'
6717 (cond
6718 ((= eos eoh)
6719 ;; Nothing is hidden behind this heading
6720 (unless (org-before-first-heading-p)
6721 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6722 (message "EMPTY ENTRY")
6723 (setq org-cycle-subtree-status nil)
6724 (save-excursion
6725 (goto-char eos)
6726 (outline-next-heading)
6727 (if (outline-invisible-p) (org-flag-heading nil))))
6728 ((and (or (>= eol eos)
6729 (not (string-match "\\S-" (buffer-substring eol eos))))
6730 (or has-children
6731 (not (setq children-skipped
6732 org-cycle-skip-children-state-if-no-children))))
6733 ;; Entire subtree is hidden in one line: children view
6734 (unless (org-before-first-heading-p)
6735 (run-hook-with-args 'org-pre-cycle-hook 'children))
6736 (if (org-at-item-p)
6737 (org-list-set-item-visibility (point-at-bol) struct 'children)
6738 (org-show-entry)
6739 (org-with-limited-levels (show-children))
6740 ;; FIXME: This slows down the func way too much.
6741 ;; How keep drawers hidden in subtree anyway?
6742 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6743 ;; (org-cycle-hide-drawers 'subtree))
6745 ;; Fold every list in subtree to top-level items.
6746 (when (eq org-cycle-include-plain-lists 'integrate)
6747 (save-excursion
6748 (org-back-to-heading)
6749 (while (org-list-search-forward (org-item-beginning-re) eos t)
6750 (beginning-of-line 1)
6751 (let* ((struct (org-list-struct))
6752 (prevs (org-list-prevs-alist struct))
6753 (end (org-list-get-bottom-point struct)))
6754 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6755 (org-list-get-all-items (point) struct prevs))
6756 (goto-char (if (< end eos) end eos)))))))
6757 (message "CHILDREN")
6758 (save-excursion
6759 (goto-char eos)
6760 (outline-next-heading)
6761 (if (outline-invisible-p) (org-flag-heading nil)))
6762 (setq org-cycle-subtree-status 'children)
6763 (unless (org-before-first-heading-p)
6764 (run-hook-with-args 'org-cycle-hook 'children)))
6765 ((or children-skipped
6766 (and (eq last-command this-command)
6767 (eq org-cycle-subtree-status 'children)))
6768 ;; We just showed the children, or no children are there,
6769 ;; now show everything.
6770 (unless (org-before-first-heading-p)
6771 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6772 (outline-flag-region eoh eos nil)
6773 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6774 (setq org-cycle-subtree-status 'subtree)
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-cycle-hook 'subtree)))
6778 ;; Default action: hide the subtree.
6779 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6780 (outline-flag-region eoh eos t)
6781 (message "FOLDED")
6782 (setq org-cycle-subtree-status 'folded)
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-cycle-hook 'folded))))))
6786 ;;;###autoload
6787 (defun org-global-cycle (&optional arg)
6788 "Cycle the global visibility. For details see `org-cycle'.
6789 With \\[universal-argument] prefix arg, switch to startup visibility.
6790 With a numeric prefix, show all headlines up to that level."
6791 (interactive "P")
6792 (let ((org-cycle-include-plain-lists
6793 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6794 (cond
6795 ((integerp arg)
6796 (show-all)
6797 (hide-sublevels arg)
6798 (setq org-cycle-global-status 'contents))
6799 ((equal arg '(4))
6800 (org-set-startup-visibility)
6801 (message "Startup visibility, plus VISIBILITY properties."))
6803 (org-cycle '(4))))))
6805 (defun org-set-startup-visibility ()
6806 "Set the visibility required by startup options and properties."
6807 (cond
6808 ((eq org-startup-folded t)
6809 (org-cycle '(4)))
6810 ((eq org-startup-folded 'content)
6811 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6812 (org-cycle '(4)) (org-cycle '(4)))))
6813 (unless (eq org-startup-folded 'showeverything)
6814 (if org-hide-block-startup (org-hide-block-all))
6815 (org-set-visibility-according-to-property 'no-cleanup)
6816 (org-cycle-hide-archived-subtrees 'all)
6817 (org-cycle-hide-drawers 'all)
6818 (org-cycle-show-empty-lines t)))
6820 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6821 "Switch subtree visibilities according to :VISIBILITY: property."
6822 (interactive)
6823 (let (org-show-entry-below state)
6824 (save-excursion
6825 (goto-char (point-min))
6826 (while (re-search-forward
6827 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6828 nil t)
6829 (setq state (match-string 1))
6830 (save-excursion
6831 (org-back-to-heading t)
6832 (hide-subtree)
6833 (org-reveal)
6834 (cond
6835 ((equal state '("fold" "folded"))
6836 (hide-subtree))
6837 ((equal state "children")
6838 (org-show-hidden-entry)
6839 (show-children))
6840 ((equal state "content")
6841 (save-excursion
6842 (save-restriction
6843 (org-narrow-to-subtree)
6844 (org-content))))
6845 ((member state '("all" "showall"))
6846 (show-subtree)))))
6847 (unless no-cleanup
6848 (org-cycle-hide-archived-subtrees 'all)
6849 (org-cycle-hide-drawers 'all)
6850 (org-cycle-show-empty-lines 'all)))))
6852 ;; This function uses outline-regexp instead of the more fundamental
6853 ;; org-outline-regexp so that org-cycle-global works outside of Org
6854 ;; buffers, where outline-regexp is needed.
6855 (defun org-overview ()
6856 "Switch to overview mode, showing only top-level headlines.
6857 Really, this shows all headlines with level equal or greater than the level
6858 of the first headline in the buffer. This is important, because if the
6859 first headline is not level one, then (hide-sublevels 1) gives confusing
6860 results."
6861 (interactive)
6862 (let ((l (org-current-line))
6863 (level (save-excursion
6864 (goto-char (point-min))
6865 (if (re-search-forward (concat "^" outline-regexp) nil t)
6866 (progn
6867 (goto-char (match-beginning 0))
6868 (funcall outline-level))))))
6869 (and level (hide-sublevels level))
6870 (recenter '(4))
6871 (org-goto-line l)))
6873 (defun org-content (&optional arg)
6874 "Show all headlines in the buffer, like a table of contents.
6875 With numerical argument N, show content up to level N."
6876 (interactive "P")
6877 (save-excursion
6878 ;; Visit all headings and show their offspring
6879 (and (integerp arg) (org-overview))
6880 (goto-char (point-max))
6881 (catch 'exit
6882 (while (and (progn (condition-case nil
6883 (outline-previous-visible-heading 1)
6884 (error (goto-char (point-min))))
6886 (looking-at org-outline-regexp))
6887 (if (integerp arg)
6888 (show-children (1- arg))
6889 (show-branches))
6890 (if (bobp) (throw 'exit nil))))))
6893 (defun org-optimize-window-after-visibility-change (state)
6894 "Adjust the window after a change in outline visibility.
6895 This function is the default value of the hook `org-cycle-hook'."
6896 (when (get-buffer-window (current-buffer))
6897 (cond
6898 ((eq state 'content) nil)
6899 ((eq state 'all) nil)
6900 ((eq state 'folded) nil)
6901 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6902 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6904 (defun org-remove-empty-overlays-at (pos)
6905 "Remove outline overlays that do not contain non-white stuff."
6906 (mapc
6907 (lambda (o)
6908 (and (eq 'outline (overlay-get o 'invisible))
6909 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6910 (overlay-end o))))
6911 (delete-overlay o)))
6912 (overlays-at pos)))
6914 (defun org-clean-visibility-after-subtree-move ()
6915 "Fix visibility issues after moving a subtree."
6916 ;; First, find a reasonable region to look at:
6917 ;; Start two siblings above, end three below
6918 (let* ((beg (save-excursion
6919 (and (org-get-last-sibling)
6920 (org-get-last-sibling))
6921 (point)))
6922 (end (save-excursion
6923 (and (org-get-next-sibling)
6924 (org-get-next-sibling)
6925 (org-get-next-sibling))
6926 (if (org-at-heading-p)
6927 (point-at-eol)
6928 (point))))
6929 (level (looking-at "\\*+"))
6930 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6931 (save-excursion
6932 (save-restriction
6933 (narrow-to-region beg end)
6934 (when re
6935 ;; Properly fold already folded siblings
6936 (goto-char (point-min))
6937 (while (re-search-forward re nil t)
6938 (if (and (not (outline-invisible-p))
6939 (save-excursion
6940 (goto-char (point-at-eol)) (outline-invisible-p)))
6941 (hide-entry))))
6942 (org-cycle-show-empty-lines 'overview)
6943 (org-cycle-hide-drawers 'overview)))))
6945 (defun org-cycle-show-empty-lines (state)
6946 "Show empty lines above all visible headlines.
6947 The region to be covered depends on STATE when called through
6948 `org-cycle-hook'. Lisp program can use t for STATE to get the
6949 entire buffer covered. Note that an empty line is only shown if there
6950 are at least `org-cycle-separator-lines' empty lines before the headline."
6951 (when (not (= org-cycle-separator-lines 0))
6952 (save-excursion
6953 (let* ((n (abs org-cycle-separator-lines))
6954 (re (cond
6955 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6956 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6957 (t (let ((ns (number-to-string (- n 2))))
6958 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6959 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6960 beg end b e)
6961 (cond
6962 ((memq state '(overview contents t))
6963 (setq beg (point-min) end (point-max)))
6964 ((memq state '(children folded))
6965 (setq beg (point) end (progn (org-end-of-subtree t t)
6966 (beginning-of-line 2)
6967 (point)))))
6968 (when beg
6969 (goto-char beg)
6970 (while (re-search-forward re end t)
6971 (unless (get-char-property (match-end 1) 'invisible)
6972 (setq e (match-end 1))
6973 (if (< org-cycle-separator-lines 0)
6974 (setq b (save-excursion
6975 (goto-char (match-beginning 0))
6976 (org-back-over-empty-lines)
6977 (if (save-excursion
6978 (goto-char (max (point-min) (1- (point))))
6979 (org-at-heading-p))
6980 (1- (point))
6981 (point))))
6982 (setq b (match-beginning 1)))
6983 (outline-flag-region b e nil)))))))
6984 ;; Never hide empty lines at the end of the file.
6985 (save-excursion
6986 (goto-char (point-max))
6987 (outline-previous-heading)
6988 (outline-end-of-heading)
6989 (if (and (looking-at "[ \t\n]+")
6990 (= (match-end 0) (point-max)))
6991 (outline-flag-region (point) (match-end 0) nil))))
6993 (defun org-show-empty-lines-in-parent ()
6994 "Move to the parent and re-show empty lines before visible headlines."
6995 (save-excursion
6996 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6997 (org-cycle-show-empty-lines context))))
6999 (defun org-files-list ()
7000 "Return `org-agenda-files' list, plus all open org-mode files.
7001 This is useful for operations that need to scan all of a user's
7002 open and agenda-wise Org files."
7003 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7004 (dolist (buf (buffer-list))
7005 (with-current-buffer buf
7006 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7007 (let ((file (expand-file-name (buffer-file-name))))
7008 (unless (member file files)
7009 (push file files))))))
7010 files))
7012 (defsubst org-entry-beginning-position ()
7013 "Return the beginning position of the current entry."
7014 (save-excursion (outline-back-to-heading t) (point)))
7016 (defsubst org-entry-end-position ()
7017 "Return the end position of the current entry."
7018 (save-excursion (outline-next-heading) (point)))
7020 (defun org-cycle-hide-drawers (state)
7021 "Re-hide all drawers after a visibility state change."
7022 (when (and (derived-mode-p 'org-mode)
7023 (not (memq state '(overview folded contents))))
7024 (save-excursion
7025 (let* ((globalp (memq state '(contents all)))
7026 (beg (if globalp (point-min) (point)))
7027 (end (if globalp (point-max)
7028 (if (eq state 'children)
7029 (save-excursion (outline-next-heading) (point))
7030 (org-end-of-subtree t)))))
7031 (goto-char beg)
7032 (while (re-search-forward org-drawer-regexp end t)
7033 (org-flag-drawer t))))))
7035 (defun org-cycle-hide-inline-tasks (state)
7036 "Re-hide inline task when switching to 'contents visibility state."
7037 (when (and (eq state 'contents)
7038 (boundp 'org-inlinetask-min-level)
7039 org-inlinetask-min-level)
7040 (hide-sublevels (1- org-inlinetask-min-level))))
7042 (defun org-flag-drawer (flag)
7043 "When FLAG is non-nil, hide the drawer we are within.
7044 Otherwise make it visible."
7045 (save-excursion
7046 (beginning-of-line 1)
7047 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7048 (let ((b (match-end 0)))
7049 (if (re-search-forward
7050 "^[ \t]*:END:"
7051 (save-excursion (outline-next-heading) (point)) t)
7052 (outline-flag-region b (point-at-eol) flag)
7053 (user-error ":END: line missing at position %s" b))))))
7055 (defun org-subtree-end-visible-p ()
7056 "Is the end of the current subtree visible?"
7057 (pos-visible-in-window-p
7058 (save-excursion (org-end-of-subtree t) (point))))
7060 (defun org-first-headline-recenter (&optional N)
7061 "Move cursor to the first headline and recenter the headline.
7062 Optional argument N means put the headline into the Nth line of the window."
7063 (goto-char (point-min))
7064 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7065 (beginning-of-line)
7066 (recenter (prefix-numeric-value N))))
7068 ;;; Saving and restoring visibility
7070 (defun org-outline-overlay-data (&optional use-markers)
7071 "Return a list of the locations of all outline overlays.
7072 These are overlays with the `invisible' property value `outline'.
7073 The return value is a list of cons cells, with start and stop
7074 positions for each overlay.
7075 If USE-MARKERS is set, return the positions as markers."
7076 (let (beg end)
7077 (save-excursion
7078 (save-restriction
7079 (widen)
7080 (delq nil
7081 (mapcar (lambda (o)
7082 (when (eq (overlay-get o 'invisible) 'outline)
7083 (setq beg (overlay-start o)
7084 end (overlay-end o))
7085 (and beg end (> end beg)
7086 (if use-markers
7087 (cons (move-marker (make-marker) beg)
7088 (move-marker (make-marker) end))
7089 (cons beg end)))))
7090 (overlays-in (point-min) (point-max))))))))
7092 (defun org-set-outline-overlay-data (data)
7093 "Create visibility overlays for all positions in DATA.
7094 DATA should have been made by `org-outline-overlay-data'."
7095 (let (o)
7096 (save-excursion
7097 (save-restriction
7098 (widen)
7099 (show-all)
7100 (mapc (lambda (c)
7101 (outline-flag-region (car c) (cdr c) t))
7102 data)))))
7104 ;;; Folding of blocks
7106 (defvar org-hide-block-overlays nil
7107 "Overlays hiding blocks.")
7108 (make-variable-buffer-local 'org-hide-block-overlays)
7110 (defun org-block-map (function &optional start end)
7111 "Call FUNCTION at the head of all source blocks in the current buffer.
7112 Optional arguments START and END can be used to limit the range."
7113 (let ((start (or start (point-min)))
7114 (end (or end (point-max))))
7115 (save-excursion
7116 (goto-char start)
7117 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7118 (save-excursion
7119 (save-match-data
7120 (goto-char (match-beginning 0))
7121 (funcall function)))))))
7123 (defun org-hide-block-toggle-all ()
7124 "Toggle the visibility of all blocks in the current buffer."
7125 (org-block-map #'org-hide-block-toggle))
7127 (defun org-hide-block-all ()
7128 "Fold all blocks in the current buffer."
7129 (interactive)
7130 (org-show-block-all)
7131 (org-block-map #'org-hide-block-toggle-maybe))
7133 (defun org-show-block-all ()
7134 "Unfold all blocks in the current buffer."
7135 (interactive)
7136 (mapc 'delete-overlay org-hide-block-overlays)
7137 (setq org-hide-block-overlays nil))
7139 (defun org-hide-block-toggle-maybe ()
7140 "Toggle visibility of block at point."
7141 (interactive)
7142 (let ((case-fold-search t))
7143 (if (save-excursion
7144 (beginning-of-line 1)
7145 (looking-at org-block-regexp))
7146 (progn (org-hide-block-toggle)
7147 t) ;; to signal that we took action
7148 nil))) ;; to signal that we did not
7150 (defun org-hide-block-toggle (&optional force)
7151 "Toggle the visibility of the current block."
7152 (interactive)
7153 (save-excursion
7154 (beginning-of-line)
7155 (if (re-search-forward org-block-regexp nil t)
7156 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7157 (end (match-end 0)) ;; end of entire body
7159 (if (memq t (mapcar (lambda (overlay)
7160 (eq (overlay-get overlay 'invisible)
7161 'org-hide-block))
7162 (overlays-at start)))
7163 (if (or (not force) (eq force 'off))
7164 (mapc (lambda (ov)
7165 (when (member ov org-hide-block-overlays)
7166 (setq org-hide-block-overlays
7167 (delq ov org-hide-block-overlays)))
7168 (when (eq (overlay-get ov 'invisible)
7169 'org-hide-block)
7170 (delete-overlay ov)))
7171 (overlays-at start)))
7172 (setq ov (make-overlay start end))
7173 (overlay-put ov 'invisible 'org-hide-block)
7174 ;; make the block accessible to isearch
7175 (overlay-put
7176 ov 'isearch-open-invisible
7177 (lambda (ov)
7178 (when (member ov org-hide-block-overlays)
7179 (setq org-hide-block-overlays
7180 (delq ov org-hide-block-overlays)))
7181 (when (eq (overlay-get ov 'invisible)
7182 'org-hide-block)
7183 (delete-overlay ov))))
7184 (push ov org-hide-block-overlays)))
7185 (user-error "Not looking at a source block"))))
7187 ;; org-tab-after-check-for-cycling-hook
7188 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7189 ;; Remove overlays when changing major mode
7190 (add-hook 'org-mode-hook
7191 (lambda () (org-add-hook 'change-major-mode-hook
7192 'org-show-block-all 'append 'local)))
7194 ;;; Org-goto
7196 (defvar org-goto-window-configuration nil)
7197 (defvar org-goto-marker nil)
7198 (defvar org-goto-map)
7199 (defun org-goto-map ()
7200 "Set the keymap `org-goto'."
7201 (setq org-goto-map
7202 (let ((map (make-sparse-keymap)))
7203 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7204 mouse-drag-region universal-argument org-occur))
7205 cmd)
7206 (while (setq cmd (pop cmds))
7207 (substitute-key-definition cmd cmd map global-map)))
7208 (suppress-keymap map)
7209 (org-defkey map "\C-m" 'org-goto-ret)
7210 (org-defkey map [(return)] 'org-goto-ret)
7211 (org-defkey map [(left)] 'org-goto-left)
7212 (org-defkey map [(right)] 'org-goto-right)
7213 (org-defkey map [(control ?g)] 'org-goto-quit)
7214 (org-defkey map "\C-i" 'org-cycle)
7215 (org-defkey map [(tab)] 'org-cycle)
7216 (org-defkey map [(down)] 'outline-next-visible-heading)
7217 (org-defkey map [(up)] 'outline-previous-visible-heading)
7218 (if org-goto-auto-isearch
7219 (if (fboundp 'define-key-after)
7220 (define-key-after map [t] 'org-goto-local-auto-isearch)
7221 nil)
7222 (org-defkey map "q" 'org-goto-quit)
7223 (org-defkey map "n" 'outline-next-visible-heading)
7224 (org-defkey map "p" 'outline-previous-visible-heading)
7225 (org-defkey map "f" 'outline-forward-same-level)
7226 (org-defkey map "b" 'outline-backward-same-level)
7227 (org-defkey map "u" 'outline-up-heading))
7228 (org-defkey map "/" 'org-occur)
7229 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7230 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7231 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7232 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7233 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7234 map)))
7236 (defconst org-goto-help
7237 "Browse buffer copy, to find location or copy text.%s
7238 RET=jump to location C-g=quit and return to previous location
7239 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7241 (defvar org-goto-start-pos) ; dynamically scoped parameter
7243 (defun org-goto (&optional alternative-interface)
7244 "Look up a different location in the current file, keeping current visibility.
7246 When you want look-up or go to a different location in a
7247 document, the fastest way is often to fold the entire buffer and
7248 then dive into the tree. This method has the disadvantage, that
7249 the previous location will be folded, which may not be what you
7250 want.
7252 This command works around this by showing a copy of the current
7253 buffer in an indirect buffer, in overview mode. You can dive
7254 into the tree in that copy, use org-occur and incremental search
7255 to find a location. When pressing RET or `Q', the command
7256 returns to the original buffer in which the visibility is still
7257 unchanged. After RET it will also jump to the location selected
7258 in the indirect buffer and expose the headline hierarchy above.
7260 With a prefix argument, use the alternative interface: e.g. if
7261 `org-goto-interface' is 'outline use 'outline-path-completion."
7262 (interactive "P")
7263 (org-goto-map)
7264 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7265 (org-refile-use-outline-path t)
7266 (org-refile-target-verify-function nil)
7267 (interface
7268 (if (not alternative-interface)
7269 org-goto-interface
7270 (if (eq org-goto-interface 'outline)
7271 'outline-path-completion
7272 'outline)))
7273 (org-goto-start-pos (point))
7274 (selected-point
7275 (if (eq interface 'outline)
7276 (car (org-get-location (current-buffer) org-goto-help))
7277 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7278 (org-refile-check-position pa)
7279 (nth 3 pa)))))
7280 (if selected-point
7281 (progn
7282 (org-mark-ring-push org-goto-start-pos)
7283 (goto-char selected-point)
7284 (if (or (outline-invisible-p) (org-invisible-p2))
7285 (org-show-context 'org-goto)))
7286 (message "Quit"))))
7288 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7289 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7290 (defvar org-goto-local-auto-isearch-map) ; defined below
7292 (defun org-get-location (buf help)
7293 "Let the user select a location in the Org-mode buffer BUF.
7294 This function uses a recursive edit. It returns the selected position
7295 or nil."
7296 (org-no-popups
7297 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7298 (isearch-hide-immediately nil)
7299 (isearch-search-fun-function
7300 (lambda () 'org-goto-local-search-headings))
7301 (org-goto-selected-point org-goto-exit-command))
7302 (save-excursion
7303 (save-window-excursion
7304 (delete-other-windows)
7305 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7306 (org-pop-to-buffer-same-window
7307 (condition-case nil
7308 (make-indirect-buffer (current-buffer) "*org-goto*")
7309 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7310 (with-output-to-temp-buffer "*Org Help*"
7311 (princ (format help (if org-goto-auto-isearch
7312 " Just type for auto-isearch."
7313 " n/p/f/b/u to navigate, q to quit."))))
7314 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7315 (setq buffer-read-only nil)
7316 (let ((org-startup-truncated t)
7317 (org-startup-folded nil)
7318 (org-startup-align-all-tables nil))
7319 (org-mode)
7320 (org-overview))
7321 (setq buffer-read-only t)
7322 (if (and (boundp 'org-goto-start-pos)
7323 (integer-or-marker-p org-goto-start-pos))
7324 (let ((org-show-hierarchy-above t)
7325 (org-show-siblings t)
7326 (org-show-following-heading t))
7327 (goto-char org-goto-start-pos)
7328 (and (outline-invisible-p) (org-show-context)))
7329 (goto-char (point-min)))
7330 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7331 (message "Select location and press RET")
7332 (use-local-map org-goto-map)
7333 (recursive-edit)))
7334 (kill-buffer "*org-goto*")
7335 (cons org-goto-selected-point org-goto-exit-command))))
7337 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7338 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7339 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7340 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7342 (defun org-goto-local-search-headings (string bound noerror)
7343 "Search and make sure that any matches are in headlines."
7344 (catch 'return
7345 (while (if isearch-forward
7346 (search-forward string bound noerror)
7347 (search-backward string bound noerror))
7348 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7349 (and (member :headline context)
7350 (not (member :tags context))))
7351 (throw 'return (point))))))
7353 (defun org-goto-local-auto-isearch ()
7354 "Start isearch."
7355 (interactive)
7356 (goto-char (point-min))
7357 (let ((keys (this-command-keys)))
7358 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7359 (isearch-mode t)
7360 (isearch-process-search-char (string-to-char keys)))))
7362 (defun org-goto-ret (&optional arg)
7363 "Finish `org-goto' by going to the new location."
7364 (interactive "P")
7365 (setq org-goto-selected-point (point)
7366 org-goto-exit-command 'return)
7367 (throw 'exit nil))
7369 (defun org-goto-left ()
7370 "Finish `org-goto' by going to the new location."
7371 (interactive)
7372 (if (org-at-heading-p)
7373 (progn
7374 (beginning-of-line 1)
7375 (setq org-goto-selected-point (point)
7376 org-goto-exit-command 'left)
7377 (throw 'exit nil))
7378 (user-error "Not on a heading")))
7380 (defun org-goto-right ()
7381 "Finish `org-goto' by going to the new location."
7382 (interactive)
7383 (if (org-at-heading-p)
7384 (progn
7385 (setq org-goto-selected-point (point)
7386 org-goto-exit-command 'right)
7387 (throw 'exit nil))
7388 (user-error "Not on a heading")))
7390 (defun org-goto-quit ()
7391 "Finish `org-goto' without cursor motion."
7392 (interactive)
7393 (setq org-goto-selected-point nil)
7394 (setq org-goto-exit-command 'quit)
7395 (throw 'exit nil))
7397 ;;; Indirect buffer display of subtrees
7399 (defvar org-indirect-dedicated-frame nil
7400 "This is the frame being used for indirect tree display.")
7401 (defvar org-last-indirect-buffer nil)
7403 (defun org-tree-to-indirect-buffer (&optional arg)
7404 "Create indirect buffer and narrow it to current subtree.
7405 With a numerical prefix ARG, go up to this level and then take that tree.
7406 If ARG is negative, go up that many levels.
7408 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7409 indirect buffer previously made with this command, to avoid proliferation of
7410 indirect buffers. However, when you call the command with a \
7411 \\[universal-argument] prefix, or
7412 when `org-indirect-buffer-display' is `new-frame', the last buffer
7413 is kept so that you can work with several indirect buffers at the same time.
7414 If `org-indirect-buffer-display' is `dedicated-frame', the \
7415 \\[universal-argument] prefix also
7416 requests that a new frame be made for the new buffer, so that the dedicated
7417 frame is not changed."
7418 (interactive "P")
7419 (let ((cbuf (current-buffer))
7420 (cwin (selected-window))
7421 (pos (point))
7422 beg end level heading ibuf)
7423 (save-excursion
7424 (org-back-to-heading t)
7425 (when (numberp arg)
7426 (setq level (org-outline-level))
7427 (if (< arg 0) (setq arg (+ level arg)))
7428 (while (> (setq level (org-outline-level)) arg)
7429 (org-up-heading-safe)))
7430 (setq beg (point)
7431 heading (org-get-heading))
7432 (org-end-of-subtree t t)
7433 (if (org-at-heading-p) (backward-char 1))
7434 (setq end (point)))
7435 (if (and (buffer-live-p org-last-indirect-buffer)
7436 (not (eq org-indirect-buffer-display 'new-frame))
7437 (not arg))
7438 (kill-buffer org-last-indirect-buffer))
7439 (setq ibuf (org-get-indirect-buffer cbuf)
7440 org-last-indirect-buffer ibuf)
7441 (cond
7442 ((or (eq org-indirect-buffer-display 'new-frame)
7443 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7444 (select-frame (make-frame))
7445 (delete-other-windows)
7446 (org-pop-to-buffer-same-window ibuf)
7447 (org-set-frame-title heading))
7448 ((eq org-indirect-buffer-display 'dedicated-frame)
7449 (raise-frame
7450 (select-frame (or (and org-indirect-dedicated-frame
7451 (frame-live-p org-indirect-dedicated-frame)
7452 org-indirect-dedicated-frame)
7453 (setq org-indirect-dedicated-frame (make-frame)))))
7454 (delete-other-windows)
7455 (org-pop-to-buffer-same-window ibuf)
7456 (org-set-frame-title (concat "Indirect: " heading)))
7457 ((eq org-indirect-buffer-display 'current-window)
7458 (org-pop-to-buffer-same-window ibuf))
7459 ((eq org-indirect-buffer-display 'other-window)
7460 (pop-to-buffer ibuf))
7461 (t (error "Invalid value")))
7462 (if (featurep 'xemacs)
7463 (save-excursion (org-mode) (turn-on-font-lock)))
7464 (narrow-to-region beg end)
7465 (show-all)
7466 (goto-char pos)
7467 (run-hook-with-args 'org-cycle-hook 'all)
7468 (and (window-live-p cwin) (select-window cwin))))
7470 (defun org-get-indirect-buffer (&optional buffer)
7471 (setq buffer (or buffer (current-buffer)))
7472 (let ((n 1) (base (buffer-name buffer)) bname)
7473 (while (buffer-live-p
7474 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7475 (setq n (1+ n)))
7476 (condition-case nil
7477 (make-indirect-buffer buffer bname 'clone)
7478 (error (make-indirect-buffer buffer bname)))))
7480 (defun org-set-frame-title (title)
7481 "Set the title of the current frame to the string TITLE."
7482 ;; FIXME: how to name a single frame in XEmacs???
7483 (unless (featurep 'xemacs)
7484 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7486 ;;;; Structure editing
7488 ;;; Inserting headlines
7490 (defun org-previous-line-empty-p (&optional next)
7491 "Is the previous line a blank line?
7492 When NEXT is non-nil, check the next line instead."
7493 (save-excursion
7494 (and (not (bobp))
7495 (or (beginning-of-line (if next 2 0)) t)
7496 (save-match-data
7497 (looking-at "[ \t]*$")))))
7499 (defun org-insert-heading (&optional arg invisible-ok)
7500 "Insert a new heading or item with same depth at point.
7501 If point is in a plain list and ARG is nil, create a new list item.
7502 With one universal prefix argument, insert a heading even in lists.
7503 With two universal prefix arguments, insert the heading at the end
7504 of the parent subtree.
7506 If point is at the beginning of a headline, insert a sibling before
7507 the current headline. If point is not at the beginning, split the line
7508 and create a new headline with the text in the current line after point
7509 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7511 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7512 This is important for non-interactive uses of the command."
7513 (interactive "P")
7514 (if (org-called-interactively-p 'any) (org-reveal))
7515 (let ((itemp (org-in-item-p)))
7516 (cond
7517 ((or (= (buffer-size) 0)
7518 (and (not (save-excursion
7519 (and (ignore-errors (org-back-to-heading invisible-ok))
7520 (org-at-heading-p))))
7521 (or arg (not itemp))))
7522 (insert
7523 (if (org-previous-line-empty-p) "" "\n")
7524 (if (org-in-src-block-p) ",* " "* "))
7525 (run-hooks 'org-insert-heading-hook))
7526 ((or arg
7527 (and (not itemp) org-insert-heading-respect-content)
7528 (not (org-insert-item
7529 (save-excursion
7530 (and itemp
7531 (goto-char itemp)
7532 (looking-at org-list-full-item-re)
7533 (match-string 3))))))
7534 (let (begn endn)
7535 (when (org-buffer-narrowed-p)
7536 (setq begn (point-min) endn (point-max))
7537 (widen))
7538 (let* ((empty-line-p nil)
7539 (eops (equal arg '(16))) ; insert at end of parent subtree
7540 (org-insert-heading-respect-content
7541 (or (not (null arg)) org-insert-heading-respect-content))
7542 (level nil)
7543 (on-heading (org-at-heading-p))
7544 ;; Get a level to fall back on
7545 (fix-level
7546 (save-excursion
7547 (org-back-to-heading t)
7548 (looking-at org-outline-regexp)
7549 (make-string (1- (length (match-string 0))) ?*)))
7550 (on-empty-line
7551 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7552 (head (save-excursion
7553 (condition-case nil
7554 (progn
7555 (org-back-to-heading invisible-ok)
7556 (when (and (not on-heading)
7557 (featurep 'org-inlinetask)
7558 (integerp org-inlinetask-min-level)
7559 (>= (length (match-string 0))
7560 org-inlinetask-min-level))
7561 ;; Find a heading level before the inline task
7562 (while (and (setq level (org-up-heading-safe))
7563 (>= level org-inlinetask-min-level)))
7564 (if (org-at-heading-p)
7565 (org-back-to-heading invisible-ok)
7566 (error "This should not happen")))
7567 (unless (and (save-excursion
7568 (save-match-data
7569 (org-backward-heading-same-level 1 invisible-ok))
7570 (= (point) (match-beginning 0)))
7571 (not (org-previous-line-empty-p t)))
7572 (setq empty-line-p (org-previous-line-empty-p)))
7573 (match-string 0))
7574 (error (or fix-level "* ")))))
7575 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7576 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7577 pos hide-previous previous-pos)
7578 (if ;; At the beginning of a heading, open a new line for insertion
7579 (and (bolp) (org-at-heading-p)
7580 (not eops)
7581 (or (bobp)
7582 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7583 (open-line (if blank 2 1))
7584 (save-excursion
7585 (setq previous-pos (point-at-bol))
7586 (end-of-line)
7587 (setq hide-previous (outline-invisible-p)))
7588 (and org-insert-heading-respect-content
7589 (save-excursion
7590 (while (outline-invisible-p)
7591 (org-show-subtree)
7592 (org-up-heading-safe))))
7593 (let ((split
7594 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7595 (save-excursion
7596 (let ((p (point)))
7597 (goto-char (point-at-bol))
7598 (and (looking-at org-complex-heading-regexp)
7599 (match-beginning 4)
7600 (> p (match-beginning 4)))))))
7601 tags pos)
7602 (cond
7603 ;; Insert a new line, possibly at end of parent subtree
7604 ((and (not arg) (not on-heading) (not on-empty-line)
7605 (not (save-excursion
7606 (beginning-of-line 1)
7607 (or (looking-at org-list-full-item-re)
7608 ;; Don't convert :end: lines to headline
7609 (looking-at "^\\s-*:end:")
7610 (looking-at "^\\s-*#\\+end_?")))))
7611 (beginning-of-line 1))
7612 (org-insert-heading-respect-content
7613 (if (not eops)
7614 (progn
7615 (org-end-of-subtree nil t)
7616 (and (looking-at "^\\*") (backward-char 1))
7617 (while (and (not (bobp))
7618 ;; Don't delete spaces in empty headlines
7619 (not (looking-back org-outline-regexp))
7620 (member (char-before) '(?\ ?\t ?\n)))
7621 (backward-delete-char 1)))
7622 (let ((p (point)))
7623 (org-up-heading-safe)
7624 (if (= p (point))
7625 (goto-char (point-max))
7626 (org-end-of-subtree nil t))))
7627 (when (featurep 'org-inlinetask)
7628 (while (and (not (eobp))
7629 (looking-at "\\(\\*+\\)[ \t]+")
7630 (>= (length (match-string 1))
7631 org-inlinetask-min-level))
7632 (org-end-of-subtree nil t)))
7633 (or (bolp) (newline))
7634 (or (org-previous-line-empty-p)
7635 (and blank (newline)))
7636 (if (or empty-line-p eops) (open-line 1)))
7637 ;; Insert a headling containing text after point
7638 ((org-at-heading-p)
7639 (when hide-previous
7640 (show-children)
7641 (org-show-entry))
7642 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7643 (setq tags (and (match-end 2) (match-string 2)))
7644 (and (match-end 1)
7645 (delete-region (match-beginning 1) (match-end 1)))
7646 (setq pos (point-at-bol))
7647 (or split (end-of-line 1))
7648 (delete-horizontal-space)
7649 (if (string-match "\\`\\*+\\'"
7650 (buffer-substring (point-at-bol) (point)))
7651 (insert " "))
7652 (newline (if blank 2 1))
7653 (when tags
7654 (save-excursion
7655 (goto-char pos)
7656 (end-of-line 1)
7657 (insert " " tags)
7658 (org-set-tags nil 'align))))
7660 (or split (end-of-line 1))
7661 (newline (cond ((and blank (not on-empty-line)) 2)
7662 (blank 1)
7663 (on-empty-line 0) (t 1)))))))
7664 (insert head) (just-one-space)
7665 (setq pos (point))
7666 (end-of-line 1)
7667 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7668 (when (and org-insert-heading-respect-content hide-previous)
7669 (save-excursion
7670 (goto-char previous-pos)
7671 (hide-subtree)))
7672 (when (and begn endn)
7673 (narrow-to-region (min (point) begn) (max (point) endn)))
7674 (run-hooks 'org-insert-heading-hook)))))))
7676 (defun org-get-heading (&optional no-tags no-todo)
7677 "Return the heading of the current entry, without the stars.
7678 When NO-TAGS is non-nil, don't include tags.
7679 When NO-TODO is non-nil, don't include TODO keywords."
7680 (save-excursion
7681 (org-back-to-heading t)
7682 (cond
7683 ((and no-tags no-todo)
7684 (looking-at org-complex-heading-regexp)
7685 (match-string 4))
7686 (no-tags
7687 (looking-at (concat org-outline-regexp
7688 "\\(.*?\\)"
7689 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7690 (match-string 1))
7691 (no-todo
7692 (looking-at org-todo-line-regexp)
7693 (match-string 3))
7694 (t (looking-at org-heading-regexp)
7695 (match-string 2)))))
7697 (defvar orgstruct-mode) ; defined below
7699 (defun org-heading-components ()
7700 "Return the components of the current heading.
7701 This is a list with the following elements:
7702 - the level as an integer
7703 - the reduced level, different if `org-odd-levels-only' is set.
7704 - the TODO keyword, or nil
7705 - the priority character, like ?A, or nil if no priority is given
7706 - the headline text itself, or the tags string if no headline text
7707 - the tags string, or nil."
7708 (save-excursion
7709 (org-back-to-heading t)
7710 (if (let (case-fold-search)
7711 (looking-at
7712 (if orgstruct-mode
7713 org-heading-regexp
7714 org-complex-heading-regexp)))
7715 (if orgstruct-mode
7716 (list (length (match-string 1))
7717 (org-reduced-level (length (match-string 1)))
7720 (match-string 2)
7721 nil)
7722 (list (length (match-string 1))
7723 (org-reduced-level (length (match-string 1)))
7724 (org-match-string-no-properties 2)
7725 (and (match-end 3) (aref (match-string 3) 2))
7726 (org-match-string-no-properties 4)
7727 (org-match-string-no-properties 5))))))
7729 (defun org-get-entry ()
7730 "Get the entry text, after heading, entire subtree."
7731 (save-excursion
7732 (org-back-to-heading t)
7733 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7735 (defun org-insert-heading-after-current ()
7736 "Insert a new heading with same level as current, after current subtree."
7737 (interactive)
7738 (org-back-to-heading)
7739 (org-insert-heading)
7740 (org-move-subtree-down)
7741 (end-of-line 1))
7743 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7744 "Insert heading with `org-insert-heading-respect-content' set to t."
7745 (interactive "P")
7746 (let ((org-insert-heading-respect-content t))
7747 (org-insert-heading arg invisible-ok)))
7749 (defun org-insert-todo-heading-respect-content (&optional force-state)
7750 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7751 (interactive "P")
7752 (let ((org-insert-heading-respect-content t))
7753 (org-insert-todo-heading force-state t)))
7755 (defun org-insert-todo-heading (arg &optional force-heading)
7756 "Insert a new heading with the same level and TODO state as current heading.
7757 If the heading has no TODO state, or if the state is DONE, use the first
7758 state (TODO by default). Also one prefix arg, force first state. With two
7759 prefix args, force inserting at the end of the parent subtree."
7760 (interactive "P")
7761 (when (or force-heading (not (org-insert-item 'checkbox)))
7762 (org-insert-heading (or (and (equal arg '(16)) '(16))
7763 force-heading))
7764 (save-excursion
7765 (org-back-to-heading)
7766 (outline-previous-heading)
7767 (looking-at org-todo-line-regexp))
7768 (let*
7769 ((new-mark-x
7770 (if (or arg
7771 (not (match-beginning 2))
7772 (member (match-string 2) org-done-keywords))
7773 (car org-todo-keywords-1)
7774 (match-string 2)))
7775 (new-mark
7777 (run-hook-with-args-until-success
7778 'org-todo-get-default-hook new-mark-x nil)
7779 new-mark-x)))
7780 (beginning-of-line 1)
7781 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7782 (if org-treat-insert-todo-heading-as-state-change
7783 (org-todo new-mark)
7784 (insert new-mark " "))))
7785 (when org-provide-todo-statistics
7786 (org-update-parent-todo-statistics))))
7788 (defun org-insert-subheading (arg)
7789 "Insert a new subheading and demote it.
7790 Works for outline headings and for plain lists alike."
7791 (interactive "P")
7792 (org-insert-heading arg)
7793 (cond
7794 ((org-at-heading-p) (org-do-demote))
7795 ((org-at-item-p) (org-indent-item))))
7797 (defun org-insert-todo-subheading (arg)
7798 "Insert a new subheading with TODO keyword or checkbox and demote it.
7799 Works for outline headings and for plain lists alike."
7800 (interactive "P")
7801 (org-insert-todo-heading arg)
7802 (cond
7803 ((org-at-heading-p) (org-do-demote))
7804 ((org-at-item-p) (org-indent-item))))
7806 ;;; Promotion and Demotion
7808 (defvar org-after-demote-entry-hook nil
7809 "Hook run after an entry has been demoted.
7810 The cursor will be at the beginning of the entry.
7811 When a subtree is being demoted, the hook will be called for each node.")
7813 (defvar org-after-promote-entry-hook nil
7814 "Hook run after an entry has been promoted.
7815 The cursor will be at the beginning of the entry.
7816 When a subtree is being promoted, the hook will be called for each node.")
7818 (defun org-promote-subtree ()
7819 "Promote the entire subtree.
7820 See also `org-promote'."
7821 (interactive)
7822 (save-excursion
7823 (org-with-limited-levels (org-map-tree 'org-promote)))
7824 (org-fix-position-after-promote))
7826 (defun org-demote-subtree ()
7827 "Demote the entire subtree. See `org-demote'.
7828 See also `org-promote'."
7829 (interactive)
7830 (save-excursion
7831 (org-with-limited-levels (org-map-tree 'org-demote)))
7832 (org-fix-position-after-promote))
7835 (defun org-do-promote ()
7836 "Promote the current heading higher up the tree.
7837 If the region is active in `transient-mark-mode', promote all headings
7838 in the region."
7839 (interactive)
7840 (save-excursion
7841 (if (org-region-active-p)
7842 (org-map-region 'org-promote (region-beginning) (region-end))
7843 (org-promote)))
7844 (org-fix-position-after-promote))
7846 (defun org-do-demote ()
7847 "Demote the current heading lower down the tree.
7848 If the region is active in `transient-mark-mode', demote all headings
7849 in the region."
7850 (interactive)
7851 (save-excursion
7852 (if (org-region-active-p)
7853 (org-map-region 'org-demote (region-beginning) (region-end))
7854 (org-demote)))
7855 (org-fix-position-after-promote))
7857 (defun org-fix-position-after-promote ()
7858 "Make sure that after pro/demotion cursor position is right."
7859 (let ((pos (point)))
7860 (when (save-excursion
7861 (beginning-of-line 1)
7862 (looking-at org-todo-line-regexp)
7863 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7864 (cond ((eobp) (insert " "))
7865 ((eolp) (insert " "))
7866 ((equal (char-after) ?\ ) (forward-char 1))))))
7868 (defun org-current-level ()
7869 "Return the level of the current entry, or nil if before the first headline.
7870 The level is the number of stars at the beginning of the headline."
7871 (save-excursion
7872 (org-with-limited-levels
7873 (if (ignore-errors (org-back-to-heading t))
7874 (funcall outline-level)))))
7876 (defun org-get-previous-line-level ()
7877 "Return the outline depth of the last headline before the current line.
7878 Returns 0 for the first headline in the buffer, and nil if before the
7879 first headline."
7880 (let ((current-level (org-current-level))
7881 (prev-level (when (> (line-number-at-pos) 1)
7882 (save-excursion
7883 (beginning-of-line 0)
7884 (org-current-level)))))
7885 (cond ((null current-level) nil) ; Before first headline
7886 ((null prev-level) 0) ; At first headline
7887 (prev-level))))
7889 (defun org-reduced-level (l)
7890 "Compute the effective level of a heading.
7891 This takes into account the setting of `org-odd-levels-only'."
7892 (cond
7893 ((zerop l) 0)
7894 (org-odd-levels-only (1+ (floor (/ l 2))))
7895 (t l)))
7897 (defun org-level-increment ()
7898 "Return the number of stars that will be added or removed at a
7899 time to headlines when structure editing, based on the value of
7900 `org-odd-levels-only'."
7901 (if org-odd-levels-only 2 1))
7903 (defun org-get-valid-level (level &optional change)
7904 "Rectify a level change under the influence of `org-odd-levels-only'
7905 LEVEL is a current level, CHANGE is by how much the level should be
7906 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7907 even level numbers will become the next higher odd number."
7908 (if org-odd-levels-only
7909 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7910 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7911 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7912 (max 1 (+ level (or change 0)))))
7914 (if (boundp 'define-obsolete-function-alias)
7915 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7916 (define-obsolete-function-alias 'org-get-legal-level
7917 'org-get-valid-level)
7918 (define-obsolete-function-alias 'org-get-legal-level
7919 'org-get-valid-level "23.1")))
7921 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7922 ;; ̀org-with-limited-levels'
7923 (defun org-promote ()
7924 "Promote the current heading higher up the tree.
7925 If the region is active in `transient-mark-mode', promote all headings
7926 in the region."
7927 (org-back-to-heading t)
7928 (let* ((level (save-match-data (funcall outline-level)))
7929 (after-change-functions (remove 'flyspell-after-change-function
7930 after-change-functions))
7931 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7932 (diff (abs (- level (length up-head) -1))))
7933 (cond ((and (= level 1) org-called-with-limited-levels
7934 org-allow-promoting-top-level-subtree)
7935 (replace-match "# " nil t))
7936 ((= level 1)
7937 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7938 (t (replace-match up-head nil t)))
7939 ;; Fixup tag positioning
7940 (unless (= level 1)
7941 (and org-auto-align-tags (org-set-tags nil t))
7942 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7943 (run-hooks 'org-after-promote-entry-hook)))
7945 (defun org-demote ()
7946 "Demote the current heading lower down the tree.
7947 If the region is active in `transient-mark-mode', demote all headings
7948 in the region."
7949 (org-back-to-heading t)
7950 (let* ((level (save-match-data (funcall outline-level)))
7951 (after-change-functions (remove 'flyspell-after-change-function
7952 after-change-functions))
7953 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7954 (diff (abs (- level (length down-head) -1))))
7955 (replace-match down-head nil t)
7956 ;; Fixup tag positioning
7957 (and org-auto-align-tags (org-set-tags nil t))
7958 (if org-adapt-indentation (org-fixup-indentation diff))
7959 (run-hooks 'org-after-demote-entry-hook)))
7961 (defun org-cycle-level ()
7962 "Cycle the level of an empty headline through possible states.
7963 This goes first to child, then to parent, level, then up the hierarchy.
7964 After top level, it switches back to sibling level."
7965 (interactive)
7966 (let ((org-adapt-indentation nil))
7967 (when (org-point-at-end-of-empty-headline)
7968 (setq this-command 'org-cycle-level) ; Only needed for caching
7969 (let ((cur-level (org-current-level))
7970 (prev-level (org-get-previous-line-level)))
7971 (cond
7972 ;; If first headline in file, promote to top-level.
7973 ((= prev-level 0)
7974 (loop repeat (/ (- cur-level 1) (org-level-increment))
7975 do (org-do-promote)))
7976 ;; If same level as prev, demote one.
7977 ((= prev-level cur-level)
7978 (org-do-demote))
7979 ;; If parent is top-level, promote to top level if not already.
7980 ((= prev-level 1)
7981 (loop repeat (/ (- cur-level 1) (org-level-increment))
7982 do (org-do-promote)))
7983 ;; If top-level, return to prev-level.
7984 ((= cur-level 1)
7985 (loop repeat (/ (- prev-level 1) (org-level-increment))
7986 do (org-do-demote)))
7987 ;; If less than prev-level, promote one.
7988 ((< cur-level prev-level)
7989 (org-do-promote))
7990 ;; If deeper than prev-level, promote until higher than
7991 ;; prev-level.
7992 ((> cur-level prev-level)
7993 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7994 do (org-do-promote))))
7995 t))))
7997 (defun org-map-tree (fun)
7998 "Call FUN for every heading underneath the current one."
7999 (org-back-to-heading)
8000 (let ((level (funcall outline-level)))
8001 (save-excursion
8002 (funcall fun)
8003 (while (and (progn
8004 (outline-next-heading)
8005 (> (funcall outline-level) level))
8006 (not (eobp)))
8007 (funcall fun)))))
8009 (defun org-map-region (fun beg end)
8010 "Call FUN for every heading between BEG and END."
8011 (let ((org-ignore-region t))
8012 (save-excursion
8013 (setq end (copy-marker end))
8014 (goto-char beg)
8015 (if (and (re-search-forward org-outline-regexp-bol nil t)
8016 (< (point) end))
8017 (funcall fun))
8018 (while (and (progn
8019 (outline-next-heading)
8020 (< (point) end))
8021 (not (eobp)))
8022 (funcall fun)))))
8024 (defvar org-property-end-re) ; silence byte-compiler
8025 (defun org-fixup-indentation (diff)
8026 "Change the indentation in the current entry by DIFF.
8027 However, if any line in the current entry has no indentation, or if it
8028 would end up with no indentation after the change, nothing at all is done."
8029 (save-excursion
8030 (let ((end (save-excursion (outline-next-heading)
8031 (point-marker)))
8032 (prohibit (if (> diff 0)
8033 "^\\S-"
8034 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8035 col)
8036 (unless (save-excursion (end-of-line 1)
8037 (re-search-forward prohibit end t))
8038 (while (and (< (point) end)
8039 (re-search-forward "^[ \t]+" end t))
8040 (goto-char (match-end 0))
8041 (setq col (current-column))
8042 (if (< diff 0) (replace-match ""))
8043 (org-indent-to-column (+ diff col))))
8044 (move-marker end nil))))
8046 (defun org-convert-to-odd-levels ()
8047 "Convert an org-mode file with all levels allowed to one with odd levels.
8048 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8049 level 5 etc."
8050 (interactive)
8051 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8052 (let ((outline-level 'org-outline-level)
8053 (org-odd-levels-only nil) n)
8054 (save-excursion
8055 (goto-char (point-min))
8056 (while (re-search-forward "^\\*\\*+ " nil t)
8057 (setq n (- (length (match-string 0)) 2))
8058 (while (>= (setq n (1- n)) 0)
8059 (org-demote))
8060 (end-of-line 1))))))
8062 (defun org-convert-to-oddeven-levels ()
8063 "Convert an org-mode file with only odd levels to one with odd/even levels.
8064 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8065 file contains a section with an even level, conversion would
8066 destroy the structure of the file. An error is signaled in this
8067 case."
8068 (interactive)
8069 (goto-char (point-min))
8070 ;; First check if there are no even levels
8071 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8072 (org-show-context t)
8073 (error "Not all levels are odd in this file. Conversion not possible"))
8074 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8075 (let ((outline-regexp org-outline-regexp)
8076 (outline-level 'org-outline-level)
8077 (org-odd-levels-only nil) n)
8078 (save-excursion
8079 (goto-char (point-min))
8080 (while (re-search-forward "^\\*\\*+ " nil t)
8081 (setq n (/ (1- (length (match-string 0))) 2))
8082 (while (>= (setq n (1- n)) 0)
8083 (org-promote))
8084 (end-of-line 1))))))
8086 (defun org-tr-level (n)
8087 "Make N odd if required."
8088 (if org-odd-levels-only (1+ (/ n 2)) n))
8090 ;;; Vertical tree motion, cutting and pasting of subtrees
8092 (defun org-move-subtree-up (&optional arg)
8093 "Move the current subtree up past ARG headlines of the same level."
8094 (interactive "p")
8095 (org-move-subtree-down (- (prefix-numeric-value arg))))
8097 (defun org-move-subtree-down (&optional arg)
8098 "Move the current subtree down past ARG headlines of the same level."
8099 (interactive "p")
8100 (setq arg (prefix-numeric-value arg))
8101 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8102 'org-get-last-sibling))
8103 (ins-point (make-marker))
8104 (cnt (abs arg))
8105 (col (current-column))
8106 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8107 ;; Select the tree
8108 (org-back-to-heading)
8109 (setq beg0 (point))
8110 (save-excursion
8111 (setq ne-beg (org-back-over-empty-lines))
8112 (setq beg (point)))
8113 (save-match-data
8114 (save-excursion (outline-end-of-heading)
8115 (setq folded (outline-invisible-p)))
8116 (outline-end-of-subtree))
8117 (outline-next-heading)
8118 (setq ne-end (org-back-over-empty-lines))
8119 (setq end (point))
8120 (goto-char beg0)
8121 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8122 ;; include less whitespace
8123 (save-excursion
8124 (goto-char beg)
8125 (forward-line (- ne-beg ne-end))
8126 (setq beg (point))))
8127 ;; Find insertion point, with error handling
8128 (while (> cnt 0)
8129 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8130 (progn (goto-char beg0)
8131 (user-error "Cannot move past superior level or buffer limit")))
8132 (setq cnt (1- cnt)))
8133 (if (> arg 0)
8134 ;; Moving forward - still need to move over subtree
8135 (progn (org-end-of-subtree t t)
8136 (save-excursion
8137 (org-back-over-empty-lines)
8138 (or (bolp) (newline)))))
8139 (setq ne-ins (org-back-over-empty-lines))
8140 (move-marker ins-point (point))
8141 (setq txt (buffer-substring beg end))
8142 (org-save-markers-in-region beg end)
8143 (delete-region beg end)
8144 (org-remove-empty-overlays-at beg)
8145 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8146 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8147 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8148 (let ((bbb (point)))
8149 (insert-before-markers txt)
8150 (org-reinstall-markers-in-region bbb)
8151 (move-marker ins-point bbb))
8152 (or (bolp) (insert "\n"))
8153 (setq ins-end (point))
8154 (goto-char ins-point)
8155 (org-skip-whitespace)
8156 (when (and (< arg 0)
8157 (org-first-sibling-p)
8158 (> ne-ins ne-beg))
8159 ;; Move whitespace back to beginning
8160 (save-excursion
8161 (goto-char ins-end)
8162 (let ((kill-whole-line t))
8163 (kill-line (- ne-ins ne-beg)) (point)))
8164 (insert (make-string (- ne-ins ne-beg) ?\n)))
8165 (move-marker ins-point nil)
8166 (if folded
8167 (hide-subtree)
8168 (org-show-entry)
8169 (show-children)
8170 (org-cycle-hide-drawers 'children))
8171 (org-clean-visibility-after-subtree-move)
8172 ;; move back to the initial column we were at
8173 (move-to-column col)))
8175 (defvar org-subtree-clip ""
8176 "Clipboard for cut and paste of subtrees.
8177 This is actually only a copy of the kill, because we use the normal kill
8178 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8180 (defvar org-subtree-clip-folded nil
8181 "Was the last copied subtree folded?
8182 This is used to fold the tree back after pasting.")
8184 (defun org-cut-subtree (&optional n)
8185 "Cut the current subtree into the clipboard.
8186 With prefix arg N, cut this many sequential subtrees.
8187 This is a short-hand for marking the subtree and then cutting it."
8188 (interactive "p")
8189 (org-copy-subtree n 'cut))
8191 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8192 "Cut the current subtree into the clipboard.
8193 With prefix arg N, cut this many sequential subtrees.
8194 This is a short-hand for marking the subtree and then copying it.
8195 If CUT is non-nil, actually cut the subtree.
8196 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8197 of some markers in the region, even if CUT is non-nil. This is
8198 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8199 (interactive "p")
8200 (let (beg end folded (beg0 (point)))
8201 (if (org-called-interactively-p 'any)
8202 (org-back-to-heading nil) ; take what looks like a subtree
8203 (org-back-to-heading t)) ; take what is really there
8204 (setq beg (point))
8205 (skip-chars-forward " \t\r\n")
8206 (save-match-data
8207 (if nosubtrees
8208 (outline-next-heading)
8209 (save-excursion (outline-end-of-heading)
8210 (setq folded (outline-invisible-p)))
8211 (condition-case nil
8212 (org-forward-heading-same-level (1- n) t)
8213 (error nil))
8214 (org-end-of-subtree t t)))
8215 (setq end (point))
8216 (goto-char beg0)
8217 (when (> end beg)
8218 (setq org-subtree-clip-folded folded)
8219 (when (or cut force-store-markers)
8220 (org-save-markers-in-region beg end))
8221 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8222 (setq org-subtree-clip (current-kill 0))
8223 (message "%s: Subtree(s) with %d characters"
8224 (if cut "Cut" "Copied")
8225 (length org-subtree-clip)))))
8227 (defun org-paste-subtree (&optional level tree for-yank)
8228 "Paste the clipboard as a subtree, with modification of headline level.
8229 The entire subtree is promoted or demoted in order to match a new headline
8230 level.
8232 If the cursor is at the beginning of a headline, the same level as
8233 that headline is used to paste the tree.
8235 If not, the new level is derived from the *visible* headings
8236 before and after the insertion point, and taken to be the inferior headline
8237 level of the two. So if the previous visible heading is level 3 and the
8238 next is level 4 (or vice versa), level 4 will be used for insertion.
8239 This makes sure that the subtree remains an independent subtree and does
8240 not swallow low level entries.
8242 You can also force a different level, either by using a numeric prefix
8243 argument, or by inserting the heading marker by hand. For example, if the
8244 cursor is after \"*****\", then the tree will be shifted to level 5.
8246 If optional TREE is given, use this text instead of the kill ring.
8248 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8249 move back over whitespace before inserting, and move point to the end of
8250 the inserted text when done."
8251 (interactive "P")
8252 (setq tree (or tree (and kill-ring (current-kill 0))))
8253 (unless (org-kill-is-subtree-p tree)
8254 (user-error "%s"
8255 (substitute-command-keys
8256 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8257 (org-with-limited-levels
8258 (let* ((visp (not (outline-invisible-p)))
8259 (txt tree)
8260 (^re_ "\\(\\*+\\)[ \t]*")
8261 (old-level (if (string-match org-outline-regexp-bol txt)
8262 (- (match-end 0) (match-beginning 0) 1)
8263 -1))
8264 (force-level (cond (level (prefix-numeric-value level))
8265 ((and (looking-at "[ \t]*$")
8266 (string-match
8267 "^\\*+$" (buffer-substring
8268 (point-at-bol) (point))))
8269 (- (match-end 1) (match-beginning 1)))
8270 ((and (bolp)
8271 (looking-at org-outline-regexp))
8272 (- (match-end 0) (point) 1))))
8273 (previous-level (save-excursion
8274 (condition-case nil
8275 (progn
8276 (outline-previous-visible-heading 1)
8277 (if (looking-at ^re_)
8278 (- (match-end 0) (match-beginning 0) 1)
8280 (error 1))))
8281 (next-level (save-excursion
8282 (condition-case nil
8283 (progn
8284 (or (looking-at org-outline-regexp)
8285 (outline-next-visible-heading 1))
8286 (if (looking-at ^re_)
8287 (- (match-end 0) (match-beginning 0) 1)
8289 (error 1))))
8290 (new-level (or force-level (max previous-level next-level)))
8291 (shift (if (or (= old-level -1)
8292 (= new-level -1)
8293 (= old-level new-level))
8295 (- new-level old-level)))
8296 (delta (if (> shift 0) -1 1))
8297 (func (if (> shift 0) 'org-demote 'org-promote))
8298 (org-odd-levels-only nil)
8299 beg end newend)
8300 ;; Remove the forced level indicator
8301 (if force-level
8302 (delete-region (point-at-bol) (point)))
8303 ;; Paste
8304 (beginning-of-line (if (bolp) 1 2))
8305 (setq beg (point))
8306 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8307 (insert-before-markers txt)
8308 (unless (string-match "\n\\'" txt) (insert "\n"))
8309 (setq newend (point))
8310 (org-reinstall-markers-in-region beg)
8311 (setq end (point))
8312 (goto-char beg)
8313 (skip-chars-forward " \t\n\r")
8314 (setq beg (point))
8315 (if (and (outline-invisible-p) visp)
8316 (save-excursion (outline-show-heading)))
8317 ;; Shift if necessary
8318 (unless (= shift 0)
8319 (save-restriction
8320 (narrow-to-region beg end)
8321 (while (not (= shift 0))
8322 (org-map-region func (point-min) (point-max))
8323 (setq shift (+ delta shift)))
8324 (goto-char (point-min))
8325 (setq newend (point-max))))
8326 (when (or (org-called-interactively-p 'interactive) for-yank)
8327 (message "Clipboard pasted as level %d subtree" new-level))
8328 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8329 kill-ring
8330 (eq org-subtree-clip (current-kill 0))
8331 org-subtree-clip-folded)
8332 ;; The tree was folded before it was killed/copied
8333 (hide-subtree))
8334 (and for-yank (goto-char newend)))))
8336 (defun org-kill-is-subtree-p (&optional txt)
8337 "Check if the current kill is an outline subtree, or a set of trees.
8338 Returns nil if kill does not start with a headline, or if the first
8339 headline level is not the largest headline level in the tree.
8340 So this will actually accept several entries of equal levels as well,
8341 which is OK for `org-paste-subtree'.
8342 If optional TXT is given, check this string instead of the current kill."
8343 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8344 (re (org-get-limited-outline-regexp))
8345 (^re (concat "^" re))
8346 (start-level (and kill
8347 (string-match
8348 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8349 kill)
8350 (- (match-end 2) (match-beginning 2) 1)))
8351 (start (1+ (or (match-beginning 2) -1))))
8352 (if (not start-level)
8353 (progn
8354 nil) ;; does not even start with a heading
8355 (catch 'exit
8356 (while (setq start (string-match ^re kill (1+ start)))
8357 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8358 (throw 'exit nil)))
8359 t))))
8361 (defvar org-markers-to-move nil
8362 "Markers that should be moved with a cut-and-paste operation.
8363 Those markers are stored together with their positions relative to
8364 the start of the region.")
8366 (defun org-save-markers-in-region (beg end)
8367 "Check markers in region.
8368 If these markers are between BEG and END, record their position relative
8369 to BEG, so that after moving the block of text, we can put the markers back
8370 into place.
8371 This function gets called just before an entry or tree gets cut from the
8372 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8373 called immediately, to move the markers with the entries."
8374 (setq org-markers-to-move nil)
8375 (when (featurep 'org-clock)
8376 (org-clock-save-markers-for-cut-and-paste beg end))
8377 (when (featurep 'org-agenda)
8378 (org-agenda-save-markers-for-cut-and-paste beg end)))
8380 (defun org-check-and-save-marker (marker beg end)
8381 "Check if MARKER is between BEG and END.
8382 If yes, remember the marker and the distance to BEG."
8383 (when (and (marker-buffer marker)
8384 (equal (marker-buffer marker) (current-buffer)))
8385 (if (and (>= marker beg) (< marker end))
8386 (push (cons marker (- marker beg)) org-markers-to-move))))
8388 (defun org-reinstall-markers-in-region (beg)
8389 "Move all remembered markers to their position relative to BEG."
8390 (mapc (lambda (x)
8391 (move-marker (car x) (+ beg (cdr x))))
8392 org-markers-to-move)
8393 (setq org-markers-to-move nil))
8395 (defun org-narrow-to-subtree ()
8396 "Narrow buffer to the current subtree."
8397 (interactive)
8398 (save-excursion
8399 (save-match-data
8400 (org-with-limited-levels
8401 (narrow-to-region
8402 (progn (org-back-to-heading t) (point))
8403 (progn (org-end-of-subtree t t)
8404 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8405 (point)))))))
8407 (defun org-narrow-to-block ()
8408 "Narrow buffer to the current block."
8409 (interactive)
8410 (let* ((case-fold-search t)
8411 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8412 "^[ \t]*#\\+end_.*")))
8413 (if blockp
8414 (narrow-to-region (car blockp) (cdr blockp))
8415 (user-error "Not in a block"))))
8417 (eval-when-compile
8418 (defvar org-property-drawer-re))
8420 (defvar org-property-start-re) ;; defined below
8421 (defun org-clone-subtree-with-time-shift (n &optional shift)
8422 "Clone the task (subtree) at point N times.
8423 The clones will be inserted as siblings.
8425 In interactive use, the user will be prompted for the number of
8426 clones to be produced. If the entry has a timestamp, the user
8427 will also be prompted for a time shift, which may be a repeater
8428 as used in time stamps, for example `+3d'. To disable this,
8429 you can call the function with a universal prefix argument.
8431 When a valid repeater is given and the entry contains any time
8432 stamps, the clones will become a sequence in time, with time
8433 stamps in the subtree shifted for each clone produced. If SHIFT
8434 is nil or the empty string, time stamps will be left alone. The
8435 ID property of the original subtree is removed.
8437 If the original subtree did contain time stamps with a repeater,
8438 the following will happen:
8439 - the repeater will be removed in each clone
8440 - an additional clone will be produced, with the current, unshifted
8441 date(s) in the entry.
8442 - the original entry will be placed *after* all the clones, with
8443 repeater intact.
8444 - the start days in the repeater in the original entry will be shifted
8445 to past the last clone.
8446 In this way you can spell out a number of instances of a repeating task,
8447 and still retain the repeater to cover future instances of the task."
8448 (interactive "nNumber of clones to produce: ")
8449 (let ((shift
8450 (or shift
8451 (if (and (not (equal current-prefix-arg '(4)))
8452 (save-excursion
8453 (re-search-forward org-ts-regexp-both
8454 (save-excursion
8455 (org-end-of-subtree t)
8456 (point)) t)))
8457 (read-from-minibuffer
8458 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8459 ""))) ;; No time shift
8460 (n-no-remove -1)
8461 (drawer-re org-drawer-regexp)
8462 beg end template task idprop
8463 shift-n shift-what doshift nmin nmax)
8464 (if (not (and (integerp n) (> n 0)))
8465 (error "Invalid number of replications %s" n))
8466 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8467 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8468 shift)))
8469 (error "Invalid shift specification %s" shift))
8470 (when doshift
8471 (setq shift-n (string-to-number (match-string 1 shift))
8472 shift-what (cdr (assoc (match-string 2 shift)
8473 '(("d" . day) ("w" . week)
8474 ("m" . month) ("y" . year))))))
8475 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8476 (setq nmin 1 nmax n)
8477 (org-back-to-heading t)
8478 (setq beg (point))
8479 (setq idprop (org-entry-get nil "ID"))
8480 (org-end-of-subtree t t)
8481 (or (bolp) (insert "\n"))
8482 (setq end (point))
8483 (setq template (buffer-substring beg end))
8484 (when (and doshift
8485 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8486 (delete-region beg end)
8487 (setq end beg)
8488 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8489 (goto-char end)
8490 (loop for n from nmin to nmax do
8491 ;; prepare clone
8492 (with-temp-buffer
8493 (insert template)
8494 (org-mode)
8495 (goto-char (point-min))
8496 (org-show-subtree)
8497 (and idprop (if org-clone-delete-id
8498 (org-entry-delete nil "ID")
8499 (org-id-get-create t)))
8500 (unless (= n 0)
8501 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8502 (kill-whole-line))
8503 (goto-char (point-min))
8504 (while (re-search-forward drawer-re nil t)
8505 (mapc (lambda (d)
8506 (org-remove-empty-drawer-at d (point))) org-drawers)))
8507 (goto-char (point-min))
8508 (when doshift
8509 (while (re-search-forward org-ts-regexp-both nil t)
8510 (org-timestamp-change (* n shift-n) shift-what))
8511 (unless (= n n-no-remove)
8512 (goto-char (point-min))
8513 (while (re-search-forward org-ts-regexp nil t)
8514 (save-excursion
8515 (goto-char (match-beginning 0))
8516 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8517 (delete-region (match-beginning 1) (match-end 1)))))))
8518 (setq task (buffer-string)))
8519 (insert task))
8520 (goto-char beg)))
8522 ;;; Outline Sorting
8524 (defun org-sort (with-case)
8525 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8526 Optional argument WITH-CASE means sort case-sensitively."
8527 (interactive "P")
8528 (cond
8529 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8530 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8532 (org-call-with-arg 'org-sort-entries with-case))))
8534 (defun org-sort-remove-invisible (s)
8535 "Remove invisible links from string S."
8536 (remove-text-properties 0 (length s) org-rm-props s)
8537 (while (string-match org-bracket-link-regexp s)
8538 (setq s (replace-match (if (match-end 2)
8539 (match-string 3 s)
8540 (match-string 1 s)) t t s)))
8541 (let ((st (format " %s " s)))
8542 (while (string-match org-emph-re st)
8543 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8544 (setq s (substring st 1 -1)))
8547 (defvar org-priority-regexp) ; defined later in the file
8549 (defvar org-after-sorting-entries-or-items-hook nil
8550 "Hook that is run after a bunch of entries or items have been sorted.
8551 When children are sorted, the cursor is in the parent line when this
8552 hook gets called. When a region or a plain list is sorted, the cursor
8553 will be in the first entry of the sorted region/list.")
8555 (defun org-sort-entries
8556 (&optional with-case sorting-type getkey-func compare-func property)
8557 "Sort entries on a certain level of an outline tree.
8558 If there is an active region, the entries in the region are sorted.
8559 Else, if the cursor is before the first entry, sort the top-level items.
8560 Else, the children of the entry at point are sorted.
8562 Sorting can be alphabetically, numerically, by date/time as given by
8563 a time stamp, by a property, by priority order, or by a custom function.
8565 The command prompts for the sorting type unless it has been given to the
8566 function through the SORTING-TYPE argument, which needs to be a character,
8567 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8568 precise meaning of each character:
8570 n Numerically, by converting the beginning of the entry/item to a number.
8571 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8572 o By order of TODO keywords.
8573 t By date/time, either the first active time stamp in the entry, or, if
8574 none exist, by the first inactive one.
8575 s By the scheduled date/time.
8576 d By deadline date/time.
8577 c By creation time, which is assumed to be the first inactive time stamp
8578 at the beginning of a line.
8579 p By priority according to the cookie.
8580 r By the value of a property.
8582 Capital letters will reverse the sort order.
8584 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8585 called with point at the beginning of the record. It must return either
8586 a string or a number that should serve as the sorting key for that record.
8588 Comparing entries ignores case by default. However, with an optional argument
8589 WITH-CASE, the sorting considers case as well.
8591 Sorting is done against the visible part of the headlines, it ignores hidden
8592 links."
8593 (interactive "P")
8594 (let ((case-func (if with-case 'identity 'downcase))
8595 (cmstr
8596 ;; The clock marker is lost when using `sort-subr', let's
8597 ;; store the clocking string.
8598 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8599 (save-excursion
8600 (goto-char org-clock-marker)
8601 (looking-back "^.*") (match-string-no-properties 0))))
8602 start beg end stars re re2
8603 txt what tmp)
8604 ;; Find beginning and end of region to sort
8605 (cond
8606 ((org-region-active-p)
8607 ;; we will sort the region
8608 (setq end (region-end)
8609 what "region")
8610 (goto-char (region-beginning))
8611 (if (not (org-at-heading-p)) (outline-next-heading))
8612 (setq start (point)))
8613 ((or (org-at-heading-p)
8614 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8615 ;; we will sort the children of the current headline
8616 (org-back-to-heading)
8617 (setq start (point)
8618 end (progn (org-end-of-subtree t t)
8619 (or (bolp) (insert "\n"))
8620 (org-back-over-empty-lines)
8621 (point))
8622 what "children")
8623 (goto-char start)
8624 (show-subtree)
8625 (outline-next-heading))
8627 ;; we will sort the top-level entries in this file
8628 (goto-char (point-min))
8629 (or (org-at-heading-p) (outline-next-heading))
8630 (setq start (point))
8631 (goto-char (point-max))
8632 (beginning-of-line 1)
8633 (when (looking-at ".*?\\S-")
8634 ;; File ends in a non-white line
8635 (end-of-line 1)
8636 (insert "\n"))
8637 (setq end (point-max))
8638 (setq what "top-level")
8639 (goto-char start)
8640 (show-all)))
8642 (setq beg (point))
8643 (if (>= beg end) (user-error "Nothing to sort"))
8645 (looking-at "\\(\\*+\\)")
8646 (setq stars (match-string 1)
8647 re (concat "^" (regexp-quote stars) " +")
8648 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8649 txt (buffer-substring beg end))
8650 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8651 (if (and (not (equal stars "*")) (string-match re2 txt))
8652 (user-error "Region to sort contains a level above the first entry"))
8654 (unless sorting-type
8655 (message
8656 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8657 [t]ime [s]cheduled [d]eadline [c]reated
8658 A/N/P/R/O/F/T/S/D/C means reversed:"
8659 what)
8660 (setq sorting-type (read-char-exclusive))
8662 (unless getkey-func
8663 (and (= (downcase sorting-type) ?f)
8664 (setq getkey-func
8665 (org-icompleting-read "Sort using function: "
8666 obarray 'fboundp t nil nil))
8667 (setq getkey-func (intern getkey-func))))
8669 (and (= (downcase sorting-type) ?r)
8670 (not property)
8671 (setq property
8672 (org-icompleting-read "Property: "
8673 (mapcar 'list (org-buffer-property-keys t))
8674 nil t))))
8676 (message "Sorting entries...")
8678 (save-restriction
8679 (narrow-to-region start end)
8680 (let ((dcst (downcase sorting-type))
8681 (case-fold-search nil)
8682 (now (current-time)))
8683 (sort-subr
8684 (/= dcst sorting-type)
8685 ;; This function moves to the beginning character of the "record" to
8686 ;; be sorted.
8687 (lambda nil
8688 (if (re-search-forward re nil t)
8689 (goto-char (match-beginning 0))
8690 (goto-char (point-max))))
8691 ;; This function moves to the last character of the "record" being
8692 ;; sorted.
8693 (lambda nil
8694 (save-match-data
8695 (condition-case nil
8696 (outline-forward-same-level 1)
8697 (error
8698 (goto-char (point-max))))))
8699 ;; This function returns the value that gets sorted against.
8700 (lambda nil
8701 (cond
8702 ((= dcst ?n)
8703 (if (looking-at org-complex-heading-regexp)
8704 (string-to-number (org-sort-remove-invisible (match-string 4)))
8705 nil))
8706 ((= dcst ?a)
8707 (if (looking-at org-complex-heading-regexp)
8708 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8709 nil))
8710 ((= dcst ?t)
8711 (let ((end (save-excursion (outline-next-heading) (point))))
8712 (if (or (re-search-forward org-ts-regexp end t)
8713 (re-search-forward org-ts-regexp-both end t))
8714 (org-time-string-to-seconds (match-string 0))
8715 (org-float-time now))))
8716 ((= dcst ?c)
8717 (let ((end (save-excursion (outline-next-heading) (point))))
8718 (if (re-search-forward
8719 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8720 end t)
8721 (org-time-string-to-seconds (match-string 0))
8722 (org-float-time now))))
8723 ((= dcst ?s)
8724 (let ((end (save-excursion (outline-next-heading) (point))))
8725 (if (re-search-forward org-scheduled-time-regexp end t)
8726 (org-time-string-to-seconds (match-string 1))
8727 (org-float-time now))))
8728 ((= dcst ?d)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (re-search-forward org-deadline-time-regexp end t)
8731 (org-time-string-to-seconds (match-string 1))
8732 (org-float-time now))))
8733 ((= dcst ?p)
8734 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8735 (string-to-char (match-string 2))
8736 org-default-priority))
8737 ((= dcst ?r)
8738 (or (org-entry-get nil property) ""))
8739 ((= dcst ?o)
8740 (if (looking-at org-complex-heading-regexp)
8741 (- 9999 (length (member (match-string 2)
8742 org-todo-keywords-1)))))
8743 ((= dcst ?f)
8744 (if getkey-func
8745 (progn
8746 (setq tmp (funcall getkey-func))
8747 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8748 tmp)
8749 (error "Invalid key function `%s'" getkey-func)))
8750 (t (error "Invalid sorting type `%c'" sorting-type))))
8752 (cond
8753 ((= dcst ?a) 'string<)
8754 ((= dcst ?f) compare-func)
8755 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8756 (run-hooks 'org-after-sorting-entries-or-items-hook)
8757 ;; Reset the clock marker if needed
8758 (when cmstr
8759 (save-excursion
8760 (goto-char start)
8761 (search-forward cmstr nil t)
8762 (move-marker org-clock-marker (point))))
8763 (message "Sorting entries...done")))
8765 (defun org-do-sort (table what &optional with-case sorting-type)
8766 "Sort TABLE of WHAT according to SORTING-TYPE.
8767 The user will be prompted for the SORTING-TYPE if the call to this
8768 function does not specify it. WHAT is only for the prompt, to indicate
8769 what is being sorted. The sorting key will be extracted from
8770 the car of the elements of the table.
8771 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8772 (unless sorting-type
8773 (message
8774 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8775 what)
8776 (setq sorting-type (read-char-exclusive)))
8777 (let ((dcst (downcase sorting-type))
8778 extractfun comparefun)
8779 ;; Define the appropriate functions
8780 (cond
8781 ((= dcst ?n)
8782 (setq extractfun 'string-to-number
8783 comparefun (if (= dcst sorting-type) '< '>)))
8784 ((= dcst ?a)
8785 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8786 (lambda(x) (downcase (org-sort-remove-invisible x))))
8787 comparefun (if (= dcst sorting-type)
8788 'string<
8789 (lambda (a b) (and (not (string< a b))
8790 (not (string= a b)))))))
8791 ((= dcst ?t)
8792 (setq extractfun
8793 (lambda (x)
8794 (if (or (string-match org-ts-regexp x)
8795 (string-match org-ts-regexp-both x))
8796 (org-float-time
8797 (org-time-string-to-time (match-string 0 x)))
8799 comparefun (if (= dcst sorting-type) '< '>)))
8800 (t (error "Invalid sorting type `%c'" sorting-type)))
8802 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8803 table)
8804 (lambda (a b) (funcall comparefun (car a) (car b))))))
8807 ;;; The orgstruct minor mode
8809 ;; Define a minor mode which can be used in other modes in order to
8810 ;; integrate the org-mode structure editing commands.
8812 ;; This is really a hack, because the org-mode structure commands use
8813 ;; keys which normally belong to the major mode. Here is how it
8814 ;; works: The minor mode defines all the keys necessary to operate the
8815 ;; structure commands, but wraps the commands into a function which
8816 ;; tests if the cursor is currently at a headline or a plain list
8817 ;; item. If that is the case, the structure command is used,
8818 ;; temporarily setting many Org-mode variables like regular
8819 ;; expressions for filling etc. However, when any of those keys is
8820 ;; used at a different location, function uses `key-binding' to look
8821 ;; up if the key has an associated command in another currently active
8822 ;; keymap (minor modes, major mode, global), and executes that
8823 ;; command. There might be problems if any of the keys is otherwise
8824 ;; used as a prefix key.
8826 (defcustom orgstruct-heading-prefix-regexp nil
8827 "Regexp that matches the custom prefix of Org headlines in
8828 orgstruct(++)-mode."
8829 :group 'org
8830 :version "24.4"
8831 :package-version '(Org . "8.0")
8832 :type 'string)
8833 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8835 (defcustom orgstruct-setup-hook nil
8836 "Hook run after orgstruct-mode-map is filled."
8837 :group 'org
8838 :version "24.4"
8839 :package-version '(Org . "8.0")
8840 :type 'hook)
8842 (defvar orgstruct-initialized nil)
8844 (defvar org-local-vars nil
8845 "List of local variables, for use by `orgstruct-mode'.")
8847 ;;;###autoload
8848 (define-minor-mode orgstruct-mode
8849 "Toggle the minor mode `orgstruct-mode'.
8850 This mode is for using Org-mode structure commands in other
8851 modes. The following keys behave as if Org-mode were active, if
8852 the cursor is on a headline, or on a plain list item (both as
8853 defined by Org-mode)."
8854 nil " OrgStruct" (make-sparse-keymap)
8855 (funcall (if orgstruct-mode
8856 'add-to-invisibility-spec
8857 'remove-from-invisibility-spec)
8858 '(outline . t))
8859 (when orgstruct-mode
8860 (org-load-modules-maybe)
8861 (unless orgstruct-initialized
8862 (orgstruct-setup)
8863 (setq orgstruct-initialized t))))
8865 ;;;###autoload
8866 (defun turn-on-orgstruct ()
8867 "Unconditionally turn on `orgstruct-mode'."
8868 (orgstruct-mode 1))
8870 (defvar org-fb-vars nil)
8871 (make-variable-buffer-local 'org-fb-vars)
8872 (defun orgstruct++-mode (&optional arg)
8873 "Toggle `orgstruct-mode', the enhanced version of it.
8874 In addition to setting orgstruct-mode, this also exports all
8875 indentation and autofilling variables from org-mode into the
8876 buffer. It will also recognize item context in multiline items."
8877 (interactive "P")
8878 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8879 (if (< arg 1)
8880 (progn (orgstruct-mode -1)
8881 (mapc (lambda(v)
8882 (org-set-local (car v)
8883 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8884 org-fb-vars))
8885 (orgstruct-mode 1)
8886 (setq org-fb-vars nil)
8887 (unless org-local-vars
8888 (setq org-local-vars (org-get-local-variables)))
8889 (let (var val)
8890 (mapc
8891 (lambda (x)
8892 (when (string-match
8893 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8894 (symbol-name (car x)))
8895 (setq var (car x) val (nth 1 x))
8896 (push (list var `(quote ,(eval var))) org-fb-vars)
8897 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8898 org-local-vars)
8899 (org-set-local 'orgstruct-is-++ t))))
8901 (defvar orgstruct-is-++ nil
8902 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8903 (make-variable-buffer-local 'orgstruct-is-++)
8905 ;;;###autoload
8906 (defun turn-on-orgstruct++ ()
8907 "Unconditionally turn on `orgstruct++-mode'."
8908 (orgstruct++-mode 1))
8910 (defun orgstruct-error ()
8911 "Error when there is no default binding for a structure key."
8912 (interactive)
8913 (funcall (if (fboundp 'user-error)
8914 'user-error
8915 'error)
8916 "This key has no function outside structure elements"))
8918 (defun orgstruct-setup ()
8919 "Setup orgstruct keymap."
8920 (dolist (cell '((org-demote . t)
8921 (org-metaleft . t)
8922 (org-metaright . t)
8923 (org-promote . t)
8924 (org-shiftmetaleft . t)
8925 (org-shiftmetaright . t)
8926 org-backward-element
8927 org-backward-heading-same-level
8928 org-ctrl-c-ret
8929 org-ctrl-c-minus
8930 org-ctrl-c-star
8931 org-cycle
8932 org-forward-heading-same-level
8933 org-insert-heading
8934 org-insert-heading-respect-content
8935 org-kill-note-or-show-branches
8936 org-mark-subtree
8937 org-meta-return
8938 org-metadown
8939 org-metaup
8940 org-narrow-to-subtree
8941 org-promote-subtree
8942 org-reveal
8943 org-shiftdown
8944 org-shiftleft
8945 org-shiftmetadown
8946 org-shiftmetaup
8947 org-shiftright
8948 org-shifttab
8949 org-shifttab
8950 org-shiftup
8951 org-show-subtree
8952 org-sort
8953 org-up-element
8954 outline-demote
8955 outline-next-visible-heading
8956 outline-previous-visible-heading
8957 outline-promote
8958 outline-up-heading
8959 show-children))
8960 (let ((f (or (car-safe cell) cell))
8961 (disable-when-heading-prefix (cdr-safe cell)))
8962 (when (fboundp f)
8963 (let ((new-bindings))
8964 (dolist (binding (nconc (where-is-internal f org-mode-map)
8965 (where-is-internal f outline-mode-map)))
8966 (push binding new-bindings)
8967 ;; TODO use local-function-key-map
8968 (dolist (rep '(("<tab>" . "TAB")
8969 ("<return>" . "RET")
8970 ("<escape>" . "ESC")
8971 ("<delete>" . "DEL")))
8972 (setq binding (read-kbd-macro
8973 (let ((case-fold-search))
8974 (replace-regexp-in-string
8975 (regexp-quote (cdr rep))
8976 (car rep)
8977 (key-description binding)))))
8978 (pushnew binding new-bindings :test 'equal)))
8979 (dolist (binding new-bindings)
8980 (let ((key (lookup-key orgstruct-mode-map binding)))
8981 (when (or (not key) (numberp key))
8982 (condition-case nil
8983 (org-defkey orgstruct-mode-map
8984 binding
8985 (orgstruct-make-binding f binding disable-when-heading-prefix))
8986 (error nil)))))))))
8987 (run-hooks 'orgstruct-setup-hook))
8989 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8990 "Create a function for binding in the structure minor mode.
8991 FUN is the command to call inside a table. KEY is the key that
8992 should be checked in for a command to execute outside of tables.
8993 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8994 if `orgstruct-heading-prefix-regexp' is non-nil."
8995 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8996 (let ((nname name)
8997 (i 0))
8998 (while (fboundp (intern nname))
8999 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9000 (setq name (intern nname)))
9001 (eval
9002 (let ((bindings '((org-heading-regexp
9003 (concat "^"
9004 orgstruct-heading-prefix-regexp
9005 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9006 (org-outline-regexp
9007 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9008 (org-outline-regexp-bol
9009 (concat "^" org-outline-regexp))
9010 (outline-regexp org-outline-regexp)
9011 (outline-heading-end-regexp "\n")
9012 (outline-level 'org-outline-level)
9013 (outline-heading-alist))))
9014 `(defun ,name (arg)
9015 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9016 "Outside of structure, run the binding of `"
9017 (key-description key) "'."
9018 (when disable-when-heading-prefix
9019 (concat
9020 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9021 "back to the default binding due to limitations of Org's implementation of\n"
9022 "`" (symbol-name fun) "'.")))
9023 (interactive "p")
9024 (let* ((disable
9025 ,(when disable-when-heading-prefix
9026 '(and orgstruct-heading-prefix-regexp
9027 (not (string= orgstruct-heading-prefix-regexp "")))))
9028 (fallback
9029 (or disable
9030 (not
9031 (let* ,bindings
9032 (org-context-p 'headline 'item
9033 ,(when (memq fun
9034 '(org-insert-heading
9035 org-insert-heading-respect-content
9036 org-meta-return))
9037 '(when orgstruct-is-++
9038 'item-body))))))))
9039 (if fallback
9040 (let* ((orgstruct-mode)
9041 (binding
9042 (loop with key = ,key
9043 for rep in
9044 '(nil
9045 ("<\\([^>]*\\)tab>" . "\\1TAB")
9046 ("<\\([^>]*\\)return>" . "\\1RET")
9047 ("<\\([^>]*\\)escape>" . "\\1ESC")
9048 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9050 (when rep
9051 (setq key (read-kbd-macro
9052 (let ((case-fold-search))
9053 (replace-regexp-in-string
9054 (car rep)
9055 (cdr rep)
9056 (key-description key))))))
9057 thereis (key-binding key))))
9058 (if (keymapp binding)
9059 (set-temporary-overlay-map binding)
9060 (let ((func (or binding
9061 (unless disable
9062 'orgstruct-error))))
9063 (when func
9064 (call-interactively func)))))
9065 (org-run-like-in-org-mode
9066 (lambda ()
9067 (interactive)
9068 (let* ,bindings
9069 (call-interactively ',fun)))))))))
9070 name))
9072 (defun org-contextualize-keys (alist contexts)
9073 "Return valid elements in ALIST depending on CONTEXTS.
9075 `org-agenda-custom-commands' or `org-capture-templates' are the
9076 values used for ALIST, and `org-agenda-custom-commands-contexts'
9077 or `org-capture-templates-contexts' are the associated contexts
9078 definitions."
9079 (let ((contexts
9080 ;; normalize contexts
9081 (mapcar
9082 (lambda(c) (cond ((listp (cadr c))
9083 (list (car c) (car c) (cadr c)))
9084 ((string= "" (cadr c))
9085 (list (car c) (car c) (caddr c)))
9086 (t c))) contexts))
9087 (a alist) c r s)
9088 ;; loop over all commands or templates
9089 (while (setq c (pop a))
9090 (let (vrules repl)
9091 (cond
9092 ((not (assoc (car c) contexts))
9093 (push c r))
9094 ((and (assoc (car c) contexts)
9095 (setq vrules (org-contextualize-validate-key
9096 (car c) contexts)))
9097 (mapc (lambda (vr)
9098 (when (not (equal (car vr) (cadr vr)))
9099 (setq repl vr))) vrules)
9100 (if (not repl) (push c r)
9101 (push (cadr repl) s)
9102 (push
9103 (cons (car c)
9104 (cdr (or (assoc (cadr repl) alist)
9105 (error "Undefined key `%s' as contextual replacement for `%s'"
9106 (cadr repl) (car c)))))
9107 r))))))
9108 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9109 (delq
9111 (delete-dups
9112 (mapcar (lambda (x)
9113 (let ((tpl (car x)))
9114 (when (not (delq
9116 (mapcar (lambda(y)
9117 (equal y tpl)) s))) x)))
9118 (reverse r))))))
9120 (defun org-contextualize-validate-key (key contexts)
9121 "Check CONTEXTS for agenda or capture KEY."
9122 (let (r rr res)
9123 (while (setq r (pop contexts))
9124 (mapc
9125 (lambda (rr)
9126 (when
9127 (and (equal key (car r))
9128 (if (functionp rr) (funcall rr)
9129 (or (and (eq (car rr) 'in-file)
9130 (buffer-file-name)
9131 (string-match (cdr rr) (buffer-file-name)))
9132 (and (eq (car rr) 'in-mode)
9133 (string-match (cdr rr) (symbol-name major-mode)))
9134 (and (eq (car rr) 'in-buffer)
9135 (string-match (cdr rr) (buffer-name)))
9136 (when (and (eq (car rr) 'not-in-file)
9137 (buffer-file-name))
9138 (not (string-match (cdr rr) (buffer-file-name))))
9139 (when (eq (car rr) 'not-in-mode)
9140 (not (string-match (cdr rr) (symbol-name major-mode))))
9141 (when (eq (car rr) 'not-in-buffer)
9142 (not (string-match (cdr rr) (buffer-name)))))))
9143 (push r res)))
9144 (car (last r))))
9145 (delete-dups (delq nil res))))
9147 (defun org-context-p (&rest contexts)
9148 "Check if local context is any of CONTEXTS.
9149 Possible values in the list of contexts are `table', `headline', and `item'."
9150 (let ((pos (point)))
9151 (goto-char (point-at-bol))
9152 (prog1 (or (and (memq 'table contexts)
9153 (looking-at "[ \t]*|"))
9154 (and (memq 'headline contexts)
9155 (looking-at org-outline-regexp))
9156 (and (memq 'item contexts)
9157 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9158 (and (memq 'item-body contexts)
9159 (org-in-item-p)))
9160 (goto-char pos))))
9162 (defun org-get-local-variables ()
9163 "Return a list of all local variables in an Org mode buffer."
9164 (let (varlist)
9165 (with-current-buffer (get-buffer-create "*Org tmp*")
9166 (erase-buffer)
9167 (org-mode)
9168 (setq varlist (buffer-local-variables)))
9169 (kill-buffer "*Org tmp*")
9170 (delq nil
9171 (mapcar
9172 (lambda (x)
9173 (setq x
9174 (if (symbolp x)
9175 (list x)
9176 (list (car x) (cdr x))))
9177 (if (and (not (get (car x) 'org-state))
9178 (string-match
9179 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9180 (symbol-name (car x))))
9181 x nil))
9182 varlist))))
9184 (defun org-clone-local-variables (from-buffer &optional regexp)
9185 "Clone local variables from FROM-BUFFER.
9186 Optional argument REGEXP selects variables to clone."
9187 (mapc
9188 (lambda (pair)
9189 (and (symbolp (car pair))
9190 (or (null regexp)
9191 (string-match regexp (symbol-name (car pair))))
9192 (set (make-local-variable (car pair))
9193 (cdr pair))))
9194 (buffer-local-variables from-buffer)))
9196 ;;;###autoload
9197 (defun org-run-like-in-org-mode (cmd)
9198 "Run a command, pretending that the current buffer is in Org-mode.
9199 This will temporarily bind local variables that are typically bound in
9200 Org-mode to the values they have in Org-mode, and then interactively
9201 call CMD."
9202 (org-load-modules-maybe)
9203 (unless org-local-vars
9204 (setq org-local-vars (org-get-local-variables)))
9205 (let (binds)
9206 (dolist (var org-local-vars)
9207 (when (or (not (boundp (car var)))
9208 (eq (symbol-value (car var))
9209 (default-value (car var))))
9210 (push (list (car var) `(quote ,(cadr var))) binds)))
9211 (eval `(let ,binds
9212 (call-interactively (quote ,cmd))))))
9214 ;;;; Archiving
9216 (defun org-get-category (&optional pos force-refresh)
9217 "Get the category applying to position POS."
9218 (save-match-data
9219 (if force-refresh (org-refresh-category-properties))
9220 (let ((pos (or pos (point))))
9221 (or (get-text-property pos 'org-category)
9222 (progn (org-refresh-category-properties)
9223 (get-text-property pos 'org-category))))))
9225 (defun org-refresh-category-properties ()
9226 "Refresh category text properties in the buffer."
9227 (let ((case-fold-search t)
9228 (inhibit-read-only t)
9229 (def-cat (cond
9230 ((null org-category)
9231 (if buffer-file-name
9232 (file-name-sans-extension
9233 (file-name-nondirectory buffer-file-name))
9234 "???"))
9235 ((symbolp org-category) (symbol-name org-category))
9236 (t org-category)))
9237 beg end cat pos optionp)
9238 (org-with-silent-modifications
9239 (save-excursion
9240 (save-restriction
9241 (widen)
9242 (goto-char (point-min))
9243 (put-text-property (point) (point-max) 'org-category def-cat)
9244 (while (re-search-forward
9245 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9246 (setq pos (match-end 0)
9247 optionp (equal (char-after (match-beginning 0)) ?#)
9248 cat (org-trim (match-string 2)))
9249 (if optionp
9250 (setq beg (point-at-bol) end (point-max))
9251 (org-back-to-heading t)
9252 (setq beg (point) end (org-end-of-subtree t t)))
9253 (put-text-property beg end 'org-category cat)
9254 (put-text-property beg end 'org-category-position beg)
9255 (goto-char pos)))))))
9257 (defun org-refresh-properties (dprop tprop)
9258 "Refresh buffer text properties.
9259 DPROP is the drawer property and TPROP is the corresponding text
9260 property to set."
9261 (let ((case-fold-search t)
9262 (inhibit-read-only t) p)
9263 (org-with-silent-modifications
9264 (save-excursion
9265 (save-restriction
9266 (widen)
9267 (goto-char (point-min))
9268 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9269 (setq p (org-match-string-no-properties 1))
9270 (save-excursion
9271 (org-back-to-heading t)
9272 (put-text-property
9273 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9276 ;;;; Link Stuff
9278 ;;; Link abbreviations
9280 (defun org-link-expand-abbrev (link)
9281 "Apply replacements as defined in `org-link-abbrev-alist'."
9282 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9283 (let* ((key (match-string 1 link))
9284 (as (or (assoc key org-link-abbrev-alist-local)
9285 (assoc key org-link-abbrev-alist)))
9286 (tag (and (match-end 2) (match-string 3 link)))
9287 rpl)
9288 (if (not as)
9289 link
9290 (setq rpl (cdr as))
9291 (cond
9292 ((symbolp rpl) (funcall rpl tag))
9293 ((string-match "%(\\([^)]+\\))" rpl)
9294 (replace-match
9295 (save-match-data
9296 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9297 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9298 ((string-match "%h" rpl)
9299 (replace-match (url-hexify-string (or tag "")) t t rpl))
9300 (t (concat rpl tag)))))
9301 link))
9303 ;;; Storing and inserting links
9305 (defvar org-insert-link-history nil
9306 "Minibuffer history for links inserted with `org-insert-link'.")
9308 (defvar org-stored-links nil
9309 "Contains the links stored with `org-store-link'.")
9311 (defvar org-store-link-plist nil
9312 "Plist with info about the most recently link created with `org-store-link'.")
9314 (defvar org-link-protocols nil
9315 "Link protocols added to Org-mode using `org-add-link-type'.")
9317 (defvar org-store-link-functions nil
9318 "List of functions that are called to create and store a link.
9319 Each function will be called in turn until one returns a non-nil
9320 value. Each function should check if it is responsible for creating
9321 this link (for example by looking at the major mode).
9322 If not, it must exit and return nil.
9323 If yes, it should return a non-nil value after a calling
9324 `org-store-link-props' with a list of properties and values.
9325 Special properties are:
9327 :type The link prefix, like \"http\". This must be given.
9328 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9329 This is obligatory as well.
9330 :description Optional default description for the second pair
9331 of brackets in an Org-mode link. The user can still change
9332 this when inserting this link into an Org-mode buffer.
9334 In addition to these, any additional properties can be specified
9335 and then used in capture templates.")
9337 (defun org-add-link-type (type &optional follow export)
9338 "Add TYPE to the list of `org-link-types'.
9339 Re-compute all regular expressions depending on `org-link-types'
9341 FOLLOW and EXPORT are two functions.
9343 FOLLOW should take the link path as the single argument and do whatever
9344 is necessary to follow the link, for example find a file or display
9345 a mail message.
9347 EXPORT should format the link path for export to one of the export formats.
9348 It should be a function accepting three arguments:
9350 path the path of the link, the text after the prefix (like \"http:\")
9351 desc the description of the link, if any, or a description added by
9352 org-export-normalize-links if there is none
9353 format the export format, a symbol like `html' or `latex' or `ascii'..
9355 The function may use the FORMAT information to return different values
9356 depending on the format. The return value will be put literally into
9357 the exported file. If the return value is nil, this means Org should
9358 do what it normally does with links which do not have EXPORT defined.
9360 Org-mode has a built-in default for exporting links. If you are happy with
9361 this default, there is no need to define an export function for the link
9362 type. For a simple example of an export function, see `org-bbdb.el'."
9363 (add-to-list 'org-link-types type t)
9364 (org-make-link-regexps)
9365 (if (assoc type org-link-protocols)
9366 (setcdr (assoc type org-link-protocols) (list follow export))
9367 (push (list type follow export) org-link-protocols)))
9369 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9370 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9372 ;;;###autoload
9373 (defun org-store-link (arg)
9374 "\\<org-mode-map>Store an org-link to the current location.
9375 This link is added to `org-stored-links' and can later be inserted
9376 into an org-buffer with \\[org-insert-link].
9378 For some link types, a prefix arg is interpreted.
9379 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9380 For file links, arg negates `org-context-in-file-links'.
9382 A double prefix arg force skipping storing functions that are not
9383 part of Org's core.
9385 A triple prefix arg force storing a link for each line in the
9386 active region."
9387 (interactive "P")
9388 (org-load-modules-maybe)
9389 (if (and (equal arg '(64)) (org-region-active-p))
9390 (save-excursion
9391 (let ((end (region-end)))
9392 (goto-char (region-beginning))
9393 (set-mark (point))
9394 (while (< (point-at-eol) end)
9395 (move-end-of-line 1) (activate-mark)
9396 (let (current-prefix-arg)
9397 (call-interactively 'org-store-link))
9398 (move-beginning-of-line 2)
9399 (set-mark (point)))))
9400 (org-with-limited-levels
9401 (setq org-store-link-plist nil)
9402 (let (link cpltxt desc description search
9403 txt custom-id agenda-link sfuns sfunsn)
9404 (cond
9406 ;; Store a link using an external link type
9407 ((and (not (equal arg '(16)))
9408 (setq sfuns
9409 (delq
9410 nil (mapcar (lambda (f)
9411 (let (fs) (if (funcall f) (push f fs))))
9412 org-store-link-functions))
9413 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9414 (or (and (cdr sfuns)
9415 (funcall (intern
9416 (completing-read
9417 "Which function for creating the link? "
9418 sfunsn t (car sfunsn)))))
9419 (funcall (caar sfuns)))
9420 (setq link (plist-get org-store-link-plist :link)
9421 desc (or (plist-get org-store-link-plist
9422 :description) link))))
9424 ;; Store a link from a source code buffer
9425 ((org-src-edit-buffer-p)
9426 (let (label gc)
9427 (while (or (not label)
9428 (save-excursion
9429 (save-restriction
9430 (widen)
9431 (goto-char (point-min))
9432 (re-search-forward
9433 (regexp-quote (format org-coderef-label-format label))
9434 nil t))))
9435 (when label (message "Label exists already") (sit-for 2))
9436 (setq label (read-string "Code line label: " label)))
9437 (end-of-line 1)
9438 (setq link (format org-coderef-label-format label))
9439 (setq gc (- 79 (length link)))
9440 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9441 (insert link)
9442 (setq link (concat "(" label ")") desc nil)))
9444 ;; We are in the agenda, link to referenced location
9445 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9446 (let ((m (or (get-text-property (point) 'org-hd-marker)
9447 (get-text-property (point) 'org-marker))))
9448 (when m
9449 (org-with-point-at m
9450 (setq agenda-link
9451 (if (org-called-interactively-p 'any)
9452 (call-interactively 'org-store-link)
9453 (org-store-link nil)))))))
9455 ((eq major-mode 'calendar-mode)
9456 (let ((cd (calendar-cursor-to-date)))
9457 (setq link
9458 (format-time-string
9459 (car org-time-stamp-formats)
9460 (apply 'encode-time
9461 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9462 nil nil nil))))
9463 (org-store-link-props :type "calendar" :date cd)))
9465 ((eq major-mode 'help-mode)
9466 (setq link (concat "help:" (save-excursion
9467 (goto-char (point-min))
9468 (looking-at "^[^ ]+")
9469 (match-string 0))))
9470 (org-store-link-props :type "help"))
9472 ((eq major-mode 'w3-mode)
9473 (setq cpltxt (if (and (buffer-name)
9474 (not (string-match "Untitled" (buffer-name))))
9475 (buffer-name)
9476 (url-view-url t))
9477 link (url-view-url t))
9478 (org-store-link-props :type "w3" :url (url-view-url t)))
9480 ((eq major-mode 'image-mode)
9481 (setq cpltxt (concat "file:"
9482 (abbreviate-file-name buffer-file-name))
9483 link cpltxt)
9484 (org-store-link-props :type "image" :file buffer-file-name))
9486 ;; In dired, store a link to the file of the current line
9487 ((eq major-mode 'dired-mode)
9488 (let ((file (dired-get-filename nil t)))
9489 (setq file (if file
9490 (abbreviate-file-name
9491 (expand-file-name (dired-get-filename nil t)))
9492 ;; otherwise, no file so use current directory.
9493 default-directory))
9494 (setq cpltxt (concat "file:" file)
9495 link cpltxt)))
9497 ((setq search (run-hook-with-args-until-success
9498 'org-create-file-search-functions))
9499 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9500 "::" search))
9501 (setq cpltxt (or description link)))
9503 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9504 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9505 (cond
9506 ;; Store a link using the target at point
9507 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9508 (setq cpltxt
9509 (concat "file:"
9510 (abbreviate-file-name
9511 (buffer-file-name (buffer-base-buffer)))
9512 "::" (match-string 1))
9513 link cpltxt))
9514 ((and (featurep 'org-id)
9515 (or (eq org-id-link-to-org-use-id t)
9516 (and (org-called-interactively-p 'any)
9517 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9518 (and (eq org-id-link-to-org-use-id
9519 'create-if-interactive-and-no-custom-id)
9520 (not custom-id))))
9521 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9522 ;; Store a link using the ID at point
9523 (setq link (condition-case nil
9524 (prog1 (org-id-store-link)
9525 (setq desc (plist-get org-store-link-plist
9526 :description)))
9527 (error
9528 ;; Probably before first headline, link only to file
9529 (concat "file:"
9530 (abbreviate-file-name
9531 (buffer-file-name (buffer-base-buffer))))))))
9533 ;; Just link to current headline
9534 (setq cpltxt (concat "file:"
9535 (abbreviate-file-name
9536 (buffer-file-name (buffer-base-buffer)))))
9537 ;; Add a context search string
9538 (when (org-xor org-context-in-file-links arg)
9539 (let* ((ee (org-element-at-point))
9540 (et (org-element-type ee))
9541 (ev (plist-get (cadr ee) :value))
9542 (ek (plist-get (cadr ee) :key))
9543 (eok (and (stringp ek) (string-match "name" ek))))
9544 (setq txt (cond
9545 ((org-at-heading-p) nil)
9546 ((and (eq et 'keyword) eok) ev)
9547 ((org-region-active-p)
9548 (buffer-substring (region-beginning) (region-end)))))
9549 (when (or (null txt) (string-match "\\S-" txt))
9550 (setq cpltxt
9551 (concat cpltxt "::"
9552 (condition-case nil
9553 (org-make-org-heading-search-string txt)
9554 (error "")))
9555 desc (or (and (eq et 'keyword) eok ev)
9556 (nth 4 (ignore-errors (org-heading-components)))
9557 "NONE")))))
9558 (if (string-match "::\\'" cpltxt)
9559 (setq cpltxt (substring cpltxt 0 -2)))
9560 (setq link cpltxt))))
9562 ((buffer-file-name (buffer-base-buffer))
9563 ;; Just link to this file here.
9564 (setq cpltxt (concat "file:"
9565 (abbreviate-file-name
9566 (buffer-file-name (buffer-base-buffer)))))
9567 ;; Add a context string.
9568 (when (org-xor org-context-in-file-links arg)
9569 (setq txt (if (org-region-active-p)
9570 (buffer-substring (region-beginning) (region-end))
9571 (buffer-substring (point-at-bol) (point-at-eol))))
9572 ;; Only use search option if there is some text.
9573 (when (string-match "\\S-" txt)
9574 (setq cpltxt
9575 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9576 desc "NONE")))
9577 (setq link cpltxt))
9579 ((org-called-interactively-p 'interactive)
9580 (user-error "No method for storing a link from this buffer"))
9582 (t (setq link nil)))
9584 ;; We're done setting link and desc, clean up
9585 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9586 (setq link (or link cpltxt)
9587 desc (or desc cpltxt))
9588 (cond ((equal desc "NONE") (setq desc nil))
9589 ((string-match org-bracket-link-analytic-regexp desc)
9590 (let ((d0 (match-string 3 desc))
9591 (p0 (match-string 5 desc)))
9592 (setq desc
9593 (replace-regexp-in-string
9594 org-bracket-link-regexp
9595 (concat (or p0 d0)
9596 (if (equal (length (match-string 0 desc))
9597 (length desc)) "*" "")) desc)))))
9599 ;; Return the link
9600 (if (not (and (or (org-called-interactively-p 'any)
9601 executing-kbd-macro) link))
9602 (or agenda-link (and link (org-make-link-string link desc)))
9603 (push (list link desc) org-stored-links)
9604 (message "Stored: %s" (or desc link))
9605 (when custom-id
9606 (setq link (concat "file:" (abbreviate-file-name
9607 (buffer-file-name)) "::#" custom-id))
9608 (push (list link desc) org-stored-links)))))))
9610 (defun org-store-link-props (&rest plist)
9611 "Store link properties, extract names and addresses."
9612 (let (x adr)
9613 (when (setq x (plist-get plist :from))
9614 (setq adr (mail-extract-address-components x))
9615 (setq plist (plist-put plist :fromname (car adr)))
9616 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9617 (when (setq x (plist-get plist :to))
9618 (setq adr (mail-extract-address-components x))
9619 (setq plist (plist-put plist :toname (car adr)))
9620 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9621 (let ((from (plist-get plist :from))
9622 (to (plist-get plist :to)))
9623 (when (and from to org-from-is-user-regexp)
9624 (setq plist
9625 (plist-put plist :fromto
9626 (if (string-match org-from-is-user-regexp from)
9627 (concat "to %t")
9628 (concat "from %f"))))))
9629 (setq org-store-link-plist plist))
9631 (defun org-add-link-props (&rest plist)
9632 "Add these properties to the link property list."
9633 (let (key value)
9634 (while plist
9635 (setq key (pop plist) value (pop plist))
9636 (setq org-store-link-plist
9637 (plist-put org-store-link-plist key value)))))
9639 (defun org-email-link-description (&optional fmt)
9640 "Return the description part of an email link.
9641 This takes information from `org-store-link-plist' and formats it
9642 according to FMT (default from `org-email-link-description-format')."
9643 (setq fmt (or fmt org-email-link-description-format))
9644 (let* ((p org-store-link-plist)
9645 (to (plist-get p :toaddress))
9646 (from (plist-get p :fromaddress))
9647 (table
9648 (list
9649 (cons "%c" (plist-get p :fromto))
9650 (cons "%F" (plist-get p :from))
9651 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9652 (cons "%T" (plist-get p :to))
9653 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9654 (cons "%s" (plist-get p :subject))
9655 (cons "%d" (plist-get p :date))
9656 (cons "%m" (plist-get p :message-id)))))
9657 (when (string-match "%c" fmt)
9658 ;; Check if the user wrote this message
9659 (if (and org-from-is-user-regexp from to
9660 (save-match-data (string-match org-from-is-user-regexp from)))
9661 (setq fmt (replace-match "to %t" t t fmt))
9662 (setq fmt (replace-match "from %f" t t fmt))))
9663 (org-replace-escapes fmt table)))
9665 (defun org-make-org-heading-search-string (&optional string)
9666 "Make search string for the current headline or STRING."
9667 (let ((s (or string
9668 (and (derived-mode-p 'org-mode)
9669 (save-excursion
9670 (org-back-to-heading t)
9671 (org-element-property :raw-value (org-element-at-point))))))
9672 (lines org-context-in-file-links))
9673 (or string (setq s (concat "*" s))) ; Add * for headlines
9674 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9675 (when (and string (integerp lines) (> lines 0))
9676 (let ((slines (org-split-string s "\n")))
9677 (when (< lines (length slines))
9678 (setq s (mapconcat
9679 'identity
9680 (reverse (nthcdr (- (length slines) lines)
9681 (reverse slines))) "\n")))))
9682 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9684 (defun org-make-link-string (link &optional description)
9685 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9686 (unless (string-match "\\S-" link)
9687 (error "Empty link"))
9688 (when (and description
9689 (stringp description)
9690 (not (string-match "\\S-" description)))
9691 (setq description nil))
9692 (when (stringp description)
9693 ;; Remove brackets from the description, they are fatal.
9694 (while (string-match "\\[" description)
9695 (setq description (replace-match "{" t t description)))
9696 (while (string-match "\\]" description)
9697 (setq description (replace-match "}" t t description))))
9698 (when (equal link description)
9699 ;; No description needed, it is identical
9700 (setq description nil))
9701 (when (and (not description)
9702 (not (string-match (org-image-file-name-regexp) link))
9703 (not (equal link (org-link-escape link))))
9704 (setq description (org-extract-attributes link)))
9705 (setq link
9706 (cond ((string-match (org-image-file-name-regexp) link) link)
9707 ((string-match org-link-types-re link)
9708 (concat (match-string 1 link)
9709 (org-link-escape (substring link (match-end 1)))))
9710 (t (org-link-escape link))))
9711 (concat "[[" link "]"
9712 (if description (concat "[" description "]") "")
9713 "]"))
9715 (defconst org-link-escape-chars
9716 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9717 "List of characters that should be escaped in link.
9718 This is the list that is used for internal purposes.")
9720 (defconst org-link-escape-chars-browser
9721 '(?\ ?\")
9722 "List of escapes for characters that are problematic in links.
9723 This is the list that is used before handing over to the browser.")
9725 (defun org-link-escape (text &optional table merge)
9726 "Return percent escaped representation of TEXT.
9727 TEXT is a string with the text to escape.
9728 Optional argument TABLE is a list with characters that should be
9729 escaped. When nil, `org-link-escape-chars' is used.
9730 If optional argument MERGE is set, merge TABLE into
9731 `org-link-escape-chars'."
9732 (cond
9733 ((and table merge)
9734 (mapc (lambda (defchr)
9735 (unless (member defchr table)
9736 (setq table (cons defchr table)))) org-link-escape-chars))
9737 ((null table)
9738 (setq table org-link-escape-chars)))
9739 (mapconcat
9740 (lambda (char)
9741 (if (or (member char table)
9742 (and (or (< char 32) (= char 37) (> char 126))
9743 org-url-hexify-p))
9744 (mapconcat (lambda (sequence-element)
9745 (format "%%%.2X" sequence-element))
9746 (or (encode-coding-char char 'utf-8)
9747 (error "Unable to percent escape character: %s"
9748 (char-to-string char))) "")
9749 (char-to-string char))) text ""))
9751 (defun org-link-unescape (str)
9752 "Unhex hexified Unicode strings as returned from the JavaScript function
9753 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9754 (unless (and (null str) (string= "" str))
9755 (let ((pos 0) (case-fold-search t) unhexed)
9756 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9757 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9758 (setq str (replace-match unhexed t t str))
9759 (setq pos (+ pos (length unhexed))))))
9760 str)
9762 (defun org-link-unescape-compound (hex)
9763 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9764 Note: this function also decodes single byte encodings like
9765 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9766 (save-match-data
9767 (let* ((bytes (cdr (split-string hex "%")))
9768 (ret "")
9769 (eat 0)
9770 (sum 0))
9771 (while bytes
9772 (let* ((val (string-to-number (pop bytes) 16))
9773 (shift-xor
9774 (if (= 0 eat)
9775 (cond
9776 ((>= val 252) (cons 6 252))
9777 ((>= val 248) (cons 5 248))
9778 ((>= val 240) (cons 4 240))
9779 ((>= val 224) (cons 3 224))
9780 ((>= val 192) (cons 2 192))
9781 (t (cons 0 0)))
9782 (cons 6 128))))
9783 (if (>= val 192) (setq eat (car shift-xor)))
9784 (setq val (logxor val (cdr shift-xor)))
9785 (setq sum (+ (lsh sum (car shift-xor)) val))
9786 (if (> eat 0) (setq eat (- eat 1)))
9787 (cond
9788 ((= 0 eat) ;multi byte
9789 (setq ret (concat ret (org-char-to-string sum)))
9790 (setq sum 0))
9791 ((not bytes) ; single byte(s)
9792 (setq ret (org-link-unescape-single-byte-sequence hex))))
9793 )) ;; end (while bytes
9794 ret )))
9796 (defun org-link-unescape-single-byte-sequence (hex)
9797 "Unhexify hex-encoded single byte character sequences."
9798 (mapconcat (lambda (byte)
9799 (char-to-string (string-to-number byte 16)))
9800 (cdr (split-string hex "%")) ""))
9802 (defun org-xor (a b)
9803 "Exclusive or."
9804 (if a (not b) b))
9806 (defun org-fixup-message-id-for-http (s)
9807 "Replace special characters in a message id, so it can be used in an http query."
9808 (when (string-match "%" s)
9809 (setq s (mapconcat (lambda (c)
9810 (if (eq c ?%)
9811 "%25"
9812 (char-to-string c)))
9813 s "")))
9814 (while (string-match "<" s)
9815 (setq s (replace-match "%3C" t t s)))
9816 (while (string-match ">" s)
9817 (setq s (replace-match "%3E" t t s)))
9818 (while (string-match "@" s)
9819 (setq s (replace-match "%40" t t s)))
9822 (defun org-link-prettify (link)
9823 "Return a human-readable representation of LINK.
9824 The car of LINK must be a raw link the cdr of LINK must be either
9825 a link description or nil."
9826 (let ((desc (or (cadr link) "<no description>")))
9827 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9828 "<" (car link) ">")))
9830 ;;;###autoload
9831 (defun org-insert-link-global ()
9832 "Insert a link like Org-mode does.
9833 This command can be called in any mode to insert a link in Org-mode syntax."
9834 (interactive)
9835 (org-load-modules-maybe)
9836 (org-run-like-in-org-mode 'org-insert-link))
9838 (defun org-insert-all-links (&optional keep)
9839 "Insert all links in `org-stored-links'."
9840 (interactive "P")
9841 (let ((links (copy-sequence org-stored-links)) l)
9842 (while (setq l (if keep (pop links) (pop org-stored-links)))
9843 (insert "- ")
9844 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9845 (insert "\n"))))
9847 (defun org-link-fontify-links-to-this-file ()
9848 "Fontify links to the current file in `org-stored-links'."
9849 (let ((f (buffer-file-name)) a b)
9850 (setq a (mapcar (lambda(l)
9851 (let ((ll (car l)))
9852 (when (and (string-match "^file:\\(.+\\)::" ll)
9853 (equal f (expand-file-name (match-string 1 ll))))
9854 ll)))
9855 org-stored-links))
9856 (when (featurep 'org-id)
9857 (setq b (mapcar (lambda(l)
9858 (let ((ll (car l)))
9859 (when (and (string-match "^id:\\(.+\\)$" ll)
9860 (equal f (expand-file-name
9861 (or (org-id-find-id-file
9862 (match-string 1 ll)) ""))))
9863 ll)))
9864 org-stored-links)))
9865 (mapcar (lambda(l)
9866 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9867 (delq nil (append a b)))))
9869 (defvar org-link-links-in-this-file nil)
9870 (defun org-insert-link (&optional complete-file link-location default-description)
9871 "Insert a link. At the prompt, enter the link.
9873 Completion can be used to insert any of the link protocol prefixes like
9874 http or ftp in use.
9876 The history can be used to select a link previously stored with
9877 `org-store-link'. When the empty string is entered (i.e. if you just
9878 press RET at the prompt), the link defaults to the most recently
9879 stored link. As SPC triggers completion in the minibuffer, you need to
9880 use M-SPC or C-q SPC to force the insertion of a space character.
9882 You will also be prompted for a description, and if one is given, it will
9883 be displayed in the buffer instead of the link.
9885 If there is already a link at point, this command will allow you to edit link
9886 and description parts.
9888 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9889 be selected using completion. The path to the file will be relative to the
9890 current directory if the file is in the current directory or a subdirectory.
9891 Otherwise, the link will be the absolute path as completed in the minibuffer
9892 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9893 option `org-link-file-path-type'.
9895 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9896 the current directory or below.
9898 With three \\[universal-argument] prefixes, negate the meaning of
9899 `org-keep-stored-link-after-insertion'.
9901 If `org-make-link-description-function' is non-nil, this function will be
9902 called with the link target, and the result will be the default
9903 link description.
9905 If the LINK-LOCATION parameter is non-nil, this value will be
9906 used as the link location instead of reading one interactively.
9908 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9909 be used as the default description."
9910 (interactive "P")
9911 (let* ((wcf (current-window-configuration))
9912 (origbuf (current-buffer))
9913 (region (if (org-region-active-p)
9914 (buffer-substring (region-beginning) (region-end))))
9915 (remove (and region (list (region-beginning) (region-end))))
9916 (desc region)
9917 tmphist ; byte-compile incorrectly complains about this
9918 (link link-location)
9919 (abbrevs org-link-abbrev-alist-local)
9920 entry file all-prefixes auto-desc)
9921 (cond
9922 (link-location) ; specified by arg, just use it.
9923 ((org-in-regexp org-bracket-link-regexp 1)
9924 ;; We do have a link at point, and we are going to edit it.
9925 (setq remove (list (match-beginning 0) (match-end 0)))
9926 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9927 (setq link (read-string "Link: "
9928 (org-link-unescape
9929 (org-match-string-no-properties 1)))))
9930 ((or (org-in-regexp org-angle-link-re)
9931 (org-in-regexp org-plain-link-re))
9932 ;; Convert to bracket link
9933 (setq remove (list (match-beginning 0) (match-end 0))
9934 link (read-string "Link: "
9935 (org-remove-angle-brackets (match-string 0)))))
9936 ((member complete-file '((4) (16)))
9937 ;; Completing read for file names.
9938 (setq link (org-file-complete-link complete-file)))
9940 ;; Read link, with completion for stored links.
9941 (org-link-fontify-links-to-this-file)
9942 (org-switch-to-buffer-other-window "*Org Links*")
9943 (with-current-buffer "*Org Links*"
9944 (erase-buffer)
9945 (insert "Insert a link.
9946 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9947 (when org-stored-links
9948 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9949 (insert (mapconcat 'org-link-prettify
9950 (reverse org-stored-links) "\n")))
9951 (goto-char (point-min)))
9952 (let ((cw (selected-window)))
9953 (select-window (get-buffer-window "*Org Links*" 'visible))
9954 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9955 (unless (pos-visible-in-window-p (point-max))
9956 (org-fit-window-to-buffer))
9957 (and (window-live-p cw) (select-window cw)))
9958 ;; Fake a link history, containing the stored links.
9959 (setq tmphist (append (mapcar 'car org-stored-links)
9960 org-insert-link-history))
9961 (setq all-prefixes (append (mapcar 'car abbrevs)
9962 (mapcar 'car org-link-abbrev-alist)
9963 org-link-types))
9964 (unwind-protect
9965 (progn
9966 (setq link
9967 (org-completing-read
9968 "Link: "
9969 (append
9970 (mapcar (lambda (x) (concat x ":"))
9971 all-prefixes)
9972 (mapcar 'car org-stored-links))
9973 nil nil nil
9974 'tmphist
9975 (caar org-stored-links)))
9976 (if (not (string-match "\\S-" link))
9977 (user-error "No link selected"))
9978 (mapc (lambda(l)
9979 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9980 org-stored-links)
9981 (if (or (member link all-prefixes)
9982 (and (equal ":" (substring link -1))
9983 (member (substring link 0 -1) all-prefixes)
9984 (setq link (substring link 0 -1))))
9985 (setq link (with-current-buffer origbuf
9986 (org-link-try-special-completion link)))))
9987 (set-window-configuration wcf)
9988 (kill-buffer "*Org Links*"))
9989 (setq entry (assoc link org-stored-links))
9990 (or entry (push link org-insert-link-history))
9991 (setq desc (or desc (nth 1 entry)))))
9993 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9994 (not org-keep-stored-link-after-insertion))
9995 (setq org-stored-links (delq (assoc link org-stored-links)
9996 org-stored-links)))
9998 (if (string-match org-plain-link-re link)
9999 ;; URL-like link, normalize the use of angular brackets.
10000 (setq link (org-remove-angle-brackets link)))
10002 ;; Check if we are linking to the current file with a search
10003 ;; option If yes, simplify the link by using only the search
10004 ;; option.
10005 (when (and buffer-file-name
10006 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10007 (let* ((path (match-string 1 link))
10008 (case-fold-search nil)
10009 (search (match-string 2 link)))
10010 (save-match-data
10011 (if (equal (file-truename buffer-file-name) (file-truename path))
10012 ;; We are linking to this same file, with a search option
10013 (setq link search)))))
10015 ;; Check if we can/should use a relative path. If yes, simplify the link
10016 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10017 (let* ((type (match-string 1 link))
10018 (path (match-string 2 link))
10019 (origpath path)
10020 (case-fold-search nil))
10021 (cond
10022 ((or (eq org-link-file-path-type 'absolute)
10023 (equal complete-file '(16)))
10024 (setq path (abbreviate-file-name (expand-file-name path))))
10025 ((eq org-link-file-path-type 'noabbrev)
10026 (setq path (expand-file-name path)))
10027 ((eq org-link-file-path-type 'relative)
10028 (setq path (file-relative-name path)))
10030 (save-match-data
10031 (if (string-match (concat "^" (regexp-quote
10032 (expand-file-name
10033 (file-name-as-directory
10034 default-directory))))
10035 (expand-file-name path))
10036 ;; We are linking a file with relative path name.
10037 (setq path (substring (expand-file-name path)
10038 (match-end 0)))
10039 (setq path (abbreviate-file-name (expand-file-name path)))))))
10040 (setq link (concat type path))
10041 (if (equal desc origpath)
10042 (setq desc path))))
10044 (if org-make-link-description-function
10045 (setq desc
10046 (or (condition-case nil
10047 (funcall org-make-link-description-function link desc)
10048 (error (progn (message "Can't get link description from `%s'"
10049 (symbol-name org-make-link-description-function))
10050 (sit-for 2) nil)))
10051 (read-string "Description: " default-description)))
10052 (if default-description (setq desc default-description)
10053 (setq desc (or (and auto-desc desc)
10054 (read-string "Description: " desc)))))
10056 (unless (string-match "\\S-" desc) (setq desc nil))
10057 (if remove (apply 'delete-region remove))
10058 (insert (org-make-link-string link desc))))
10060 (defun org-link-try-special-completion (type)
10061 "If there is completion support for link type TYPE, offer it."
10062 (let ((fun (intern (concat "org-" type "-complete-link"))))
10063 (if (functionp fun)
10064 (funcall fun)
10065 (read-string "Link (no completion support): " (concat type ":")))))
10067 (defun org-file-complete-link (&optional arg)
10068 "Create a file link using completion."
10069 (let (file link)
10070 (setq file (org-iread-file-name "File: "))
10071 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10072 (pwd1 (file-name-as-directory (abbreviate-file-name
10073 (expand-file-name ".")))))
10074 (cond
10075 ((equal arg '(16))
10076 (setq link (concat
10077 "file:"
10078 (abbreviate-file-name (expand-file-name file)))))
10079 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10080 (setq link (concat "file:" (match-string 1 file))))
10081 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10082 (expand-file-name file))
10083 (setq link (concat
10084 "file:" (match-string 1 (expand-file-name file)))))
10085 (t (setq link (concat "file:" file)))))
10086 link))
10088 (defun org-iread-file-name (&rest args)
10089 "Read-file-name using `ido-mode' speedup if available.
10090 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10091 See `read-file-name' for a description of parameters."
10092 (org-without-partial-completion
10093 (if (and org-completion-use-ido
10094 (fboundp 'ido-read-file-name)
10095 (boundp 'ido-mode) ido-mode
10096 (listp (second args)))
10097 (let ((ido-enter-matching-directory nil))
10098 (apply 'ido-read-file-name args))
10099 (apply 'read-file-name args))))
10101 (defun org-completing-read (&rest args)
10102 "Completing-read with SPACE being a normal character."
10103 (let ((enable-recursive-minibuffers t)
10104 (minibuffer-local-completion-map
10105 (copy-keymap minibuffer-local-completion-map)))
10106 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10107 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10108 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10109 (apply 'org-icompleting-read args)))
10111 (defun org-completing-read-no-i (&rest args)
10112 (let (org-completion-use-ido org-completion-use-iswitchb)
10113 (apply 'org-completing-read args)))
10115 (defun org-iswitchb-completing-read (prompt choices &rest args)
10116 "Use iswitch as a completing-read replacement to choose from choices.
10117 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10118 from."
10119 (let* ((iswitchb-use-virtual-buffers nil)
10120 (iswitchb-make-buflist-hook
10121 (lambda ()
10122 (setq iswitchb-temp-buflist choices))))
10123 (iswitchb-read-buffer prompt)))
10125 (defun org-icompleting-read (&rest args)
10126 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10127 (org-without-partial-completion
10128 (if (and org-completion-use-ido
10129 (fboundp 'ido-completing-read)
10130 (boundp 'ido-mode) ido-mode
10131 (listp (second args)))
10132 (let ((ido-enter-matching-directory nil))
10133 (apply 'ido-completing-read (concat (car args))
10134 (if (consp (car (nth 1 args)))
10135 (mapcar 'car (nth 1 args))
10136 (nth 1 args))
10137 (cddr args)))
10138 (if (and org-completion-use-iswitchb
10139 (boundp 'iswitchb-mode) iswitchb-mode
10140 (listp (second args)))
10141 (apply 'org-iswitchb-completing-read (concat (car args))
10142 (if (consp (car (nth 1 args)))
10143 (mapcar 'car (nth 1 args))
10144 (nth 1 args))
10145 (cddr args))
10146 (apply 'completing-read args)))))
10148 (defun org-extract-attributes (s)
10149 "Extract the attributes cookie from a string and set as text property."
10150 (let (a attr (start 0) key value)
10151 (save-match-data
10152 (when (string-match "{{\\([^}]+\\)}}$" s)
10153 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10154 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10155 (setq key (match-string 1 a) value (match-string 2 a)
10156 start (match-end 0)
10157 attr (plist-put attr (intern key) value))))
10158 (org-add-props s nil 'org-attr attr))
10161 ;;; Opening/following a link
10163 (defvar org-link-search-failed nil)
10165 (defvar org-open-link-functions nil
10166 "Hook for functions finding a plain text link.
10167 These functions must take a single argument, the link content.
10168 They will be called for links that look like [[link text][description]]
10169 when LINK TEXT does not have a protocol like \"http:\" and does not look
10170 like a filename (e.g. \"./blue.png\").
10172 These functions will be called *before* Org attempts to resolve the
10173 link by doing text searches in the current buffer - so if you want a
10174 link \"[[target]]\" to still find \"<<target>>\", your function should
10175 handle this as a special case.
10177 When the function does handle the link, it must return a non-nil value.
10178 If it decides that it is not responsible for this link, it must return
10179 nil to indicate that that Org-mode can continue with other options
10180 like exact and fuzzy text search.")
10182 (defun org-next-link (&optional search-backward)
10183 "Move forward to the next link.
10184 If the link is in hidden text, expose it."
10185 (interactive "P")
10186 (when (and org-link-search-failed (eq this-command last-command))
10187 (goto-char (point-min))
10188 (message "Link search wrapped back to beginning of buffer"))
10189 (setq org-link-search-failed nil)
10190 (let* ((pos (point))
10191 (ct (org-context))
10192 (a (assoc :link ct))
10193 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10194 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10195 ((looking-at org-any-link-re)
10196 ;; Don't stay stuck at link without an org-link face
10197 (forward-char (if search-backward -1 1))))
10198 (if (funcall srch-fun org-any-link-re nil t)
10199 (progn
10200 (goto-char (match-beginning 0))
10201 (if (outline-invisible-p) (org-show-context)))
10202 (goto-char pos)
10203 (setq org-link-search-failed t)
10204 (message "No further link found"))))
10206 (defun org-previous-link ()
10207 "Move backward to the previous link.
10208 If the link is in hidden text, expose it."
10209 (interactive)
10210 (funcall 'org-next-link t))
10212 (defun org-translate-link (s)
10213 "Translate a link string if a translation function has been defined."
10214 (if (and org-link-translation-function
10215 (fboundp org-link-translation-function)
10216 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10217 (progn
10218 (setq s (funcall org-link-translation-function
10219 (match-string 1 s) (match-string 2 s)))
10220 (concat (car s) ":" (cdr s)))
10223 (defun org-translate-link-from-planner (type path)
10224 "Translate a link from Emacs Planner syntax so that Org can follow it.
10225 This is still an experimental function, your mileage may vary."
10226 (cond
10227 ((member type '("http" "https" "news" "ftp"))
10228 ;; standard Internet links are the same.
10229 nil)
10230 ((and (equal type "irc") (string-match "^//" path))
10231 ;; Planner has two / at the beginning of an irc link, we have 1.
10232 ;; We should have zero, actually....
10233 (setq path (substring path 1)))
10234 ((and (equal type "lisp") (string-match "^/" path))
10235 ;; Planner has a slash, we do not.
10236 (setq type "elisp" path (substring path 1)))
10237 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10238 ;; A typical message link. Planner has the id after the final slash,
10239 ;; we separate it with a hash mark
10240 (setq path (concat (match-string 1 path) "#"
10241 (org-remove-angle-brackets (match-string 2 path))))))
10242 (cons type path))
10244 (defun org-find-file-at-mouse (ev)
10245 "Open file link or URL at mouse."
10246 (interactive "e")
10247 (mouse-set-point ev)
10248 (org-open-at-point 'in-emacs))
10250 (defun org-open-at-mouse (ev)
10251 "Open file link or URL at mouse.
10252 See the docstring of `org-open-file' for details."
10253 (interactive "e")
10254 (mouse-set-point ev)
10255 (if (eq major-mode 'org-agenda-mode)
10256 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10257 (org-open-at-point))
10259 (defvar org-window-config-before-follow-link nil
10260 "The window configuration before following a link.
10261 This is saved in case the need arises to restore it.")
10263 (defvar org-open-link-marker (make-marker)
10264 "Marker pointing to the location where `org-open-at-point; was called.")
10266 ;;;###autoload
10267 (defun org-open-at-point-global ()
10268 "Follow a link like Org-mode does.
10269 This command can be called in any mode to follow a link that has
10270 Org-mode syntax."
10271 (interactive)
10272 (org-run-like-in-org-mode 'org-open-at-point))
10274 ;;;###autoload
10275 (defun org-open-link-from-string (s &optional arg reference-buffer)
10276 "Open a link in the string S, as if it was in Org-mode."
10277 (interactive "sLink: \nP")
10278 (let ((reference-buffer (or reference-buffer (current-buffer))))
10279 (with-temp-buffer
10280 (let ((org-inhibit-startup (not reference-buffer)))
10281 (org-mode)
10282 (insert s)
10283 (goto-char (point-min))
10284 (when reference-buffer
10285 (setq org-link-abbrev-alist-local
10286 (with-current-buffer reference-buffer
10287 org-link-abbrev-alist-local)))
10288 (org-open-at-point arg reference-buffer)))))
10290 (defvar org-open-at-point-functions nil
10291 "Hook that is run when following a link at point.
10293 Functions in this hook must return t if they identify and follow
10294 a link at point. If they don't find anything interesting at point,
10295 they must return nil.")
10297 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10298 (defun org-open-at-point (&optional arg reference-buffer)
10299 "Open link at or after point.
10300 If there is no link at point, this function will search forward up to
10301 the end of the current line.
10302 Normally, files will be opened by an appropriate application. If the
10303 optional prefix argument ARG is non-nil, Emacs will visit the file.
10304 With a double prefix argument, try to open outside of Emacs, in the
10305 application the system uses for this file type."
10306 (interactive "P")
10307 ;; if in a code block, then open the block's results
10308 (unless (call-interactively #'org-babel-open-src-block-result)
10309 (org-load-modules-maybe)
10310 (move-marker org-open-link-marker (point))
10311 (setq org-window-config-before-follow-link (current-window-configuration))
10312 (org-remove-occur-highlights nil nil t)
10313 (cond
10314 ((and (org-at-heading-p)
10315 (not (org-at-timestamp-p t))
10316 (not (org-in-regexp
10317 (concat org-plain-link-re "\\|"
10318 org-bracket-link-regexp "\\|"
10319 org-angle-link-re "\\|"
10320 "[ \t]:[^ \t\n]+:[ \t]*$")))
10321 (not (get-text-property (point) 'org-linked-text)))
10322 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10323 (lk0 (car lkall))
10324 (lk (if (stringp lk0) (list lk0) lk0))
10325 (lkend (cdr lkall)))
10326 (mapcar (lambda(l)
10327 (search-forward l nil lkend)
10328 (goto-char (match-beginning 0))
10329 (org-open-at-point))
10330 lk))
10331 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10332 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10333 ((and (org-at-timestamp-p t)
10334 (not (org-in-regexp org-bracket-link-regexp)))
10335 (org-follow-timestamp-link))
10336 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10337 (not (org-in-regexp org-any-link-re)))
10338 (org-footnote-action))
10340 (let (type path link line search (pos (point)))
10341 (catch 'match
10342 (save-excursion
10343 (skip-chars-forward "^]\n\r")
10344 (when (org-in-regexp org-bracket-link-regexp 1)
10345 (setq link (org-extract-attributes
10346 (org-link-unescape (org-match-string-no-properties 1))))
10347 (while (string-match " *\n *" link)
10348 (setq link (replace-match " " t t link)))
10349 (setq link (org-link-expand-abbrev link))
10350 (cond
10351 ((or (file-name-absolute-p link)
10352 (string-match "^\\.\\.?/" link))
10353 (setq type "file" path link))
10354 ((string-match org-link-re-with-space3 link)
10355 (setq type (match-string 1 link) path (match-string 2 link)))
10356 ((string-match "^help:+\\(.+\\)" link)
10357 (setq type "help" path (match-string 1 link)))
10358 (t (setq type "thisfile" path link)))
10359 (throw 'match t)))
10361 (when (get-text-property (point) 'org-linked-text)
10362 (setq type "thisfile"
10363 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10364 (1+ (point)) (point))
10365 path (buffer-substring
10366 (or (previous-single-property-change pos 'org-linked-text)
10367 (point-min))
10368 (or (next-single-property-change pos 'org-linked-text)
10369 (point-max)))
10370 ;; Ensure we will search for a <<<radio>>> link, not
10371 ;; a simple reference like <<ref>>
10372 path (concat "<" path))
10373 (throw 'match t))
10375 (save-excursion
10376 (when (or (org-in-regexp org-angle-link-re)
10377 (let ((match (org-in-regexp org-plain-link-re)))
10378 ;; Check a plain link is not within a bracket link
10379 (and match
10380 (save-excursion
10381 (progn
10382 (goto-char (car match))
10383 (not (org-in-regexp org-bracket-link-regexp))))))
10384 (let ((line_ending (save-excursion (end-of-line) (point))))
10385 ;; We are in a line before a plain or bracket link
10386 (or (re-search-forward org-plain-link-re line_ending t)
10387 (re-search-forward org-bracket-link-regexp line_ending t))))
10388 (setq type (match-string 1)
10389 path (org-link-unescape (match-string 2)))
10390 (throw 'match t)))
10391 (save-excursion
10392 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10393 (setq type "tags"
10394 path (match-string 1))
10395 (while (string-match ":" path)
10396 (setq path (replace-match "+" t t path)))
10397 (throw 'match t)))
10398 (when (org-in-regexp "<\\([^><\n]+\\)>")
10399 (setq type "tree-match"
10400 path (match-string 1))
10401 (throw 'match t)))
10402 (unless path
10403 (user-error "No link found"))
10405 ;; switch back to reference buffer
10406 ;; needed when if called in a temporary buffer through
10407 ;; org-open-link-from-string
10408 (with-current-buffer (or reference-buffer (current-buffer))
10410 ;; Remove any trailing spaces in path
10411 (if (string-match " +\\'" path)
10412 (setq path (replace-match "" t t path)))
10413 (if (and org-link-translation-function
10414 (fboundp org-link-translation-function))
10415 ;; Check if we need to translate the link
10416 (let ((tmp (funcall org-link-translation-function type path)))
10417 (setq type (car tmp) path (cdr tmp))))
10419 (cond
10421 ((assoc type org-link-protocols)
10422 (funcall (nth 1 (assoc type org-link-protocols)) path))
10424 ((equal type "help")
10425 (let ((f-or-v (intern path)))
10426 (cond ((fboundp f-or-v)
10427 (describe-function f-or-v))
10428 ((boundp f-or-v)
10429 (describe-variable f-or-v))
10430 (t (error "Not a known function or variable")))))
10432 ((equal type "mailto")
10433 (let ((cmd (car org-link-mailto-program))
10434 (args (cdr org-link-mailto-program)) args1
10435 (address path) (subject "") a)
10436 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10437 (setq address (match-string 1 path)
10438 subject (org-link-escape (match-string 2 path))))
10439 (while args
10440 (cond
10441 ((not (stringp (car args))) (push (pop args) args1))
10442 (t (setq a (pop args))
10443 (if (string-match "%a" a)
10444 (setq a (replace-match address t t a)))
10445 (if (string-match "%s" a)
10446 (setq a (replace-match subject t t a)))
10447 (push a args1))))
10448 (apply cmd (nreverse args1))))
10450 ((member type '("http" "https" "ftp" "news"))
10451 (browse-url
10452 (concat type ":"
10453 (if (org-string-match-p
10454 (concat "[[:nonascii:]"
10455 org-link-escape-chars-browser "]")
10456 path)
10457 (org-link-escape path org-link-escape-chars-browser)
10458 path))))
10460 ((string= type "doi")
10461 (browse-url
10462 (concat org-doi-server-url
10463 (if (org-string-match-p
10464 (concat "[[:nonascii:]"
10465 org-link-escape-chars-browser "]")
10466 path)
10467 (org-link-escape path org-link-escape-chars-browser)
10468 path))))
10470 ((member type '("message"))
10471 (browse-url (concat type ":" path)))
10473 ((string= type "tags")
10474 (org-tags-view arg path))
10476 ((string= type "tree-match")
10477 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10479 ((string= type "file")
10480 (if (string-match "::\\([0-9]+\\)\\'" path)
10481 (setq line (string-to-number (match-string 1 path))
10482 path (substring path 0 (match-beginning 0)))
10483 (if (string-match "::\\(.+\\)\\'" path)
10484 (setq search (match-string 1 path)
10485 path (substring path 0 (match-beginning 0)))))
10486 (if (string-match "[*?{]" (file-name-nondirectory path))
10487 (dired path)
10488 (org-open-file path arg line search)))
10490 ((string= type "shell")
10491 (let ((buf (generate-new-buffer "*Org Shell Output"))
10492 (cmd path))
10493 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10494 (string-match org-confirm-shell-link-not-regexp cmd))
10495 (not org-confirm-shell-link-function)
10496 (funcall org-confirm-shell-link-function
10497 (format "Execute \"%s\" in shell? "
10498 (org-add-props cmd nil
10499 'face 'org-warning))))
10500 (progn
10501 (message "Executing %s" cmd)
10502 (shell-command cmd buf)
10503 (if (featurep 'midnight)
10504 (setq clean-buffer-list-kill-buffer-names
10505 (cons buf clean-buffer-list-kill-buffer-names))))
10506 (error "Abort"))))
10508 ((string= type "elisp")
10509 (let ((cmd path))
10510 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10511 (string-match org-confirm-elisp-link-not-regexp cmd))
10512 (not org-confirm-elisp-link-function)
10513 (funcall org-confirm-elisp-link-function
10514 (format "Execute \"%s\" as elisp? "
10515 (org-add-props cmd nil
10516 'face 'org-warning))))
10517 (message "%s => %s" cmd
10518 (if (equal (string-to-char cmd) ?\()
10519 (eval (read cmd))
10520 (call-interactively (read cmd))))
10521 (error "Abort"))))
10523 ((and (string= type "thisfile")
10524 (run-hook-with-args-until-success
10525 'org-open-link-functions path)))
10527 ((string= type "thisfile")
10528 (if arg
10529 (switch-to-buffer-other-window
10530 (org-get-buffer-for-internal-link (current-buffer)))
10531 (org-mark-ring-push))
10532 (let ((cmd `(org-link-search
10533 ,path
10534 ,(cond ((equal arg '(4)) ''occur)
10535 ((equal arg '(16)) ''org-occur))
10536 ,pos)))
10537 (condition-case nil (let ((org-link-search-inhibit-query t))
10538 (eval cmd))
10539 (error (progn (widen) (eval cmd))))))
10541 (t (browse-url-at-point)))))))
10542 (move-marker org-open-link-marker nil)
10543 (run-hook-with-args 'org-follow-link-hook)))
10545 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10546 "Offer links in the current entry and return the selected link.
10547 If there is only one link, return it.
10548 If NTH is an integer, return the NTH link found.
10549 If ZERO is a string, check also this string for a link, and if
10550 there is one, return it."
10551 (with-current-buffer buffer
10552 (save-excursion
10553 (save-restriction
10554 (widen)
10555 (goto-char marker)
10556 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10557 "\\(" org-angle-link-re "\\)\\|"
10558 "\\(" org-plain-link-re "\\)"))
10559 (cnt ?0)
10560 (in-emacs (if (integerp nth) nil nth))
10561 have-zero end links link c)
10562 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10563 (push (match-string 0 zero) links)
10564 (setq cnt (1- cnt) have-zero t))
10565 (save-excursion
10566 (org-back-to-heading t)
10567 (setq end (save-excursion (outline-next-heading) (point)))
10568 (while (re-search-forward re end t)
10569 (push (match-string 0) links))
10570 (setq links (org-uniquify (reverse links))))
10571 (cond
10572 ((null links)
10573 (message "No links"))
10574 ((equal (length links) 1)
10575 (setq link (car links)))
10576 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10577 (setq link (nth (if have-zero nth (1- nth)) links)))
10578 (t ; we have to select a link
10579 (save-excursion
10580 (save-window-excursion
10581 (delete-other-windows)
10582 (with-output-to-temp-buffer "*Select Link*"
10583 (mapc (lambda (l)
10584 (if (not (string-match org-bracket-link-regexp l))
10585 (princ (format "[%c] %s\n" (incf cnt)
10586 (org-remove-angle-brackets l)))
10587 (if (match-end 3)
10588 (princ (format "[%c] %s (%s)\n" (incf cnt)
10589 (match-string 3 l) (match-string 1 l)))
10590 (princ (format "[%c] %s\n" (incf cnt)
10591 (match-string 1 l))))))
10592 links))
10593 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10594 (message "Select link to open, RET to open all:")
10595 (setq c (read-char-exclusive))
10596 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10597 (when (equal c ?q) (error "Abort"))
10598 (if (equal c ?\C-m)
10599 (setq link links)
10600 (setq nth (- c ?0))
10601 (if have-zero (setq nth (1+ nth)))
10602 (unless (and (integerp nth) (>= (length links) nth))
10603 (user-error "Invalid link selection"))
10604 (setq link (nth (1- nth) links)))))
10605 (cons link end))))))
10607 ;; Add special file links that specify the way of opening
10609 (org-add-link-type "file+sys" 'org-open-file-with-system)
10610 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10611 (defun org-open-file-with-system (path)
10612 "Open file at PATH using the system way of opening it."
10613 (org-open-file path 'system))
10614 (defun org-open-file-with-emacs (path)
10615 "Open file at PATH in Emacs."
10616 (org-open-file path 'emacs))
10619 ;;; File search
10621 (defvar org-create-file-search-functions nil
10622 "List of functions to construct the right search string for a file link.
10623 These functions are called in turn with point at the location to
10624 which the link should point.
10626 A function in the hook should first test if it would like to
10627 handle this file type, for example by checking the `major-mode'
10628 or the file extension. If it decides not to handle this file, it
10629 should just return nil to give other functions a chance. If it
10630 does handle the file, it must return the search string to be used
10631 when following the link. The search string will be part of the
10632 file link, given after a double colon, and `org-open-at-point'
10633 will automatically search for it. If special measures must be
10634 taken to make the search successful, another function should be
10635 added to the companion hook `org-execute-file-search-functions',
10636 which see.
10638 A function in this hook may also use `setq' to set the variable
10639 `description' to provide a suggestion for the descriptive text to
10640 be used for this link when it gets inserted into an Org-mode
10641 buffer with \\[org-insert-link].")
10643 (defvar org-execute-file-search-functions nil
10644 "List of functions to execute a file search triggered by a link.
10646 Functions added to this hook must accept a single argument, the
10647 search string that was part of the file link, the part after the
10648 double colon. The function must first check if it would like to
10649 handle this search, for example by checking the `major-mode' or
10650 the file extension. If it decides not to handle this search, it
10651 should just return nil to give other functions a chance. If it
10652 does handle the search, it must return a non-nil value to keep
10653 other functions from trying.
10655 Each function can access the current prefix argument through the
10656 variable `current-prefix-arg'. Note that a single prefix is used
10657 to force opening a link in Emacs, so it may be good to only use a
10658 numeric or double prefix to guide the search function.
10660 In case this is needed, a function in this hook can also restore
10661 the window configuration before `org-open-at-point' was called using:
10663 (set-window-configuration org-window-config-before-follow-link)")
10665 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10666 (defun org-link-search (s &optional type avoid-pos stealth)
10667 "Search for a link search option.
10668 If S is surrounded by forward slashes, it is interpreted as a
10669 regular expression. In org-mode files, this will create an `org-occur'
10670 sparse tree. In ordinary files, `occur' will be used to list matches.
10671 If the current buffer is in `dired-mode', grep will be used to search
10672 in all files. If AVOID-POS is given, ignore matches near that position.
10674 When optional argument STEALTH is non-nil, do not modify
10675 visibility around point, thus ignoring
10676 `org-show-hierarchy-above', `org-show-following-heading' and
10677 `org-show-siblings' variables."
10678 (let ((case-fold-search t)
10679 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10680 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10681 (append '(("") (" ") ("\t") ("\n"))
10682 org-emphasis-alist)
10683 "\\|") "\\)"))
10684 (pos (point))
10685 (pre nil) (post nil)
10686 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10687 (cond
10688 ;; First check if there are any special search functions
10689 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10690 ;; Now try the builtin stuff
10691 ((and (equal (string-to-char s0) ?#)
10692 (> (length s0) 1)
10693 (save-excursion
10694 (goto-char (point-min))
10695 (and
10696 (re-search-forward
10697 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10698 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10699 (setq type 'dedicated
10700 pos (match-beginning 0))))
10701 ;; There is an exact target for this
10702 (goto-char pos)
10703 (org-back-to-heading t)))
10704 ((save-excursion
10705 (goto-char (point-min))
10706 (and
10707 (re-search-forward
10708 (concat "<<" (regexp-quote s0) ">>") nil t)
10709 (setq type 'dedicated
10710 pos (match-beginning 0))))
10711 ;; There is an exact target for this
10712 (goto-char pos))
10713 ((save-excursion
10714 (goto-char (point-min))
10715 (and
10716 (re-search-forward
10717 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10718 (setq type 'dedicated pos (match-beginning 0))))
10719 ;; Found an element with a matching #+name affiliated keyword.
10720 (goto-char pos))
10721 ((and (string-match "^(\\(.*\\))$" s0)
10722 (save-excursion
10723 (goto-char (point-min))
10724 (and
10725 (re-search-forward
10726 (concat "[^[]" (regexp-quote
10727 (format org-coderef-label-format
10728 (match-string 1 s0))))
10729 nil t)
10730 (setq type 'dedicated
10731 pos (1+ (match-beginning 0))))))
10732 ;; There is a coderef target for this
10733 (goto-char pos))
10734 ((string-match "^/\\(.*\\)/$" s)
10735 ;; A regular expression
10736 (cond
10737 ((derived-mode-p 'org-mode)
10738 (org-occur (match-string 1 s)))
10739 (t (org-do-occur (match-string 1 s)))))
10740 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10741 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10742 (goto-char (point-min))
10743 (cond
10744 ((let (case-fold-search)
10745 (re-search-forward (format org-complex-heading-regexp-format
10746 (regexp-quote s))
10747 nil t))
10748 ;; OK, found a match
10749 (setq type 'dedicated)
10750 (goto-char (match-beginning 0)))
10751 ((and (not org-link-search-inhibit-query)
10752 (eq org-link-search-must-match-exact-headline 'query-to-create)
10753 (y-or-n-p "No match - create this as a new heading? "))
10754 (goto-char (point-max))
10755 (or (bolp) (newline))
10756 (insert "* " s "\n")
10757 (beginning-of-line 0))
10759 (goto-char pos)
10760 (error "No match"))))
10762 ;; A normal search string
10763 (when (equal (string-to-char s) ?*)
10764 ;; Anchor on headlines, post may include tags.
10765 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10766 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10767 s (substring s 1)))
10768 (remove-text-properties
10769 0 (length s)
10770 '(face nil mouse-face nil keymap nil fontified nil) s)
10771 ;; Make a series of regular expressions to find a match
10772 (setq words (org-split-string s "[ \n\r\t]+")
10774 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10775 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10776 "\\)" markers)
10777 re2a_ (concat "\\(" (mapconcat 'downcase words
10778 "[ \t\r\n]+") "\\)[ \t\r\n]")
10779 re2a (concat "[ \t\r\n]" re2a_)
10780 re4_ (concat "\\(" (mapconcat 'downcase words
10781 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10782 re4 (concat "[^a-zA-Z_]" re4_)
10784 re1 (concat pre re2 post)
10785 re3 (concat pre (if pre re4_ re4) post)
10786 re5 (concat pre ".*" re4)
10787 re2 (concat pre re2)
10788 re2a (concat pre (if pre re2a_ re2a))
10789 re4 (concat pre (if pre re4_ re4))
10790 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10791 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10792 re5 "\\)"))
10793 (cond
10794 ((eq type 'org-occur) (org-occur reall))
10795 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10796 (t (goto-char (point-min))
10797 (setq type 'fuzzy)
10798 (if (or (and (org-search-not-self 1 re0 nil t)
10799 (setq type 'dedicated))
10800 (org-search-not-self 1 re1 nil t)
10801 (org-search-not-self 1 re2 nil t)
10802 (org-search-not-self 1 re2a nil t)
10803 (org-search-not-self 1 re3 nil t)
10804 (org-search-not-self 1 re4 nil t)
10805 (org-search-not-self 1 re5 nil t))
10806 (goto-char (match-beginning 1))
10807 (goto-char pos)
10808 (error "No match"))))))
10809 (and (derived-mode-p 'org-mode)
10810 (not stealth)
10811 (org-show-context 'link-search))
10812 type))
10814 (defun org-search-not-self (group &rest args)
10815 "Execute `re-search-forward', but only accept matches that do not
10816 enclose the position of `org-open-link-marker'."
10817 (let ((m org-open-link-marker))
10818 (catch 'exit
10819 (while (apply 're-search-forward args)
10820 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10821 (goto-char (match-end group))
10822 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10823 (> (match-beginning 0) (marker-position m))
10824 (< (match-end 0) (marker-position m)))
10825 (save-match-data
10826 (or (not (org-in-regexp
10827 org-bracket-link-analytic-regexp 1))
10828 (not (match-end 4)) ; no description
10829 (and (<= (match-beginning 4) (point))
10830 (>= (match-end 4) (point))))))
10831 (throw 'exit (point))))))))
10833 (defun org-get-buffer-for-internal-link (buffer)
10834 "Return a buffer to be used for displaying the link target of internal links."
10835 (cond
10836 ((not org-display-internal-link-with-indirect-buffer)
10837 buffer)
10838 ((string-match "(Clone)$" (buffer-name buffer))
10839 (message "Buffer is already a clone, not making another one")
10840 ;; we also do not modify visibility in this case
10841 buffer)
10842 (t ; make a new indirect buffer for displaying the link
10843 (let* ((bn (buffer-name buffer))
10844 (ibn (concat bn "(Clone)"))
10845 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10846 (with-current-buffer ib (org-overview))
10847 ib))))
10849 (defun org-do-occur (regexp &optional cleanup)
10850 "Call the Emacs command `occur'.
10851 If CLEANUP is non-nil, remove the printout of the regular expression
10852 in the *Occur* buffer. This is useful if the regex is long and not useful
10853 to read."
10854 (occur regexp)
10855 (when cleanup
10856 (let ((cwin (selected-window)) win beg end)
10857 (when (setq win (get-buffer-window "*Occur*"))
10858 (select-window win))
10859 (goto-char (point-min))
10860 (when (re-search-forward "match[a-z]+" nil t)
10861 (setq beg (match-end 0))
10862 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10863 (setq end (1- (match-beginning 0)))))
10864 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10865 (goto-char (point-min))
10866 (select-window cwin))))
10868 ;;; The mark ring for links jumps
10870 (defvar org-mark-ring nil
10871 "Mark ring for positions before jumps in Org-mode.")
10872 (defvar org-mark-ring-last-goto nil
10873 "Last position in the mark ring used to go back.")
10874 ;; Fill and close the ring
10875 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10876 (loop for i from 1 to org-mark-ring-length do
10877 (push (make-marker) org-mark-ring))
10878 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10879 org-mark-ring)
10881 (defun org-mark-ring-push (&optional pos buffer)
10882 "Put the current position or POS into the mark ring and rotate it."
10883 (interactive)
10884 (setq pos (or pos (point)))
10885 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10886 (move-marker (car org-mark-ring)
10887 (or pos (point))
10888 (or buffer (current-buffer)))
10889 (message "%s"
10890 (substitute-command-keys
10891 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10893 (defun org-mark-ring-goto (&optional n)
10894 "Jump to the previous position in the mark ring.
10895 With prefix arg N, jump back that many stored positions. When
10896 called several times in succession, walk through the entire ring.
10897 Org-mode commands jumping to a different position in the current file,
10898 or to another Org-mode file, automatically push the old position
10899 onto the ring."
10900 (interactive "p")
10901 (let (p m)
10902 (if (eq last-command this-command)
10903 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10904 (setq p org-mark-ring))
10905 (setq org-mark-ring-last-goto p)
10906 (setq m (car p))
10907 (org-pop-to-buffer-same-window (marker-buffer m))
10908 (goto-char m)
10909 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10911 (defun org-remove-angle-brackets (s)
10912 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10913 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10915 (defun org-add-angle-brackets (s)
10916 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10917 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10919 (defun org-remove-double-quotes (s)
10920 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10921 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10924 ;;; Following specific links
10926 (defun org-follow-timestamp-link ()
10927 "Open an agenda view for the time-stamp date/range at point."
10928 (cond
10929 ((org-at-date-range-p t)
10930 (let ((org-agenda-start-on-weekday)
10931 (t1 (match-string 1))
10932 (t2 (match-string 2)) tt1 tt2)
10933 (setq tt1 (time-to-days (org-time-string-to-time t1))
10934 tt2 (time-to-days (org-time-string-to-time t2)))
10935 (let ((org-agenda-buffer-tmp-name
10936 (format "*Org Agenda(a:%s)"
10937 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10938 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10939 ((org-at-timestamp-p t)
10940 (let ((org-agenda-buffer-tmp-name
10941 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10942 (org-agenda-list nil (time-to-days (org-time-string-to-time
10943 (substring (match-string 1) 0 10)))
10944 1)))
10945 (t (error "This should not happen"))))
10948 ;;; Following file links
10949 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10950 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10951 (declare-function mailcap-mime-info
10952 "mailcap" (string &optional request no-decode))
10953 (defvar org-wait nil)
10954 (defun org-open-file (path &optional in-emacs line search)
10955 "Open the file at PATH.
10956 First, this expands any special file name abbreviations. Then the
10957 configuration variable `org-file-apps' is checked if it contains an
10958 entry for this file type, and if yes, the corresponding command is launched.
10960 If no application is found, Emacs simply visits the file.
10962 With optional prefix argument IN-EMACS, Emacs will visit the file.
10963 With a double \\[universal-argument] \\[universal-argument] \
10964 prefix arg, Org tries to avoid opening in Emacs
10965 and to use an external application to visit the file.
10967 Optional LINE specifies a line to go to, optional SEARCH a string
10968 to search for. If LINE or SEARCH is given, the file will be
10969 opened in Emacs, unless an entry from org-file-apps that makes
10970 use of groups in a regexp matches.
10972 If you want to change the way frames are used when following a
10973 link, please customize `org-link-frame-setup'.
10975 If the file does not exist, an error is thrown."
10976 (let* ((file (if (equal path "")
10977 buffer-file-name
10978 (substitute-in-file-name (expand-file-name path))))
10979 (file-apps (append org-file-apps (org-default-apps)))
10980 (apps (org-remove-if
10981 'org-file-apps-entry-match-against-dlink-p file-apps))
10982 (apps-dlink (org-remove-if-not
10983 'org-file-apps-entry-match-against-dlink-p file-apps))
10984 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10985 (dirp (if remp nil (file-directory-p file)))
10986 (file (if (and dirp org-open-directory-means-index-dot-org)
10987 (concat (file-name-as-directory file) "index.org")
10988 file))
10989 (a-m-a-p (assq 'auto-mode apps))
10990 (dfile (downcase file))
10991 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10992 (link (cond ((and (eq line nil)
10993 (eq search nil))
10994 file)
10995 (line
10996 (concat file "::" (number-to-string line)))
10997 (search
10998 (concat file "::" search))))
10999 (dlink (downcase link))
11000 (old-buffer (current-buffer))
11001 (old-pos (point))
11002 (old-mode major-mode)
11003 ext cmd link-match-data)
11004 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11005 (setq ext (match-string 1 dfile))
11006 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11007 (setq ext (match-string 1 dfile))))
11008 (cond
11009 ((member in-emacs '((16) system))
11010 (setq cmd (cdr (assoc 'system apps))))
11011 (in-emacs (setq cmd 'emacs))
11013 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11014 (and dirp (cdr (assoc 'directory apps)))
11015 ; first, try matching against apps-dlink
11016 ; if we get a match here, store the match data for later
11017 (let ((match (assoc-default dlink apps-dlink
11018 'string-match)))
11019 (if match
11020 (progn (setq link-match-data (match-data))
11021 match)
11022 (progn (setq in-emacs (or in-emacs line search))
11023 nil))) ; if we have no match in apps-dlink,
11024 ; always open the file in emacs if line or search
11025 ; is given (for backwards compatibility)
11026 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11027 'string-match)
11028 (cdr (assoc ext apps))
11029 (cdr (assoc t apps))))))
11030 (when (eq cmd 'system)
11031 (setq cmd (cdr (assoc 'system apps))))
11032 (when (eq cmd 'default)
11033 (setq cmd (cdr (assoc t apps))))
11034 (when (eq cmd 'mailcap)
11035 (require 'mailcap)
11036 (mailcap-parse-mailcaps)
11037 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11038 (command (mailcap-mime-info mime-type)))
11039 (if (stringp command)
11040 (setq cmd command)
11041 (setq cmd 'emacs))))
11042 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11043 (not (file-exists-p file))
11044 (not org-open-non-existing-files))
11045 (user-error "No such file: %s" file))
11046 (cond
11047 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11048 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11049 (while (string-match "['\"]%s['\"]" cmd)
11050 (setq cmd (replace-match "%s" t t cmd)))
11051 (while (string-match "%s" cmd)
11052 (setq cmd (replace-match
11053 (save-match-data
11054 (shell-quote-argument
11055 (convert-standard-filename file)))
11056 t t cmd)))
11058 ;; Replace "%1", "%2" etc. in command with group matches from regex
11059 (save-match-data
11060 (let ((match-index 1)
11061 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11062 (set-match-data link-match-data)
11063 (while (<= match-index number-of-groups)
11064 (let ((regex (concat "%" (number-to-string match-index)))
11065 (replace-with (match-string match-index dlink)))
11066 (while (string-match regex cmd)
11067 (setq cmd (replace-match replace-with t t cmd))))
11068 (setq match-index (+ match-index 1)))))
11070 (save-window-excursion
11071 (message "Running %s...done" cmd)
11072 (start-process-shell-command cmd nil cmd)
11073 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11074 ((or (stringp cmd)
11075 (eq cmd 'emacs))
11076 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11077 (widen)
11078 (if line (org-goto-line line)
11079 (if search (org-link-search search))))
11080 ((consp cmd)
11081 (let ((file (convert-standard-filename file)))
11082 (save-match-data
11083 (set-match-data link-match-data)
11084 (eval cmd))))
11085 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11086 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11087 (or (not (equal old-buffer (current-buffer)))
11088 (not (equal old-pos (point))))
11089 (org-mark-ring-push old-pos old-buffer))))
11091 (defun org-file-apps-entry-match-against-dlink-p (entry)
11092 "This function returns non-nil if `entry' uses a regular
11093 expression which should be matched against the whole link by
11094 org-open-file.
11096 It assumes that is the case when the entry uses a regular
11097 expression which has at least one grouping construct and the
11098 action is either a lisp form or a command string containing
11099 '%1', i.e. using at least one subexpression match as a
11100 parameter."
11101 (let ((selector (car entry))
11102 (action (cdr entry)))
11103 (if (stringp selector)
11104 (and (> (regexp-opt-depth selector) 0)
11105 (or (and (stringp action)
11106 (string-match "%[0-9]" action))
11107 (consp action)))
11108 nil)))
11110 (defun org-default-apps ()
11111 "Return the default applications for this operating system."
11112 (cond
11113 ((eq system-type 'darwin)
11114 org-file-apps-defaults-macosx)
11115 ((eq system-type 'windows-nt)
11116 org-file-apps-defaults-windowsnt)
11117 (t org-file-apps-defaults-gnu)))
11119 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11120 "Convert extensions to regular expressions in the cars of LIST.
11121 Also, weed out any non-string entries, because the return value is used
11122 only for regexp matching.
11123 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11124 point to the symbol `emacs', indicating that the file should
11125 be opened in Emacs."
11126 (append
11127 (delq nil
11128 (mapcar (lambda (x)
11129 (if (not (stringp (car x)))
11131 (if (string-match "\\W" (car x))
11133 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11134 list))
11135 (if add-auto-mode
11136 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11138 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11139 (defun org-file-remote-p (file)
11140 "Test whether FILE specifies a location on a remote system.
11141 Return non-nil if the location is indeed remote.
11143 For example, the filename \"/user@host:/foo\" specifies a location
11144 on the system \"/user@host:\"."
11145 (cond ((fboundp 'file-remote-p)
11146 (file-remote-p file))
11147 ((fboundp 'tramp-handle-file-remote-p)
11148 (tramp-handle-file-remote-p file))
11149 ((and (boundp 'ange-ftp-name-format)
11150 (string-match (car ange-ftp-name-format) file))
11151 t)))
11154 ;;;; Refiling
11156 (defun org-get-org-file ()
11157 "Read a filename, with default directory `org-directory'."
11158 (let ((default (or org-default-notes-file remember-data-file)))
11159 (read-file-name (format "File name [%s]: " default)
11160 (file-name-as-directory org-directory)
11161 default)))
11163 (defun org-notes-order-reversed-p ()
11164 "Check if the current file should receive notes in reversed order."
11165 (cond
11166 ((not org-reverse-note-order) nil)
11167 ((eq t org-reverse-note-order) t)
11168 ((not (listp org-reverse-note-order)) nil)
11169 (t (catch 'exit
11170 (let ((all org-reverse-note-order)
11171 entry)
11172 (while (setq entry (pop all))
11173 (if (string-match (car entry) buffer-file-name)
11174 (throw 'exit (cdr entry))))
11175 nil)))))
11177 (defvar org-refile-target-table nil
11178 "The list of refile targets, created by `org-refile'.")
11180 (defvar org-agenda-new-buffers nil
11181 "Buffers created to visit agenda files.")
11183 (defvar org-refile-cache nil
11184 "Cache for refile targets.")
11186 (defvar org-refile-markers nil
11187 "All the markers used for caching refile locations.")
11189 (defun org-refile-marker (pos)
11190 "Get a new refile marker, but only if caching is in use."
11191 (if (not org-refile-use-cache)
11193 (let ((m (make-marker)))
11194 (move-marker m pos)
11195 (push m org-refile-markers)
11196 m)))
11198 (defun org-refile-cache-clear ()
11199 "Clear the refile cache and disable all the markers."
11200 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11201 (setq org-refile-markers nil)
11202 (setq org-refile-cache nil)
11203 (message "Refile cache has been cleared"))
11205 (defun org-refile-cache-check-set (set)
11206 "Check if all the markers in the cache still have live buffers."
11207 (let (marker)
11208 (catch 'exit
11209 (while (and set (setq marker (nth 3 (pop set))))
11210 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11211 (when (and marker (null (marker-buffer marker)))
11212 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11213 (sit-for 3)
11214 (throw 'exit nil)))
11215 t)))
11217 (defun org-refile-cache-put (set &rest identifiers)
11218 "Push the refile targets SET into the cache, under IDENTIFIERS."
11219 (let* ((key (sha1 (prin1-to-string identifiers)))
11220 (entry (assoc key org-refile-cache)))
11221 (if entry
11222 (setcdr entry set)
11223 (push (cons key set) org-refile-cache))))
11225 (defun org-refile-cache-get (&rest identifiers)
11226 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11227 (cond
11228 ((not org-refile-cache) nil)
11229 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11231 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11232 org-refile-cache))))
11233 (and set (org-refile-cache-check-set set) set)))))
11235 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11236 "Produce a table with refile targets."
11237 (let ((case-fold-search nil)
11238 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11239 (entries (or org-refile-targets '((nil . (:level . 1)))))
11240 targets tgs txt re files f desc descre fast-path-p level pos0)
11241 (message "Getting targets...")
11242 (with-current-buffer (or default-buffer (current-buffer))
11243 (while (setq entry (pop entries))
11244 (setq files (car entry) desc (cdr entry))
11245 (setq fast-path-p nil)
11246 (cond
11247 ((null files) (setq files (list (current-buffer))))
11248 ((eq files 'org-agenda-files)
11249 (setq files (org-agenda-files 'unrestricted)))
11250 ((and (symbolp files) (fboundp files))
11251 (setq files (funcall files)))
11252 ((and (symbolp files) (boundp files))
11253 (setq files (symbol-value files))))
11254 (if (stringp files) (setq files (list files)))
11255 (cond
11256 ((eq (car desc) :tag)
11257 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11258 ((eq (car desc) :todo)
11259 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11260 ((eq (car desc) :regexp)
11261 (setq descre (cdr desc)))
11262 ((eq (car desc) :level)
11263 (setq descre (concat "^\\*\\{" (number-to-string
11264 (if org-odd-levels-only
11265 (1- (* 2 (cdr desc)))
11266 (cdr desc)))
11267 "\\}[ \t]")))
11268 ((eq (car desc) :maxlevel)
11269 (setq fast-path-p t)
11270 (setq descre (concat "^\\*\\{1," (number-to-string
11271 (if org-odd-levels-only
11272 (1- (* 2 (cdr desc)))
11273 (cdr desc)))
11274 "\\}[ \t]")))
11275 (t (error "Bad refiling target description %s" desc)))
11276 (while (setq f (pop files))
11277 (with-current-buffer
11278 (if (bufferp f) f (org-get-agenda-file-buffer f))
11280 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11281 (progn
11282 (if (bufferp f) (setq f (buffer-file-name
11283 (buffer-base-buffer f))))
11284 (setq f (and f (expand-file-name f)))
11285 (if (eq org-refile-use-outline-path 'file)
11286 (push (list (file-name-nondirectory f) f nil nil) tgs))
11287 (save-excursion
11288 (save-restriction
11289 (widen)
11290 (goto-char (point-min))
11291 (while (re-search-forward descre nil t)
11292 (goto-char (setq pos0 (point-at-bol)))
11293 (catch 'next
11294 (when org-refile-target-verify-function
11295 (save-match-data
11296 (or (funcall org-refile-target-verify-function)
11297 (throw 'next t))))
11298 (when (and (looking-at org-complex-heading-regexp)
11299 (not (member (match-string 4) excluded-entries))
11300 (match-string 4))
11301 (setq level (org-reduced-level
11302 (- (match-end 1) (match-beginning 1)))
11303 txt (org-link-display-format (match-string 4))
11304 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11305 re (format org-complex-heading-regexp-format
11306 (regexp-quote (match-string 4))))
11307 (when org-refile-use-outline-path
11308 (setq txt (mapconcat
11309 'org-protect-slash
11310 (append
11311 (if (eq org-refile-use-outline-path
11312 'file)
11313 (list (file-name-nondirectory
11314 (buffer-file-name
11315 (buffer-base-buffer))))
11316 (if (eq org-refile-use-outline-path
11317 'full-file-path)
11318 (list (buffer-file-name
11319 (buffer-base-buffer)))))
11320 (org-get-outline-path fast-path-p
11321 level txt)
11322 (list txt))
11323 "/")))
11324 (push (list txt f re (org-refile-marker (point)))
11325 tgs)))
11326 (when (= (point) pos0)
11327 ;; verification function has not moved point
11328 (goto-char (point-at-eol))))))))
11329 (when org-refile-use-cache
11330 (org-refile-cache-put tgs (buffer-file-name) descre))
11331 (setq targets (append tgs targets))))))
11332 (message "Getting targets...done")
11333 (nreverse targets)))
11335 (defun org-protect-slash (s)
11336 (while (string-match "/" s)
11337 (setq s (replace-match "\\" t t s)))
11340 (defvar org-olpa (make-vector 20 nil))
11342 (defun org-get-outline-path (&optional fastp level heading)
11343 "Return the outline path to the current entry, as a list.
11345 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11346 routine which makes outline path derivations for an entire file,
11347 avoiding backtracing. Refile target collection makes use of that."
11348 (if fastp
11349 (progn
11350 (if (> level 19)
11351 (error "Outline path failure, more than 19 levels"))
11352 (loop for i from level upto 19 do
11353 (aset org-olpa i nil))
11354 (prog1
11355 (delq nil (append org-olpa nil))
11356 (aset org-olpa level heading)))
11357 (let (rtn case-fold-search)
11358 (save-excursion
11359 (save-restriction
11360 (widen)
11361 (while (org-up-heading-safe)
11362 (when (looking-at org-complex-heading-regexp)
11363 (push (org-trim
11364 (replace-regexp-in-string
11365 ;; Remove statistical/checkboxes cookies
11366 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11367 (org-match-string-no-properties 4)))
11368 rtn)))
11369 rtn)))))
11371 (defun org-format-outline-path (path &optional width prefix separator)
11372 "Format the outline path PATH for display.
11373 WIDTH is the maximum number of characters that is available.
11374 PREFIX is a prefix to be included in the returned string,
11375 such as the file name.
11376 SEPARATOR is inserted between the different parts of the path,
11377 the default is \"/\"."
11378 (setq width (or width 79))
11379 (if prefix (setq width (- width (length prefix))))
11380 (if (not path)
11381 (or prefix "")
11382 (let* ((nsteps (length path))
11383 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11384 (maxwidth (if (<= total-width width)
11385 10000 ;; everything fits
11386 ;; we need to shorten the level headings
11387 (/ (- width nsteps) nsteps)))
11388 (org-odd-levels-only nil)
11389 (n 0)
11390 (total (1+ (length prefix))))
11391 (setq maxwidth (max maxwidth 10))
11392 (concat prefix
11393 (if prefix (or separator "/"))
11394 (mapconcat
11395 (lambda (h)
11396 (setq n (1+ n))
11397 (if (and (= n nsteps) (< maxwidth 10000))
11398 (setq maxwidth (- total-width total)))
11399 (if (< (length h) maxwidth)
11400 (progn (setq total (+ total (length h) 1)) h)
11401 (setq h (substring h 0 (- maxwidth 2))
11402 total (+ total maxwidth 1))
11403 (if (string-match "[ \t]+\\'" h)
11404 (setq h (substring h 0 (match-beginning 0))))
11405 (setq h (concat h "..")))
11406 (org-add-props h nil 'face
11407 (nth (% (1- n) org-n-level-faces)
11408 org-level-faces))
11410 path (or separator "/"))))))
11412 (defun org-display-outline-path (&optional file current separator just-return-string)
11413 "Display the current outline path in the echo area.
11415 If FILE is non-nil, prepend the output with the file name.
11416 If CURRENT is non-nil, append the current heading to the output.
11417 SEPARATOR is passed through to `org-format-outline-path'. It separates
11418 the different parts of the path and defaults to \"/\".
11419 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11420 (interactive "P")
11421 (let* (case-fold-search
11422 message-log-max ; Don't populate the *Messages* buffer
11423 (bfn (buffer-file-name (buffer-base-buffer)))
11424 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11425 res)
11426 (if current (setq path (append path
11427 (save-excursion
11428 (org-back-to-heading t)
11429 (if (looking-at org-complex-heading-regexp)
11430 (list (match-string 4)))))))
11431 (setq res
11432 (org-format-outline-path
11433 path
11434 (1- (frame-width))
11435 (and file bfn (concat (file-name-nondirectory bfn) separator))
11436 separator))
11437 (if just-return-string
11438 (org-no-properties res)
11439 (message "%s" res))))
11441 (defvar org-refile-history nil
11442 "History for refiling operations.")
11444 (defvar org-after-refile-insert-hook nil
11445 "Hook run after `org-refile' has inserted its stuff at the new location.
11446 Note that this is still *before* the stuff will be removed from
11447 the *old* location.")
11449 (defvar org-capture-last-stored-marker)
11450 (defvar org-refile-keep nil
11451 "Non-nil means `org-refile' will copy instead of refile.")
11453 (defun org-copy ()
11454 "Like `org-refile', but copy."
11455 (interactive)
11456 (let ((org-refile-keep t))
11457 (funcall 'org-refile nil nil nil "Copy")))
11459 (defun org-refile (&optional goto default-buffer rfloc msg)
11460 "Move the entry or entries at point to another heading.
11461 The list of target headings is compiled using the information in
11462 `org-refile-targets', which see.
11464 At the target location, the entry is filed as a subitem of the target
11465 heading. Depending on `org-reverse-note-order', the new subitem will
11466 either be the first or the last subitem.
11468 If there is an active region, all entries in that region will be moved.
11469 However, the region must fulfill the requirement that the first heading
11470 is the first one sets the top-level of the moved text - at most siblings
11471 below it are allowed.
11473 With prefix arg GOTO, the command will only visit the target location
11474 and not actually move anything.
11476 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11477 go to the location where the last refiling operation has put the subtree.
11478 With a prefix argument of `2', refile to the running clock.
11480 RFLOC can be a refile location obtained in a different way.
11482 MSG is a string to replace \"Refile\" in the default prompt with
11483 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11485 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11487 If you are using target caching (see `org-refile-use-cache'),
11488 you have to clear the target cache in order to find new targets.
11489 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11490 prefix argument (`C-u C-u C-u C-c C-w')."
11492 (interactive "P")
11493 (if (member goto '(0 (64)))
11494 (org-refile-cache-clear)
11495 (let* ((actionmsg (or msg "Refile"))
11496 (cbuf (current-buffer))
11497 (regionp (org-region-active-p))
11498 (region-start (and regionp (region-beginning)))
11499 (region-end (and regionp (region-end)))
11500 (region-length (and regionp (- region-end region-start)))
11501 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11502 pos it nbuf file re level reversed)
11503 (setq last-command nil)
11504 (when regionp
11505 (goto-char region-start)
11506 (or (bolp) (goto-char (point-at-bol)))
11507 (setq region-start (point))
11508 (unless (or (org-kill-is-subtree-p
11509 (buffer-substring region-start region-end))
11510 (prog1 org-refile-active-region-within-subtree
11511 (org-toggle-heading)))
11512 (user-error "The region is not a (sequence of) subtree(s)")))
11513 (if (equal goto '(16))
11514 (org-refile-goto-last-stored)
11515 (when (or
11516 (and (equal goto 2)
11517 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11518 (prog1
11519 (setq it (list (or org-clock-heading "running clock")
11520 (buffer-file-name
11521 (marker-buffer org-clock-hd-marker))
11523 (marker-position org-clock-hd-marker)))
11524 (setq goto nil)))
11525 (setq it (or rfloc
11526 (let (heading-text)
11527 (save-excursion
11528 (unless goto
11529 (org-back-to-heading t)
11530 (setq heading-text
11531 (nth 4 (org-heading-components))))
11533 (org-refile-get-location
11534 (cond (goto "Goto")
11535 (regionp (concat actionmsg " region to"))
11536 (t (concat actionmsg " subtree \""
11537 heading-text "\" to")))
11538 default-buffer
11539 (and (not (equal '(4) goto))
11540 org-refile-allow-creating-parent-nodes)
11541 goto))))))
11542 (setq file (nth 1 it)
11543 re (nth 2 it)
11544 pos (nth 3 it))
11545 (if (and (not goto)
11547 (equal (buffer-file-name) file)
11548 (if regionp
11549 (and (>= pos region-start)
11550 (<= pos region-end))
11551 (and (>= pos (point))
11552 (< pos (save-excursion
11553 (org-end-of-subtree t t))))))
11554 (error "Cannot refile to position inside the tree or region"))
11556 (setq nbuf (or (find-buffer-visiting file)
11557 (find-file-noselect file)))
11558 (if goto
11559 (progn
11560 (org-pop-to-buffer-same-window nbuf)
11561 (goto-char pos)
11562 (org-show-context 'org-goto))
11563 (if regionp
11564 (progn
11565 (org-kill-new (buffer-substring region-start region-end))
11566 (org-save-markers-in-region region-start region-end))
11567 (org-copy-subtree 1 nil t))
11568 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11569 (find-file-noselect file)))
11570 (setq reversed (org-notes-order-reversed-p))
11571 (save-excursion
11572 (save-restriction
11573 (widen)
11574 (if pos
11575 (progn
11576 (goto-char pos)
11577 (looking-at org-outline-regexp)
11578 (setq level (org-get-valid-level (funcall outline-level) 1))
11579 (goto-char
11580 (if reversed
11581 (or (outline-next-heading) (point-max))
11582 (or (save-excursion (org-get-next-sibling))
11583 (org-end-of-subtree t t)
11584 (point-max)))))
11585 (setq level 1)
11586 (if (not reversed)
11587 (goto-char (point-max))
11588 (goto-char (point-min))
11589 (or (outline-next-heading) (goto-char (point-max)))))
11590 (if (not (bolp)) (newline))
11591 (org-paste-subtree level)
11592 (when org-log-refile
11593 (org-add-log-setup 'refile nil nil 'findpos
11594 org-log-refile)
11595 (unless (eq org-log-refile 'note)
11596 (save-excursion (org-add-log-note))))
11597 (and org-auto-align-tags
11598 (let ((org-loop-over-headlines-in-active-region nil))
11599 (org-set-tags nil t)))
11600 (with-demoted-errors
11601 (bookmark-set "org-refile-last-stored"))
11602 ;; If we are refiling for capture, make sure that the
11603 ;; last-capture pointers point here
11604 (when (org-bound-and-true-p org-refile-for-capture)
11605 (with-demoted-errors
11606 (bookmark-set "org-capture-last-stored-marker"))
11607 (move-marker org-capture-last-stored-marker (point)))
11608 (if (fboundp 'deactivate-mark) (deactivate-mark))
11609 (run-hooks 'org-after-refile-insert-hook))))
11610 (unless org-refile-keep
11611 (if regionp
11612 (delete-region (point) (+ (point) region-length))
11613 (org-cut-subtree)))
11614 (when (featurep 'org-inlinetask)
11615 (org-inlinetask-remove-END-maybe))
11616 (setq org-markers-to-move nil)
11617 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11619 (defun org-refile-goto-last-stored ()
11620 "Go to the location where the last refile was stored."
11621 (interactive)
11622 (bookmark-jump "org-refile-last-stored")
11623 (message "This is the location of the last refile"))
11625 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11626 no-exclude)
11627 "Prompt the user for a refile location, using PROMPT.
11628 PROMPT should not be suffixed with a colon and a space, because
11629 this function appends the default value from
11630 `org-refile-history' automatically, if that is not empty.
11631 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11632 this is used for the GOTO interface."
11633 (let ((org-refile-targets org-refile-targets)
11634 (org-refile-use-outline-path org-refile-use-outline-path)
11635 excluded-entries)
11636 (when (and (derived-mode-p 'org-mode)
11637 (not org-refile-use-cache)
11638 (not no-exclude))
11639 (org-map-tree
11640 (lambda()
11641 (setq excluded-entries
11642 (append excluded-entries (list (org-get-heading t t)))))))
11643 (setq org-refile-target-table
11644 (org-refile-get-targets default-buffer excluded-entries)))
11645 (unless org-refile-target-table
11646 (user-error "No refile targets"))
11647 (let* ((cbuf (current-buffer))
11648 (partial-completion-mode nil)
11649 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11650 (cfunc (if (and org-refile-use-outline-path
11651 org-outline-path-complete-in-steps)
11652 'org-olpath-completing-read
11653 'org-icompleting-read))
11654 (extra (if org-refile-use-outline-path "/" ""))
11655 (cbnex (concat (buffer-name) extra))
11656 (filename (and cfn (expand-file-name cfn)))
11657 (tbl (mapcar
11658 (lambda (x)
11659 (if (and (not (member org-refile-use-outline-path
11660 '(file full-file-path)))
11661 (not (equal filename (nth 1 x))))
11662 (cons (concat (car x) extra " ("
11663 (file-name-nondirectory (nth 1 x)) ")")
11664 (cdr x))
11665 (cons (concat (car x) extra) (cdr x))))
11666 org-refile-target-table))
11667 (completion-ignore-case t)
11668 cdef
11669 (prompt (concat prompt
11670 (or (and (car org-refile-history)
11671 (concat " (default " (car org-refile-history) ")"))
11672 (and (assoc cbnex tbl) (setq cdef cbnex)
11673 (concat " (default " cbnex ")"))) ": "))
11674 pa answ parent-target child parent old-hist)
11675 (setq old-hist org-refile-history)
11676 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11677 nil 'org-refile-history (or cdef (car org-refile-history))))
11678 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11679 (org-refile-check-position pa)
11680 (if pa
11681 (progn
11682 (when (or (not org-refile-history)
11683 (not (eq old-hist org-refile-history))
11684 (not (equal (car pa) (car org-refile-history))))
11685 (setq org-refile-history
11686 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11687 org-refile-history
11688 (cdr org-refile-history))))
11689 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11690 (pop org-refile-history)))
11692 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11693 (progn
11694 (setq parent (match-string 1 answ)
11695 child (match-string 2 answ))
11696 (setq parent-target (or (assoc parent tbl)
11697 (assoc (concat parent "/") tbl)))
11698 (when (and parent-target
11699 (or (eq new-nodes t)
11700 (and (eq new-nodes 'confirm)
11701 (y-or-n-p (format "Create new node \"%s\"? "
11702 child)))))
11703 (org-refile-new-child parent-target child)))
11704 (user-error "Invalid target location")))))
11706 (declare-function org-string-nw-p "org-macs" (s))
11707 (defun org-refile-check-position (refile-pointer)
11708 "Check if the refile pointer matches the headline to which it points."
11709 (let* ((file (nth 1 refile-pointer))
11710 (re (nth 2 refile-pointer))
11711 (pos (nth 3 refile-pointer))
11712 buffer)
11713 (if (and (not (markerp pos)) (not file))
11714 (user-error "Please save the buffer to a file before refiling")
11715 (when (org-string-nw-p re)
11716 (setq buffer (if (markerp pos)
11717 (marker-buffer pos)
11718 (or (find-buffer-visiting file)
11719 (find-file-noselect file))))
11720 (with-current-buffer buffer
11721 (save-excursion
11722 (save-restriction
11723 (widen)
11724 (goto-char pos)
11725 (beginning-of-line 1)
11726 (unless (org-looking-at-p re)
11727 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11729 (defun org-refile-new-child (parent-target child)
11730 "Use refile target PARENT-TARGET to add new CHILD below it."
11731 (unless parent-target
11732 (error "Cannot find parent for new node"))
11733 (let ((file (nth 1 parent-target))
11734 (pos (nth 3 parent-target))
11735 level)
11736 (with-current-buffer (or (find-buffer-visiting file)
11737 (find-file-noselect file))
11738 (save-excursion
11739 (save-restriction
11740 (widen)
11741 (if pos
11742 (goto-char pos)
11743 (goto-char (point-max))
11744 (if (not (bolp)) (newline)))
11745 (when (looking-at org-outline-regexp)
11746 (setq level (funcall outline-level))
11747 (org-end-of-subtree t t))
11748 (org-back-over-empty-lines)
11749 (insert "\n" (make-string
11750 (if pos (org-get-valid-level level 1) 1) ?*)
11751 " " child "\n")
11752 (beginning-of-line 0)
11753 (list (concat (car parent-target) "/" child) file "" (point)))))))
11755 (defun org-olpath-completing-read (prompt collection &rest args)
11756 "Read an outline path like a file name."
11757 (let ((thetable collection)
11758 (org-completion-use-ido nil) ; does not work with ido.
11759 (org-completion-use-iswitchb nil)) ; or iswitchb
11760 (apply
11761 'org-icompleting-read prompt
11762 (lambda (string predicate &optional flag)
11763 (let (rtn r f (l (length string)))
11764 (cond
11765 ((eq flag nil)
11766 ;; try completion
11767 (try-completion string thetable))
11768 ((eq flag t)
11769 ;; all-completions
11770 (setq rtn (all-completions string thetable predicate))
11771 (mapcar
11772 (lambda (x)
11773 (setq r (substring x l))
11774 (if (string-match " ([^)]*)$" x)
11775 (setq f (match-string 0 x))
11776 (setq f ""))
11777 (if (string-match "/" r)
11778 (concat string (substring r 0 (match-end 0)) f)
11780 rtn))
11781 ((eq flag 'lambda)
11782 ;; exact match?
11783 (assoc string thetable)))))
11784 args)))
11786 ;;;; Dynamic blocks
11788 (defun org-find-dblock (name)
11789 "Find the first dynamic block with name NAME in the buffer.
11790 If not found, stay at current position and return nil."
11791 (let ((case-fold-search t) pos)
11792 (save-excursion
11793 (goto-char (point-min))
11794 (setq pos (and (re-search-forward
11795 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11796 (match-beginning 0))))
11797 (if pos (goto-char pos))
11798 pos))
11800 (defconst org-dblock-start-re
11801 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11802 "Matches the start line of a dynamic block, with parameters.")
11804 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11805 "Matches the end of a dynamic block.")
11807 (defun org-create-dblock (plist)
11808 "Create a dynamic block section, with parameters taken from PLIST.
11809 PLIST must contain a :name entry which is used as name of the block."
11810 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11811 (end-of-line 1)
11812 (newline))
11813 (let ((col (current-column))
11814 (name (plist-get plist :name)))
11815 (insert "#+BEGIN: " name)
11816 (while plist
11817 (if (eq (car plist) :name)
11818 (setq plist (cddr plist))
11819 (insert " " (prin1-to-string (pop plist)))))
11820 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11821 (beginning-of-line -2)))
11823 (defun org-prepare-dblock ()
11824 "Prepare dynamic block for refresh.
11825 This empties the block, puts the cursor at the insert position and returns
11826 the property list including an extra property :name with the block name."
11827 (unless (looking-at org-dblock-start-re)
11828 (user-error "Not at a dynamic block"))
11829 (let* ((begdel (1+ (match-end 0)))
11830 (name (org-no-properties (match-string 1)))
11831 (params (append (list :name name)
11832 (read (concat "(" (match-string 3) ")")))))
11833 (save-excursion
11834 (beginning-of-line 1)
11835 (skip-chars-forward " \t")
11836 (setq params (plist-put params :indentation-column (current-column))))
11837 (unless (re-search-forward org-dblock-end-re nil t)
11838 (error "Dynamic block not terminated"))
11839 (setq params
11840 (append params
11841 (list :content (buffer-substring
11842 begdel (match-beginning 0)))))
11843 (delete-region begdel (match-beginning 0))
11844 (goto-char begdel)
11845 (open-line 1)
11846 params))
11848 (defun org-map-dblocks (&optional command)
11849 "Apply COMMAND to all dynamic blocks in the current buffer.
11850 If COMMAND is not given, use `org-update-dblock'."
11851 (let ((cmd (or command 'org-update-dblock)))
11852 (save-excursion
11853 (goto-char (point-min))
11854 (while (re-search-forward org-dblock-start-re nil t)
11855 (goto-char (match-beginning 0))
11856 (save-excursion
11857 (condition-case nil
11858 (funcall cmd)
11859 (error (message "Error during update of dynamic block"))))
11860 (unless (re-search-forward org-dblock-end-re nil t)
11861 (error "Dynamic block not terminated"))))))
11863 (defun org-dblock-update (&optional arg)
11864 "User command for updating dynamic blocks.
11865 Update the dynamic block at point. With prefix ARG, update all dynamic
11866 blocks in the buffer."
11867 (interactive "P")
11868 (if arg
11869 (org-update-all-dblocks)
11870 (or (looking-at org-dblock-start-re)
11871 (org-beginning-of-dblock))
11872 (org-update-dblock)))
11874 (defun org-update-dblock ()
11875 "Update the dynamic block at point.
11876 This means to empty the block, parse for parameters and then call
11877 the correct writing function."
11878 (interactive)
11879 (save-window-excursion
11880 (let* ((pos (point))
11881 (line (org-current-line))
11882 (params (org-prepare-dblock))
11883 (name (plist-get params :name))
11884 (indent (plist-get params :indentation-column))
11885 (cmd (intern (concat "org-dblock-write:" name))))
11886 (message "Updating dynamic block `%s' at line %d..." name line)
11887 (funcall cmd params)
11888 (message "Updating dynamic block `%s' at line %d...done" name line)
11889 (goto-char pos)
11890 (when (and indent (> indent 0))
11891 (setq indent (make-string indent ?\ ))
11892 (save-excursion
11893 (org-beginning-of-dblock)
11894 (forward-line 1)
11895 (while (not (looking-at org-dblock-end-re))
11896 (insert indent)
11897 (beginning-of-line 2))
11898 (when (looking-at org-dblock-end-re)
11899 (and (looking-at "[ \t]+")
11900 (replace-match ""))
11901 (insert indent)))))))
11903 (defun org-beginning-of-dblock ()
11904 "Find the beginning of the dynamic block at point.
11905 Error if there is no such block at point."
11906 (let ((pos (point))
11907 beg)
11908 (end-of-line 1)
11909 (if (and (re-search-backward org-dblock-start-re nil t)
11910 (setq beg (match-beginning 0))
11911 (re-search-forward org-dblock-end-re nil t)
11912 (> (match-end 0) pos))
11913 (goto-char beg)
11914 (goto-char pos)
11915 (error "Not in a dynamic block"))))
11917 (defun org-update-all-dblocks ()
11918 "Update all dynamic blocks in the buffer.
11919 This function can be used in a hook."
11920 (interactive)
11921 (when (derived-mode-p 'org-mode)
11922 (org-map-dblocks 'org-update-dblock)))
11925 ;;;; Completion
11927 (defun org-get-export-keywords ()
11928 "Return a list of all currently understood export keywords.
11929 Export keywords include options, block names, attributes and
11930 keywords relative to each registered export back-end."
11931 (delq nil
11932 (let (keywords)
11933 (mapc
11934 (lambda (back-end)
11935 (let ((props (cdr back-end)))
11936 ;; Back-end name (for keywords, like #+LATEX:)
11937 (push (upcase (symbol-name (car back-end))) keywords)
11938 ;; Back-end options.
11939 (mapc (lambda (option) (push (cadr option) keywords))
11940 (plist-get (cdr back-end) :options-alist))))
11941 (org-bound-and-true-p org-export-registered-backends))
11942 keywords)))
11944 (defconst org-options-keywords
11945 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11946 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11947 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11948 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11949 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11951 (defcustom org-structure-template-alist
11952 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11953 "<src lang=\"?\">\n\n</src>")
11954 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11955 "<example>\n?\n</example>")
11956 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11957 "<quote>\n?\n</quote>")
11958 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11959 "<verse>\n?\n</verse>")
11960 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11961 "<verbatim>\n?\n</verbatim>")
11962 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11963 "<center>\n?\n</center>")
11964 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11965 "<literal style=\"latex\">\n?\n</literal>")
11966 ("L" "#+LaTeX: "
11967 "<literal style=\"latex\">?</literal>")
11968 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11969 "<literal style=\"html\">\n?\n</literal>")
11970 ("H" "#+HTML: "
11971 "<literal style=\"html\">?</literal>")
11972 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11973 ("A" "#+ASCII: ")
11974 ("i" "#+INDEX: ?"
11975 "#+INDEX: ?")
11976 ("I" "#+INCLUDE: %file ?"
11977 "<include file=%file markup=\"?\">"))
11978 "Structure completion elements.
11979 This is a list of abbreviation keys and values. The value gets inserted
11980 if you type `<' followed by the key and then press the completion key,
11981 usually `M-TAB'. %file will be replaced by a file name after prompting
11982 for the file using completion. The cursor will be placed at the position
11983 of the `?` in the template.
11984 There are two templates for each key, the first uses the original Org syntax,
11985 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11986 the default when the /org-mtags.el/ module has been loaded. See also the
11987 variable `org-mtags-prefer-muse-templates'."
11988 :group 'org-completion
11989 :type '(repeat
11990 (string :tag "Key")
11991 (string :tag "Template")
11992 (string :tag "Muse Template")))
11994 (defun org-try-structure-completion ()
11995 "Try to complete a structure template before point.
11996 This looks for strings like \"<e\" on an otherwise empty line and
11997 expands them."
11998 (let ((l (buffer-substring (point-at-bol) (point)))
12000 (when (and (looking-at "[ \t]*$")
12001 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12002 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12003 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12004 (match-beginning 1)) a)
12005 t)))
12007 (defun org-complete-expand-structure-template (start cell)
12008 "Expand a structure template."
12009 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12010 (rpl (nth (if musep 2 1) cell))
12011 (ind ""))
12012 (delete-region start (point))
12013 (when (string-match "\\`#\\+" rpl)
12014 (cond
12015 ((bolp))
12016 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12017 (setq ind (buffer-substring (point-at-bol) (point))))
12018 (t (newline))))
12019 (setq start (point))
12020 (if (string-match "%file" rpl)
12021 (setq rpl (replace-match
12022 (concat
12023 "\""
12024 (save-match-data
12025 (abbreviate-file-name (read-file-name "Include file: ")))
12026 "\"")
12027 t t rpl)))
12028 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12029 (concat "\n" ind)))
12030 (insert rpl)
12031 (if (re-search-backward "\\?" start t) (delete-char 1))))
12033 ;;;; TODO, DEADLINE, Comments
12035 (defun org-toggle-comment ()
12036 "Change the COMMENT state of an entry."
12037 (interactive)
12038 (save-excursion
12039 (org-back-to-heading)
12040 (let (case-fold-search)
12041 (cond
12042 ((looking-at (format org-heading-keyword-regexp-format
12043 org-comment-string))
12044 (goto-char (match-end 1))
12045 (looking-at (concat " +" org-comment-string))
12046 (replace-match "" t t)
12047 (when (eolp) (insert " ")))
12048 ((looking-at org-outline-regexp)
12049 (goto-char (match-end 0))
12050 (insert org-comment-string " "))))))
12052 (defvar org-last-todo-state-is-todo nil
12053 "This is non-nil when the last TODO state change led to a TODO state.
12054 If the last change removed the TODO tag or switched to DONE, then
12055 this is nil.")
12057 (defvar org-setting-tags nil) ; dynamically skipped
12059 (defvar org-todo-setup-filter-hook nil
12060 "Hook for functions that pre-filter todo specs.
12061 Each function takes a todo spec and returns either nil or the spec
12062 transformed into canonical form." )
12064 (defvar org-todo-get-default-hook nil
12065 "Hook for functions that get a default item for todo.
12066 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12067 nil or a string to be used for the todo mark." )
12069 (defvar org-agenda-headline-snapshot-before-repeat)
12071 (defun org-current-effective-time ()
12072 "Return current time adjusted for `org-extend-today-until' variable."
12073 (let* ((ct (org-current-time))
12074 (dct (decode-time ct))
12075 (ct1
12076 (cond
12077 (org-use-last-clock-out-time-as-effective-time
12078 (or (org-clock-get-last-clock-out-time) ct))
12079 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12080 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12081 (t ct))))
12082 ct1))
12084 (defun org-todo-yesterday (&optional arg)
12085 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12086 (interactive "P")
12087 (if (eq major-mode 'org-agenda-mode)
12088 (apply 'org-agenda-todo-yesterday arg)
12089 (let* ((hour (third (decode-time
12090 (org-current-time))))
12091 (org-extend-today-until (1+ hour)))
12092 (org-todo arg))))
12094 (defvar org-block-entry-blocking ""
12095 "First entry preventing the TODO state change.")
12097 (defun org-todo (&optional arg)
12098 "Change the TODO state of an item.
12099 The state of an item is given by a keyword at the start of the heading,
12100 like
12101 *** TODO Write paper
12102 *** DONE Call mom
12104 The different keywords are specified in the variable `org-todo-keywords'.
12105 By default the available states are \"TODO\" and \"DONE\".
12106 So for this example: when the item starts with TODO, it is changed to DONE.
12107 When it starts with DONE, the DONE is removed. And when neither TODO nor
12108 DONE are present, add TODO at the beginning of the heading.
12110 With \\[universal-argument] prefix arg, use completion to determine the new \
12111 state.
12112 With numeric prefix arg, switch to that state.
12113 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12114 keywords (nextset).
12115 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12116 With a numeric prefix arg of 0, inhibit note taking for the change.
12118 For calling through lisp, arg is also interpreted in the following way:
12119 'none -> empty state
12120 \"\"(empty string) -> switch to empty state
12121 'done -> switch to DONE
12122 'nextset -> switch to the next set of keywords
12123 'previousset -> switch to the previous set of keywords
12124 \"WAITING\" -> switch to the specified keyword, but only if it
12125 really is a member of `org-todo-keywords'."
12126 (interactive "P")
12127 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12128 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12129 'region-start-level 'region))
12130 org-loop-over-headlines-in-active-region)
12131 (org-map-entries
12132 `(org-todo ,arg)
12133 org-loop-over-headlines-in-active-region
12134 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12135 (if (equal arg '(16)) (setq arg 'nextset))
12136 (let ((org-blocker-hook org-blocker-hook)
12137 commentp
12138 case-fold-search)
12139 (when (equal arg '(64))
12140 (setq arg nil org-blocker-hook nil))
12141 (when (and org-blocker-hook
12142 (or org-inhibit-blocking
12143 (org-entry-get nil "NOBLOCKING")))
12144 (setq org-blocker-hook nil))
12145 (save-excursion
12146 (catch 'exit
12147 (org-back-to-heading t)
12148 (when (looking-at (concat "^\\*+ " org-comment-string))
12149 (org-toggle-comment)
12150 (setq commentp t))
12151 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12152 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12153 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12154 (let* ((match-data (match-data))
12155 (startpos (point-at-bol))
12156 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12157 (org-log-done org-log-done)
12158 (org-log-repeat org-log-repeat)
12159 (org-todo-log-states org-todo-log-states)
12160 (org-inhibit-logging
12161 (if (equal arg 0)
12162 (progn (setq arg nil) 'note) org-inhibit-logging))
12163 (this (match-string 1))
12164 (hl-pos (match-beginning 0))
12165 (head (org-get-todo-sequence-head this))
12166 (ass (assoc head org-todo-kwd-alist))
12167 (interpret (nth 1 ass))
12168 (done-word (nth 3 ass))
12169 (final-done-word (nth 4 ass))
12170 (org-last-state (or this ""))
12171 (completion-ignore-case t)
12172 (member (member this org-todo-keywords-1))
12173 (tail (cdr member))
12174 (org-state (cond
12175 ((and org-todo-key-trigger
12176 (or (and (equal arg '(4))
12177 (eq org-use-fast-todo-selection 'prefix))
12178 (and (not arg) org-use-fast-todo-selection
12179 (not (eq org-use-fast-todo-selection
12180 'prefix)))))
12181 ;; Use fast selection
12182 (org-fast-todo-selection))
12183 ((and (equal arg '(4))
12184 (or (not org-use-fast-todo-selection)
12185 (not org-todo-key-trigger)))
12186 ;; Read a state with completion
12187 (org-icompleting-read
12188 "State: " (mapcar 'list org-todo-keywords-1)
12189 nil t))
12190 ((eq arg 'right)
12191 (if this
12192 (if tail (car tail) nil)
12193 (car org-todo-keywords-1)))
12194 ((eq arg 'left)
12195 (if (equal member org-todo-keywords-1)
12197 (if this
12198 (nth (- (length org-todo-keywords-1)
12199 (length tail) 2)
12200 org-todo-keywords-1)
12201 (org-last org-todo-keywords-1))))
12202 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12203 (setq arg nil))) ; hack to fall back to cycling
12204 (arg
12205 ;; user or caller requests a specific state
12206 (cond
12207 ((equal arg "") nil)
12208 ((eq arg 'none) nil)
12209 ((eq arg 'done) (or done-word (car org-done-keywords)))
12210 ((eq arg 'nextset)
12211 (or (car (cdr (member head org-todo-heads)))
12212 (car org-todo-heads)))
12213 ((eq arg 'previousset)
12214 (let ((org-todo-heads (reverse org-todo-heads)))
12215 (or (car (cdr (member head org-todo-heads)))
12216 (car org-todo-heads))))
12217 ((car (member arg org-todo-keywords-1)))
12218 ((stringp arg)
12219 (user-error "State `%s' not valid in this file" arg))
12220 ((nth (1- (prefix-numeric-value arg))
12221 org-todo-keywords-1))))
12222 ((null member) (or head (car org-todo-keywords-1)))
12223 ((equal this final-done-word) nil) ;; -> make empty
12224 ((null tail) nil) ;; -> first entry
12225 ((memq interpret '(type priority))
12226 (if (eq this-command last-command)
12227 (car tail)
12228 (if (> (length tail) 0)
12229 (or done-word (car org-done-keywords))
12230 nil)))
12232 (car tail))))
12233 (org-state (or
12234 (run-hook-with-args-until-success
12235 'org-todo-get-default-hook org-state org-last-state)
12236 org-state))
12237 (next (if org-state (concat " " org-state " ") " "))
12238 (change-plist (list :type 'todo-state-change :from this :to org-state
12239 :position startpos))
12240 dolog now-done-p)
12241 (when org-blocker-hook
12242 (setq org-last-todo-state-is-todo
12243 (not (member this org-done-keywords)))
12244 (unless (save-excursion
12245 (save-match-data
12246 (org-with-wide-buffer
12247 (run-hook-with-args-until-failure
12248 'org-blocker-hook change-plist))))
12249 (if (org-called-interactively-p 'interactive)
12250 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12251 this org-state org-block-entry-blocking)
12252 ;; fail silently
12253 (message "TODO state change from %s to %s blocked (by \"%s\")"
12254 this org-state org-block-entry-blocking)
12255 (throw 'exit nil))))
12256 (store-match-data match-data)
12257 (replace-match next t t)
12258 (unless (pos-visible-in-window-p hl-pos)
12259 (message "TODO state changed to %s" (org-trim next)))
12260 (unless head
12261 (setq head (org-get-todo-sequence-head org-state)
12262 ass (assoc head org-todo-kwd-alist)
12263 interpret (nth 1 ass)
12264 done-word (nth 3 ass)
12265 final-done-word (nth 4 ass)))
12266 (when (memq arg '(nextset previousset))
12267 (message "Keyword-Set %d/%d: %s"
12268 (- (length org-todo-sets) -1
12269 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12270 (length org-todo-sets)
12271 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12272 (setq org-last-todo-state-is-todo
12273 (not (member org-state org-done-keywords)))
12274 (setq now-done-p (and (member org-state org-done-keywords)
12275 (not (member this org-done-keywords))))
12276 (and logging (org-local-logging logging))
12277 (when (and (or org-todo-log-states org-log-done)
12278 (not (eq org-inhibit-logging t))
12279 (not (memq arg '(nextset previousset))))
12280 ;; we need to look at recording a time and note
12281 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12282 (nth 2 (assoc this org-todo-log-states))))
12283 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12284 (setq dolog 'time))
12285 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12286 (and org-state
12287 (member org-state org-not-done-keywords)
12288 (not (member this org-not-done-keywords))))
12289 ;; This is now a todo state and was not one before
12290 ;; If there was a CLOSED time stamp, get rid of it.
12291 (org-add-planning-info nil nil 'closed))
12292 (when (and now-done-p org-log-done)
12293 ;; It is now done, and it was not done before
12294 (org-add-planning-info 'closed (org-current-effective-time))
12295 (if (and (not dolog) (eq 'note org-log-done))
12296 (org-add-log-setup 'done org-state this 'findpos 'note)))
12297 (when (and org-state dolog)
12298 ;; This is a non-nil state, and we need to log it
12299 (org-add-log-setup 'state org-state this 'findpos dolog)))
12300 ;; Fixup tag positioning
12301 (org-todo-trigger-tag-changes org-state)
12302 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12303 (when org-provide-todo-statistics
12304 (org-update-parent-todo-statistics))
12305 (run-hooks 'org-after-todo-state-change-hook)
12306 (if (and arg (not (member org-state org-done-keywords)))
12307 (setq head (org-get-todo-sequence-head org-state)))
12308 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12309 ;; Do we need to trigger a repeat?
12310 (when now-done-p
12311 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12312 ;; This is for the agenda, take a snapshot of the headline.
12313 (save-match-data
12314 (setq org-agenda-headline-snapshot-before-repeat
12315 (org-get-heading))))
12316 (org-auto-repeat-maybe org-state))
12317 ;; Fixup cursor location if close to the keyword
12318 (if (and (outline-on-heading-p)
12319 (not (bolp))
12320 (save-excursion (beginning-of-line 1)
12321 (looking-at org-todo-line-regexp))
12322 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12323 (progn
12324 (goto-char (or (match-end 2) (match-end 1)))
12325 (and (looking-at " ") (just-one-space))))
12326 (when org-trigger-hook
12327 (save-excursion
12328 (run-hook-with-args 'org-trigger-hook change-plist)))
12329 (when commentp (org-toggle-comment))))))))
12331 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12332 "Block turning an entry into a TODO, using the hierarchy.
12333 This checks whether the current task should be blocked from state
12334 changes. Such blocking occurs when:
12336 1. The task has children which are not all in a completed state.
12338 2. A task has a parent with the property :ORDERED:, and there
12339 are siblings prior to the current task with incomplete
12340 status.
12342 3. The parent of the task is blocked because it has siblings that should
12343 be done first, or is child of a block grandparent TODO entry."
12345 (if (not org-enforce-todo-dependencies)
12346 t ; if locally turned off don't block
12347 (catch 'dont-block
12348 ;; If this is not a todo state change, or if this entry is already DONE,
12349 ;; do not block
12350 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12351 (member (plist-get change-plist :from)
12352 (cons 'done org-done-keywords))
12353 (member (plist-get change-plist :to)
12354 (cons 'todo org-not-done-keywords))
12355 (not (plist-get change-plist :to)))
12356 (throw 'dont-block t))
12357 ;; If this task has children, and any are undone, it's blocked
12358 (save-excursion
12359 (org-back-to-heading t)
12360 (let ((this-level (funcall outline-level)))
12361 (outline-next-heading)
12362 (let ((child-level (funcall outline-level)))
12363 (while (and (not (eobp))
12364 (> child-level this-level))
12365 ;; this todo has children, check whether they are all
12366 ;; completed
12367 (if (and (not (org-entry-is-done-p))
12368 (org-entry-is-todo-p))
12369 (progn (setq org-block-entry-blocking (org-get-heading))
12370 (throw 'dont-block nil)))
12371 (outline-next-heading)
12372 (setq child-level (funcall outline-level))))))
12373 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12374 ;; any previous siblings are undone, it's blocked
12375 (save-excursion
12376 (org-back-to-heading t)
12377 (let* ((pos (point))
12378 (parent-pos (and (org-up-heading-safe) (point))))
12379 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12380 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12381 (forward-line 1)
12382 (re-search-forward org-not-done-heading-regexp pos t))
12383 (setq org-block-entry-blocking (match-string 0))
12384 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12385 ;; Search further up the hierarchy, to see if an ancestor is blocked
12386 (while t
12387 (goto-char parent-pos)
12388 (if (not (looking-at org-not-done-heading-regexp))
12389 (throw 'dont-block t)) ; do not block, parent is not a TODO
12390 (setq pos (point))
12391 (setq parent-pos (and (org-up-heading-safe) (point)))
12392 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12393 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12394 (forward-line 1)
12395 (re-search-forward org-not-done-heading-regexp pos t)
12396 (setq org-block-entry-blocking (org-get-heading)))
12397 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12399 (defcustom org-track-ordered-property-with-tag nil
12400 "Should the ORDERED property also be shown as a tag?
12401 The ORDERED property decides if an entry should require subtasks to be
12402 completed in sequence. Since a property is not very visible, setting
12403 this option means that toggling the ORDERED property with the command
12404 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12405 not relevant for the behavior, but it makes things more visible.
12407 Note that toggling the tag with tags commands will not change the property
12408 and therefore not influence behavior!
12410 This can be t, meaning the tag ORDERED should be used, It can also be a
12411 string to select a different tag for this task."
12412 :group 'org-todo
12413 :type '(choice
12414 (const :tag "No tracking" nil)
12415 (const :tag "Track with ORDERED tag" t)
12416 (string :tag "Use other tag")))
12418 (defun org-toggle-ordered-property ()
12419 "Toggle the ORDERED property of the current entry.
12420 For better visibility, you can track the value of this property with a tag.
12421 See variable `org-track-ordered-property-with-tag'."
12422 (interactive)
12423 (let* ((t1 org-track-ordered-property-with-tag)
12424 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12425 (save-excursion
12426 (org-back-to-heading)
12427 (if (org-entry-get nil "ORDERED")
12428 (progn
12429 (org-delete-property "ORDERED" "PROPERTIES")
12430 (and tag (org-toggle-tag tag 'off))
12431 (message "Subtasks can be completed in arbitrary order"))
12432 (org-entry-put nil "ORDERED" "t")
12433 (and tag (org-toggle-tag tag 'on))
12434 (message "Subtasks must be completed in sequence")))))
12436 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12437 (defun org-block-todo-from-checkboxes (change-plist)
12438 "Block turning an entry into a TODO, using checkboxes.
12439 This checks whether the current task should be blocked from state
12440 changes because there are unchecked boxes in this entry."
12441 (if (not org-enforce-todo-checkbox-dependencies)
12442 t ; if locally turned off don't block
12443 (catch 'dont-block
12444 ;; If this is not a todo state change, or if this entry is already DONE,
12445 ;; do not block
12446 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12447 (member (plist-get change-plist :from)
12448 (cons 'done org-done-keywords))
12449 (member (plist-get change-plist :to)
12450 (cons 'todo org-not-done-keywords))
12451 (not (plist-get change-plist :to)))
12452 (throw 'dont-block t))
12453 ;; If this task has checkboxes that are not checked, it's blocked
12454 (save-excursion
12455 (org-back-to-heading t)
12456 (let ((beg (point)) end)
12457 (outline-next-heading)
12458 (setq end (point))
12459 (goto-char beg)
12460 (if (org-list-search-forward
12461 (concat (org-item-beginning-re)
12462 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12463 "\\[[- ]\\]")
12464 end t)
12465 (progn
12466 (if (boundp 'org-blocked-by-checkboxes)
12467 (setq org-blocked-by-checkboxes t))
12468 (throw 'dont-block nil)))))
12469 t))) ; do not block
12471 (defun org-entry-blocked-p ()
12472 "Is the current entry blocked?"
12473 (org-with-silent-modifications
12474 (if (org-entry-get nil "NOBLOCKING")
12475 nil ;; Never block this entry
12476 (not (run-hook-with-args-until-failure
12477 'org-blocker-hook
12478 (list :type 'todo-state-change
12479 :position (point)
12480 :from 'todo
12481 :to 'done))))))
12483 (defun org-update-statistics-cookies (all)
12484 "Update the statistics cookie, either from TODO or from checkboxes.
12485 This should be called with the cursor in a line with a statistics cookie."
12486 (interactive "P")
12487 (if all
12488 (progn
12489 (org-update-checkbox-count 'all)
12490 (org-map-entries 'org-update-parent-todo-statistics))
12491 (if (not (org-at-heading-p))
12492 (org-update-checkbox-count)
12493 (let ((pos (point-marker))
12494 end l1 l2)
12495 (ignore-errors (org-back-to-heading t))
12496 (if (not (org-at-heading-p))
12497 (org-update-checkbox-count)
12498 (setq l1 (org-outline-level))
12499 (setq end (save-excursion
12500 (outline-next-heading)
12501 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12502 (point)))
12503 (if (and (save-excursion
12504 (re-search-forward
12505 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12506 (not (save-excursion (re-search-forward
12507 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12508 (org-update-checkbox-count)
12509 (if (and l2 (> l2 l1))
12510 (progn
12511 (goto-char end)
12512 (org-update-parent-todo-statistics))
12513 (goto-char pos)
12514 (beginning-of-line 1)
12515 (while (re-search-forward
12516 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12517 (point-at-eol) t)
12518 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12519 (goto-char pos)
12520 (move-marker pos nil)))))
12522 (defvar org-entry-property-inherited-from) ;; defined below
12523 (defun org-update-parent-todo-statistics ()
12524 "Update any statistics cookie in the parent of the current headline.
12525 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12526 the entire subtree and this will travel up the hierarchy and update
12527 statistics everywhere."
12528 (let* ((prop (save-excursion (org-up-heading-safe)
12529 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12530 (recursive (or (not org-hierarchical-todo-statistics)
12531 (and prop (string-match "\\<recursive\\>" prop))))
12532 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12534 (first t)
12535 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12536 level ltoggle l1 new ndel
12537 (cnt-all 0) (cnt-done 0) is-percent kwd
12538 checkbox-beg ov ovs ove cookie-present)
12539 (catch 'exit
12540 (save-excursion
12541 (beginning-of-line 1)
12542 (setq ltoggle (funcall outline-level))
12543 ;; Three situations are to consider:
12545 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12546 ;; to the top-level ancestor on the headline;
12548 ;; 2. If parent has "recursive" property, repeat up to the
12549 ;; headline setting that property, taking inheritance into
12550 ;; account;
12552 ;; 3. Else, move up to direct parent and proceed only once.
12553 (while (and (setq level (org-up-heading-safe))
12554 (or recursive first)
12555 (>= (point) lim))
12556 (setq first nil cookie-present nil)
12557 (unless (and level
12558 (not (string-match
12559 "\\<checkbox\\>"
12560 (downcase (or (org-entry-get nil "COOKIE_DATA")
12561 "")))))
12562 (throw 'exit nil))
12563 (while (re-search-forward box-re (point-at-eol) t)
12564 (setq cnt-all 0 cnt-done 0 cookie-present t)
12565 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12566 (save-match-data
12567 (unless (outline-next-heading) (throw 'exit nil))
12568 (while (and (looking-at org-complex-heading-regexp)
12569 (> (setq l1 (length (match-string 1))) level))
12570 (setq kwd (and (or recursive (= l1 ltoggle))
12571 (match-string 2)))
12572 (if (or (eq org-provide-todo-statistics 'all-headlines)
12573 (and (listp org-provide-todo-statistics)
12574 (or (member kwd org-provide-todo-statistics)
12575 (member kwd org-done-keywords))))
12576 (setq cnt-all (1+ cnt-all))
12577 (if (eq org-provide-todo-statistics t)
12578 (and kwd (setq cnt-all (1+ cnt-all)))))
12579 (and (member kwd org-done-keywords)
12580 (setq cnt-done (1+ cnt-done)))
12581 (outline-next-heading)))
12582 (setq new
12583 (if is-percent
12584 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12585 (format "[%d/%d]" cnt-done cnt-all))
12586 ndel (- (match-end 0) checkbox-beg))
12587 ;; handle overlays when updating cookie from column view
12588 (when (setq ov (car (overlays-at checkbox-beg)))
12589 (setq ovs (overlay-start ov) ove (overlay-end ov))
12590 (delete-overlay ov))
12591 (goto-char checkbox-beg)
12592 (insert new)
12593 (delete-region (point) (+ (point) ndel))
12594 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12595 (when ov (move-overlay ov ovs ove)))
12596 (when cookie-present
12597 (run-hook-with-args 'org-after-todo-statistics-hook
12598 cnt-done (- cnt-all cnt-done))))))
12599 (run-hooks 'org-todo-statistics-hook)))
12601 (defvar org-after-todo-statistics-hook nil
12602 "Hook that is called after a TODO statistics cookie has been updated.
12603 Each function is called with two arguments: the number of not-done entries
12604 and the number of done entries.
12606 For example, the following function, when added to this hook, will switch
12607 an entry to DONE when all children are done, and back to TODO when new
12608 entries are set to a TODO status. Note that this hook is only called
12609 when there is a statistics cookie in the headline!
12611 (defun org-summary-todo (n-done n-not-done)
12612 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12613 (let (org-log-done org-log-states) ; turn off logging
12614 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12617 (defvar org-todo-statistics-hook nil
12618 "Hook that is run whenever Org thinks TODO statistics should be updated.
12619 This hook runs even if there is no statistics cookie present, in which case
12620 `org-after-todo-statistics-hook' would not run.")
12622 (defun org-todo-trigger-tag-changes (state)
12623 "Apply the changes defined in `org-todo-state-tags-triggers'."
12624 (let ((l org-todo-state-tags-triggers)
12625 changes)
12626 (when (or (not state) (equal state ""))
12627 (setq changes (append changes (cdr (assoc "" l)))))
12628 (when (and (stringp state) (> (length state) 0))
12629 (setq changes (append changes (cdr (assoc state l)))))
12630 (when (member state org-not-done-keywords)
12631 (setq changes (append changes (cdr (assoc 'todo l)))))
12632 (when (member state org-done-keywords)
12633 (setq changes (append changes (cdr (assoc 'done l)))))
12634 (dolist (c changes)
12635 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12637 (defun org-local-logging (value)
12638 "Get logging settings from a property VALUE."
12639 (let* (words w a)
12640 ;; directly set the variables, they are already local.
12641 (setq org-log-done nil
12642 org-log-repeat nil
12643 org-todo-log-states nil)
12644 (setq words (org-split-string value))
12645 (while (setq w (pop words))
12646 (cond
12647 ((setq a (assoc w org-startup-options))
12648 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12649 (set (nth 1 a) (nth 2 a))))
12650 ((setq a (org-extract-log-state-settings w))
12651 (and (member (car a) org-todo-keywords-1)
12652 (push a org-todo-log-states)))))))
12654 (defun org-get-todo-sequence-head (kwd)
12655 "Return the head of the TODO sequence to which KWD belongs.
12656 If KWD is not set, check if there is a text property remembering the
12657 right sequence."
12658 (let (p)
12659 (cond
12660 ((not kwd)
12661 (or (get-text-property (point-at-bol) 'org-todo-head)
12662 (progn
12663 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12664 nil (point-at-eol)))
12665 (get-text-property p 'org-todo-head))))
12666 ((not (member kwd org-todo-keywords-1))
12667 (car org-todo-keywords-1))
12668 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12670 (defun org-fast-todo-selection ()
12671 "Fast TODO keyword selection with single keys.
12672 Returns the new TODO keyword, or nil if no state change should occur."
12673 (let* ((fulltable org-todo-key-alist)
12674 (done-keywords org-done-keywords) ;; needed for the faces.
12675 (maxlen (apply 'max (mapcar
12676 (lambda (x)
12677 (if (stringp (car x)) (string-width (car x)) 0))
12678 fulltable)))
12679 (expert nil)
12680 (fwidth (+ maxlen 3 1 3))
12681 (ncol (/ (- (window-width) 4) fwidth))
12682 tg cnt e c tbl
12683 groups ingroup)
12684 (save-excursion
12685 (save-window-excursion
12686 (if expert
12687 (set-buffer (get-buffer-create " *Org todo*"))
12688 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12689 (erase-buffer)
12690 (org-set-local 'org-done-keywords done-keywords)
12691 (setq tbl fulltable cnt 0)
12692 (while (setq e (pop tbl))
12693 (cond
12694 ((equal e '(:startgroup))
12695 (push '() groups) (setq ingroup t)
12696 (when (not (= cnt 0))
12697 (setq cnt 0)
12698 (insert "\n"))
12699 (insert "{ "))
12700 ((equal e '(:endgroup))
12701 (setq ingroup nil cnt 0)
12702 (insert "}\n"))
12703 ((equal e '(:newline))
12704 (when (not (= cnt 0))
12705 (setq cnt 0)
12706 (insert "\n")
12707 (setq e (car tbl))
12708 (while (equal (car tbl) '(:newline))
12709 (insert "\n")
12710 (setq tbl (cdr tbl)))))
12712 (setq tg (car e) c (cdr e))
12713 (if ingroup (push tg (car groups)))
12714 (setq tg (org-add-props tg nil 'face
12715 (org-get-todo-face tg)))
12716 (if (and (= cnt 0) (not ingroup)) (insert " "))
12717 (insert "[" c "] " tg (make-string
12718 (- fwidth 4 (length tg)) ?\ ))
12719 (when (= (setq cnt (1+ cnt)) ncol)
12720 (insert "\n")
12721 (if ingroup (insert " "))
12722 (setq cnt 0)))))
12723 (insert "\n")
12724 (goto-char (point-min))
12725 (if (not expert) (org-fit-window-to-buffer))
12726 (message "[a-z..]:Set [SPC]:clear")
12727 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12728 (cond
12729 ((or (= c ?\C-g)
12730 (and (= c ?q) (not (rassoc c fulltable))))
12731 (setq quit-flag t))
12732 ((= c ?\ ) nil)
12733 ((setq e (rassoc c fulltable) tg (car e))
12735 (t (setq quit-flag t)))))))
12737 (defun org-entry-is-todo-p ()
12738 (member (org-get-todo-state) org-not-done-keywords))
12740 (defun org-entry-is-done-p ()
12741 (member (org-get-todo-state) org-done-keywords))
12743 (defun org-get-todo-state ()
12744 "Return the TODO keyword of the current subtree."
12745 (save-excursion
12746 (org-back-to-heading t)
12747 (and (looking-at org-todo-line-regexp)
12748 (match-end 2)
12749 (match-string 2))))
12751 (defun org-at-date-range-p (&optional inactive-ok)
12752 "Is the cursor inside a date range?"
12753 (interactive)
12754 (save-excursion
12755 (catch 'exit
12756 (let ((pos (point)))
12757 (skip-chars-backward "^[<\r\n")
12758 (skip-chars-backward "<[")
12759 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12760 (>= (match-end 0) pos)
12761 (throw 'exit t))
12762 (skip-chars-backward "^<[\r\n")
12763 (skip-chars-backward "<[")
12764 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12765 (>= (match-end 0) pos)
12766 (throw 'exit t)))
12767 nil)))
12769 (defun org-get-repeat (&optional tagline)
12770 "Check if there is a deadline/schedule with repeater in this entry."
12771 (save-match-data
12772 (save-excursion
12773 (org-back-to-heading t)
12774 (and (re-search-forward (if tagline
12775 (concat tagline "\\s-*" org-repeat-re)
12776 org-repeat-re)
12777 (org-entry-end-position) t)
12778 (match-string-no-properties 1)))))
12780 (defvar org-last-changed-timestamp)
12781 (defvar org-last-inserted-timestamp)
12782 (defvar org-log-post-message)
12783 (defvar org-log-note-purpose)
12784 (defvar org-log-note-how)
12785 (defvar org-log-note-extra)
12786 (defun org-auto-repeat-maybe (done-word)
12787 "Check if the current headline contains a repeated deadline/schedule.
12788 If yes, set TODO state back to what it was and change the base date
12789 of repeating deadline/scheduled time stamps to new date.
12790 This function is run automatically after each state change to a DONE state."
12791 ;; last-state is dynamically scoped into this function
12792 (let* ((repeat (org-get-repeat))
12793 (aa (assoc org-last-state org-todo-kwd-alist))
12794 (interpret (nth 1 aa))
12795 (head (nth 2 aa))
12796 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12797 (msg "Entry repeats: ")
12798 (org-log-done nil)
12799 (org-todo-log-states nil)
12800 re type n what ts time to-state)
12801 (when repeat
12802 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12803 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12804 org-todo-repeat-to-state))
12805 (unless (and to-state (member to-state org-todo-keywords-1))
12806 (setq to-state (if (eq interpret 'type) org-last-state head)))
12807 (org-todo to-state)
12808 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12809 (org-entry-put nil "LAST_REPEAT" (format-time-string
12810 (org-time-stamp-format t t))))
12811 (when org-log-repeat
12812 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12813 (memq 'org-add-log-note post-command-hook))
12814 ;; OK, we are already setup for some record
12815 (if (eq org-log-repeat 'note)
12816 ;; make sure we take a note, not only a time stamp
12817 (setq org-log-note-how 'note))
12818 ;; Set up for taking a record
12819 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12820 org-last-state
12821 'findpos org-log-repeat)))
12822 (org-back-to-heading t)
12823 (org-add-planning-info nil nil 'closed)
12824 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12825 org-deadline-time-regexp "\\)\\|\\("
12826 org-ts-regexp "\\)"))
12827 (while (re-search-forward
12828 re (save-excursion (outline-next-heading) (point)) t)
12829 (setq type (if (match-end 1) org-scheduled-string
12830 (if (match-end 3) org-deadline-string "Plain:"))
12831 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12832 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12833 (setq n (string-to-number (match-string 2 ts))
12834 what (match-string 3 ts))
12835 (if (equal what "w") (setq n (* n 7) what "d"))
12836 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12837 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12838 ;; Preparation, see if we need to modify the start date for the change
12839 (when (match-end 1)
12840 (setq time (save-match-data (org-time-string-to-time ts)))
12841 (cond
12842 ((equal (match-string 1 ts) ".")
12843 ;; Shift starting date to today
12844 (org-timestamp-change
12845 (- (org-today) (time-to-days time))
12846 'day))
12847 ((equal (match-string 1 ts) "+")
12848 (let ((nshiftmax 10) (nshift 0))
12849 (while (or (= nshift 0)
12850 (<= (time-to-days time)
12851 (time-to-days (current-time))))
12852 (when (= (incf nshift) nshiftmax)
12853 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12854 (error "Abort")))
12855 (org-timestamp-change n (cdr (assoc what whata)))
12856 (org-at-timestamp-p t)
12857 (setq ts (match-string 1))
12858 (setq time (save-match-data (org-time-string-to-time ts)))))
12859 (org-timestamp-change (- n) (cdr (assoc what whata)))
12860 ;; rematch, so that we have everything in place for the real shift
12861 (org-at-timestamp-p t)
12862 (setq ts (match-string 1))
12863 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12864 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12865 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12866 (setq org-log-post-message msg)
12867 (message "%s" msg))))
12869 (defun org-show-todo-tree (arg)
12870 "Make a compact tree which shows all headlines marked with TODO.
12871 The tree will show the lines where the regexp matches, and all higher
12872 headlines above the match.
12873 With a \\[universal-argument] prefix, prompt for a regexp to match.
12874 With a numeric prefix N, construct a sparse tree for the Nth element
12875 of `org-todo-keywords-1'."
12876 (interactive "P")
12877 (let ((case-fold-search nil)
12878 (kwd-re
12879 (cond ((null arg) org-not-done-regexp)
12880 ((equal arg '(4))
12881 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12882 (mapcar 'list org-todo-keywords-1))))
12883 (concat "\\("
12884 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12885 "\\)\\>")))
12886 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12887 (regexp-quote (nth (1- (prefix-numeric-value arg))
12888 org-todo-keywords-1)))
12889 (t (user-error "Invalid prefix argument: %s" arg)))))
12890 (message "%d TODO entries found"
12891 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12893 (defun org-deadline (arg &optional time)
12894 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12895 With one universal prefix argument, remove any deadline from the item.
12896 With two universal prefix arguments, prompt for a warning delay.
12897 With argument TIME, set the deadline at the corresponding date. TIME
12898 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12899 (interactive "P")
12900 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12901 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12902 'region-start-level 'region))
12903 org-loop-over-headlines-in-active-region)
12904 (org-map-entries
12905 `(org-deadline ',arg ,time)
12906 org-loop-over-headlines-in-active-region
12907 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12908 (let* ((old-date (org-entry-get nil "DEADLINE"))
12909 (old-date-time (if old-date (org-time-string-to-time old-date)))
12910 (repeater (and old-date
12911 (string-match
12912 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12913 old-date)
12914 (match-string 1 old-date))))
12915 (cond
12916 ((equal arg '(4))
12917 (when (and old-date org-log-redeadline)
12918 (org-add-log-setup 'deldeadline nil old-date 'findpos
12919 org-log-redeadline))
12920 (org-remove-timestamp-with-keyword org-deadline-string)
12921 (message "Item no longer has a deadline."))
12922 ((equal arg '(16))
12923 (save-excursion
12924 (if (re-search-forward
12925 org-deadline-time-regexp
12926 (save-excursion (outline-next-heading) (point)) t)
12927 (let* ((rpl0 (match-string 1))
12928 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12929 (replace-match
12930 (concat org-deadline-string
12931 " <" rpl
12932 (format " -%dd"
12933 (abs
12934 (- (time-to-days
12935 (save-match-data
12936 (org-read-date nil t nil "Warn starting from" old-date-time)))
12937 (time-to-days old-date-time))))
12938 ">") t t))
12939 (user-error "No deadline information to update"))))
12941 (org-add-planning-info 'deadline time 'closed)
12942 (when (and old-date org-log-redeadline
12943 (not (equal old-date
12944 (substring org-last-inserted-timestamp 1 -1))))
12945 (org-add-log-setup 'redeadline nil old-date 'findpos
12946 org-log-redeadline))
12947 (when repeater
12948 (save-excursion
12949 (org-back-to-heading t)
12950 (when (re-search-forward (concat org-deadline-string " "
12951 org-last-inserted-timestamp)
12952 (save-excursion
12953 (outline-next-heading) (point)) t)
12954 (goto-char (1- (match-end 0)))
12955 (insert " " repeater)
12956 (setq org-last-inserted-timestamp
12957 (concat (substring org-last-inserted-timestamp 0 -1)
12958 " " repeater
12959 (substring org-last-inserted-timestamp -1))))))
12960 (message "Deadline on %s" org-last-inserted-timestamp))))))
12962 (defun org-schedule (arg &optional time)
12963 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12964 With one universal prefix argument, remove any scheduling date from the item.
12965 With two universal prefix arguments, prompt for a delay cookie.
12966 With argument TIME, scheduled at the corresponding date. TIME can
12967 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12968 (interactive "P")
12969 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12970 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12971 'region-start-level 'region))
12972 org-loop-over-headlines-in-active-region)
12973 (org-map-entries
12974 `(org-schedule ',arg ,time)
12975 org-loop-over-headlines-in-active-region
12976 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12977 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12978 (old-date-time (if old-date (org-time-string-to-time old-date)))
12979 (repeater (and old-date
12980 (string-match
12981 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12982 old-date)
12983 (match-string 1 old-date))))
12984 (cond
12985 ((equal arg '(4))
12986 (progn
12987 (when (and old-date org-log-reschedule)
12988 (org-add-log-setup 'delschedule nil old-date 'findpos
12989 org-log-reschedule))
12990 (org-remove-timestamp-with-keyword org-scheduled-string)
12991 (message "Item is no longer scheduled.")))
12992 ((equal arg '(16))
12993 (save-excursion
12994 (if (re-search-forward
12995 org-scheduled-time-regexp
12996 (save-excursion (outline-next-heading) (point)) t)
12997 (let* ((rpl0 (match-string 1))
12998 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12999 (replace-match
13000 (concat org-scheduled-string
13001 " <" rpl
13002 (format " -%dd"
13003 (abs
13004 (- (time-to-days
13005 (save-match-data
13006 (org-read-date nil t nil "Delay until" old-date-time)))
13007 (time-to-days old-date-time))))
13008 ">") t t))
13009 (user-error "No scheduled information to update"))))
13011 (org-add-planning-info 'scheduled time 'closed)
13012 (when (and old-date org-log-reschedule
13013 (not (equal old-date
13014 (substring org-last-inserted-timestamp 1 -1))))
13015 (org-add-log-setup 'reschedule nil old-date 'findpos
13016 org-log-reschedule))
13017 (when repeater
13018 (save-excursion
13019 (org-back-to-heading t)
13020 (when (re-search-forward (concat org-scheduled-string " "
13021 org-last-inserted-timestamp)
13022 (save-excursion
13023 (outline-next-heading) (point)) t)
13024 (goto-char (1- (match-end 0)))
13025 (insert " " repeater)
13026 (setq org-last-inserted-timestamp
13027 (concat (substring org-last-inserted-timestamp 0 -1)
13028 " " repeater
13029 (substring org-last-inserted-timestamp -1))))))
13030 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13032 (defun org-get-scheduled-time (pom &optional inherit)
13033 "Get the scheduled time as a time tuple, of a format suitable
13034 for calling org-schedule with, or if there is no scheduling,
13035 returns nil."
13036 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13037 (when time
13038 (apply 'encode-time (org-parse-time-string time)))))
13040 (defun org-get-deadline-time (pom &optional inherit)
13041 "Get the deadline as a time tuple, of a format suitable for
13042 calling org-deadline with, or if there is no scheduling, returns
13043 nil."
13044 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13045 (when time
13046 (apply 'encode-time (org-parse-time-string time)))))
13048 (defun org-remove-timestamp-with-keyword (keyword)
13049 "Remove all time stamps with KEYWORD in the current entry."
13050 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13051 beg)
13052 (save-excursion
13053 (org-back-to-heading t)
13054 (setq beg (point))
13055 (outline-next-heading)
13056 (while (re-search-backward re beg t)
13057 (replace-match "")
13058 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13059 (equal (char-before) ?\ ))
13060 (backward-delete-char 1)
13061 (if (string-match "^[ \t]*$" (buffer-substring
13062 (point-at-bol) (point-at-eol)))
13063 (delete-region (point-at-bol)
13064 (min (point-max) (1+ (point-at-eol))))))))))
13066 (defun org-add-planning-info (what &optional time &rest remove)
13067 "Insert new timestamp with keyword in the line directly after the headline.
13068 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13069 If non is given, the user is prompted for a date.
13070 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13071 be removed."
13072 (interactive)
13073 (let (org-time-was-given org-end-time-was-given ts
13074 end default-time default-input)
13076 (catch 'exit
13077 (when (and (memq what '(scheduled deadline))
13078 (or (not time)
13079 (and (stringp time)
13080 (string-match "^[-+]+[0-9]" time))))
13081 ;; Try to get a default date/time from existing timestamp
13082 (save-excursion
13083 (org-back-to-heading t)
13084 (setq end (save-excursion (outline-next-heading) (point)))
13085 (when (re-search-forward (if (eq what 'scheduled)
13086 org-scheduled-time-regexp
13087 org-deadline-time-regexp)
13088 end t)
13089 (setq ts (match-string 1)
13090 default-time
13091 (apply 'encode-time (org-parse-time-string ts))
13092 default-input (and ts (org-get-compact-tod ts))))))
13093 (when what
13094 (setq time
13095 (if (stringp time)
13096 ;; This is a string (relative or absolute), set proper date
13097 (apply 'encode-time
13098 (org-read-date-analyze
13099 time default-time (decode-time default-time)))
13100 ;; If necessary, get the time from the user
13101 (or time (org-read-date nil 'to-time nil nil
13102 default-time default-input)))))
13104 (when (and org-insert-labeled-timestamps-at-point
13105 (member what '(scheduled deadline)))
13106 (insert
13107 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13108 (org-insert-time-stamp time org-time-was-given
13109 nil nil nil (list org-end-time-was-given))
13110 (setq what nil))
13111 (save-excursion
13112 (save-restriction
13113 (let (col list elt ts buffer-invisibility-spec)
13114 (org-back-to-heading t)
13115 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13116 (goto-char (match-end 1))
13117 (setq col (current-column))
13118 (goto-char (match-end 0))
13119 (if (eobp) (insert "\n") (forward-char 1))
13120 (when (and (not what)
13121 (not (looking-at
13122 (concat "[ \t]*"
13123 org-keyword-time-not-clock-regexp))))
13124 ;; Nothing to add, nothing to remove...... :-)
13125 (throw 'exit nil))
13126 (if (and (not (looking-at org-outline-regexp))
13127 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13128 "[^\r\n]*"))
13129 (not (equal (match-string 1) org-clock-string)))
13130 (narrow-to-region (match-beginning 0) (match-end 0))
13131 (insert-before-markers "\n")
13132 (backward-char 1)
13133 (narrow-to-region (point) (point))
13134 (and org-adapt-indentation (org-indent-to-column col)))
13135 ;; Check if we have to remove something.
13136 (setq list (cons what remove))
13137 (while list
13138 (setq elt (pop list))
13139 (when (or (and (eq elt 'scheduled)
13140 (re-search-forward org-scheduled-time-regexp nil t))
13141 (and (eq elt 'deadline)
13142 (re-search-forward org-deadline-time-regexp nil t))
13143 (and (eq elt 'closed)
13144 (re-search-forward org-closed-time-regexp nil t)))
13145 (replace-match "")
13146 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13147 (and (looking-at "[ \t]+") (replace-match ""))
13148 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13149 (when what
13150 (insert
13151 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13152 (cond ((eq what 'scheduled) org-scheduled-string)
13153 ((eq what 'deadline) org-deadline-string)
13154 ((eq what 'closed) org-closed-string))
13155 " ")
13156 (setq ts (org-insert-time-stamp
13157 time
13158 (or org-time-was-given
13159 (and (eq what 'closed) org-log-done-with-time))
13160 (eq what 'closed)
13161 nil nil (list org-end-time-was-given)))
13162 (insert
13163 (if (not (or (bolp) (eq (char-before) ?\ )
13164 (memq (char-after) '(32 10))
13165 (eobp))) " " ""))
13166 (end-of-line 1))
13167 (goto-char (point-min))
13168 (widen)
13169 (if (and (looking-at "[ \t]*\n")
13170 (equal (char-before) ?\n))
13171 (delete-region (1- (point)) (point-at-eol)))
13172 ts))))))
13174 (defvar org-log-note-marker (make-marker))
13175 (defvar org-log-note-purpose nil)
13176 (defvar org-log-note-state nil)
13177 (defvar org-log-note-previous-state nil)
13178 (defvar org-log-note-how nil)
13179 (defvar org-log-note-extra nil)
13180 (defvar org-log-note-window-configuration nil)
13181 (defvar org-log-note-return-to (make-marker))
13182 (defvar org-log-note-effective-time nil
13183 "Remembered current time so that dynamically scoped
13184 `org-extend-today-until' affects tha timestamps in state change
13185 log")
13187 (defvar org-log-post-message nil
13188 "Message to be displayed after a log note has been stored.
13189 The auto-repeater uses this.")
13191 (defun org-add-note ()
13192 "Add a note to the current entry.
13193 This is done in the same way as adding a state change note."
13194 (interactive)
13195 (org-add-log-setup 'note nil nil 'findpos nil))
13197 (defvar org-property-end-re)
13198 (defun org-add-log-setup (&optional purpose state prev-state
13199 findpos how extra)
13200 "Set up the post command hook to take a note.
13201 If this is about to TODO state change, the new state is expected in STATE.
13202 When FINDPOS is non-nil, find the correct position for the note in
13203 the current entry. If not, assume that it can be inserted at point.
13204 HOW is an indicator what kind of note should be created.
13205 EXTRA is additional text that will be inserted into the notes buffer."
13206 (let* ((org-log-into-drawer (org-log-into-drawer))
13207 (drawer (cond ((stringp org-log-into-drawer)
13208 org-log-into-drawer)
13209 (org-log-into-drawer "LOGBOOK"))))
13210 (save-restriction
13211 (save-excursion
13212 (when findpos
13213 (org-back-to-heading t)
13214 (narrow-to-region (point) (save-excursion
13215 (outline-next-heading) (point)))
13216 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13217 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13218 "[^\r\n]*\\)?"))
13219 (goto-char (match-end 0))
13220 (cond
13221 (drawer
13222 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13223 nil t)
13224 (progn
13225 (goto-char (match-end 0))
13226 (or org-log-states-order-reversed
13227 (and (re-search-forward org-property-end-re nil t)
13228 (goto-char (1- (match-beginning 0))))))
13229 (insert "\n:" drawer ":\n:END:")
13230 (beginning-of-line 0)
13231 (org-indent-line)
13232 (beginning-of-line 2)
13233 (org-indent-line)
13234 (end-of-line 0)))
13235 ((and org-log-state-notes-insert-after-drawers
13236 (save-excursion
13237 (forward-line) (looking-at org-drawer-regexp)))
13238 (forward-line)
13239 (while (looking-at org-drawer-regexp)
13240 (goto-char (match-end 0))
13241 (re-search-forward org-property-end-re (point-max) t)
13242 (forward-line))
13243 (forward-line -1)))
13244 (unless org-log-states-order-reversed
13245 (and (= (char-after) ?\n) (forward-char 1))
13246 (org-skip-over-state-notes)
13247 (skip-chars-backward " \t\n\r")))
13248 (move-marker org-log-note-marker (point))
13249 (setq org-log-note-purpose purpose
13250 org-log-note-state state
13251 org-log-note-previous-state prev-state
13252 org-log-note-how how
13253 org-log-note-extra extra
13254 org-log-note-effective-time (org-current-effective-time))
13255 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13257 (defun org-skip-over-state-notes ()
13258 "Skip past the list of State notes in an entry."
13259 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13260 (when (ignore-errors (goto-char (org-in-item-p)))
13261 (let* ((struct (org-list-struct))
13262 (prevs (org-list-prevs-alist struct)))
13263 (while (looking-at "[ \t]*- State")
13264 (goto-char (or (org-list-get-next-item (point) struct prevs)
13265 (org-list-get-item-end (point) struct)))))))
13267 (defun org-add-log-note (&optional purpose)
13268 "Pop up a window for taking a note, and add this note later at point."
13269 (remove-hook 'post-command-hook 'org-add-log-note)
13270 (setq org-log-note-window-configuration (current-window-configuration))
13271 (delete-other-windows)
13272 (move-marker org-log-note-return-to (point))
13273 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13274 (goto-char org-log-note-marker)
13275 (org-switch-to-buffer-other-window "*Org Note*")
13276 (erase-buffer)
13277 (if (memq org-log-note-how '(time state))
13278 (let (current-prefix-arg) (org-store-log-note))
13279 (let ((org-inhibit-startup t)) (org-mode))
13280 (insert (format "# Insert note for %s.
13281 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13282 (cond
13283 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13284 ((eq org-log-note-purpose 'done) "closed todo item")
13285 ((eq org-log-note-purpose 'state)
13286 (format "state change from \"%s\" to \"%s\""
13287 (or org-log-note-previous-state "")
13288 (or org-log-note-state "")))
13289 ((eq org-log-note-purpose 'reschedule)
13290 "rescheduling")
13291 ((eq org-log-note-purpose 'delschedule)
13292 "no longer scheduled")
13293 ((eq org-log-note-purpose 'redeadline)
13294 "changing deadline")
13295 ((eq org-log-note-purpose 'deldeadline)
13296 "removing deadline")
13297 ((eq org-log-note-purpose 'refile)
13298 "refiling")
13299 ((eq org-log-note-purpose 'note)
13300 "this entry")
13301 (t (error "This should not happen")))))
13302 (if org-log-note-extra (insert org-log-note-extra))
13303 (org-set-local 'org-finish-function 'org-store-log-note)
13304 (run-hooks 'org-log-buffer-setup-hook)))
13306 (defvar org-note-abort nil) ; dynamically scoped
13307 (defun org-store-log-note ()
13308 "Finish taking a log note, and insert it to where it belongs."
13309 (let ((txt (buffer-string)))
13310 (kill-buffer (current-buffer))
13311 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13312 lines ind bul)
13313 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13314 (setq txt (replace-match "" t t txt)))
13315 (if (string-match "\\s-+\\'" txt)
13316 (setq txt (replace-match "" t t txt)))
13317 (setq lines (org-split-string txt "\n"))
13318 (when (and note (string-match "\\S-" note))
13319 (setq note
13320 (org-replace-escapes
13321 note
13322 (list (cons "%u" (user-login-name))
13323 (cons "%U" user-full-name)
13324 (cons "%t" (format-time-string
13325 (org-time-stamp-format 'long 'inactive)
13326 org-log-note-effective-time))
13327 (cons "%T" (format-time-string
13328 (org-time-stamp-format 'long nil)
13329 org-log-note-effective-time))
13330 (cons "%d" (format-time-string
13331 (org-time-stamp-format nil 'inactive)
13332 org-log-note-effective-time))
13333 (cons "%D" (format-time-string
13334 (org-time-stamp-format nil nil)
13335 org-log-note-effective-time))
13336 (cons "%s" (if org-log-note-state
13337 (concat "\"" org-log-note-state "\"")
13338 ""))
13339 (cons "%S" (if org-log-note-previous-state
13340 (concat "\"" org-log-note-previous-state "\"")
13341 "\"\"")))))
13342 (if lines (setq note (concat note " \\\\")))
13343 (push note lines))
13344 (when (or current-prefix-arg org-note-abort)
13345 (when org-log-into-drawer
13346 (org-remove-empty-drawer-at
13347 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13348 org-log-note-marker))
13349 (setq lines nil))
13350 (when lines
13351 (with-current-buffer (marker-buffer org-log-note-marker)
13352 (save-excursion
13353 (goto-char org-log-note-marker)
13354 (move-marker org-log-note-marker nil)
13355 (end-of-line 1)
13356 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13357 (setq ind (save-excursion
13358 (if (ignore-errors (goto-char (org-in-item-p)))
13359 (let ((struct (org-list-struct)))
13360 (org-list-get-ind
13361 (org-list-get-top-point struct) struct))
13362 (skip-chars-backward " \r\t\n")
13363 (cond
13364 ((and (org-at-heading-p)
13365 org-adapt-indentation)
13366 (1+ (org-current-level)))
13367 ((org-at-heading-p) 0)
13368 (t (org-get-indentation))))))
13369 (setq bul (org-list-bullet-string "-"))
13370 (org-indent-line-to ind)
13371 (insert bul (pop lines))
13372 (let ((ind-body (+ (length bul) ind)))
13373 (while lines
13374 (insert "\n")
13375 (org-indent-line-to ind-body)
13376 (insert (pop lines))))
13377 (message "Note stored")
13378 (org-back-to-heading t)
13379 (org-cycle-hide-drawers 'children))
13380 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13381 ;; from within `org-add-log-note' because `buffer-undo-list'
13382 ;; is then modified outside of `org-with-remote-undo'.
13383 (when (eq this-command 'org-agenda-todo)
13384 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13385 ;; Don't add undo information when called from `org-agenda-todo'
13386 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13387 (set-window-configuration org-log-note-window-configuration)
13388 (with-current-buffer (marker-buffer org-log-note-return-to)
13389 (goto-char org-log-note-return-to))
13390 (move-marker org-log-note-return-to nil)
13391 (and org-log-post-message (message "%s" org-log-post-message))))
13393 (defun org-remove-empty-drawer-at (drawer pos)
13394 "Remove an empty drawer DRAWER at position POS.
13395 POS may also be a marker."
13396 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13397 (save-excursion
13398 (save-restriction
13399 (widen)
13400 (goto-char pos)
13401 (if (org-in-regexp
13402 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13403 (replace-match ""))))))
13405 (defvar org-ts-type nil)
13406 (defun org-sparse-tree (&optional arg type)
13407 "Create a sparse tree, prompt for the details.
13408 This command can create sparse trees. You first need to select the type
13409 of match used to create the tree:
13411 t Show all TODO entries.
13412 T Show entries with a specific TODO keyword.
13413 m Show entries selected by a tags/property match.
13414 p Enter a property name and its value (both with completion on existing
13415 names/values) and show entries with that property.
13416 r Show entries matching a regular expression (`/' can be used as well).
13417 b Show deadlines and scheduled items before a date.
13418 a Show deadlines and scheduled items after a date.
13419 d Show deadlines due within `org-deadline-warning-days'.
13420 D Show deadlines and scheduled items between a date range."
13421 (interactive "P")
13422 (let (ans kwd value ts-type)
13423 (setq type (or type org-sparse-tree-default-date-type))
13424 (setq org-ts-type type)
13425 (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"
13426 (cond ((eq type 'all) "all timestamps")
13427 ((eq type 'scheduled) "only scheduled")
13428 ((eq type 'deadline) "only deadline")
13429 ((eq type 'active) "only active timestamps")
13430 ((eq type 'inactive) "only inactive timestamps")
13431 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13432 ((eq type 'closed) "with a closed time-stamp")
13433 (t "scheduled/deadline")))
13434 (setq ans (read-char-exclusive))
13435 (cond
13436 ((equal ans ?c)
13437 (org-sparse-tree
13438 arg (cadr (member type '(scheduled-or-deadline
13439 all scheduled deadline active inactive closed)))))
13440 ((equal ans ?d)
13441 (call-interactively 'org-check-deadlines))
13442 ((equal ans ?b)
13443 (call-interactively 'org-check-before-date))
13444 ((equal ans ?a)
13445 (call-interactively 'org-check-after-date))
13446 ((equal ans ?D)
13447 (call-interactively 'org-check-dates-range))
13448 ((equal ans ?t)
13449 (call-interactively 'org-show-todo-tree))
13450 ((equal ans ?T)
13451 (org-show-todo-tree '(4)))
13452 ((member ans '(?T ?m))
13453 (call-interactively 'org-match-sparse-tree))
13454 ((member ans '(?p ?P))
13455 (setq kwd (org-icompleting-read "Property: "
13456 (mapcar 'list (org-buffer-property-keys))))
13457 (setq value (org-icompleting-read "Value: "
13458 (mapcar 'list (org-property-values kwd))))
13459 (unless (string-match "\\`{.*}\\'" value)
13460 (setq value (concat "\"" value "\"")))
13461 (org-match-sparse-tree arg (concat kwd "=" value)))
13462 ((member ans '(?r ?R ?/))
13463 (call-interactively 'org-occur))
13464 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13466 (defvar org-occur-highlights nil
13467 "List of overlays used for occur matches.")
13468 (make-variable-buffer-local 'org-occur-highlights)
13469 (defvar org-occur-parameters nil
13470 "Parameters of the active org-occur calls.
13471 This is a list, each call to org-occur pushes as cons cell,
13472 containing the regular expression and the callback, onto the list.
13473 The list can contain several entries if `org-occur' has been called
13474 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13475 will only contain one set of parameters. When the highlights are
13476 removed (for example with `C-c C-c', or with the next edit (depending
13477 on `org-remove-highlights-with-change'), this variable is emptied
13478 as well.")
13479 (make-variable-buffer-local 'org-occur-parameters)
13481 (defun org-occur (regexp &optional keep-previous callback)
13482 "Make a compact tree which shows all matches of REGEXP.
13483 The tree will show the lines where the regexp matches, and all higher
13484 headlines above the match. It will also show the heading after the match,
13485 to make sure editing the matching entry is easy.
13486 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13487 call to `org-occur' will be kept, to allow stacking of calls to this
13488 command.
13489 If CALLBACK is non-nil, it is a function which is called to confirm
13490 that the match should indeed be shown."
13491 (interactive "sRegexp: \nP")
13492 (when (equal regexp "")
13493 (user-error "Regexp cannot be empty"))
13494 (unless keep-previous
13495 (org-remove-occur-highlights nil nil t))
13496 (push (cons regexp callback) org-occur-parameters)
13497 (let ((cnt 0))
13498 (save-excursion
13499 (goto-char (point-min))
13500 (if (or (not keep-previous) ; do not want to keep
13501 (not org-occur-highlights)) ; no previous matches
13502 ;; hide everything
13503 (org-overview))
13504 (while (re-search-forward regexp nil t)
13505 (when (or (not callback)
13506 (save-match-data (funcall callback)))
13507 (setq cnt (1+ cnt))
13508 (when org-highlight-sparse-tree-matches
13509 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13510 (org-show-context 'occur-tree))))
13511 (when org-remove-highlights-with-change
13512 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13513 nil 'local))
13514 (unless org-sparse-tree-open-archived-trees
13515 (org-hide-archived-subtrees (point-min) (point-max)))
13516 (run-hooks 'org-occur-hook)
13517 (if (org-called-interactively-p 'interactive)
13518 (message "%d match(es) for regexp %s" cnt regexp))
13519 cnt))
13521 (defun org-occur-next-match (&optional n reset)
13522 "Function for `next-error-function' to find sparse tree matches.
13523 N is the number of matches to move, when negative move backwards.
13524 RESET is entirely ignored - this function always goes back to the
13525 starting point when no match is found."
13526 (let* ((limit (if (< n 0) (point-min) (point-max)))
13527 (search-func (if (< n 0)
13528 'previous-single-char-property-change
13529 'next-single-char-property-change))
13530 (n (abs n))
13531 (pos (point))
13533 (catch 'exit
13534 (while (setq p1 (funcall search-func (point) 'org-type))
13535 (when (equal p1 limit)
13536 (goto-char pos)
13537 (error "No more matches"))
13538 (when (equal (get-char-property p1 'org-type) 'org-occur)
13539 (setq n (1- n))
13540 (when (= n 0)
13541 (goto-char p1)
13542 (throw 'exit (point))))
13543 (goto-char p1))
13544 (goto-char p1)
13545 (error "No more matches"))))
13547 (defun org-show-context (&optional key)
13548 "Make sure point and context are visible.
13549 How much context is shown depends upon the variables
13550 `org-show-hierarchy-above', `org-show-following-heading',
13551 `org-show-entry-below' and `org-show-siblings'."
13552 (let ((heading-p (org-at-heading-p t))
13553 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13554 (following-p (org-get-alist-option org-show-following-heading key))
13555 (entry-p (org-get-alist-option org-show-entry-below key))
13556 (siblings-p (org-get-alist-option org-show-siblings key)))
13557 ;; Show heading or entry text
13558 (if (and heading-p (not entry-p))
13559 (org-flag-heading nil) ; only show the heading
13560 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13561 (org-show-hidden-entry))) ; show entire entry
13562 (when following-p
13563 ;; Show next sibling, or heading below text
13564 (save-excursion
13565 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13566 (org-flag-heading nil))))
13567 (when siblings-p (org-show-siblings))
13568 (when hierarchy-p
13569 ;; show all higher headings, possibly with siblings
13570 (save-excursion
13571 (while (and (condition-case nil
13572 (progn (org-up-heading-all 1) t)
13573 (error nil))
13574 (not (bobp)))
13575 (org-flag-heading nil)
13576 (when siblings-p (org-show-siblings)))))
13577 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13579 (defvar org-reveal-start-hook nil
13580 "Hook run before revealing a location.")
13582 (defun org-reveal (&optional siblings)
13583 "Show current entry, hierarchy above it, and the following headline.
13584 This can be used to show a consistent set of context around locations
13585 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13586 not t for the search context.
13588 With optional argument SIBLINGS, on each level of the hierarchy all
13589 siblings are shown. This repairs the tree structure to what it would
13590 look like when opened with hierarchical calls to `org-cycle'.
13591 With double optional argument \\[universal-argument] \\[universal-argument], \
13592 go to the parent and show the
13593 entire tree."
13594 (interactive "P")
13595 (run-hooks 'org-reveal-start-hook)
13596 (let ((org-show-hierarchy-above t)
13597 (org-show-following-heading t)
13598 (org-show-siblings (if siblings t org-show-siblings)))
13599 (org-show-context nil))
13600 (when (equal siblings '(16))
13601 (save-excursion
13602 (when (org-up-heading-safe)
13603 (org-show-subtree)
13604 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13606 (defun org-highlight-new-match (beg end)
13607 "Highlight from BEG to END and mark the highlight is an occur headline."
13608 (let ((ov (make-overlay beg end)))
13609 (overlay-put ov 'face 'secondary-selection)
13610 (overlay-put ov 'org-type 'org-occur)
13611 (push ov org-occur-highlights)))
13613 (defun org-remove-occur-highlights (&optional beg end noremove)
13614 "Remove the occur highlights from the buffer.
13615 BEG and END are ignored. If NOREMOVE is nil, remove this function
13616 from the `before-change-functions' in the current buffer."
13617 (interactive)
13618 (unless org-inhibit-highlight-removal
13619 (mapc 'delete-overlay org-occur-highlights)
13620 (setq org-occur-highlights nil)
13621 (setq org-occur-parameters nil)
13622 (unless noremove
13623 (remove-hook 'before-change-functions
13624 'org-remove-occur-highlights 'local))))
13626 ;;;; Priorities
13628 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13629 "Regular expression matching the priority indicator.")
13631 (defvar org-remove-priority-next-time nil)
13633 (defun org-priority-up ()
13634 "Increase the priority of the current item."
13635 (interactive)
13636 (org-priority 'up))
13638 (defun org-priority-down ()
13639 "Decrease the priority of the current item."
13640 (interactive)
13641 (org-priority 'down))
13643 (defun org-priority (&optional action show)
13644 "Change the priority of an item.
13645 ACTION can be `set', `up', `down', or a character."
13646 (interactive "P")
13647 (if (equal action '(4))
13648 (org-show-priority)
13649 (unless org-enable-priority-commands
13650 (user-error "Priority commands are disabled"))
13651 (setq action (or action 'set))
13652 (let (current new news have remove)
13653 (save-excursion
13654 (org-back-to-heading t)
13655 (if (looking-at org-priority-regexp)
13656 (setq current (string-to-char (match-string 2))
13657 have t))
13658 (cond
13659 ((eq action 'remove)
13660 (setq remove t new ?\ ))
13661 ((or (eq action 'set)
13662 (if (featurep 'xemacs) (characterp action) (integerp action)))
13663 (if (not (eq action 'set))
13664 (setq new action)
13665 (message "Priority %c-%c, SPC to remove: "
13666 org-highest-priority org-lowest-priority)
13667 (save-match-data
13668 (setq new (read-char-exclusive))))
13669 (if (and (= (upcase org-highest-priority) org-highest-priority)
13670 (= (upcase org-lowest-priority) org-lowest-priority))
13671 (setq new (upcase new)))
13672 (cond ((equal new ?\ ) (setq remove t))
13673 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13674 (user-error "Priority must be between `%c' and `%c'"
13675 org-highest-priority org-lowest-priority))))
13676 ((eq action 'up)
13677 (setq new (if have
13678 (1- current) ; normal cycling
13679 ;; last priority was empty
13680 (if (eq last-command this-command)
13681 org-lowest-priority ; wrap around empty to lowest
13682 ;; default
13683 (if org-priority-start-cycle-with-default
13684 org-default-priority
13685 (1- org-default-priority))))))
13686 ((eq action 'down)
13687 (setq new (if have
13688 (1+ current) ; normal cycling
13689 ;; last priority was empty
13690 (if (eq last-command this-command)
13691 org-highest-priority ; wrap around empty to highest
13692 ;; default
13693 (if org-priority-start-cycle-with-default
13694 org-default-priority
13695 (1+ org-default-priority))))))
13696 (t (user-error "Invalid action")))
13697 (if (or (< (upcase new) org-highest-priority)
13698 (> (upcase new) org-lowest-priority))
13699 (if (and (memq action '(up down))
13700 (not have) (not (eq last-command this-command)))
13701 ;; `new' is from default priority
13702 (error
13703 "The default can not be set, see `org-default-priority' why")
13704 ;; normal cycling: `new' is beyond highest/lowest priority
13705 ;; and is wrapped around to the empty priority
13706 (setq remove t)))
13707 (setq news (format "%c" new))
13708 (if have
13709 (if remove
13710 (replace-match "" t t nil 1)
13711 (replace-match news t t nil 2))
13712 (if remove
13713 (user-error "No priority cookie found in line")
13714 (let ((case-fold-search nil))
13715 (looking-at org-todo-line-regexp))
13716 (if (match-end 2)
13717 (progn
13718 (goto-char (match-end 2))
13719 (insert " [#" news "]"))
13720 (goto-char (match-beginning 3))
13721 (insert "[#" news "] "))))
13722 (org-preserve-lc (org-set-tags nil 'align)))
13723 (if remove
13724 (message "Priority removed")
13725 (message "Priority of current item set to %s" news)))))
13727 (defun org-show-priority ()
13728 "Show the priority of the current item.
13729 This priority is composed of the main priority given with the [#A] cookies,
13730 and by additional input from the age of a schedules or deadline entry."
13731 (interactive)
13732 (let ((pri (if (eq major-mode 'org-agenda-mode)
13733 (org-get-at-bol 'priority)
13734 (save-excursion
13735 (save-match-data
13736 (beginning-of-line)
13737 (and (looking-at org-heading-regexp)
13738 (org-get-priority (match-string 0))))))))
13739 (message "Priority is %d" (if pri pri -1000))))
13741 (defun org-get-priority (s)
13742 "Find priority cookie and return priority."
13743 (save-match-data
13744 (if (functionp org-get-priority-function)
13745 (funcall org-get-priority-function)
13746 (if (not (string-match org-priority-regexp s))
13747 (* 1000 (- org-lowest-priority org-default-priority))
13748 (* 1000 (- org-lowest-priority
13749 (string-to-char (match-string 2 s))))))))
13751 ;;;; Tags
13753 (defvar org-agenda-archives-mode)
13754 (defvar org-map-continue-from nil
13755 "Position from where mapping should continue.
13756 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13758 (defvar org-scanner-tags nil
13759 "The current tag list while the tags scanner is running.")
13760 (defvar org-trust-scanner-tags nil
13761 "Should `org-get-tags-at' use the tags for the scanner.
13762 This is for internal dynamical scoping only.
13763 When this is non-nil, the function `org-get-tags-at' will return the value
13764 of `org-scanner-tags' instead of building the list by itself. This
13765 can lead to large speed-ups when the tags scanner is used in a file with
13766 many entries, and when the list of tags is retrieved, for example to
13767 obtain a list of properties. Building the tags list for each entry in such
13768 a file becomes an N^2 operation - but with this variable set, it scales
13769 as N.")
13771 (defun org-scan-tags (action matcher todo-only &optional start-level)
13772 "Sca headline tags with inheritance and produce output ACTION.
13774 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13775 or `agenda' to produce an entry list for an agenda view. It can also be
13776 a Lisp form or a function that should be called at each matched headline, in
13777 this case the return value is a list of all return values from these calls.
13779 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13780 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13781 only lines with a not-done TODO keyword are included in the output.
13782 This should be the same variable that was scoped into
13783 and set by `org-make-tags-matcher' when it constructed MATCHER.
13785 START-LEVEL can be a string with asterisks, reducing the scope to
13786 headlines matching this string."
13787 (require 'org-agenda)
13788 (let* ((re (concat "^"
13789 (if start-level
13790 ;; Get the correct level to match
13791 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13792 org-outline-regexp)
13793 " *\\(\\<\\("
13794 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13795 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13796 (props (list 'face 'default
13797 'done-face 'org-agenda-done
13798 'undone-face 'default
13799 'mouse-face 'highlight
13800 'org-not-done-regexp org-not-done-regexp
13801 'org-todo-regexp org-todo-regexp
13802 'org-complex-heading-regexp org-complex-heading-regexp
13803 'help-echo
13804 (format "mouse-2 or RET jump to org file %s"
13805 (abbreviate-file-name
13806 (or (buffer-file-name (buffer-base-buffer))
13807 (buffer-name (buffer-base-buffer)))))))
13808 (case-fold-search nil)
13809 (org-map-continue-from nil)
13810 lspos tags tags-list
13811 (tags-alist (list (cons 0 org-file-tags)))
13812 (llast 0) rtn rtn1 level category i txt
13813 todo marker entry priority)
13814 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13815 (setq action (list 'lambda nil action)))
13816 (save-excursion
13817 (goto-char (point-min))
13818 (when (eq action 'sparse-tree)
13819 (org-overview)
13820 (org-remove-occur-highlights))
13821 (while (re-search-forward re nil t)
13822 (setq org-map-continue-from nil)
13823 (catch :skip
13824 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13825 tags (if (match-end 4) (org-match-string-no-properties 4)))
13826 (goto-char (setq lspos (match-beginning 0)))
13827 (setq level (org-reduced-level (org-outline-level))
13828 category (org-get-category))
13829 (setq i llast llast level)
13830 ;; remove tag lists from same and sublevels
13831 (while (>= i level)
13832 (when (setq entry (assoc i tags-alist))
13833 (setq tags-alist (delete entry tags-alist)))
13834 (setq i (1- i)))
13835 ;; add the next tags
13836 (when tags
13837 (setq tags (org-split-string tags ":")
13838 tags-alist
13839 (cons (cons level tags) tags-alist)))
13840 ;; compile tags for current headline
13841 (setq tags-list
13842 (if org-use-tag-inheritance
13843 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13844 tags)
13845 org-scanner-tags tags-list)
13846 (when org-use-tag-inheritance
13847 (setcdr (car tags-alist)
13848 (mapcar (lambda (x)
13849 (setq x (copy-sequence x))
13850 (org-add-prop-inherited x))
13851 (cdar tags-alist))))
13852 (when (and tags org-use-tag-inheritance
13853 (or (not (eq t org-use-tag-inheritance))
13854 org-tags-exclude-from-inheritance))
13855 ;; selective inheritance, remove uninherited ones
13856 (setcdr (car tags-alist)
13857 (org-remove-uninherited-tags (cdar tags-alist))))
13858 (when (and
13860 ;; eval matcher only when the todo condition is OK
13861 (and (or (not todo-only) (member todo org-not-done-keywords))
13862 (let ((case-fold-search t) (org-trust-scanner-tags t))
13863 (eval matcher)))
13865 ;; Call the skipper, but return t if it does not skip,
13866 ;; so that the `and' form continues evaluating
13867 (progn
13868 (unless (eq action 'sparse-tree) (org-agenda-skip))
13871 ;; Check if timestamps are deselecting this entry
13872 (or (not todo-only)
13873 (and (member todo org-not-done-keywords)
13874 (or (not org-agenda-tags-todo-honor-ignore-options)
13875 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13877 ;; select this headline
13878 (cond
13879 ((eq action 'sparse-tree)
13880 (and org-highlight-sparse-tree-matches
13881 (org-get-heading) (match-end 0)
13882 (org-highlight-new-match
13883 (match-beginning 1) (match-end 1)))
13884 (org-show-context 'tags-tree))
13885 ((eq action 'agenda)
13886 (setq txt (org-agenda-format-item
13888 (concat
13889 (if (eq org-tags-match-list-sublevels 'indented)
13890 (make-string (1- level) ?.) "")
13891 (org-get-heading))
13892 level category
13893 tags-list)
13894 priority (org-get-priority txt))
13895 (goto-char lspos)
13896 (setq marker (org-agenda-new-marker))
13897 (org-add-props txt props
13898 'org-marker marker 'org-hd-marker marker 'org-category category
13899 'todo-state todo
13900 'priority priority 'type "tagsmatch")
13901 (push txt rtn))
13902 ((functionp action)
13903 (setq org-map-continue-from nil)
13904 (save-excursion
13905 (setq rtn1 (funcall action))
13906 (push rtn1 rtn)))
13907 (t (user-error "Invalid action")))
13909 ;; if we are to skip sublevels, jump to end of subtree
13910 (unless org-tags-match-list-sublevels
13911 (org-end-of-subtree t)
13912 (backward-char 1))))
13913 ;; Get the correct position from where to continue
13914 (if org-map-continue-from
13915 (goto-char org-map-continue-from)
13916 (and (= (point) lspos) (end-of-line 1)))))
13917 (when (and (eq action 'sparse-tree)
13918 (not org-sparse-tree-open-archived-trees))
13919 (org-hide-archived-subtrees (point-min) (point-max)))
13920 (nreverse rtn)))
13922 (defun org-remove-uninherited-tags (tags)
13923 "Remove all tags that are not inherited from the list TAGS."
13924 (cond
13925 ((eq org-use-tag-inheritance t)
13926 (if org-tags-exclude-from-inheritance
13927 (org-delete-all org-tags-exclude-from-inheritance tags)
13928 tags))
13929 ((not org-use-tag-inheritance) nil)
13930 ((stringp org-use-tag-inheritance)
13931 (delq nil (mapcar
13932 (lambda (x)
13933 (if (and (string-match org-use-tag-inheritance x)
13934 (not (member x org-tags-exclude-from-inheritance)))
13935 x nil))
13936 tags)))
13937 ((listp org-use-tag-inheritance)
13938 (delq nil (mapcar
13939 (lambda (x)
13940 (if (member x org-use-tag-inheritance) x nil))
13941 tags)))))
13943 (defun org-match-sparse-tree (&optional todo-only match)
13944 "Create a sparse tree according to tags string MATCH.
13945 MATCH can contain positive and negative selection of tags, like
13946 \"+WORK+URGENT-WITHBOSS\".
13947 If optional argument TODO-ONLY is non-nil, only select lines that are
13948 also TODO lines."
13949 (interactive "P")
13950 (org-agenda-prepare-buffers (list (current-buffer)))
13951 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13953 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13955 (defvar org-cached-props nil)
13956 (defun org-cached-entry-get (pom property)
13957 (if (or (eq t org-use-property-inheritance)
13958 (and (stringp org-use-property-inheritance)
13959 (string-match org-use-property-inheritance property))
13960 (and (listp org-use-property-inheritance)
13961 (member property org-use-property-inheritance)))
13962 ;; Caching is not possible, check it directly
13963 (org-entry-get pom property 'inherit)
13964 ;; Get all properties, so that we can do complicated checks easily
13965 (cdr (assoc property (or org-cached-props
13966 (setq org-cached-props
13967 (org-entry-properties pom)))))))
13969 (defun org-global-tags-completion-table (&optional files)
13970 "Return the list of all tags in all agenda buffer/files.
13971 Optional FILES argument is a list of files which can be used
13972 instead of the agenda files."
13973 (save-excursion
13974 (org-uniquify
13975 (delq nil
13976 (apply 'append
13977 (mapcar
13978 (lambda (file)
13979 (set-buffer (find-file-noselect file))
13980 (append (org-get-buffer-tags)
13981 (mapcar (lambda (x) (if (stringp (car-safe x))
13982 (list (car-safe x)) nil))
13983 org-tag-alist)))
13984 (if (and files (car files))
13985 files
13986 (org-agenda-files))))))))
13988 (defun org-make-tags-matcher (match)
13989 "Create the TAGS/TODO matcher form for the selection string MATCH.
13991 The variable `todo-only' is scoped dynamically into this function.
13992 It will be set to t if the matcher restricts matching to TODO entries,
13993 otherwise will not be touched.
13995 Returns a cons of the selection string MATCH and the constructed
13996 lisp form implementing the matcher. The matcher is to be evaluated
13997 at an Org entry, with point on the headline, and returns t if the
13998 entry matches the selection string MATCH. The returned lisp form
13999 references two variables with information about the entry, which
14000 must be bound around the form's evaluation: todo, the TODO keyword
14001 at the entry (or nil of none); and tags-list, the list of all tags
14002 at the entry including inherited ones. Additionally, the category
14003 of the entry (if any) must be specified as the text property
14004 'org-category on the headline.
14006 See also `org-scan-tags'.
14008 (declare (special todo-only))
14009 (unless (boundp 'todo-only)
14010 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14011 (unless match
14012 ;; Get a new match request, with completion against the global
14013 ;; tags table and the local tags in current buffer
14014 (let ((org-last-tags-completion-table
14015 (org-uniquify
14016 (delq nil (append (org-get-buffer-tags)
14017 (org-global-tags-completion-table))))))
14018 (setq match (org-completing-read-no-i
14019 "Match: " 'org-tags-completion-function nil nil nil
14020 'org-tags-history))))
14022 ;; Parse the string and create a lisp form
14023 (let ((match0 match)
14024 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14025 minus tag mm
14026 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14027 orterms term orlist re-p str-p level-p level-op time-p
14028 prop-p pn pv po gv rest)
14029 ;; Expand group tags
14030 (setq match (org-tags-expand match))
14031 (if (string-match "/+" match)
14032 ;; match contains also a todo-matching request
14033 (progn
14034 (setq tagsmatch (substring match 0 (match-beginning 0))
14035 todomatch (substring match (match-end 0)))
14036 (if (string-match "^!" todomatch)
14037 (setq todo-only t todomatch (substring todomatch 1)))
14038 (if (string-match "^\\s-*$" todomatch)
14039 (setq todomatch nil)))
14040 ;; only matching tags
14041 (setq tagsmatch match todomatch nil))
14043 ;; Make the tags matcher
14044 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14045 (setq tagsmatcher t)
14046 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14047 (while (setq term (pop orterms))
14048 (while (and (equal (substring term -1) "\\") orterms)
14049 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14050 (while (string-match re term)
14051 (setq rest (substring term (match-end 0))
14052 minus (and (match-end 1)
14053 (equal (match-string 1 term) "-"))
14054 tag (save-match-data (replace-regexp-in-string
14055 "\\\\-" "-"
14056 (match-string 2 term)))
14057 re-p (equal (string-to-char tag) ?{)
14058 level-p (match-end 4)
14059 prop-p (match-end 5)
14060 mm (cond
14061 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14062 (level-p
14063 (setq level-op (org-op-to-function (match-string 3 term)))
14064 `(,level-op level ,(string-to-number
14065 (match-string 4 term))))
14066 (prop-p
14067 (setq pn (match-string 5 term)
14068 po (match-string 6 term)
14069 pv (match-string 7 term)
14070 re-p (equal (string-to-char pv) ?{)
14071 str-p (equal (string-to-char pv) ?\")
14072 time-p (save-match-data
14073 (string-match "^\"[[<].*[]>]\"$" pv))
14074 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14075 (if time-p (setq pv (org-matcher-time pv)))
14076 (setq po (org-op-to-function po (if time-p 'time str-p)))
14077 (cond
14078 ((equal pn "CATEGORY")
14079 (setq gv '(get-text-property (point) 'org-category)))
14080 ((equal pn "TODO")
14081 (setq gv 'todo))
14083 (setq gv `(org-cached-entry-get nil ,pn))))
14084 (if re-p
14085 (if (eq po 'org<>)
14086 `(not (string-match ,pv (or ,gv "")))
14087 `(string-match ,pv (or ,gv "")))
14088 (if str-p
14089 `(,po (or ,gv "") ,pv)
14090 `(,po (string-to-number (or ,gv ""))
14091 ,(string-to-number pv) ))))
14092 (t `(member ,tag tags-list)))
14093 mm (if minus (list 'not mm) mm)
14094 term rest)
14095 (push mm tagsmatcher))
14096 (push (if (> (length tagsmatcher) 1)
14097 (cons 'and tagsmatcher)
14098 (car tagsmatcher))
14099 orlist)
14100 (setq tagsmatcher nil))
14101 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14102 (setq tagsmatcher
14103 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14104 ;; Make the todo matcher
14105 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14106 (setq todomatcher t)
14107 (setq orterms (org-split-string todomatch "|") orlist nil)
14108 (while (setq term (pop orterms))
14109 (while (string-match re term)
14110 (setq minus (and (match-end 1)
14111 (equal (match-string 1 term) "-"))
14112 kwd (match-string 2 term)
14113 re-p (equal (string-to-char kwd) ?{)
14114 term (substring term (match-end 0))
14115 mm (if re-p
14116 `(string-match ,(substring kwd 1 -1) todo)
14117 (list 'equal 'todo kwd))
14118 mm (if minus (list 'not mm) mm))
14119 (push mm todomatcher))
14120 (push (if (> (length todomatcher) 1)
14121 (cons 'and todomatcher)
14122 (car todomatcher))
14123 orlist)
14124 (setq todomatcher nil))
14125 (setq todomatcher (if (> (length orlist) 1)
14126 (cons 'or orlist) (car orlist))))
14128 ;; Return the string and lisp forms of the matcher
14129 (setq matcher (if todomatcher
14130 (list 'and tagsmatcher todomatcher)
14131 tagsmatcher))
14132 (when todo-only
14133 (setq matcher (list 'and '(member todo org-not-done-keywords)
14134 matcher)))
14135 (cons match0 matcher)))
14137 (defun org-tags-expand (match &optional single-as-list downcased)
14138 "Expand group tags in MATCH.
14140 This replaces every group tag in MATCH with a regexp tag search.
14141 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14142 will be replaced like this:
14144 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14145 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14146 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14148 Replacing by a regexp preserves the structure of the match.
14149 E.g., this expansion
14151 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14153 will match anything tagged with \"Lab\" and \"Home\", or tagged
14154 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14156 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14157 assumed to be a single group tag, and the function will return
14158 the list of tags in this group.
14160 When DOWNCASE is non-nil, expand downcased TAGS."
14161 (if org-group-tags
14162 (let* ((case-fold-search t)
14163 (stable org-mode-syntax-table)
14164 (tal (or org-tag-groups-alist-for-agenda
14165 org-tag-groups-alist))
14166 (tal (if downcased
14167 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14168 (tml (mapcar 'car tal))
14169 (rtnmatch match) rpl)
14170 ;; @ and _ are allowed as word-components in tags
14171 (modify-syntax-entry ?@ "w" stable)
14172 (modify-syntax-entry ?_ "w" stable)
14173 (while (and tml
14174 (string-match
14175 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14176 (regexp-opt tml) "\\>\\)") rtnmatch))
14177 (let* ((dir (match-string 1 rtnmatch))
14178 (tag (match-string 2 rtnmatch))
14179 (tag (if downcased (downcase tag) tag)))
14180 (setq tml (delete tag tml))
14181 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14182 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14183 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14184 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14185 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14186 (if single-as-list
14187 (or (reverse rpl) (list rtnmatch))
14188 rtnmatch))
14189 (if single-as-list (list (if downcased (downcase match) match))
14190 match)))
14192 (defun org-op-to-function (op &optional stringp)
14193 "Turn an operator into the appropriate function."
14194 (setq op
14195 (cond
14196 ((equal op "<" ) '(< string< org-time<))
14197 ((equal op ">" ) '(> org-string> org-time>))
14198 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14199 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14200 ((member op '("=" "==")) '(= string= org-time=))
14201 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14202 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14204 (defun org<> (a b) (not (= a b)))
14205 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14206 (defun org-string>= (a b) (not (string< a b)))
14207 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14208 (defun org-string<> (a b) (not (string= a b)))
14209 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14210 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14211 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14212 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14213 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14214 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14215 (defun org-2ft (s)
14216 "Convert S to a floating point time.
14217 If S is already a number, just return it. If it is a string, parse
14218 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14219 (cond
14220 ((numberp s) s)
14221 ((stringp s)
14222 (condition-case nil
14223 (float-time (apply 'encode-time (org-parse-time-string s)))
14224 (error 0.)))
14225 (t 0.)))
14227 (defun org-time-today ()
14228 "Time in seconds today at 0:00.
14229 Returns the float number of seconds since the beginning of the
14230 epoch to the beginning of today (00:00)."
14231 (float-time (apply 'encode-time
14232 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14234 (defun org-matcher-time (s)
14235 "Interpret a time comparison value."
14236 (save-match-data
14237 (cond
14238 ((string= s "<now>") (float-time))
14239 ((string= s "<today>") (org-time-today))
14240 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14241 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14242 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14243 (+ (org-time-today)
14244 (* (string-to-number (match-string 1 s))
14245 (cdr (assoc (match-string 2 s)
14246 '(("d" . 86400.0) ("w" . 604800.0)
14247 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14248 (t (org-2ft s)))))
14250 (defun org-match-any-p (re list)
14251 "Does re match any element of list?"
14252 (setq list (mapcar (lambda (x) (string-match re x)) list))
14253 (delq nil list))
14255 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14256 (defvar org-tags-overlay (make-overlay 1 1))
14257 (org-detach-overlay org-tags-overlay)
14259 (defun org-get-local-tags-at (&optional pos)
14260 "Get a list of tags defined in the current headline."
14261 (org-get-tags-at pos 'local))
14263 (defun org-get-local-tags ()
14264 "Get a list of tags defined in the current headline."
14265 (org-get-tags-at nil 'local))
14267 (defun org-get-tags-at (&optional pos local)
14268 "Get a list of all headline tags applicable at POS.
14269 POS defaults to point. If tags are inherited, the list contains
14270 the targets in the same sequence as the headlines appear, i.e.
14271 the tags of the current headline come last.
14272 When LOCAL is non-nil, only return tags from the current headline,
14273 ignore inherited ones."
14274 (interactive)
14275 (if (and org-trust-scanner-tags
14276 (or (not pos) (equal pos (point)))
14277 (not local))
14278 org-scanner-tags
14279 (let (tags ltags lastpos parent)
14280 (save-excursion
14281 (save-restriction
14282 (widen)
14283 (goto-char (or pos (point)))
14284 (save-match-data
14285 (catch 'done
14286 (condition-case nil
14287 (progn
14288 (org-back-to-heading t)
14289 (while (not (equal lastpos (point)))
14290 (setq lastpos (point))
14291 (when (looking-at
14292 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14293 (setq ltags (org-split-string
14294 (org-match-string-no-properties 1) ":"))
14295 (when parent
14296 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14297 (setq tags (append
14298 (if parent
14299 (org-remove-uninherited-tags ltags)
14300 ltags)
14301 tags)))
14302 (or org-use-tag-inheritance (throw 'done t))
14303 (if local (throw 'done t))
14304 (or (org-up-heading-safe) (error nil))
14305 (setq parent t)))
14306 (error nil)))))
14307 (if local
14308 tags
14309 (reverse (delete-dups
14310 (reverse (append
14311 (org-remove-uninherited-tags
14312 org-file-tags) tags)))))))))
14314 (defun org-add-prop-inherited (s)
14315 (add-text-properties 0 (length s) '(inherited t) s)
14318 (defun org-toggle-tag (tag &optional onoff)
14319 "Toggle the tag TAG for the current line.
14320 If ONOFF is `on' or `off', don't toggle but set to this state."
14321 (let (res current)
14322 (save-excursion
14323 (org-back-to-heading t)
14324 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14325 (point-at-eol) t)
14326 (progn
14327 (setq current (match-string 1))
14328 (replace-match ""))
14329 (setq current ""))
14330 (setq current (nreverse (org-split-string current ":")))
14331 (cond
14332 ((eq onoff 'on)
14333 (setq res t)
14334 (or (member tag current) (push tag current)))
14335 ((eq onoff 'off)
14336 (or (not (member tag current)) (setq current (delete tag current))))
14337 (t (if (member tag current)
14338 (setq current (delete tag current))
14339 (setq res t)
14340 (push tag current))))
14341 (end-of-line 1)
14342 (if current
14343 (progn
14344 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14345 (org-set-tags nil t))
14346 (delete-horizontal-space))
14347 (run-hooks 'org-after-tags-change-hook))
14348 res))
14350 (defun org-align-tags-here (to-col)
14351 ;; Assumes that this is a headline
14352 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14353 (beginning-of-line 1)
14354 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14355 (< pos (match-beginning 2)))
14356 (progn
14357 (setq tags-l (- (match-end 2) (match-beginning 2)))
14358 (goto-char (match-beginning 1))
14359 (insert " ")
14360 (delete-region (point) (1+ (match-beginning 2)))
14361 (setq ncol (max (current-column)
14362 (1+ col)
14363 (if (> to-col 0)
14364 to-col
14365 (- (abs to-col) tags-l))))
14366 (setq p (point))
14367 (insert (make-string (- ncol (current-column)) ?\ ))
14368 (setq ncol (current-column))
14369 (when indent-tabs-mode (tabify p (point-at-eol)))
14370 (org-move-to-column (min ncol col) t))
14371 (goto-char pos))))
14373 (defun org-set-tags-command (&optional arg just-align)
14374 "Call the set-tags command for the current entry."
14375 (interactive "P")
14376 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14377 (org-set-tags arg just-align)
14378 (save-excursion
14379 (unless (and (org-region-active-p)
14380 org-loop-over-headlines-in-active-region)
14381 (org-back-to-heading t))
14382 (org-set-tags arg just-align))))
14384 (defun org-set-tags-to (data)
14385 "Set the tags of the current entry to DATA, replacing the current tags.
14386 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14387 If DATA is nil or the empty string, any tags will be removed."
14388 (interactive "sTags: ")
14389 (setq data
14390 (cond
14391 ((eq data nil) "")
14392 ((equal data "") "")
14393 ((stringp data)
14394 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14395 ":"))
14396 ((listp data)
14397 (concat ":" (mapconcat 'identity data ":") ":"))))
14398 (when data
14399 (save-excursion
14400 (org-back-to-heading t)
14401 (when (looking-at org-complex-heading-regexp)
14402 (if (match-end 5)
14403 (progn
14404 (goto-char (match-beginning 5))
14405 (insert data)
14406 (delete-region (point) (point-at-eol))
14407 (org-set-tags nil 'align))
14408 (goto-char (point-at-eol))
14409 (insert " " data)
14410 (org-set-tags nil 'align)))
14411 (beginning-of-line 1)
14412 (if (looking-at ".*?\\([ \t]+\\)$")
14413 (delete-region (match-beginning 1) (match-end 1))))))
14415 (defun org-align-all-tags ()
14416 "Align the tags i all headings."
14417 (interactive)
14418 (save-excursion
14419 (or (ignore-errors (org-back-to-heading t))
14420 (outline-next-heading))
14421 (if (org-at-heading-p)
14422 (org-set-tags t)
14423 (message "No headings"))))
14425 (defvar org-indent-indentation-per-level)
14426 (defun org-set-tags (&optional arg just-align)
14427 "Set the tags for the current headline.
14428 With prefix ARG, realign all tags in headings in the current buffer."
14429 (interactive "P")
14430 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14431 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14432 'region-start-level 'region))
14433 org-loop-over-headlines-in-active-region)
14434 (org-map-entries
14435 ;; We don't use ARG and JUST-ALIGN here these args are not
14436 ;; useful when looping over headlines
14437 `(org-set-tags)
14438 org-loop-over-headlines-in-active-region
14439 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14440 (let* ((re org-outline-regexp-bol)
14441 (current (unless arg (org-get-tags-string)))
14442 (col (current-column))
14443 (org-setting-tags t)
14444 table current-tags inherited-tags ; computed below when needed
14445 tags p0 c0 c1 rpl di tc level)
14446 (if arg
14447 (save-excursion
14448 (goto-char (point-min))
14449 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14450 (while (re-search-forward re nil t)
14451 (org-set-tags nil t)
14452 (end-of-line 1)))
14453 (message "All tags realigned to column %d" org-tags-column))
14454 (if just-align
14455 (setq tags current)
14456 ;; Get a new set of tags from the user
14457 (save-excursion
14458 (setq table (append org-tag-persistent-alist
14459 (or org-tag-alist (org-get-buffer-tags))
14460 (and
14461 org-complete-tags-always-offer-all-agenda-tags
14462 (org-global-tags-completion-table
14463 (org-agenda-files))))
14464 org-last-tags-completion-table table
14465 current-tags (org-split-string current ":")
14466 inherited-tags (nreverse
14467 (nthcdr (length current-tags)
14468 (nreverse (org-get-tags-at))))
14469 tags
14470 (if (or (eq t org-use-fast-tag-selection)
14471 (and org-use-fast-tag-selection
14472 (delq nil (mapcar 'cdr table))))
14473 (org-fast-tag-selection
14474 current-tags inherited-tags table
14475 (if org-fast-tag-selection-include-todo
14476 org-todo-key-alist))
14477 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14478 (org-trim
14479 (org-icompleting-read "Tags: "
14480 'org-tags-completion-function
14481 nil nil current 'org-tags-history))))))
14482 (while (string-match "[-+&]+" tags)
14483 ;; No boolean logic, just a list
14484 (setq tags (replace-match ":" t t tags))))
14486 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14488 (if org-tags-sort-function
14489 (setq tags (mapconcat 'identity
14490 (sort (org-split-string
14491 tags (org-re "[^[:alnum:]_@#%]+"))
14492 org-tags-sort-function) ":")))
14494 (if (string-match "\\`[\t ]*\\'" tags)
14495 (setq tags "")
14496 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14497 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14499 ;; Insert new tags at the correct column
14500 (beginning-of-line 1)
14501 (setq level (or (and (looking-at org-outline-regexp)
14502 (- (match-end 0) (point) 1))
14504 (cond
14505 ((and (equal current "") (equal tags "")))
14506 ((re-search-forward
14507 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14508 (point-at-eol) t)
14509 (if (equal tags "")
14510 (setq rpl "")
14511 (goto-char (match-beginning 0))
14512 (setq c0 (current-column)
14513 ;; compute offset for the case of org-indent-mode active
14514 di (if org-indent-mode
14515 (* (1- org-indent-indentation-per-level) (1- level))
14517 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14518 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14519 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14520 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14521 (replace-match rpl t t)
14522 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14523 tags)
14524 (t (error "Tags alignment failed")))
14525 (org-move-to-column col)
14526 (unless just-align
14527 (run-hooks 'org-after-tags-change-hook))))))
14529 (defun org-change-tag-in-region (beg end tag off)
14530 "Add or remove TAG for each entry in the region.
14531 This works in the agenda, and also in an org-mode buffer."
14532 (interactive
14533 (list (region-beginning) (region-end)
14534 (let ((org-last-tags-completion-table
14535 (if (derived-mode-p 'org-mode)
14536 (org-uniquify
14537 (delq nil (append (org-get-buffer-tags)
14538 (org-global-tags-completion-table))))
14539 (org-global-tags-completion-table))))
14540 (org-icompleting-read
14541 "Tag: " 'org-tags-completion-function nil nil nil
14542 'org-tags-history))
14543 (progn
14544 (message "[s]et or [r]emove? ")
14545 (equal (read-char-exclusive) ?r))))
14546 (if (fboundp 'deactivate-mark) (deactivate-mark))
14547 (let ((agendap (equal major-mode 'org-agenda-mode))
14548 l1 l2 m buf pos newhead (cnt 0))
14549 (goto-char end)
14550 (setq l2 (1- (org-current-line)))
14551 (goto-char beg)
14552 (setq l1 (org-current-line))
14553 (loop for l from l1 to l2 do
14554 (org-goto-line l)
14555 (setq m (get-text-property (point) 'org-hd-marker))
14556 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14557 (and agendap m))
14558 (setq buf (if agendap (marker-buffer m) (current-buffer))
14559 pos (if agendap m (point)))
14560 (with-current-buffer buf
14561 (save-excursion
14562 (save-restriction
14563 (goto-char pos)
14564 (setq cnt (1+ cnt))
14565 (org-toggle-tag tag (if off 'off 'on))
14566 (setq newhead (org-get-heading)))))
14567 (and agendap (org-agenda-change-all-lines newhead m))))
14568 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14570 (defun org-tags-completion-function (string predicate &optional flag)
14571 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14572 (confirm (lambda (x) (stringp (car x)))))
14573 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14574 (setq s1 (match-string 1 string)
14575 s2 (match-string 2 string))
14576 (setq s1 "" s2 string))
14577 (cond
14578 ((eq flag nil)
14579 ;; try completion
14580 (setq rtn (try-completion s2 ctable confirm))
14581 (if (stringp rtn)
14582 (setq rtn
14583 (concat s1 s2 (substring rtn (length s2))
14584 (if (and org-add-colon-after-tag-completion
14585 (assoc rtn ctable))
14586 ":" ""))))
14587 rtn)
14588 ((eq flag t)
14589 ;; all-completions
14590 (all-completions s2 ctable confirm))
14591 ((eq flag 'lambda)
14592 ;; exact match?
14593 (assoc s2 ctable)))))
14595 (defun org-fast-tag-insert (kwd tags face &optional end)
14596 "Insert KDW, and the TAGS, the latter with face FACE.
14597 Also insert END."
14598 (insert (format "%-12s" (concat kwd ":"))
14599 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14600 (or end "")))
14602 (defun org-fast-tag-show-exit (flag)
14603 (save-excursion
14604 (org-goto-line 3)
14605 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14606 (replace-match ""))
14607 (when flag
14608 (end-of-line 1)
14609 (org-move-to-column (- (window-width) 19) t)
14610 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14612 (defun org-set-current-tags-overlay (current prefix)
14613 "Add an overlay to CURRENT tag with PREFIX."
14614 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14615 (if (featurep 'xemacs)
14616 (org-overlay-display org-tags-overlay (concat prefix s)
14617 'secondary-selection)
14618 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14619 (org-overlay-display org-tags-overlay (concat prefix s)))))
14621 (defvar org-last-tag-selection-key nil)
14622 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14623 "Fast tag selection with single keys.
14624 CURRENT is the current list of tags in the headline, INHERITED is the
14625 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14626 possibly with grouping information. TODO-TABLE is a similar table with
14627 TODO keywords, should these have keys assigned to them.
14628 If the keys are nil, a-z are automatically assigned.
14629 Returns the new tags string, or nil to not change the current settings."
14630 (let* ((fulltable (append table todo-table))
14631 (maxlen (apply 'max (mapcar
14632 (lambda (x)
14633 (if (stringp (car x)) (string-width (car x)) 0))
14634 fulltable)))
14635 (buf (current-buffer))
14636 (expert (eq org-fast-tag-selection-single-key 'expert))
14637 (buffer-tags nil)
14638 (fwidth (+ maxlen 3 1 3))
14639 (ncol (/ (- (window-width) 4) fwidth))
14640 (i-face 'org-done)
14641 (c-face 'org-todo)
14642 tg cnt e c char c1 c2 ntable tbl rtn
14643 ov-start ov-end ov-prefix
14644 (exit-after-next org-fast-tag-selection-single-key)
14645 (done-keywords org-done-keywords)
14646 groups ingroup)
14647 (save-excursion
14648 (beginning-of-line 1)
14649 (if (looking-at
14650 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14651 (setq ov-start (match-beginning 1)
14652 ov-end (match-end 1)
14653 ov-prefix "")
14654 (setq ov-start (1- (point-at-eol))
14655 ov-end (1+ ov-start))
14656 (skip-chars-forward "^\n\r")
14657 (setq ov-prefix
14658 (concat
14659 (buffer-substring (1- (point)) (point))
14660 (if (> (current-column) org-tags-column)
14662 (make-string (- org-tags-column (current-column)) ?\ ))))))
14663 (move-overlay org-tags-overlay ov-start ov-end)
14664 (save-window-excursion
14665 (if expert
14666 (set-buffer (get-buffer-create " *Org tags*"))
14667 (delete-other-windows)
14668 (split-window-vertically)
14669 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14670 (erase-buffer)
14671 (org-set-local 'org-done-keywords done-keywords)
14672 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14673 (org-fast-tag-insert "Current" current c-face "\n\n")
14674 (org-fast-tag-show-exit exit-after-next)
14675 (org-set-current-tags-overlay current ov-prefix)
14676 (setq tbl fulltable char ?a cnt 0)
14677 (while (setq e (pop tbl))
14678 (cond
14679 ((equal (car e) :startgroup)
14680 (push '() groups) (setq ingroup t)
14681 (when (not (= cnt 0))
14682 (setq cnt 0)
14683 (insert "\n"))
14684 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14685 ((equal (car e) :endgroup)
14686 (setq ingroup nil cnt 0)
14687 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14688 ((equal e '(:newline))
14689 (when (not (= cnt 0))
14690 (setq cnt 0)
14691 (insert "\n")
14692 (setq e (car tbl))
14693 (while (equal (car tbl) '(:newline))
14694 (insert "\n")
14695 (setq tbl (cdr tbl)))))
14696 ((equal e '(:grouptags)) nil)
14698 (setq tg (copy-sequence (car e)) c2 nil)
14699 (if (cdr e)
14700 (setq c (cdr e))
14701 ;; automatically assign a character.
14702 (setq c1 (string-to-char
14703 (downcase (substring
14704 tg (if (= (string-to-char tg) ?@) 1 0)))))
14705 (if (or (rassoc c1 ntable) (rassoc c1 table))
14706 (while (or (rassoc char ntable) (rassoc char table))
14707 (setq char (1+ char)))
14708 (setq c2 c1))
14709 (setq c (or c2 char)))
14710 (if ingroup (push tg (car groups)))
14711 (setq tg (org-add-props tg nil 'face
14712 (cond
14713 ((not (assoc tg table))
14714 (org-get-todo-face tg))
14715 ((member tg current) c-face)
14716 ((member tg inherited) i-face))))
14717 (if (equal (caar tbl) :grouptags)
14718 (org-add-props tg nil 'face 'org-tag-group))
14719 (if (and (= cnt 0) (not ingroup)) (insert " "))
14720 (insert "[" c "] " tg (make-string
14721 (- fwidth 4 (length tg)) ?\ ))
14722 (push (cons tg c) ntable)
14723 (when (= (setq cnt (1+ cnt)) ncol)
14724 (insert "\n")
14725 (if ingroup (insert " "))
14726 (setq cnt 0)))))
14727 (setq ntable (nreverse ntable))
14728 (insert "\n")
14729 (goto-char (point-min))
14730 (if (not expert) (org-fit-window-to-buffer))
14731 (setq rtn
14732 (catch 'exit
14733 (while t
14734 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14735 (if (not groups) "no " "")
14736 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14737 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14738 (setq org-last-tag-selection-key c)
14739 (cond
14740 ((= c ?\r) (throw 'exit t))
14741 ((= c ?!)
14742 (setq groups (not groups))
14743 (goto-char (point-min))
14744 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14745 ((= c ?\C-c)
14746 (if (not expert)
14747 (org-fast-tag-show-exit
14748 (setq exit-after-next (not exit-after-next)))
14749 (setq expert nil)
14750 (delete-other-windows)
14751 (set-window-buffer (split-window-vertically) " *Org tags*")
14752 (org-switch-to-buffer-other-window " *Org tags*")
14753 (org-fit-window-to-buffer)))
14754 ((or (= c ?\C-g)
14755 (and (= c ?q) (not (rassoc c ntable))))
14756 (org-detach-overlay org-tags-overlay)
14757 (setq quit-flag t))
14758 ((= c ?\ )
14759 (setq current nil)
14760 (if exit-after-next (setq exit-after-next 'now)))
14761 ((= c ?\t)
14762 (condition-case nil
14763 (setq tg (org-icompleting-read
14764 "Tag: "
14765 (or buffer-tags
14766 (with-current-buffer buf
14767 (org-get-buffer-tags)))))
14768 (quit (setq tg "")))
14769 (when (string-match "\\S-" tg)
14770 (add-to-list 'buffer-tags (list tg))
14771 (if (member tg current)
14772 (setq current (delete tg current))
14773 (push tg current)))
14774 (if exit-after-next (setq exit-after-next 'now)))
14775 ((setq e (rassoc c todo-table) tg (car e))
14776 (with-current-buffer buf
14777 (save-excursion (org-todo tg)))
14778 (if exit-after-next (setq exit-after-next 'now)))
14779 ((setq e (rassoc c ntable) tg (car e))
14780 (if (member tg current)
14781 (setq current (delete tg current))
14782 (loop for g in groups do
14783 (if (member tg g)
14784 (mapc (lambda (x)
14785 (setq current (delete x current)))
14786 g)))
14787 (push tg current))
14788 (if exit-after-next (setq exit-after-next 'now))))
14790 ;; Create a sorted list
14791 (setq current
14792 (sort current
14793 (lambda (a b)
14794 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14795 (if (eq exit-after-next 'now) (throw 'exit t))
14796 (goto-char (point-min))
14797 (beginning-of-line 2)
14798 (delete-region (point) (point-at-eol))
14799 (org-fast-tag-insert "Current" current c-face)
14800 (org-set-current-tags-overlay current ov-prefix)
14801 (while (re-search-forward
14802 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14803 (setq tg (match-string 1))
14804 (add-text-properties
14805 (match-beginning 1) (match-end 1)
14806 (list 'face
14807 (cond
14808 ((member tg current) c-face)
14809 ((member tg inherited) i-face)
14810 (t (get-text-property (match-beginning 1) 'face))))))
14811 (goto-char (point-min)))))
14812 (org-detach-overlay org-tags-overlay)
14813 (if rtn
14814 (mapconcat 'identity current ":")
14815 nil))))
14817 (defun org-get-tags-string ()
14818 "Get the TAGS string in the current headline."
14819 (unless (org-at-heading-p t)
14820 (user-error "Not on a heading"))
14821 (save-excursion
14822 (beginning-of-line 1)
14823 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14824 (org-match-string-no-properties 1)
14825 "")))
14827 (defun org-get-tags ()
14828 "Get the list of tags specified in the current headline."
14829 (org-split-string (org-get-tags-string) ":"))
14831 (defun org-get-buffer-tags ()
14832 "Get a table of all tags used in the buffer, for completion."
14833 (let (tags)
14834 (save-excursion
14835 (goto-char (point-min))
14836 (while (re-search-forward
14837 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14838 (when (equal (char-after (point-at-bol 0)) ?*)
14839 (mapc (lambda (x) (add-to-list 'tags x))
14840 (org-split-string (org-match-string-no-properties 1) ":")))))
14841 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14842 (mapcar 'list tags)))
14844 ;;;; The mapping API
14846 (defun org-map-entries (func &optional match scope &rest skip)
14847 "Call FUNC at each headline selected by MATCH in SCOPE.
14849 FUNC is a function or a lisp form. The function will be called without
14850 arguments, with the cursor positioned at the beginning of the headline.
14851 The return values of all calls to the function will be collected and
14852 returned as a list.
14854 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14855 does not need to preserve point. After evaluation, the cursor will be
14856 moved to the end of the line (presumably of the headline of the
14857 processed entry) and search continues from there. Under some
14858 circumstances, this may not produce the wanted results. For example,
14859 if you have removed (e.g. archived) the current (sub)tree it could
14860 mean that the next entry will be skipped entirely. In such cases, you
14861 can specify the position from where search should continue by making
14862 FUNC set the variable `org-map-continue-from' to the desired buffer
14863 position.
14865 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14866 Only headlines that are matched by this query will be considered during
14867 the iteration. When MATCH is nil or t, all headlines will be
14868 visited by the iteration.
14870 SCOPE determines the scope of this command. It can be any of:
14872 nil The current buffer, respecting the restriction if any
14873 tree The subtree started with the entry at point
14874 region The entries within the active region, if any
14875 region-start-level
14876 The entries within the active region, but only those at
14877 the same level than the first one.
14878 file The current buffer, without restriction
14879 file-with-archives
14880 The current buffer, and any archives associated with it
14881 agenda All agenda files
14882 agenda-with-archives
14883 All agenda files with any archive files associated with them
14884 \(file1 file2 ...)
14885 If this is a list, all files in the list will be scanned
14887 The remaining args are treated as settings for the skipping facilities of
14888 the scanner. The following items can be given here:
14890 archive skip trees with the archive tag
14891 comment skip trees with the COMMENT keyword
14892 function or Emacs Lisp form:
14893 will be used as value for `org-agenda-skip-function', so
14894 whenever the function returns a position, FUNC will not be
14895 called for that entry and search will continue from the
14896 position returned
14898 If your function needs to retrieve the tags including inherited tags
14899 at the *current* entry, you can use the value of the variable
14900 `org-scanner-tags' which will be much faster than getting the value
14901 with `org-get-tags-at'. If your function gets properties with
14902 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14903 to t around the call to `org-entry-properties' to get the same speedup.
14904 Note that if your function moves around to retrieve tags and properties at
14905 a *different* entry, you cannot use these techniques."
14906 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14907 (not (org-region-active-p)))
14908 (let* ((org-agenda-archives-mode nil) ; just to make sure
14909 (org-agenda-skip-archived-trees (memq 'archive skip))
14910 (org-agenda-skip-comment-trees (memq 'comment skip))
14911 (org-agenda-skip-function
14912 (car (org-delete-all '(comment archive) skip)))
14913 (org-tags-match-list-sublevels t)
14914 (start-level (eq scope 'region-start-level))
14915 matcher file res
14916 org-todo-keywords-for-agenda
14917 org-done-keywords-for-agenda
14918 org-todo-keyword-alist-for-agenda
14919 org-drawers-for-agenda
14920 org-tag-alist-for-agenda
14921 todo-only)
14923 (cond
14924 ((eq match t) (setq matcher t))
14925 ((eq match nil) (setq matcher t))
14926 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14928 (save-window-excursion
14929 (save-restriction
14930 (cond ((eq scope 'tree)
14931 (org-back-to-heading t)
14932 (org-narrow-to-subtree)
14933 (setq scope nil))
14934 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14935 (org-region-active-p))
14936 ;; If needed, set start-level to a string like "2"
14937 (when start-level
14938 (save-excursion
14939 (goto-char (region-beginning))
14940 (unless (org-at-heading-p) (outline-next-heading))
14941 (setq start-level (org-current-level))))
14942 (narrow-to-region (region-beginning)
14943 (save-excursion
14944 (goto-char (region-end))
14945 (unless (and (bolp) (org-at-heading-p))
14946 (outline-next-heading))
14947 (point)))
14948 (setq scope nil)))
14950 (if (not scope)
14951 (progn
14952 (org-agenda-prepare-buffers
14953 (list (buffer-file-name (current-buffer))))
14954 (setq res (org-scan-tags func matcher todo-only start-level)))
14955 ;; Get the right scope
14956 (cond
14957 ((and scope (listp scope) (symbolp (car scope)))
14958 (setq scope (eval scope)))
14959 ((eq scope 'agenda)
14960 (setq scope (org-agenda-files t)))
14961 ((eq scope 'agenda-with-archives)
14962 (setq scope (org-agenda-files t))
14963 (setq scope (org-add-archive-files scope)))
14964 ((eq scope 'file)
14965 (setq scope (list (buffer-file-name))))
14966 ((eq scope 'file-with-archives)
14967 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14968 (org-agenda-prepare-buffers scope)
14969 (while (setq file (pop scope))
14970 (with-current-buffer (org-find-base-buffer-visiting file)
14971 (save-excursion
14972 (save-restriction
14973 (widen)
14974 (goto-char (point-min))
14975 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14976 res)))
14978 ;;;; Properties
14980 ;;; Setting and retrieving properties
14982 (defconst org-special-properties
14983 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14984 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14985 "The special properties valid in Org-mode.
14987 These are properties that are not defined in the property drawer,
14988 but in some other way.")
14990 (defconst org-default-properties
14991 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14992 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14993 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14994 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14995 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14996 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14997 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14998 "Some properties that are used by Org-mode for various purposes.
14999 Being in this list makes sure that they are offered for completion.")
15001 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15002 "Regular expression matching the first line of a property drawer.")
15004 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15005 "Regular expression matching the last line of a property drawer.")
15007 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15008 "Regular expression matching the first line of a property drawer.")
15010 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15011 "Regular expression matching the first line of a property drawer.")
15013 (defconst org-property-drawer-re
15014 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15015 org-property-end-re "\\)\n?")
15016 "Matches an entire property drawer.")
15018 (defconst org-clock-drawer-re
15019 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15020 org-property-end-re "\\)\n?")
15021 "Matches an entire clock drawer.")
15023 (defsubst org-re-property (property)
15024 "Return a regexp matching a PROPERTY line.
15025 Match group 1 will be set to the value."
15026 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15028 (defsubst org-re-property-keyword (property)
15029 "Return a regexp matching a PROPERTY line, possibly with no
15030 value for the property."
15031 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15033 (defun org-property-action ()
15034 "Do an action on properties."
15035 (interactive)
15036 (let (c)
15037 (org-at-property-p)
15038 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15039 (setq c (read-char-exclusive))
15040 (cond
15041 ((equal c ?s)
15042 (call-interactively 'org-set-property))
15043 ((equal c ?d)
15044 (call-interactively 'org-delete-property))
15045 ((equal c ?D)
15046 (call-interactively 'org-delete-property-globally))
15047 ((equal c ?c)
15048 (call-interactively 'org-compute-property-at-point))
15049 (t (user-error "No such property action %c" c)))))
15051 (defun org-inc-effort ()
15052 "Increment the value of the effort property in the current entry."
15053 (interactive)
15054 (org-set-effort nil t))
15056 (defvar org-clock-effort) ;; Defined in org-clock.el
15057 (defvar org-clock-current-task) ;; Defined in org-clock.el
15058 (defun org-set-effort (&optional value increment)
15059 "Set the effort property of the current entry.
15060 With numerical prefix arg, use the nth allowed value, 0 stands for the
15061 10th allowed value.
15063 When INCREMENT is non-nil, set the property to the next allowed value."
15064 (interactive "P")
15065 (if (equal value 0) (setq value 10))
15066 (let* ((completion-ignore-case t)
15067 (prop org-effort-property)
15068 (cur (org-entry-get nil prop))
15069 (allowed (org-property-get-allowed-values nil prop 'table))
15070 (existing (mapcar 'list (org-property-values prop)))
15071 (heading (nth 4 (org-heading-components)))
15073 (val (cond
15074 ((stringp value) value)
15075 ((and allowed (integerp value))
15076 (or (car (nth (1- value) allowed))
15077 (car (org-last allowed))))
15078 ((and allowed increment)
15079 (or (caadr (member (list cur) allowed))
15080 (user-error "Allowed effort values are not set")))
15081 (allowed
15082 (message "Select 1-9,0, [RET%s]: %s"
15083 (if cur (concat "=" cur) "")
15084 (mapconcat 'car allowed " "))
15085 (setq rpl (read-char-exclusive))
15086 (if (equal rpl ?\r)
15088 (setq rpl (- rpl ?0))
15089 (if (equal rpl 0) (setq rpl 10))
15090 (if (and (> rpl 0) (<= rpl (length allowed)))
15091 (car (nth (1- rpl) allowed))
15092 (org-completing-read "Effort: " allowed nil))))
15094 (let (org-completion-use-ido org-completion-use-iswitchb)
15095 (org-completing-read
15096 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15097 (concat "[" cur "]") "")
15098 ": ")
15099 existing nil nil "" nil cur))))))
15100 (unless (equal (org-entry-get nil prop) val)
15101 (org-entry-put nil prop val))
15102 (save-excursion
15103 (org-back-to-heading t)
15104 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15105 (when (string= heading org-clock-current-task)
15106 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15107 (org-clock-update-mode-line))
15108 (message "%s is now %s" prop val)))
15110 (defun org-at-property-p ()
15111 "Is cursor inside a property drawer?"
15112 (save-excursion
15113 (beginning-of-line 1)
15114 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15115 (save-match-data ;; Used by calling procedures
15116 (let ((p (point))
15117 (range (unless (org-before-first-heading-p)
15118 (org-get-property-block))))
15119 (and range (<= (car range) p) (< p (cdr range))))))))
15121 (defun org-get-property-block (&optional beg end force)
15122 "Return the (beg . end) range of the body of the property drawer.
15123 BEG and END are the beginning and end of the current subtree, or of
15124 the part before the first headline. If they are not given, they will
15125 be found. If the drawer does not exist and FORCE is non-nil, create
15126 the drawer."
15127 (catch 'exit
15128 (save-excursion
15129 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15130 (progn (org-back-to-heading t) (point))))
15131 (end (or end (and (not (outline-next-heading)) (point-max))
15132 (point))))
15133 (goto-char beg)
15134 (if (re-search-forward org-property-start-re end t)
15135 (setq beg (1+ (match-end 0)))
15136 (if force
15137 (save-excursion
15138 (org-insert-property-drawer)
15139 (setq end (progn (outline-next-heading) (point))))
15140 (throw 'exit nil))
15141 (goto-char beg)
15142 (if (re-search-forward org-property-start-re end t)
15143 (setq beg (1+ (match-end 0)))))
15144 (if (re-search-forward org-property-end-re end t)
15145 (setq end (match-beginning 0))
15146 (or force (throw 'exit nil))
15147 (goto-char beg)
15148 (setq end beg)
15149 (org-indent-line)
15150 (insert ":END:\n"))
15151 (cons beg end)))))
15153 (defun org-entry-properties (&optional pom which specific)
15154 "Get all properties of the entry at point-or-marker POM.
15155 This includes the TODO keyword, the tags, time strings for deadline,
15156 scheduled, and clocking, and any additional properties defined in the
15157 entry. The return value is an alist, keys may occur multiple times
15158 if the property key was used several times.
15159 POM may also be nil, in which case the current entry is used.
15160 If WHICH is nil or `all', get all properties. If WHICH is
15161 `special' or `standard', only get that subclass. If WHICH
15162 is a string only get exactly this property. SPECIFIC can be a string, the
15163 specific property we are interested in. Specifying it can speed
15164 things up because then unnecessary parsing is avoided."
15165 (setq which (or which 'all))
15166 (org-with-point-at pom
15167 (let ((clockstr (substring org-clock-string 0 -1))
15168 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15169 (case-fold-search nil)
15170 beg end range props sum-props key key1 value string clocksum clocksumt)
15171 (save-excursion
15172 (when (condition-case nil
15173 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15174 (error nil))
15175 (setq beg (point))
15176 (setq sum-props (get-text-property (point) 'org-summaries))
15177 (setq clocksum (get-text-property (point) :org-clock-minutes)
15178 clocksumt (get-text-property (point) :org-clock-minutes-today))
15179 (outline-next-heading)
15180 (setq end (point))
15181 (when (memq which '(all special))
15182 ;; Get the special properties, like TODO and tags
15183 (goto-char beg)
15184 (when (and (or (not specific) (string= specific "TODO"))
15185 (looking-at org-todo-line-regexp) (match-end 2))
15186 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15187 (when (and (or (not specific) (string= specific "PRIORITY"))
15188 (looking-at org-priority-regexp))
15189 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15190 (when (or (not specific) (string= specific "FILE"))
15191 (push (cons "FILE" buffer-file-name) props))
15192 (when (and (or (not specific) (string= specific "TAGS"))
15193 (setq value (org-get-tags-string))
15194 (string-match "\\S-" value))
15195 (push (cons "TAGS" value) props))
15196 (when (and (or (not specific) (string= specific "ALLTAGS"))
15197 (setq value (org-get-tags-at)))
15198 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15199 ":"))
15200 props))
15201 (when (or (not specific) (string= specific "BLOCKED"))
15202 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15203 (when (or (not specific)
15204 (member specific
15205 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15206 "TIMESTAMP" "TIMESTAMP_IA")))
15207 (catch 'match
15208 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15209 (setq key (if (match-end 1)
15210 (substring (org-match-string-no-properties 1)
15211 0 -1))
15212 string (if (equal key clockstr)
15213 (org-trim
15214 (buffer-substring-no-properties
15215 (match-beginning 3) (goto-char
15216 (point-at-eol))))
15217 (substring (org-match-string-no-properties 3)
15218 1 -1)))
15219 ;; Get the correct property name from the key. This is
15220 ;; necessary if the user has configured time keywords.
15221 (setq key1 (concat key ":"))
15222 (cond
15223 ((not key)
15224 (setq key
15225 (if (= (char-after (match-beginning 3)) ?\[)
15226 "TIMESTAMP_IA" "TIMESTAMP")))
15227 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15228 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15229 ((equal key1 org-closed-string) (setq key "CLOSED"))
15230 ((equal key1 org-clock-string) (setq key "CLOCK")))
15231 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15232 (progn
15233 (push (cons key string) props)
15234 ;; no need to search further if match is found
15235 (throw 'match t))
15236 (when (or (equal key "CLOCK") (not (assoc key props)))
15237 (push (cons key string) props)))))))
15239 (when (memq which '(all standard))
15240 ;; Get the standard properties, like :PROP: ...
15241 (setq range (org-get-property-block beg end))
15242 (when range
15243 (goto-char (car range))
15244 (while (re-search-forward
15245 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15246 (cdr range) t)
15247 (setq key (org-match-string-no-properties 1)
15248 value (org-trim (or (org-match-string-no-properties 2) "")))
15249 (unless (member key excluded)
15250 (push (cons key (or value "")) props)))))
15251 (if clocksum
15252 (push (cons "CLOCKSUM"
15253 (org-columns-number-to-string (/ (float clocksum) 60.)
15254 'add_times))
15255 props))
15256 (if clocksumt
15257 (push (cons "CLOCKSUM_T"
15258 (org-columns-number-to-string (/ (float clocksumt) 60.)
15259 'add_times))
15260 props))
15261 (unless (assoc "CATEGORY" props)
15262 (push (cons "CATEGORY" (org-get-category)) props))
15263 (append sum-props (nreverse props)))))))
15265 (defun org-entry-get (pom property &optional inherit literal-nil)
15266 "Get value of PROPERTY for entry or content at point-or-marker POM.
15267 If INHERIT is non-nil and the entry does not have the property,
15268 then also check higher levels of the hierarchy.
15269 If INHERIT is the symbol `selective', use inheritance only if the setting
15270 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15271 If the property is present but empty, the return value is the empty string.
15272 If the property is not present at all, nil is returned.
15274 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15275 do not interpret it as the list atom nil. This is used for inheritance
15276 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15277 (org-with-point-at pom
15278 (if (and inherit (if (eq inherit 'selective)
15279 (org-property-inherit-p property)
15281 (org-entry-get-with-inheritance property literal-nil)
15282 (if (member property org-special-properties)
15283 ;; We need a special property. Use `org-entry-properties' to
15284 ;; retrieve it, but specify the wanted property
15285 (cdr (assoc property (org-entry-properties nil 'special property)))
15286 (let ((range (org-get-property-block)))
15287 (when (and range (not (eq (car range) (cdr range))))
15288 (let* ((props (list (or (assoc property org-file-properties)
15289 (assoc property org-global-properties)
15290 (assoc property org-global-properties-fixed))))
15291 (ap (lambda (key)
15292 (when (re-search-forward
15293 (org-re-property key) (cdr range) t)
15294 (setq props
15295 (org-update-property-plist
15297 (if (match-end 1)
15298 (org-match-string-no-properties 1) "")
15299 props)))))
15300 val)
15301 (goto-char (car range))
15302 (funcall ap property)
15303 (goto-char (car range))
15304 (while (funcall ap (concat property "+")))
15305 (setq val (cdr (assoc property props)))
15306 (when val (if literal-nil val (org-not-nil val))))))))))
15308 (defun org-property-or-variable-value (var &optional inherit)
15309 "Check if there is a property fixing the value of VAR.
15310 If yes, return this value. If not, return the current value of the variable."
15311 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15312 (if (and prop (stringp prop) (string-match "\\S-" prop))
15313 (read prop)
15314 (symbol-value var))))
15316 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15317 "Delete the property PROPERTY from entry at point-or-marker POM.
15318 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15319 an empty drawer to delete."
15320 (org-with-point-at pom
15321 (if (member property org-special-properties)
15322 nil ; cannot delete these properties.
15323 (let ((range (org-get-property-block)))
15324 (if (and range
15325 (goto-char (car range))
15326 (re-search-forward
15327 (org-re-property property)
15328 (cdr range) t))
15329 (progn
15330 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15331 (and delete-empty-drawer
15332 (org-remove-empty-drawer-at
15333 delete-empty-drawer (car range)))
15335 nil)))))
15337 ;; Multi-values properties are properties that contain multiple values
15338 ;; These values are assumed to be single words, separated by whitespace.
15339 (defun org-entry-add-to-multivalued-property (pom property value)
15340 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15341 (let* ((old (org-entry-get pom property))
15342 (values (and old (org-split-string old "[ \t]"))))
15343 (setq value (org-entry-protect-space value))
15344 (unless (member value values)
15345 (setq values (append values (list value)))
15346 (org-entry-put pom property
15347 (mapconcat 'identity values " ")))))
15349 (defun org-entry-remove-from-multivalued-property (pom property value)
15350 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15351 (let* ((old (org-entry-get pom property))
15352 (values (and old (org-split-string old "[ \t]"))))
15353 (setq value (org-entry-protect-space value))
15354 (when (member value values)
15355 (setq values (delete value values))
15356 (org-entry-put pom property
15357 (mapconcat 'identity values " ")))))
15359 (defun org-entry-member-in-multivalued-property (pom property value)
15360 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15361 (let* ((old (org-entry-get pom property))
15362 (values (and old (org-split-string old "[ \t]"))))
15363 (setq value (org-entry-protect-space value))
15364 (member value values)))
15366 (defun org-entry-get-multivalued-property (pom property)
15367 "Return a list of values in a multivalued property."
15368 (let* ((value (org-entry-get pom property))
15369 (values (and value (org-split-string value "[ \t]"))))
15370 (mapcar 'org-entry-restore-space values)))
15372 (defun org-entry-put-multivalued-property (pom property &rest values)
15373 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15374 VALUES should be a list of strings. Spaces will be protected."
15375 (org-entry-put pom property
15376 (mapconcat 'org-entry-protect-space values " "))
15377 (let* ((value (org-entry-get pom property))
15378 (values (and value (org-split-string value "[ \t]"))))
15379 (mapcar 'org-entry-restore-space values)))
15381 (defun org-entry-protect-space (s)
15382 "Protect spaces and newline in string S."
15383 (while (string-match " " s)
15384 (setq s (replace-match "%20" t t s)))
15385 (while (string-match "\n" s)
15386 (setq s (replace-match "%0A" t t s)))
15389 (defun org-entry-restore-space (s)
15390 "Restore spaces and newline in string S."
15391 (while (string-match "%20" s)
15392 (setq s (replace-match " " t t s)))
15393 (while (string-match "%0A" s)
15394 (setq s (replace-match "\n" t t s)))
15397 (defvar org-entry-property-inherited-from (make-marker)
15398 "Marker pointing to the entry from where a property was inherited.
15399 Each call to `org-entry-get-with-inheritance' will set this marker to the
15400 location of the entry where the inheritance search matched. If there was
15401 no match, the marker will point nowhere.
15402 Note that also `org-entry-get' calls this function, if the INHERIT flag
15403 is set.")
15405 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15406 "Get PROPERTY of entry or content at point, search higher levels if needed.
15407 The search will stop at the first ancestor which has the property defined.
15408 If the value found is \"nil\", return nil to show that the property
15409 should be considered as undefined (this is the meaning of nil here).
15410 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15411 (move-marker org-entry-property-inherited-from nil)
15412 (let (tmp)
15413 (save-excursion
15414 (save-restriction
15415 (widen)
15416 (catch 'ex
15417 (while t
15418 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15419 (or (ignore-errors (org-back-to-heading t))
15420 (goto-char (point-min)))
15421 (move-marker org-entry-property-inherited-from (point))
15422 (throw 'ex tmp))
15423 (or (ignore-errors (org-up-heading-safe))
15424 (throw 'ex nil))))))
15425 (setq tmp (or tmp
15426 (cdr (assoc property org-file-properties))
15427 (cdr (assoc property org-global-properties))
15428 (cdr (assoc property org-global-properties-fixed))))
15429 (if literal-nil tmp (org-not-nil tmp))))
15431 (defvar org-property-changed-functions nil
15432 "Hook called when the value of a property has changed.
15433 Each hook function should accept two arguments, the name of the property
15434 and the new value.")
15436 (defun org-entry-put (pom property value)
15437 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15438 (org-with-point-at pom
15439 (org-back-to-heading t)
15440 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15441 range)
15442 (cond
15443 ((equal property "TODO")
15444 (when (and (stringp value) (string-match "\\S-" value)
15445 (not (member value org-todo-keywords-1)))
15446 (user-error "\"%s\" is not a valid TODO state" value))
15447 (if (or (not value)
15448 (not (string-match "\\S-" value)))
15449 (setq value 'none))
15450 (org-todo value)
15451 (org-set-tags nil 'align))
15452 ((equal property "PRIORITY")
15453 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15454 (string-to-char value) ?\ ))
15455 (org-set-tags nil 'align))
15456 ((equal property "CLOCKSUM")
15457 (if (not (re-search-forward
15458 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15459 (error "Cannot find a clock log")
15460 (goto-char (- (match-end 1) 2))
15461 (cond
15462 ((eq value 'earlier) (org-timestamp-down))
15463 ((eq value 'later) (org-timestamp-up)))
15464 (org-clock-sum-current-item)))
15465 ((equal property "SCHEDULED")
15466 (if (re-search-forward org-scheduled-time-regexp end t)
15467 (cond
15468 ((eq value 'earlier) (org-timestamp-change -1 'day))
15469 ((eq value 'later) (org-timestamp-change 1 'day))
15470 (t (call-interactively 'org-schedule)))
15471 (call-interactively 'org-schedule)))
15472 ((equal property "DEADLINE")
15473 (if (re-search-forward org-deadline-time-regexp end t)
15474 (cond
15475 ((eq value 'earlier) (org-timestamp-change -1 'day))
15476 ((eq value 'later) (org-timestamp-change 1 'day))
15477 (t (call-interactively 'org-deadline)))
15478 (call-interactively 'org-deadline)))
15479 ((member property org-special-properties)
15480 (error "The %s property can not yet be set with `org-entry-put'"
15481 property))
15482 (t ; a non-special property
15483 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15484 (setq range (org-get-property-block beg end 'force))
15485 (goto-char (car range))
15486 (if (re-search-forward
15487 (org-re-property-keyword property) (cdr range) t)
15488 (progn
15489 (delete-region (match-beginning 0) (match-end 0))
15490 (goto-char (match-beginning 0)))
15491 (goto-char (cdr range))
15492 (insert "\n")
15493 (backward-char 1)
15494 (org-indent-line))
15495 (insert ":" property ":")
15496 (and value (insert " " value))
15497 (org-indent-line)))))
15498 (run-hook-with-args 'org-property-changed-functions property value)))
15500 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15501 "Get all property keys in the current buffer.
15502 With INCLUDE-SPECIALS, also list the special properties that reflect things
15503 like tags and TODO state.
15504 With INCLUDE-DEFAULTS, also include properties that has special meaning
15505 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15506 and others.
15507 With INCLUDE-COLUMNS, also include property names given in COLUMN
15508 formats in the current buffer."
15509 (let (rtn range cfmt s p)
15510 (save-excursion
15511 (save-restriction
15512 (widen)
15513 (goto-char (point-min))
15514 (while (re-search-forward org-property-start-re nil t)
15515 (setq range (org-get-property-block))
15516 (goto-char (car range))
15517 (while (re-search-forward
15518 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15519 (cdr range) t)
15520 (add-to-list 'rtn (org-match-string-no-properties 1)))
15521 (outline-next-heading))))
15523 (when include-specials
15524 (setq rtn (append org-special-properties rtn)))
15526 (when include-defaults
15527 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15528 (add-to-list 'rtn org-effort-property))
15530 (when include-columns
15531 (save-excursion
15532 (save-restriction
15533 (widen)
15534 (goto-char (point-min))
15535 (while (re-search-forward
15536 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15537 nil t)
15538 (setq cfmt (match-string 2) s 0)
15539 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15540 cfmt s)
15541 (setq s (match-end 0)
15542 p (match-string 1 cfmt))
15543 (unless (or (equal p "ITEM")
15544 (member p org-special-properties))
15545 (add-to-list 'rtn (match-string 1 cfmt))))))))
15547 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15549 (defun org-property-values (key)
15550 "Return a list of all values of property KEY in the current buffer."
15551 (save-excursion
15552 (save-restriction
15553 (widen)
15554 (goto-char (point-min))
15555 (let ((re (org-re-property key))
15556 values)
15557 (while (re-search-forward re nil t)
15558 (add-to-list 'values (org-trim (match-string 1))))
15559 (delete "" values)))))
15561 (defun org-insert-property-drawer ()
15562 "Insert a property drawer into the current entry."
15563 (org-back-to-heading t)
15564 (looking-at org-outline-regexp)
15565 (let ((indent (if org-adapt-indentation
15566 (- (match-end 0) (match-beginning 0))
15568 (beg (point))
15569 (re (concat "^[ \t]*" org-keyword-time-regexp))
15570 end hiddenp)
15571 (outline-next-heading)
15572 (setq end (point))
15573 (goto-char beg)
15574 (while (re-search-forward re end t))
15575 (setq hiddenp (outline-invisible-p))
15576 (end-of-line 1)
15577 (and (equal (char-after) ?\n) (forward-char 1))
15578 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15579 (if (member (match-string 1) '("CLOCK:" ":END:"))
15580 ;; just skip this line
15581 (beginning-of-line 2)
15582 ;; Drawer start, find the end
15583 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15584 (beginning-of-line 1)))
15585 (org-skip-over-state-notes)
15586 (skip-chars-backward " \t\n\r")
15587 (if (eq (char-before) ?*) (forward-char 1))
15588 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15589 (beginning-of-line 0)
15590 (org-indent-to-column indent)
15591 (beginning-of-line 2)
15592 (org-indent-to-column indent)
15593 (beginning-of-line 0)
15594 (if hiddenp
15595 (save-excursion
15596 (org-back-to-heading t)
15597 (hide-entry))
15598 (org-flag-drawer t))))
15600 (defun org-insert-drawer (&optional arg drawer)
15601 "Insert a drawer at point.
15603 Optional argument DRAWER, when non-nil, is a string representing
15604 drawer's name. Otherwise, the user is prompted for a name.
15606 If a region is active, insert the drawer around that region
15607 instead.
15609 Point is left between drawer's boundaries."
15610 (interactive "P")
15611 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15612 "LOGBOOK"))
15613 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15614 ;; internally by Org. They are meant to be inserted
15615 ;; automatically.
15616 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15617 ;; Remove system drawers from list. Note: For some reason,
15618 ;; `org-completing-read' ignores the predicate while
15619 ;; `completing-read' handles it fine.
15620 (drawer (if arg "PROPERTIES"
15621 (or drawer
15622 (completing-read
15623 "Drawer: " org-drawers
15624 (lambda (d) (not (member d system-drawers))))))))
15625 (cond
15626 ;; With C-u, fall back on `org-insert-property-drawer'
15627 (arg (org-insert-property-drawer))
15628 ;; With an active region, insert a drawer at point.
15629 ((not (org-region-active-p))
15630 (progn
15631 (unless (bolp) (insert "\n"))
15632 (insert (format ":%s:\n\n:END:\n" drawer))
15633 (forward-line -2)))
15634 ;; Otherwise, insert the drawer at point
15636 (let ((rbeg (region-beginning))
15637 (rend (copy-marker (region-end))))
15638 (unwind-protect
15639 (progn
15640 (goto-char rbeg)
15641 (beginning-of-line)
15642 (when (save-excursion
15643 (re-search-forward org-outline-regexp-bol rend t))
15644 (user-error "Drawers cannot contain headlines"))
15645 ;; Position point at the beginning of the first
15646 ;; non-blank line in region. Insert drawer's opening
15647 ;; there, then indent it.
15648 (org-skip-whitespace)
15649 (beginning-of-line)
15650 (insert ":" drawer ":\n")
15651 (forward-line -1)
15652 (indent-for-tab-command)
15653 ;; Move point to the beginning of the first blank line
15654 ;; after the last non-blank line in region. Insert
15655 ;; drawer's closing, then indent it.
15656 (goto-char rend)
15657 (skip-chars-backward " \r\t\n")
15658 (insert "\n:END:")
15659 (deactivate-mark t)
15660 (indent-for-tab-command)
15661 (unless (eolp) (insert "\n")))
15662 ;; Clear marker, whatever the outcome of insertion is.
15663 (set-marker rend nil)))))))
15665 (defvar org-property-set-functions-alist nil
15666 "Property set function alist.
15667 Each entry should have the following format:
15669 (PROPERTY . READ-FUNCTION)
15671 The read function will be called with the same argument as
15672 `org-completing-read'.")
15674 (defun org-set-property-function (property)
15675 "Get the function that should be used to set PROPERTY.
15676 This is computed according to `org-property-set-functions-alist'."
15677 (or (cdr (assoc property org-property-set-functions-alist))
15678 'org-completing-read))
15680 (defun org-read-property-value (property)
15681 "Read PROPERTY value from user."
15682 (let* ((completion-ignore-case t)
15683 (allowed (org-property-get-allowed-values nil property 'table))
15684 (cur (org-entry-get nil property))
15685 (prompt (concat property " value"
15686 (if (and cur (string-match "\\S-" cur))
15687 (concat " [" cur "]") "") ": "))
15688 (set-function (org-set-property-function property))
15689 (val (if allowed
15690 (funcall set-function prompt allowed nil
15691 (not (get-text-property 0 'org-unrestricted
15692 (caar allowed))))
15693 (let (org-completion-use-ido org-completion-use-iswitchb)
15694 (funcall set-function prompt
15695 (mapcar 'list (org-property-values property))
15696 nil nil "" nil cur)))))
15697 (if (equal val "")
15699 val)))
15701 (defvar org-last-set-property nil)
15702 (defvar org-last-set-property-value nil)
15703 (defun org-read-property-name ()
15704 "Read a property name."
15705 (let* ((completion-ignore-case t)
15706 (keys (org-buffer-property-keys nil t t))
15707 (default-prop (or (save-excursion
15708 (save-match-data
15709 (beginning-of-line)
15710 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15711 (null (string= (match-string 1) "END"))
15712 (match-string 1))))
15713 org-last-set-property))
15714 (property (org-icompleting-read
15715 (concat "Property"
15716 (if default-prop (concat " [" default-prop "]") "")
15717 ": ")
15718 (mapcar 'list keys)
15719 nil nil nil nil
15720 default-prop)))
15721 (if (member property keys)
15722 property
15723 (or (cdr (assoc (downcase property)
15724 (mapcar (lambda (x) (cons (downcase x) x))
15725 keys)))
15726 property))))
15728 (defun org-set-property-and-value (use-last)
15729 "Allow to set [PROPERTY]: [value] direction from prompt.
15730 When use-default, don't even ask, just use the last
15731 \"[PROPERTY]: [value]\" string from the history."
15732 (interactive "P")
15733 (let* ((completion-ignore-case t)
15734 (pv (or (and use-last org-last-set-property-value)
15735 (org-completing-read
15736 "Enter a \"[Property]: [value]\" pair: "
15737 nil nil nil nil nil
15738 org-last-set-property-value)))
15739 prop val)
15740 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15741 (setq prop (match-string 1 pv)
15742 val (match-string 2 pv))
15743 (org-set-property prop val))))
15745 (defun org-set-property (property value)
15746 "In the current entry, set PROPERTY to VALUE.
15747 When called interactively, this will prompt for a property name, offering
15748 completion on existing and default properties. And then it will prompt
15749 for a value, offering completion either on allowed values (via an inherited
15750 xxx_ALL property) or on existing values in other instances of this property
15751 in the current file."
15752 (interactive (list nil nil))
15753 (let* ((property (or property (org-read-property-name)))
15754 (value (or value (org-read-property-value property)))
15755 (fn (cdr (assoc property org-properties-postprocess-alist))))
15756 (setq org-last-set-property property)
15757 (setq org-last-set-property-value (concat property ": " value))
15758 ;; Possibly postprocess the inserted value:
15759 (when fn (setq value (funcall fn value)))
15760 (unless (equal (org-entry-get nil property) value)
15761 (org-entry-put nil property value))))
15763 (defun org-delete-property (property &optional delete-empty-drawer)
15764 "In the current entry, delete PROPERTY.
15765 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15766 an empty drawer to delete."
15767 (interactive
15768 (let* ((completion-ignore-case t)
15769 (prop (org-icompleting-read "Property: "
15770 (org-entry-properties nil 'standard))))
15771 (list prop)))
15772 (message "Property %s %s" property
15773 (if (org-entry-delete nil property delete-empty-drawer)
15774 "deleted"
15775 "was not present in the entry")))
15777 (defun org-delete-property-globally (property)
15778 "Remove PROPERTY globally, from all entries."
15779 (interactive
15780 (let* ((completion-ignore-case t)
15781 (prop (org-icompleting-read
15782 "Globally remove property: "
15783 (mapcar 'list (org-buffer-property-keys)))))
15784 (list prop)))
15785 (save-excursion
15786 (save-restriction
15787 (widen)
15788 (goto-char (point-min))
15789 (let ((cnt 0))
15790 (while (re-search-forward
15791 (org-re-property property)
15792 nil t)
15793 (setq cnt (1+ cnt))
15794 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15795 (message "Property \"%s\" removed from %d entries" property cnt)))))
15797 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15799 (defun org-compute-property-at-point ()
15800 "Compute the property at point.
15801 This looks for an enclosing column format, extracts the operator and
15802 then applies it to the property in the column format's scope."
15803 (interactive)
15804 (unless (org-at-property-p)
15805 (user-error "Not at a property"))
15806 (let ((prop (org-match-string-no-properties 2)))
15807 (org-columns-get-format-and-top-level)
15808 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15809 (user-error "No operator defined for property %s" prop))
15810 (org-columns-compute prop)))
15812 (defvar org-property-allowed-value-functions nil
15813 "Hook for functions supplying allowed values for a specific property.
15814 The functions must take a single argument, the name of the property, and
15815 return a flat list of allowed values. If \":ETC\" is one of
15816 the values, this means that these values are intended as defaults for
15817 completion, but that other values should be allowed too.
15818 The functions must return nil if they are not responsible for this
15819 property.")
15821 (defun org-property-get-allowed-values (pom property &optional table)
15822 "Get allowed values for the property PROPERTY.
15823 When TABLE is non-nil, return an alist that can directly be used for
15824 completion."
15825 (let (vals)
15826 (cond
15827 ((equal property "TODO")
15828 (setq vals (org-with-point-at pom
15829 (append org-todo-keywords-1 '("")))))
15830 ((equal property "PRIORITY")
15831 (let ((n org-lowest-priority))
15832 (while (>= n org-highest-priority)
15833 (push (char-to-string n) vals)
15834 (setq n (1- n)))))
15835 ((member property org-special-properties))
15836 ((setq vals (run-hook-with-args-until-success
15837 'org-property-allowed-value-functions property)))
15839 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15840 (when (and vals (string-match "\\S-" vals))
15841 (setq vals (car (read-from-string (concat "(" vals ")"))))
15842 (setq vals (mapcar (lambda (x)
15843 (cond ((stringp x) x)
15844 ((numberp x) (number-to-string x))
15845 ((symbolp x) (symbol-name x))
15846 (t "???")))
15847 vals)))))
15848 (when (member ":ETC" vals)
15849 (setq vals (remove ":ETC" vals))
15850 (org-add-props (car vals) '(org-unrestricted t)))
15851 (if table (mapcar 'list vals) vals)))
15853 (defun org-property-previous-allowed-value (&optional previous)
15854 "Switch to the next allowed value for this property."
15855 (interactive)
15856 (org-property-next-allowed-value t))
15858 (defun org-property-next-allowed-value (&optional previous)
15859 "Switch to the next allowed value for this property."
15860 (interactive)
15861 (unless (org-at-property-p)
15862 (user-error "Not at a property"))
15863 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15864 (key (match-string 2))
15865 (value (match-string 3))
15866 (allowed (or (org-property-get-allowed-values (point) key)
15867 (and (member value '("[ ]" "[-]" "[X]"))
15868 '("[ ]" "[X]"))))
15869 (heading (save-match-data (nth 4 (org-heading-components))))
15870 nval)
15871 (unless allowed
15872 (user-error "Allowed values for this property have not been defined"))
15873 (if previous (setq allowed (reverse allowed)))
15874 (if (member value allowed)
15875 (setq nval (car (cdr (member value allowed)))))
15876 (setq nval (or nval (car allowed)))
15877 (if (equal nval value)
15878 (user-error "Only one allowed value for this property"))
15879 (org-at-property-p)
15880 (replace-match (concat " :" key ": " nval) t t)
15881 (org-indent-line)
15882 (beginning-of-line 1)
15883 (skip-chars-forward " \t")
15884 (when (equal prop org-effort-property)
15885 (save-excursion
15886 (org-back-to-heading t)
15887 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15888 (when (string= org-clock-current-task heading)
15889 (setq org-clock-effort nval)
15890 (org-clock-update-mode-line)))
15891 (run-hook-with-args 'org-property-changed-functions key nval)))
15893 (defun org-find-olp (path &optional this-buffer)
15894 "Return a marker pointing to the entry at outline path OLP.
15895 If anything goes wrong, throw an error.
15896 You can wrap this call to catch the error like this:
15898 (condition-case msg
15899 (org-mobile-locate-entry (match-string 4))
15900 (error (nth 1 msg)))
15902 The return value will then be either a string with the error message,
15903 or a marker if everything is OK.
15905 If THIS-BUFFER is set, the outline path does not contain a file,
15906 only headings."
15907 (let* ((file (if this-buffer buffer-file-name (pop path)))
15908 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15909 (level 1)
15910 (lmin 1)
15911 (lmax 1)
15912 limit re end found pos heading cnt flevel)
15913 (unless buffer (error "File not found :%s" file))
15914 (with-current-buffer buffer
15915 (save-excursion
15916 (save-restriction
15917 (widen)
15918 (setq limit (point-max))
15919 (goto-char (point-min))
15920 (while (setq heading (pop path))
15921 (setq re (format org-complex-heading-regexp-format
15922 (regexp-quote heading)))
15923 (setq cnt 0 pos (point))
15924 (while (re-search-forward re end t)
15925 (setq level (- (match-end 1) (match-beginning 1)))
15926 (if (and (>= level lmin) (<= level lmax))
15927 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15928 (when (= cnt 0) (error "Heading not found on level %d: %s"
15929 lmax heading))
15930 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15931 lmax heading))
15932 (goto-char found)
15933 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15934 (setq end (save-excursion (org-end-of-subtree t t))))
15935 (when (org-at-heading-p)
15936 (point-marker)))))))
15938 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15939 "Find node HEADING in BUFFER.
15940 Return a marker to the heading if it was found, or nil if not.
15941 If POS-ONLY is set, return just the position instead of a marker.
15943 The heading text must match exact, but it may have a TODO keyword,
15944 a priority cookie and tags in the standard locations."
15945 (with-current-buffer (or buffer (current-buffer))
15946 (save-excursion
15947 (save-restriction
15948 (widen)
15949 (goto-char (point-min))
15950 (let (case-fold-search)
15951 (if (re-search-forward
15952 (format org-complex-heading-regexp-format
15953 (regexp-quote heading)) nil t)
15954 (if pos-only
15955 (match-beginning 0)
15956 (move-marker (make-marker) (match-beginning 0)))))))))
15958 (defun org-find-exact-heading-in-directory (heading &optional dir)
15959 "Find Org node headline HEADING in all .org files in directory DIR.
15960 When the target headline is found, return a marker to this location."
15961 (let ((files (directory-files (or dir default-directory)
15962 nil "\\`[^.#].*\\.org\\'"))
15963 file visiting m buffer)
15964 (catch 'found
15965 (while (setq file (pop files))
15966 (message "trying %s" file)
15967 (setq visiting (org-find-base-buffer-visiting file))
15968 (setq buffer (or visiting (find-file-noselect file)))
15969 (setq m (org-find-exact-headline-in-buffer
15970 heading buffer))
15971 (when (and (not m) (not visiting)) (kill-buffer buffer))
15972 (and m (throw 'found m))))))
15974 (defun org-find-entry-with-id (ident)
15975 "Locate the entry that contains the ID property with exact value IDENT.
15976 IDENT can be a string, a symbol or a number, this function will search for
15977 the string representation of it.
15978 Return the position where this entry starts, or nil if there is no such entry."
15979 (interactive "sID: ")
15980 (let ((id (cond
15981 ((stringp ident) ident)
15982 ((symbol-name ident) (symbol-name ident))
15983 ((numberp ident) (number-to-string ident))
15984 (t (error "IDENT %s must be a string, symbol or number" ident))))
15985 (case-fold-search nil))
15986 (save-excursion
15987 (save-restriction
15988 (widen)
15989 (goto-char (point-min))
15990 (when (re-search-forward
15991 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15992 nil t)
15993 (org-back-to-heading t)
15994 (point))))))
15996 ;;;; Timestamps
15998 (defvar org-last-changed-timestamp nil)
15999 (defvar org-last-inserted-timestamp nil
16000 "The last time stamp inserted with `org-insert-time-stamp'.")
16001 (defvar org-time-was-given) ; dynamically scoped parameter
16002 (defvar org-end-time-was-given) ; dynamically scoped parameter
16003 (defvar org-ts-what) ; dynamically scoped parameter
16005 (defun org-time-stamp (arg &optional inactive)
16006 "Prompt for a date/time and insert a time stamp.
16007 If the user specifies a time like HH:MM or if this command is
16008 called with at least one prefix argument, the time stamp contains
16009 the date and the time. Otherwise, only the date is be included.
16011 All parts of a date not specified by the user is filled in from
16012 the current date/time. So if you just press return without
16013 typing anything, the time stamp will represent the current
16014 date/time.
16016 If there is already a timestamp at the cursor, it will be
16017 modified.
16019 With two universal prefix arguments, insert an active timestamp
16020 with the current time without prompting the user."
16021 (interactive "P")
16022 (let* ((ts nil)
16023 (default-time
16024 ;; Default time is either today, or, when entering a range,
16025 ;; the range start.
16026 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16027 (save-excursion
16028 (re-search-backward
16029 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16030 (- (point) 20) t)))
16031 (apply 'encode-time (org-parse-time-string (match-string 1)))
16032 (current-time)))
16033 (default-input (and ts (org-get-compact-tod ts)))
16034 (repeater (save-excursion
16035 (save-match-data
16036 (beginning-of-line)
16037 (when (re-search-forward
16038 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16039 (save-excursion (progn (end-of-line) (point))) t)
16040 (match-string 0)))))
16041 org-time-was-given org-end-time-was-given time)
16042 (cond
16043 ((and (org-at-timestamp-p t)
16044 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16045 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16046 (insert "--")
16047 (setq time (let ((this-command this-command))
16048 (org-read-date arg 'totime nil nil
16049 default-time default-input inactive)))
16050 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16051 ((org-at-timestamp-p t)
16052 (setq time (let ((this-command this-command))
16053 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16054 (when (org-at-timestamp-p t) ; just to get the match data
16055 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16056 (replace-match "")
16057 (setq org-last-changed-timestamp
16058 (org-insert-time-stamp
16059 time (or org-time-was-given arg)
16060 inactive nil nil (list org-end-time-was-given)))
16061 (when repeater (goto-char (1- (point))) (insert " " repeater)
16062 (setq org-last-changed-timestamp
16063 (concat (substring org-last-inserted-timestamp 0 -1)
16064 " " repeater ">"))))
16065 (message "Timestamp updated"))
16066 ((equal arg '(16))
16067 (org-insert-time-stamp (current-time) t))
16069 (setq time (let ((this-command this-command))
16070 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16071 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16072 nil nil (list org-end-time-was-given))))))
16074 ;; FIXME: can we use this for something else, like computing time differences?
16075 (defun org-get-compact-tod (s)
16076 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16077 (let* ((t1 (match-string 1 s))
16078 (h1 (string-to-number (match-string 2 s)))
16079 (m1 (string-to-number (match-string 3 s)))
16080 (t2 (and (match-end 4) (match-string 5 s)))
16081 (h2 (and t2 (string-to-number (match-string 6 s))))
16082 (m2 (and t2 (string-to-number (match-string 7 s))))
16083 dh dm)
16084 (if (not t2)
16086 (setq dh (- h2 h1) dm (- m2 m1))
16087 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16088 (concat t1 "+" (number-to-string dh)
16089 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16091 (defun org-time-stamp-inactive (&optional arg)
16092 "Insert an inactive time stamp.
16093 An inactive time stamp is enclosed in square brackets instead of angle
16094 brackets. It is inactive in the sense that it does not trigger agenda entries,
16095 does not link to the calendar and cannot be changed with the S-cursor keys.
16096 So these are more for recording a certain time/date."
16097 (interactive "P")
16098 (org-time-stamp arg 'inactive))
16100 (defvar org-date-ovl (make-overlay 1 1))
16101 (overlay-put org-date-ovl 'face 'org-date-selected)
16102 (org-detach-overlay org-date-ovl)
16104 (defvar org-ans1) ; dynamically scoped parameter
16105 (defvar org-ans2) ; dynamically scoped parameter
16107 (defvar org-plain-time-of-day-regexp) ; defined below
16109 (defvar org-overriding-default-time nil) ; dynamically scoped
16110 (defvar org-read-date-overlay nil)
16111 (defvar org-dcst nil) ; dynamically scoped
16112 (defvar org-read-date-history nil)
16113 (defvar org-read-date-final-answer nil)
16114 (defvar org-read-date-analyze-futurep nil)
16115 (defvar org-read-date-analyze-forced-year nil)
16116 (defvar org-read-date-inactive)
16118 (defvar org-read-date-minibuffer-local-map
16119 (let ((map (make-sparse-keymap)))
16120 (set-keymap-parent map minibuffer-local-map)
16121 (org-defkey map (kbd ".")
16122 (lambda () (interactive)
16123 ;; Are we at the beginning of the prompt?
16124 (if (looking-back "^[^:]+: ")
16125 (org-eval-in-calendar '(calendar-goto-today))
16126 (insert "."))))
16127 (org-defkey map (kbd "C-.")
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-goto-today))))
16130 (org-defkey map [(meta shift left)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-backward-month 1))))
16133 (org-defkey map [(meta shift right)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-forward-month 1))))
16136 (org-defkey map [(meta shift up)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-backward-year 1))))
16139 (org-defkey map [(meta shift down)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-forward-year 1))))
16142 (org-defkey map [?\e (shift left)]
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-backward-month 1))))
16145 (org-defkey map [?\e (shift right)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-forward-month 1))))
16148 (org-defkey map [?\e (shift up)]
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-backward-year 1))))
16151 (org-defkey map [?\e (shift down)]
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-forward-year 1))))
16154 (org-defkey map [(shift up)]
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-backward-week 1))))
16157 (org-defkey map [(shift down)]
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(calendar-forward-week 1))))
16160 (org-defkey map [(shift left)]
16161 (lambda () (interactive)
16162 (org-eval-in-calendar '(calendar-backward-day 1))))
16163 (org-defkey map [(shift right)]
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(calendar-forward-day 1))))
16166 (org-defkey map "!"
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(diary-view-entries))
16169 (message "")))
16170 (org-defkey map ">"
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(scroll-calendar-left 1))))
16173 (org-defkey map "<"
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(scroll-calendar-right 1))))
16176 (org-defkey map "\C-v"
16177 (lambda () (interactive)
16178 (org-eval-in-calendar
16179 '(calendar-scroll-left-three-months 1))))
16180 (org-defkey map "\M-v"
16181 (lambda () (interactive)
16182 (org-eval-in-calendar
16183 '(calendar-scroll-right-three-months 1))))
16184 map)
16185 "Keymap for minibuffer commands when using `org-read-date'.")
16187 (defun org-read-date (&optional org-with-time to-time from-string prompt
16188 default-time default-input inactive)
16189 "Read a date, possibly a time, and make things smooth for the user.
16190 The prompt will suggest to enter an ISO date, but you can also enter anything
16191 which will at least partially be understood by `parse-time-string'.
16192 Unrecognized parts of the date will default to the current day, month, year,
16193 hour and minute. If this command is called to replace a timestamp at point,
16194 or to enter the second timestamp of a range, the default time is taken
16195 from the existing stamp. Furthermore, the command prefers the future,
16196 so if you are giving a date where the year is not given, and the day-month
16197 combination is already past in the current year, it will assume you
16198 mean next year. For details, see the manual. A few examples:
16200 3-2-5 --> 2003-02-05
16201 feb 15 --> currentyear-02-15
16202 2/15 --> currentyear-02-15
16203 sep 12 9 --> 2009-09-12
16204 12:45 --> today 12:45
16205 22 sept 0:34 --> currentyear-09-22 0:34
16206 12 --> currentyear-currentmonth-12
16207 Fri --> nearest Friday after today
16208 -Tue --> last Tuesday
16209 etc.
16211 Furthermore you can specify a relative date by giving, as the *first* thing
16212 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16213 change in days weeks, months, years.
16214 With a single plus or minus, the date is relative to today. With a double
16215 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16216 +4d --> four days from today
16217 +4 --> same as above
16218 +2w --> two weeks from today
16219 ++5 --> five days from default date
16221 The function understands only English month and weekday abbreviations.
16223 While prompting, a calendar is popped up - you can also select the
16224 date with the mouse (button 1). The calendar shows a period of three
16225 months. To scroll it to other months, use the keys `>' and `<'.
16226 If you don't like the calendar, turn it off with
16227 \(setq org-read-date-popup-calendar nil)
16229 With optional argument TO-TIME, the date will immediately be converted
16230 to an internal time.
16231 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16232 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16233 still enter a time, and this function will inform the calling routine
16234 about this change. The calling routine may then choose to change the
16235 format used to insert the time stamp into the buffer to include the time.
16236 With optional argument FROM-STRING, read from this string instead from
16237 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16238 the time/date that is used for everything that is not specified by the
16239 user."
16240 (require 'parse-time)
16241 (let* ((org-time-stamp-rounding-minutes
16242 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16243 (org-dcst org-display-custom-times)
16244 (ct (org-current-time))
16245 (org-def (or org-overriding-default-time default-time ct))
16246 (org-defdecode (decode-time org-def))
16247 (dummy (progn
16248 (when (< (nth 2 org-defdecode) org-extend-today-until)
16249 (setcar (nthcdr 2 org-defdecode) -1)
16250 (setcar (nthcdr 1 org-defdecode) 59)
16251 (setq org-def (apply 'encode-time org-defdecode)
16252 org-defdecode (decode-time org-def)))))
16253 (mouse-autoselect-window nil) ; Don't let the mouse jump
16254 (calendar-frame-setup nil)
16255 (calendar-setup nil)
16256 (calendar-move-hook nil)
16257 (calendar-view-diary-initially-flag nil)
16258 (calendar-view-holidays-initially-flag nil)
16259 (timestr (format-time-string
16260 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16261 (prompt (concat (if prompt (concat prompt " ") "")
16262 (format "Date+time [%s]: " timestr)))
16263 ans (org-ans0 "") org-ans1 org-ans2 final)
16265 (cond
16266 (from-string (setq ans from-string))
16267 (org-read-date-popup-calendar
16268 (save-excursion
16269 (save-window-excursion
16270 (calendar)
16271 (org-eval-in-calendar '(setq cursor-type nil) t)
16272 (unwind-protect
16273 (progn
16274 (calendar-forward-day (- (time-to-days org-def)
16275 (calendar-absolute-from-gregorian
16276 (calendar-current-date))))
16277 (org-eval-in-calendar nil t)
16278 (let* ((old-map (current-local-map))
16279 (map (copy-keymap calendar-mode-map))
16280 (minibuffer-local-map
16281 (copy-keymap org-read-date-minibuffer-local-map)))
16282 (org-defkey map (kbd "RET") 'org-calendar-select)
16283 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16284 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16285 (unwind-protect
16286 (progn
16287 (use-local-map map)
16288 (setq org-read-date-inactive inactive)
16289 (add-hook 'post-command-hook 'org-read-date-display)
16290 (setq org-ans0 (read-string prompt default-input
16291 'org-read-date-history nil))
16292 ;; org-ans0: from prompt
16293 ;; org-ans1: from mouse click
16294 ;; org-ans2: from calendar motion
16295 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16296 (remove-hook 'post-command-hook 'org-read-date-display)
16297 (use-local-map old-map)
16298 (when org-read-date-overlay
16299 (delete-overlay org-read-date-overlay)
16300 (setq org-read-date-overlay nil)))))
16301 (bury-buffer "*Calendar*")))))
16303 (t ; Naked prompt only
16304 (unwind-protect
16305 (setq ans (read-string prompt default-input
16306 'org-read-date-history timestr))
16307 (when org-read-date-overlay
16308 (delete-overlay org-read-date-overlay)
16309 (setq org-read-date-overlay nil)))))
16311 (setq final (org-read-date-analyze ans org-def org-defdecode))
16313 (when org-read-date-analyze-forced-year
16314 (message "Year was forced into %s"
16315 (if org-read-date-force-compatible-dates
16316 "compatible range (1970-2037)"
16317 "range representable on this machine"))
16318 (ding))
16320 ;; One round trip to get rid of 34th of August and stuff like that....
16321 (setq final (decode-time (apply 'encode-time final)))
16323 (setq org-read-date-final-answer ans)
16325 (if to-time
16326 (apply 'encode-time final)
16327 (if (and (boundp 'org-time-was-given) org-time-was-given)
16328 (format "%04d-%02d-%02d %02d:%02d"
16329 (nth 5 final) (nth 4 final) (nth 3 final)
16330 (nth 2 final) (nth 1 final))
16331 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16333 (defvar org-def)
16334 (defvar org-defdecode)
16335 (defvar org-with-time)
16336 (defun org-read-date-display ()
16337 "Display the current date prompt interpretation in the minibuffer."
16338 (when org-read-date-display-live
16339 (when org-read-date-overlay
16340 (delete-overlay org-read-date-overlay))
16341 (when (minibufferp (current-buffer))
16342 (save-excursion
16343 (end-of-line 1)
16344 (while (not (equal (buffer-substring
16345 (max (point-min) (- (point) 4)) (point))
16346 " "))
16347 (insert " ")))
16348 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16349 " " (or org-ans1 org-ans2)))
16350 (org-end-time-was-given nil)
16351 (f (org-read-date-analyze ans org-def org-defdecode))
16352 (fmts (if org-dcst
16353 org-time-stamp-custom-formats
16354 org-time-stamp-formats))
16355 (fmt (if (or org-with-time
16356 (and (boundp 'org-time-was-given) org-time-was-given))
16357 (cdr fmts)
16358 (car fmts)))
16359 (txt (format-time-string fmt (apply 'encode-time f)))
16360 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16361 (txt (concat "=> " txt)))
16362 (when (and org-end-time-was-given
16363 (string-match org-plain-time-of-day-regexp txt))
16364 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16365 org-end-time-was-given
16366 (substring txt (match-end 0)))))
16367 (when org-read-date-analyze-futurep
16368 (setq txt (concat txt " (=>F)")))
16369 (setq org-read-date-overlay
16370 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16371 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16373 (defun org-read-date-analyze (ans org-def org-defdecode)
16374 "Analyze the combined answer of the date prompt."
16375 ;; FIXME: cleanup and comment
16376 (let ((nowdecode (decode-time (current-time)))
16377 delta deltan deltaw deltadef year month day
16378 hour minute second wday pm h2 m2 tl wday1
16379 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16380 (setq org-read-date-analyze-futurep nil
16381 org-read-date-analyze-forced-year nil)
16382 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16383 (setq ans "+0"))
16385 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16386 (setq ans (replace-match "" t t ans)
16387 deltan (car delta)
16388 deltaw (nth 1 delta)
16389 deltadef (nth 2 delta)))
16391 ;; Check if there is an iso week date in there. If yes, store the
16392 ;; info and postpone interpreting it until the rest of the parsing
16393 ;; is done.
16394 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16395 (setq iso-year (if (match-end 1)
16396 (org-small-year-to-year
16397 (string-to-number (match-string 1 ans))))
16398 iso-weekday (if (match-end 3)
16399 (string-to-number (match-string 3 ans)))
16400 iso-week (string-to-number (match-string 2 ans)))
16401 (setq ans (replace-match "" t t ans)))
16403 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16404 (when (string-match
16405 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16406 (setq year (if (match-end 2)
16407 (string-to-number (match-string 2 ans))
16408 (progn (setq kill-year t)
16409 (string-to-number (format-time-string "%Y"))))
16410 month (string-to-number (match-string 3 ans))
16411 day (string-to-number (match-string 4 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)))
16416 ;; Help matching dotted european dates
16417 (when (string-match
16418 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16419 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16420 (setq kill-year t)
16421 (string-to-number (format-time-string "%Y")))
16422 day (string-to-number (match-string 1 ans))
16423 month (string-to-number (match-string 2 ans))
16424 ans (replace-match (format "%04d-%02d-%02d" year month day)
16425 t nil ans)))
16427 ;; Help matching american dates, like 5/30 or 5/30/7
16428 (when (string-match
16429 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16430 (setq year (if (match-end 4)
16431 (string-to-number (match-string 4 ans))
16432 (progn (setq kill-year t)
16433 (string-to-number (format-time-string "%Y"))))
16434 month (string-to-number (match-string 1 ans))
16435 day (string-to-number (match-string 2 ans)))
16436 (if (< year 100) (setq year (+ 2000 year)))
16437 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16438 t nil ans)))
16439 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16440 ;; If there is a time with am/pm, and *no* time without it, we convert
16441 ;; so that matching will be successful.
16442 (loop for i from 1 to 2 do ; twice, for end time as well
16443 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16444 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16445 (setq hour (string-to-number (match-string 1 ans))
16446 minute (if (match-end 3)
16447 (string-to-number (match-string 3 ans))
16449 pm (equal ?p
16450 (string-to-char (downcase (match-string 4 ans)))))
16451 (if (and (= hour 12) (not pm))
16452 (setq hour 0)
16453 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16454 (setq ans (replace-match (format "%02d:%02d" hour minute)
16455 t t ans))))
16457 ;; Check if a time range is given as a duration
16458 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16459 (setq hour (string-to-number (match-string 1 ans))
16460 h2 (+ hour (string-to-number (match-string 3 ans)))
16461 minute (string-to-number (match-string 2 ans))
16462 m2 (+ minute (if (match-end 5) (string-to-number
16463 (match-string 5 ans))0)))
16464 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16465 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16466 t t ans)))
16468 ;; Check if there is a time range
16469 (when (boundp 'org-end-time-was-given)
16470 (setq org-time-was-given nil)
16471 (when (and (string-match org-plain-time-of-day-regexp ans)
16472 (match-end 8))
16473 (setq org-end-time-was-given (match-string 8 ans))
16474 (setq ans (concat (substring ans 0 (match-beginning 7))
16475 (substring ans (match-end 7))))))
16477 (setq tl (parse-time-string ans)
16478 day (or (nth 3 tl) (nth 3 org-defdecode))
16479 month (or (nth 4 tl)
16480 (if (and org-read-date-prefer-future
16481 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16482 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16483 (nth 4 org-defdecode)))
16484 year (or (and (not kill-year) (nth 5 tl))
16485 (if (and org-read-date-prefer-future
16486 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16487 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16488 (nth 5 org-defdecode)))
16489 hour (or (nth 2 tl) (nth 2 org-defdecode))
16490 minute (or (nth 1 tl) (nth 1 org-defdecode))
16491 second (or (nth 0 tl) 0)
16492 wday (nth 6 tl))
16494 (when (and (eq org-read-date-prefer-future 'time)
16495 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16496 (equal day (nth 3 nowdecode))
16497 (equal month (nth 4 nowdecode))
16498 (equal year (nth 5 nowdecode))
16499 (nth 2 tl)
16500 (or (< (nth 2 tl) (nth 2 nowdecode))
16501 (and (= (nth 2 tl) (nth 2 nowdecode))
16502 (nth 1 tl)
16503 (< (nth 1 tl) (nth 1 nowdecode)))))
16504 (setq day (1+ day)
16505 futurep t))
16507 ;; Special date definitions below
16508 (cond
16509 (iso-week
16510 ;; There was an iso week
16511 (require 'cal-iso)
16512 (setq futurep nil)
16513 (setq year (or iso-year year)
16514 day (or iso-weekday wday 1)
16515 wday nil ; to make sure that the trigger below does not match
16516 iso-date (calendar-gregorian-from-absolute
16517 (calendar-absolute-from-iso
16518 (list iso-week day year))))
16519 ; FIXME: Should we also push ISO weeks into the future?
16520 ; (when (and org-read-date-prefer-future
16521 ; (not iso-year)
16522 ; (< (calendar-absolute-from-gregorian iso-date)
16523 ; (time-to-days (current-time))))
16524 ; (setq year (1+ year)
16525 ; iso-date (calendar-gregorian-from-absolute
16526 ; (calendar-absolute-from-iso
16527 ; (list iso-week day year)))))
16528 (setq month (car iso-date)
16529 year (nth 2 iso-date)
16530 day (nth 1 iso-date)))
16531 (deltan
16532 (setq futurep nil)
16533 (unless deltadef
16534 (let ((now (decode-time (current-time))))
16535 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16536 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16537 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16538 ((equal deltaw "m") (setq month (+ month deltan)))
16539 ((equal deltaw "y") (setq year (+ year deltan)))))
16540 ((and wday (not (nth 3 tl)))
16541 ;; Weekday was given, but no day, so pick that day in the week
16542 ;; on or after the derived date.
16543 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16544 (unless (equal wday wday1)
16545 (setq day (+ day (% (- wday wday1 -7) 7))))))
16546 (if (and (boundp 'org-time-was-given)
16547 (nth 2 tl))
16548 (setq org-time-was-given t))
16549 (if (< year 100) (setq year (+ 2000 year)))
16550 ;; Check of the date is representable
16551 (if org-read-date-force-compatible-dates
16552 (progn
16553 (if (< year 1970)
16554 (setq year 1970 org-read-date-analyze-forced-year t))
16555 (if (> year 2037)
16556 (setq year 2037 org-read-date-analyze-forced-year t)))
16557 (condition-case nil
16558 (ignore (encode-time second minute hour day month year))
16559 (error
16560 (setq year (nth 5 org-defdecode))
16561 (setq org-read-date-analyze-forced-year t))))
16562 (setq org-read-date-analyze-futurep futurep)
16563 (list second minute hour day month year)))
16565 (defvar parse-time-weekdays)
16566 (defun org-read-date-get-relative (s today default)
16567 "Check string S for special relative date string.
16568 TODAY and DEFAULT are internal times, for today and for a default.
16569 Return shift list (N what def-flag)
16570 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16571 N is the number of WHATs to shift.
16572 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16573 the DEFAULT date rather than TODAY."
16574 (require 'parse-time)
16575 (when (and
16576 (string-match
16577 (concat
16578 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16579 "\\([0-9]+\\)?"
16580 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16581 "\\([ \t]\\|$\\)") s)
16582 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16583 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16584 (string-to-char (substring (match-string 1 s) -1))
16585 ?+))
16586 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16587 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16588 (what (if (match-end 3) (match-string 3 s) "d"))
16589 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16590 (date (if rel default today))
16591 (wday (nth 6 (decode-time date)))
16592 delta)
16593 (if wday1
16594 (progn
16595 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16596 (if (= delta 0) (setq delta 7))
16597 (if (= dir ?-)
16598 (progn
16599 (setq delta (- delta 7))
16600 (if (= delta 0) (setq delta -7))))
16601 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16602 (list delta "d" rel))
16603 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16605 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16606 "Turn a user-specified date into the internal representation.
16607 The internal representation needed by the calendar is (month day year).
16608 This is a wrapper to handle the brain-dead convention in calendar that
16609 user function argument order change dependent on argument order."
16610 (if (boundp 'calendar-date-style)
16611 (cond
16612 ((eq calendar-date-style 'american)
16613 (list arg1 arg2 arg3))
16614 ((eq calendar-date-style 'european)
16615 (list arg2 arg1 arg3))
16616 ((eq calendar-date-style 'iso)
16617 (list arg2 arg3 arg1)))
16618 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16619 (if (org-bound-and-true-p european-calendar-style)
16620 (list arg2 arg1 arg3)
16621 (list arg1 arg2 arg3)))))
16623 (defun org-eval-in-calendar (form &optional keepdate)
16624 "Eval FORM in the calendar window and return to current window.
16625 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16626 otherwise stick to the current value of `org-ans2'."
16627 (let ((sf (selected-frame))
16628 (sw (selected-window)))
16629 (select-window (get-buffer-window "*Calendar*" t))
16630 (eval form)
16631 (when (and (not keepdate) (calendar-cursor-to-date))
16632 (let* ((date (calendar-cursor-to-date))
16633 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16634 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16635 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16636 (select-window sw)
16637 (org-select-frame-set-input-focus sf)))
16639 (defun org-calendar-select ()
16640 "Return to `org-read-date' with the date currently selected.
16641 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16642 (interactive)
16643 (when (calendar-cursor-to-date)
16644 (let* ((date (calendar-cursor-to-date))
16645 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16646 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16647 (if (active-minibuffer-window) (exit-minibuffer))))
16649 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16650 "Insert a date stamp for the date given by the internal TIME.
16651 WITH-HM means use the stamp format that includes the time of the day.
16652 INACTIVE means use square brackets instead of angular ones, so that the
16653 stamp will not contribute to the agenda.
16654 PRE and POST are optional strings to be inserted before and after the
16655 stamp.
16656 The command returns the inserted time stamp."
16657 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16658 stamp)
16659 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16660 (insert-before-markers (or pre ""))
16661 (when (listp extra)
16662 (setq extra (car extra))
16663 (if (and (stringp extra)
16664 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16665 (setq extra (format "-%02d:%02d"
16666 (string-to-number (match-string 1 extra))
16667 (string-to-number (match-string 2 extra))))
16668 (setq extra nil)))
16669 (when extra
16670 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16671 (insert-before-markers (setq stamp (format-time-string fmt time)))
16672 (insert-before-markers (or post ""))
16673 (setq org-last-inserted-timestamp stamp)))
16675 (defun org-toggle-time-stamp-overlays ()
16676 "Toggle the use of custom time stamp formats."
16677 (interactive)
16678 (setq org-display-custom-times (not org-display-custom-times))
16679 (unless org-display-custom-times
16680 (let ((p (point-min)) (bmp (buffer-modified-p)))
16681 (while (setq p (next-single-property-change p 'display))
16682 (if (and (get-text-property p 'display)
16683 (eq (get-text-property p 'face) 'org-date))
16684 (remove-text-properties
16685 p (setq p (next-single-property-change p 'display))
16686 '(display t))))
16687 (set-buffer-modified-p bmp)))
16688 (if (featurep 'xemacs)
16689 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16690 (org-restart-font-lock)
16691 (setq org-table-may-need-update t)
16692 (if org-display-custom-times
16693 (message "Time stamps are overlaid with custom format")
16694 (message "Time stamp overlays removed")))
16696 (defun org-display-custom-time (beg end)
16697 "Overlay modified time stamp format over timestamp between BEG and END."
16698 (let* ((ts (buffer-substring beg end))
16699 t1 w1 with-hm tf time str w2 (off 0))
16700 (save-match-data
16701 (setq t1 (org-parse-time-string ts t))
16702 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16703 (setq off (- (match-end 0) (match-beginning 0)))))
16704 (setq end (- end off))
16705 (setq w1 (- end beg)
16706 with-hm (and (nth 1 t1) (nth 2 t1))
16707 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16708 time (org-fix-decoded-time t1)
16709 str (org-add-props
16710 (format-time-string
16711 (substring tf 1 -1) (apply 'encode-time time))
16712 nil 'mouse-face 'highlight)
16713 w2 (length str))
16714 (if (not (= w2 w1))
16715 (add-text-properties (1+ beg) (+ 2 beg)
16716 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16717 (if (featurep 'xemacs)
16718 (progn
16719 (put-text-property beg end 'invisible t)
16720 (put-text-property beg end 'end-glyph (make-glyph str)))
16721 (put-text-property beg end 'display str))))
16723 (defun org-translate-time (string)
16724 "Translate all timestamps in STRING to custom format.
16725 But do this only if the variable `org-display-custom-times' is set."
16726 (when org-display-custom-times
16727 (save-match-data
16728 (let* ((start 0)
16729 (re org-ts-regexp-both)
16730 t1 with-hm inactive tf time str beg end)
16731 (while (setq start (string-match re string start))
16732 (setq beg (match-beginning 0)
16733 end (match-end 0)
16734 t1 (save-match-data
16735 (org-parse-time-string (substring string beg end) t))
16736 with-hm (and (nth 1 t1) (nth 2 t1))
16737 inactive (equal (substring string beg (1+ beg)) "[")
16738 tf (funcall (if with-hm 'cdr 'car)
16739 org-time-stamp-custom-formats)
16740 time (org-fix-decoded-time t1)
16741 str (format-time-string
16742 (concat
16743 (if inactive "[" "<") (substring tf 1 -1)
16744 (if inactive "]" ">"))
16745 (apply 'encode-time time))
16746 string (replace-match str t t string)
16747 start (+ start (length str)))))))
16748 string)
16750 (defun org-fix-decoded-time (time)
16751 "Set 0 instead of nil for the first 6 elements of time.
16752 Don't touch the rest."
16753 (let ((n 0))
16754 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16756 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16758 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16759 "Difference between TIMESTAMP-STRING and now in days.
16760 If SECONDS is non-nil, return the difference in seconds."
16761 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16762 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16763 (funcall fdiff (current-time)))))
16765 (defun org-deadline-close (timestamp-string &optional ndays)
16766 "Is the time in TIMESTAMP-STRING close to the current date?"
16767 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16768 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16769 (not (org-entry-is-done-p))))
16771 (defun org-get-wdays (ts &optional delay zero-delay)
16772 "Get the deadline lead time appropriate for timestring TS.
16773 When DELAY is non-nil, get the delay time for scheduled items
16774 instead of the deadline lead time. When ZERO-DELAY is non-nil
16775 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16776 don't try to find the delay cookie in the scheduled timestamp."
16777 (let ((tv (if delay org-scheduled-delay-days
16778 org-deadline-warning-days)))
16779 (cond
16780 ((or (and delay (< tv 0))
16781 (and delay zero-delay (<= tv 0))
16782 (and (not delay) (<= tv 0)))
16783 ;; Enforce this value no matter what
16784 (- tv))
16785 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16786 ;; lead time is specified.
16787 (floor (* (string-to-number (match-string 1 ts))
16788 (cdr (assoc (match-string 2 ts)
16789 '(("d" . 1) ("w" . 7)
16790 ("m" . 30.4) ("y" . 365.25)
16791 ("h" . 0.041667)))))))
16792 ;; go for the default.
16793 (t tv))))
16795 (defun org-calendar-select-mouse (ev)
16796 "Return to `org-read-date' with the date currently selected.
16797 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16798 (interactive "e")
16799 (mouse-set-point ev)
16800 (when (calendar-cursor-to-date)
16801 (let* ((date (calendar-cursor-to-date))
16802 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16803 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16804 (if (active-minibuffer-window) (exit-minibuffer))))
16806 (defun org-check-deadlines (ndays)
16807 "Check if there are any deadlines due or past due.
16808 A deadline is considered due if it happens within `org-deadline-warning-days'
16809 days from today's date. If the deadline appears in an entry marked DONE,
16810 it is not shown. The prefix arg NDAYS can be used to test that many
16811 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16812 (interactive "P")
16813 (let* ((org-warn-days
16814 (cond
16815 ((equal ndays '(4)) 100000)
16816 (ndays (prefix-numeric-value ndays))
16817 (t (abs org-deadline-warning-days))))
16818 (case-fold-search nil)
16819 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16820 (callback
16821 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16823 (message "%d deadlines past-due or due within %d days"
16824 (org-occur regexp nil callback)
16825 org-warn-days)))
16827 (defsubst org-re-timestamp (type)
16828 "Return a regexp for timestamp TYPE.
16829 Allowed values for TYPE are:
16831 all: all timestamps
16832 active: only active timestamps (<...>)
16833 inactive: only inactive timestamps ([...])
16834 scheduled: only scheduled timestamps
16835 deadline: only deadline timestamps
16836 closed: only closed time-stamps
16838 When TYPE is nil, fall back on returning a regexp that matches
16839 both scheduled and deadline timestamps."
16840 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16841 ((eq type 'active) org-ts-regexp)
16842 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16843 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16844 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16845 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16846 ((eq type 'scheduled-or-deadline)
16847 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16849 (defun org-check-before-date (date)
16850 "Check if there are deadlines or scheduled entries before DATE."
16851 (interactive (list (org-read-date)))
16852 (let ((case-fold-search nil)
16853 (regexp (org-re-timestamp org-ts-type))
16854 (callback
16855 (lambda () (time-less-p
16856 (org-time-string-to-time (match-string 1))
16857 (org-time-string-to-time date)))))
16858 (message "%d entries before %s"
16859 (org-occur regexp nil callback) date)))
16861 (defun org-check-after-date (date)
16862 "Check if there are deadlines or scheduled entries after DATE."
16863 (interactive (list (org-read-date)))
16864 (let ((case-fold-search nil)
16865 (regexp (org-re-timestamp org-ts-type))
16866 (callback
16867 (lambda () (not
16868 (time-less-p
16869 (org-time-string-to-time (match-string 1))
16870 (org-time-string-to-time date))))))
16871 (message "%d entries after %s"
16872 (org-occur regexp nil callback) date)))
16874 (defun org-check-dates-range (start-date end-date)
16875 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16876 (interactive (list (org-read-date nil nil nil "Range starts")
16877 (org-read-date nil nil nil "Range end")))
16878 (let ((case-fold-search nil)
16879 (regexp (org-re-timestamp org-ts-type))
16880 (callback
16881 (lambda ()
16882 (let ((match (match-string 1)))
16883 (and
16884 (not (time-less-p
16885 (org-time-string-to-time match)
16886 (org-time-string-to-time start-date)))
16887 (time-less-p
16888 (org-time-string-to-time match)
16889 (org-time-string-to-time end-date)))))))
16890 (message "%d entries between %s and %s"
16891 (org-occur regexp nil callback) start-date end-date)))
16893 (defun org-evaluate-time-range (&optional to-buffer)
16894 "Evaluate a time range by computing the difference between start and end.
16895 Normally the result is just printed in the echo area, but with prefix arg
16896 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16897 If the time range is actually in a table, the result is inserted into the
16898 next column.
16899 For time difference computation, a year is assumed to be exactly 365
16900 days in order to avoid rounding problems."
16901 (interactive "P")
16903 (org-clock-update-time-maybe)
16904 (save-excursion
16905 (unless (org-at-date-range-p t)
16906 (goto-char (point-at-bol))
16907 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16908 (if (not (org-at-date-range-p t))
16909 (user-error "Not at a time-stamp range, and none found in current line")))
16910 (let* ((ts1 (match-string 1))
16911 (ts2 (match-string 2))
16912 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16913 (match-end (match-end 0))
16914 (time1 (org-time-string-to-time ts1))
16915 (time2 (org-time-string-to-time ts2))
16916 (t1 (org-float-time time1))
16917 (t2 (org-float-time time2))
16918 (diff (abs (- t2 t1)))
16919 (negative (< (- t2 t1) 0))
16920 ;; (ys (floor (* 365 24 60 60)))
16921 (ds (* 24 60 60))
16922 (hs (* 60 60))
16923 (fy "%dy %dd %02d:%02d")
16924 (fy1 "%dy %dd")
16925 (fd "%dd %02d:%02d")
16926 (fd1 "%dd")
16927 (fh "%02d:%02d")
16928 y d h m align)
16929 (if havetime
16930 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16932 d (floor (/ diff ds)) diff (mod diff ds)
16933 h (floor (/ diff hs)) diff (mod diff hs)
16934 m (floor (/ diff 60)))
16935 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16937 d (floor (+ (/ diff ds) 0.5))
16938 h 0 m 0))
16939 (if (not to-buffer)
16940 (message "%s" (org-make-tdiff-string y d h m))
16941 (if (org-at-table-p)
16942 (progn
16943 (goto-char match-end)
16944 (setq align t)
16945 (and (looking-at " *|") (goto-char (match-end 0))))
16946 (goto-char match-end))
16947 (if (looking-at
16948 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16949 (replace-match ""))
16950 (if negative (insert " -"))
16951 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16952 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16953 (insert " " (format fh h m))))
16954 (if align (org-table-align))
16955 (message "Time difference inserted")))))
16957 (defun org-make-tdiff-string (y d h m)
16958 (let ((fmt "")
16959 (l nil))
16960 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16961 l (push y l)))
16962 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16963 l (push d l)))
16964 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16965 l (push h l)))
16966 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16967 l (push m l)))
16968 (apply 'format fmt (nreverse l))))
16970 (defun org-time-string-to-time (s &optional buffer pos)
16971 "Convert a timestamp string into internal time."
16972 (condition-case errdata
16973 (apply 'encode-time (org-parse-time-string s))
16974 (error (error "Bad timestamp `%s'%s\nError was: %s"
16975 s (if (not (and buffer pos))
16977 (format " at %d in buffer `%s'" pos buffer))
16978 (cdr errdata)))))
16980 (defun org-time-string-to-seconds (s)
16981 "Convert a timestamp string to a number of seconds."
16982 (org-float-time (org-time-string-to-time s)))
16984 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16985 "Convert a time stamp to an absolute day number.
16986 If there is a specifier for a cyclic time stamp, get the closest
16987 date to DAYNR.
16988 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16989 The variable `date' is bound by the calendar when this is called."
16990 (cond
16991 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16992 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16993 daynr
16994 (+ daynr 1000)))
16995 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16996 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16997 (time-to-days (current-time))) (match-string 0 s)
16998 prefer show-all))
16999 (t (time-to-days
17000 (condition-case errdata
17001 (apply 'encode-time (org-parse-time-string s))
17002 (error (error "Bad timestamp `%s'%s\nError was: %s"
17003 s (if (not (and buffer pos))
17005 (format " at %d in buffer `%s'" pos buffer))
17006 (cdr errdata))))))))
17008 (defun org-days-to-iso-week (days)
17009 "Return the iso week number."
17010 (require 'cal-iso)
17011 (car (calendar-iso-from-absolute days)))
17013 (defun org-small-year-to-year (year)
17014 "Convert 2-digit years into 4-digit years.
17015 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17016 The year 2000 cannot be abbreviated. Any year larger than 99
17017 is returned unchanged."
17018 (if (< year 38)
17019 (setq year (+ 2000 year))
17020 (if (< year 100)
17021 (setq year (+ 1900 year))))
17022 year)
17024 (defun org-time-from-absolute (d)
17025 "Return the time corresponding to date D.
17026 D may be an absolute day number, or a calendar-type list (month day year)."
17027 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17028 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17030 (defun org-calendar-holiday ()
17031 "List of holidays, for Diary display in Org-mode."
17032 (require 'holidays)
17033 (let ((hl (funcall
17034 (if (fboundp 'calendar-check-holidays)
17035 'calendar-check-holidays 'check-calendar-holidays) date)))
17036 (if hl (mapconcat 'identity hl "; "))))
17038 (defun org-diary-sexp-entry (sexp entry date)
17039 "Process a SEXP diary ENTRY for DATE."
17040 (require 'diary-lib)
17041 (let ((result (if calendar-debug-sexp
17042 (let ((stack-trace-on-error t))
17043 (eval (car (read-from-string sexp))))
17044 (condition-case nil
17045 (eval (car (read-from-string sexp)))
17046 (error
17047 (beep)
17048 (message "Bad sexp at line %d in %s: %s"
17049 (org-current-line)
17050 (buffer-file-name) sexp)
17051 (sleep-for 2))))))
17052 (cond ((stringp result) (split-string result "; "))
17053 ((and (consp result)
17054 (not (consp (cdr result)))
17055 (stringp (cdr result))) (cdr result))
17056 ((and (consp result)
17057 (stringp (car result))) result)
17058 (result entry))))
17060 (defun org-diary-to-ical-string (frombuf)
17061 "Get iCalendar entries from diary entries in buffer FROMBUF.
17062 This uses the icalendar.el library."
17063 (let* ((tmpdir (if (featurep 'xemacs)
17064 (temp-directory)
17065 temporary-file-directory))
17066 (tmpfile (make-temp-name
17067 (expand-file-name "orgics" tmpdir)))
17068 buf rtn b e)
17069 (with-current-buffer frombuf
17070 (icalendar-export-region (point-min) (point-max) tmpfile)
17071 (setq buf (find-buffer-visiting tmpfile))
17072 (set-buffer buf)
17073 (goto-char (point-min))
17074 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17075 (setq b (match-beginning 0)))
17076 (goto-char (point-max))
17077 (if (re-search-backward "^END:VEVENT" nil t)
17078 (setq e (match-end 0)))
17079 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17080 (kill-buffer buf)
17081 (delete-file tmpfile)
17082 rtn))
17084 (defun org-closest-date (start current change prefer show-all)
17085 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17086 When PREFER is `past', return a date that is either CURRENT or past.
17087 When PREFER is `future', return a date that is either CURRENT or future.
17088 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17089 ;; Make the proper lists from the dates
17090 (catch 'exit
17091 (let ((a1 '(("h" . hour)
17092 ("d" . day)
17093 ("w" . week)
17094 ("m" . month)
17095 ("y" . year)))
17096 (shour (nth 2 (org-parse-time-string start)))
17097 dn dw sday cday n1 n2 n0
17098 d m y y1 y2 date1 date2 nmonths nm ny m2)
17100 (setq start (org-date-to-gregorian start)
17101 current (org-date-to-gregorian
17102 (if show-all
17103 current
17104 (time-to-days (current-time))))
17105 sday (calendar-absolute-from-gregorian start)
17106 cday (calendar-absolute-from-gregorian current))
17108 (if (<= cday sday) (throw 'exit sday))
17110 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17111 (setq dn (string-to-number (match-string 1 change))
17112 dw (cdr (assoc (match-string 2 change) a1)))
17113 (user-error "Invalid change specifier: %s" change))
17114 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17115 (cond
17116 ((eq dw 'hour)
17117 (let ((missing-hours
17118 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17119 dn)))
17120 (setq n1 (if (zerop missing-hours) cday
17121 (- cday (1+ (floor (/ missing-hours 24)))))
17122 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17123 ((eq dw 'day)
17124 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17125 n2 (+ n1 dn)))
17126 ((eq dw 'year)
17127 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17128 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17129 (setq date1 (list m d y1)
17130 n1 (calendar-absolute-from-gregorian date1)
17131 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17132 n2 (calendar-absolute-from-gregorian date2)))
17133 ((eq dw 'month)
17134 ;; approx number of month between the two dates
17135 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17136 ;; How often does dn fit in there?
17137 (setq d (nth 1 start) m (car start) y (nth 2 start)
17138 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17139 m (+ m nm)
17140 ny (floor (/ m 12))
17141 y (+ y ny)
17142 m (- m (* ny 12)))
17143 (while (> m 12) (setq m (- m 12) y (1+ y)))
17144 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17145 (setq m2 (+ m dn) y2 y)
17146 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17147 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17148 (while (<= n2 cday)
17149 (setq n1 n2 m m2 y y2)
17150 (setq m2 (+ m dn) y2 y)
17151 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17152 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17153 ;; Make sure n1 is the earlier date
17154 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17155 (if show-all
17156 (cond
17157 ((eq prefer 'past) (if (= cday n2) n2 n1))
17158 ((eq prefer 'future) (if (= cday n1) n1 n2))
17159 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17160 (cond
17161 ((eq prefer 'past) (if (= cday n2) n2 n1))
17162 ((eq prefer 'future) (if (= cday n1) n1 n2))
17163 (t (if (= cday n1) n1 n2)))))))
17165 (defun org-date-to-gregorian (date)
17166 "Turn any specification of DATE into a Gregorian date for the calendar."
17167 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17168 ((and (listp date) (= (length date) 3)) date)
17169 ((stringp date)
17170 (setq date (org-parse-time-string date))
17171 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17172 ((listp date)
17173 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17175 (defun org-parse-time-string (s &optional nodefault)
17176 "Parse the standard Org-mode time string.
17177 This should be a lot faster than the normal `parse-time-string'.
17178 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17179 hour and minute fields will be nil if not given."
17180 (cond ((string-match org-ts-regexp0 s)
17181 (list 0
17182 (if (or (match-beginning 8) (not nodefault))
17183 (string-to-number (or (match-string 8 s) "0")))
17184 (if (or (match-beginning 7) (not nodefault))
17185 (string-to-number (or (match-string 7 s) "0")))
17186 (string-to-number (match-string 4 s))
17187 (string-to-number (match-string 3 s))
17188 (string-to-number (match-string 2 s))
17189 nil nil nil))
17190 ((string-match "^<[^>]+>$" s)
17191 (decode-time (seconds-to-time (org-matcher-time s))))
17192 (t (error "Not a standard Org-mode time string: %s" s))))
17194 (defun org-timestamp-up (&optional arg)
17195 "Increase the date item at the cursor by one.
17196 If the cursor is on the year, change the year. If it is on the month,
17197 the day or the time, change that.
17198 With prefix ARG, change by that many units."
17199 (interactive "p")
17200 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17202 (defun org-timestamp-down (&optional arg)
17203 "Decrease the date item at the cursor by one.
17204 If the cursor is on the year, change the year. If it is on the month,
17205 the day or the time, change that.
17206 With prefix ARG, change by that many units."
17207 (interactive "p")
17208 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17210 (defun org-timestamp-up-day (&optional arg)
17211 "Increase the date in the time stamp by one day.
17212 With prefix ARG, change that many days."
17213 (interactive "p")
17214 (if (and (not (org-at-timestamp-p t))
17215 (org-at-heading-p))
17216 (org-todo 'up)
17217 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17219 (defun org-timestamp-down-day (&optional arg)
17220 "Decrease the date in the time stamp by one day.
17221 With prefix ARG, change that many days."
17222 (interactive "p")
17223 (if (and (not (org-at-timestamp-p t))
17224 (org-at-heading-p))
17225 (org-todo 'down)
17226 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17228 (defun org-at-timestamp-p (&optional inactive-ok)
17229 "Determine if the cursor is in or at a timestamp."
17230 (interactive)
17231 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17232 (pos (point))
17233 (ans (or (looking-at tsr)
17234 (save-excursion
17235 (skip-chars-backward "^[<\n\r\t")
17236 (if (> (point) (point-min)) (backward-char 1))
17237 (and (looking-at tsr)
17238 (> (- (match-end 0) pos) -1))))))
17239 (and ans
17240 (boundp 'org-ts-what)
17241 (setq org-ts-what
17242 (cond
17243 ((= pos (match-beginning 0)) 'bracket)
17244 ;; Point is considered to be "on the bracket" whether
17245 ;; it's really on it or right after it.
17246 ((= pos (1- (match-end 0))) 'bracket)
17247 ((= pos (match-end 0)) 'after)
17248 ((org-pos-in-match-range pos 2) 'year)
17249 ((org-pos-in-match-range pos 3) 'month)
17250 ((org-pos-in-match-range pos 7) 'hour)
17251 ((org-pos-in-match-range pos 8) 'minute)
17252 ((or (org-pos-in-match-range pos 4)
17253 (org-pos-in-match-range pos 5)) 'day)
17254 ((and (> pos (or (match-end 8) (match-end 5)))
17255 (< pos (match-end 0)))
17256 (- pos (or (match-end 8) (match-end 5))))
17257 (t 'day))))
17258 ans))
17260 (defun org-toggle-timestamp-type ()
17261 "Toggle the type (<active> or [inactive]) of a time stamp."
17262 (interactive)
17263 (when (org-at-timestamp-p t)
17264 (let ((beg (match-beginning 0)) (end (match-end 0))
17265 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17266 (save-excursion
17267 (goto-char beg)
17268 (while (re-search-forward "[][<>]" end t)
17269 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17270 t t)))
17271 (message "Timestamp is now %sactive"
17272 (if (equal (char-after beg) ?<) "" "in")))))
17274 (defun org-at-clock-log-p nil
17275 "Is the cursor on the clock log line?"
17276 (save-excursion
17277 (move-beginning-of-line 1)
17278 (looking-at "^[ \t]*CLOCK:")))
17280 (defvar org-clock-history) ; defined in org-clock.el
17281 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17282 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17283 "Change the date in the time stamp at point.
17284 The date will be changed by N times WHAT. WHAT can be `day', `month',
17285 `year', `minute', `second'. If WHAT is not given, the cursor position
17286 in the timestamp determines what will be changed.
17287 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17288 (let ((origin (point)) origin-cat
17289 with-hm inactive
17290 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17291 org-ts-what
17292 extra rem
17293 ts time time0 fixnext clrgx)
17294 (if (not (org-at-timestamp-p t))
17295 (user-error "Not at a timestamp"))
17296 (if (and (not what) (eq org-ts-what 'bracket))
17297 (org-toggle-timestamp-type)
17298 ;; Point isn't on brackets. Remember the part of the time-stamp
17299 ;; the point was in. Indeed, size of time-stamps may change,
17300 ;; but point must be kept in the same category nonetheless.
17301 (setq origin-cat org-ts-what)
17302 (if (and (not what) (not (eq org-ts-what 'day))
17303 org-display-custom-times
17304 (get-text-property (point) 'display)
17305 (not (get-text-property (1- (point)) 'display)))
17306 (setq org-ts-what 'day))
17307 (setq org-ts-what (or what org-ts-what)
17308 inactive (= (char-after (match-beginning 0)) ?\[)
17309 ts (match-string 0))
17310 (replace-match "")
17311 (when (string-match
17312 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17314 (setq extra (match-string 1 ts))
17315 (if suppress-tmp-delay
17316 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17317 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17318 (setq with-hm t))
17319 (setq time0 (org-parse-time-string ts))
17320 (when (and updown
17321 (eq org-ts-what 'minute)
17322 (not current-prefix-arg))
17323 ;; This looks like s-up and s-down. Change by one rounding step.
17324 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17325 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17326 (setcar (cdr time0) (+ (nth 1 time0)
17327 (if (> n 0) (- rem) (- dm rem))))))
17328 (setq time
17329 (encode-time (or (car time0) 0)
17330 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17331 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17332 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17333 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17334 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17335 (nthcdr 6 time0)))
17336 (when (and (member org-ts-what '(hour minute))
17337 extra
17338 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17339 (setq extra (org-modify-ts-extra
17340 extra
17341 (if (eq org-ts-what 'hour) 2 5)
17342 n dm)))
17343 (when (integerp org-ts-what)
17344 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17345 (if (eq what 'calendar)
17346 (let ((cal-date (org-get-date-from-calendar)))
17347 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17348 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17349 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17350 (setcar time0 (or (car time0) 0))
17351 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17352 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17353 (setq time (apply 'encode-time time0))))
17354 ;; Insert the new time-stamp, and ensure point stays in the same
17355 ;; category as before (i.e. not after the last position in that
17356 ;; category).
17357 (let ((pos (point)))
17358 ;; Stay before inserted string. `save-excursion' is of no use.
17359 (setq org-last-changed-timestamp
17360 (org-insert-time-stamp time with-hm inactive nil nil extra))
17361 (goto-char pos))
17362 (save-match-data
17363 (looking-at org-ts-regexp3)
17364 (goto-char (cond
17365 ;; `day' category ends before `hour' if any, or at
17366 ;; the end of the day name.
17367 ((eq origin-cat 'day)
17368 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17369 ((eq origin-cat 'hour) (min (match-end 7) origin))
17370 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17371 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17372 ;; `year' and `month' have both fixed size: point
17373 ;; couldn't have moved into another part.
17374 (t origin))))
17375 ;; Update clock if on a CLOCK line.
17376 (org-clock-update-time-maybe)
17377 ;; Maybe adjust the closest clock in `org-clock-history'
17378 (when org-clock-adjust-closest
17379 (if (not (and (org-at-clock-log-p)
17380 (< 1 (length (delq nil (mapcar 'marker-position
17381 org-clock-history))))))
17382 (message "No clock to adjust")
17383 (cond ((save-excursion ; fix previous clock?
17384 (re-search-backward org-ts-regexp0 nil t)
17385 (org-looking-back (concat org-clock-string " \\[")))
17386 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17387 ((save-excursion ; fix next clock?
17388 (re-search-backward org-ts-regexp0 nil t)
17389 (looking-at (concat org-ts-regexp0 "\\] =>")))
17390 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17391 (save-window-excursion
17392 ;; Find closest clock to point, adjust the previous/next one in history
17393 (let* ((p (save-excursion (org-back-to-heading t)))
17394 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17395 (clfixnth
17396 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17397 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17398 (if (not clfixpos)
17399 (message "No clock to adjust")
17400 (save-excursion
17401 (org-goto-marker-or-bmk clfixpos)
17402 (org-show-subtree)
17403 (when (re-search-forward clrgx nil t)
17404 (goto-char (match-beginning 1))
17405 (let (org-clock-adjust-closest)
17406 (org-timestamp-change n org-ts-what updown))
17407 (message "Clock adjusted in %s for heading: %s"
17408 (file-name-nondirectory (buffer-file-name))
17409 (org-get-heading t t)))))))))
17410 ;; Try to recenter the calendar window, if any.
17411 (if (and org-calendar-follow-timestamp-change
17412 (get-buffer-window "*Calendar*" t)
17413 (memq org-ts-what '(day month year)))
17414 (org-recenter-calendar (time-to-days time))))))
17416 (defun org-modify-ts-extra (s pos n dm)
17417 "Change the different parts of the lead-time and repeat fields in timestamp."
17418 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17419 ng h m new rem)
17420 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17421 (cond
17422 ((or (org-pos-in-match-range pos 2)
17423 (org-pos-in-match-range pos 3))
17424 (setq m (string-to-number (match-string 3 s))
17425 h (string-to-number (match-string 2 s)))
17426 (if (org-pos-in-match-range pos 2)
17427 (setq h (+ h n))
17428 (setq n (* dm (org-no-warnings (signum n))))
17429 (when (not (= 0 (setq rem (% m dm))))
17430 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17431 (setq m (+ m n)))
17432 (if (< m 0) (setq m (+ m 60) h (1- h)))
17433 (if (> m 59) (setq m (- m 60) h (1+ h)))
17434 (setq h (min 24 (max 0 h)))
17435 (setq ng 1 new (format "-%02d:%02d" h m)))
17436 ((org-pos-in-match-range pos 6)
17437 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17438 ((org-pos-in-match-range pos 5)
17439 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17441 ((org-pos-in-match-range pos 9)
17442 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17443 ((org-pos-in-match-range pos 8)
17444 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17446 (when ng
17447 (setq s (concat
17448 (substring s 0 (match-beginning ng))
17450 (substring s (match-end ng))))))
17453 (defun org-recenter-calendar (date)
17454 "If the calendar is visible, recenter it to DATE."
17455 (let ((cwin (get-buffer-window "*Calendar*" t)))
17456 (when cwin
17457 (let ((calendar-move-hook nil))
17458 (with-selected-window cwin
17459 (calendar-goto-date (if (listp date) date
17460 (calendar-gregorian-from-absolute date))))))))
17462 (defun org-goto-calendar (&optional arg)
17463 "Go to the Emacs calendar at the current date.
17464 If there is a time stamp in the current line, go to that date.
17465 A prefix ARG can be used to force the current date."
17466 (interactive "P")
17467 (let ((tsr org-ts-regexp) diff
17468 (calendar-move-hook nil)
17469 (calendar-view-holidays-initially-flag nil)
17470 (calendar-view-diary-initially-flag nil))
17471 (if (or (org-at-timestamp-p)
17472 (save-excursion
17473 (beginning-of-line 1)
17474 (looking-at (concat ".*" tsr))))
17475 (let ((d1 (time-to-days (current-time)))
17476 (d2 (time-to-days
17477 (org-time-string-to-time (match-string 1)))))
17478 (setq diff (- d2 d1))))
17479 (calendar)
17480 (calendar-goto-today)
17481 (if (and diff (not arg)) (calendar-forward-day diff))))
17483 (defun org-get-date-from-calendar ()
17484 "Return a list (month day year) of date at point in calendar."
17485 (with-current-buffer "*Calendar*"
17486 (save-match-data
17487 (calendar-cursor-to-date))))
17489 (defun org-date-from-calendar ()
17490 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17491 If there is already a time stamp at the cursor position, update it."
17492 (interactive)
17493 (if (org-at-timestamp-p t)
17494 (org-timestamp-change 0 'calendar)
17495 (let ((cal-date (org-get-date-from-calendar)))
17496 (org-insert-time-stamp
17497 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17499 (defcustom org-effort-durations
17500 `(("h" . 60)
17501 ("d" . ,(* 60 8))
17502 ("w" . ,(* 60 8 5))
17503 ("m" . ,(* 60 8 5 4))
17504 ("y" . ,(* 60 8 5 40)))
17505 "Conversion factor to minutes for an effort modifier.
17507 Each entry has the form (MODIFIER . MINUTES).
17509 In an effort string, a number followed by MODIFIER is multiplied
17510 by the specified number of MINUTES to obtain an effort in
17511 minutes.
17513 For example, if the value of this variable is ((\"hours\" . 60)), then an
17514 effort string \"2hours\" is equivalent to 120 minutes."
17515 :group 'org-agenda
17516 :version "24.1"
17517 :type '(alist :key-type (string :tag "Modifier")
17518 :value-type (number :tag "Minutes")))
17520 (defun org-minutes-to-clocksum-string (m)
17521 "Format number of minutes as a clocksum string.
17522 The format is determined by `org-time-clocksum-format',
17523 `org-time-clocksum-use-fractional' and
17524 `org-time-clocksum-fractional-format' and
17525 `org-time-clocksum-use-effort-durations'."
17526 (let ((clocksum "")
17527 (m (round m)) ; Don't allow fractions of minutes
17528 h d w mo y fmt n)
17529 (setq h (if org-time-clocksum-use-effort-durations
17530 (cdr (assoc "h" org-effort-durations)) 60)
17531 d (if org-time-clocksum-use-effort-durations
17532 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17533 w (if org-time-clocksum-use-effort-durations
17534 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17535 mo (if org-time-clocksum-use-effort-durations
17536 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17537 y (if org-time-clocksum-use-effort-durations
17538 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17539 ;; fractional format
17540 (if org-time-clocksum-use-fractional
17541 (cond
17542 ;; single format string
17543 ((stringp org-time-clocksum-fractional-format)
17544 (format org-time-clocksum-fractional-format (/ m (float h))))
17545 ;; choice of fractional formats for different time units
17546 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17547 (> (/ (truncate m) (* y d h)) 0))
17548 (format fmt (/ m (* y d (float h)))))
17549 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17550 (> (/ (truncate m) (* mo d h)) 0))
17551 (format fmt (/ m (* mo d (float h)))))
17552 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17553 (> (/ (truncate m) (* w d h)) 0))
17554 (format fmt (/ m (* w d (float h)))))
17555 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17556 (> (/ (truncate m) (* d h)) 0))
17557 (format fmt (/ m (* d (float h)))))
17558 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17559 (> (/ (truncate m) h) 0))
17560 (format fmt (/ m (float h))))
17561 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17562 (format fmt m))
17563 ;; fall back to smallest time unit with a format
17564 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17565 (format fmt (/ m (float h))))
17566 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17567 (format fmt (/ m (* d (float h)))))
17568 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17569 (format fmt (/ m (* w d (float h)))))
17570 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17571 (format fmt (/ m (* mo d (float h)))))
17572 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17573 (format fmt (/ m (* y d (float h))))))
17574 ;; standard (non-fractional) format, with single format string
17575 (if (stringp org-time-clocksum-format)
17576 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17577 ;; separate formats components
17578 (and (setq fmt (plist-get org-time-clocksum-format :years))
17579 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17580 (plist-get org-time-clocksum-format :require-years))
17581 (setq clocksum (concat clocksum (format fmt n))
17582 m (- m (* n y d h))))
17583 (and (setq fmt (plist-get org-time-clocksum-format :months))
17584 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17585 (plist-get org-time-clocksum-format :require-months))
17586 (setq clocksum (concat clocksum (format fmt n))
17587 m (- m (* n mo d h))))
17588 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17589 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17590 (plist-get org-time-clocksum-format :require-weeks))
17591 (setq clocksum (concat clocksum (format fmt n))
17592 m (- m (* n w d h))))
17593 (and (setq fmt (plist-get org-time-clocksum-format :days))
17594 (or (> (setq n (/ (truncate m) (* d h))) 0)
17595 (plist-get org-time-clocksum-format :require-days))
17596 (setq clocksum (concat clocksum (format fmt n))
17597 m (- m (* n d h))))
17598 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17599 (or (> (setq n (/ (truncate m) h)) 0)
17600 (plist-get org-time-clocksum-format :require-hours))
17601 (setq clocksum (concat clocksum (format fmt n))
17602 m (- m (* n h))))
17603 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17604 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17605 (setq clocksum (concat clocksum (format fmt m))))
17606 ;; return formatted time duration
17607 clocksum))))
17609 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17610 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17611 "Org mode version 8.0")
17613 (defun org-hours-to-clocksum-string (n)
17614 (org-minutes-to-clocksum-string (* n 60)))
17616 (defun org-hh:mm-string-to-minutes (s)
17617 "Convert a string H:MM to a number of minutes.
17618 If the string is just a number, interpret it as minutes.
17619 In fact, the first hh:mm or number in the string will be taken,
17620 there can be extra stuff in the string.
17621 If no number is found, the return value is 0."
17622 (cond
17623 ((integerp s) s)
17624 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17625 (+ (* (string-to-number (match-string 1 s)) 60)
17626 (string-to-number (match-string 2 s))))
17627 ((string-match "\\([0-9]+\\)" s)
17628 (string-to-number (match-string 1 s)))
17629 (t 0)))
17631 (defcustom org-image-actual-width t
17632 "Should we use the actual width of images when inlining them?
17634 When set to `t', always use the image width.
17636 When set to a number, use imagemagick (when available) to set
17637 the image's width to this value.
17639 When set to a number in a list, try to get the width from any
17640 #+ATTR.* keyword if it matches a width specification like
17642 #+ATTR_HTML: :width 300px
17644 and fall back on that number if none is found.
17646 When set to nil, try to get the width from an #+ATTR.* keyword
17647 and fall back on the original width if none is found.
17649 This requires Emacs >= 24.1, build with imagemagick support."
17650 :group 'org-appearance
17651 :version "24.4"
17652 :package-version '(Org . "8.0")
17653 :type '(choice
17654 (const :tag "Use the image width" t)
17655 (integer :tag "Use a number of pixels")
17656 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17657 (const :tag "Use #+ATTR* or don't resize" nil)))
17659 (defcustom org-agenda-inhibit-startup nil
17660 "Inhibit startup when preparing agenda buffers.
17661 When this variable is `t' (the default), the initialization of
17662 the Org agenda buffers is inhibited: e.g. the visibility state
17663 is not set, the tables are not re-aligned, etc."
17664 :type 'boolean
17665 :version "24.3"
17666 :group 'org-agenda)
17668 (defun org-duration-string-to-minutes (s &optional output-to-string)
17669 "Convert a duration string S to minutes.
17671 A bare number is interpreted as minutes, modifiers can be set by
17672 customizing `org-effort-durations' (which see).
17674 Entries containing a colon are interpreted as H:MM by
17675 `org-hh:mm-string-to-minutes'."
17676 (let ((result 0)
17677 (re (concat "\\([0-9.]+\\) *\\("
17678 (regexp-opt (mapcar 'car org-effort-durations))
17679 "\\)")))
17680 (while (string-match re s)
17681 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17682 (string-to-number (match-string 1 s))))
17683 (setq s (replace-match "" nil t s)))
17684 (setq result (floor result))
17685 (incf result (org-hh:mm-string-to-minutes s))
17686 (if output-to-string (number-to-string result) result)))
17688 ;;;; Files
17690 (defun org-save-all-org-buffers ()
17691 "Save all Org-mode buffers without user confirmation."
17692 (interactive)
17693 (message "Saving all Org-mode buffers...")
17694 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17695 (when (featurep 'org-id) (org-id-locations-save))
17696 (message "Saving all Org-mode buffers... done"))
17698 (defun org-revert-all-org-buffers ()
17699 "Revert all Org-mode buffers.
17700 Prompt for confirmation when there are unsaved changes.
17701 Be sure you know what you are doing before letting this function
17702 overwrite your changes.
17704 This function is useful in a setup where one tracks org files
17705 with a version control system, to revert on one machine after pulling
17706 changes from another. I believe the procedure must be like this:
17708 1. M-x org-save-all-org-buffers
17709 2. Pull changes from the other machine, resolve conflicts
17710 3. M-x org-revert-all-org-buffers"
17711 (interactive)
17712 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17713 (user-error "Abort"))
17714 (save-excursion
17715 (save-window-excursion
17716 (mapc
17717 (lambda (b)
17718 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17719 (with-current-buffer b buffer-file-name))
17720 (org-pop-to-buffer-same-window b)
17721 (revert-buffer t 'no-confirm)))
17722 (buffer-list))
17723 (when (and (featurep 'org-id) org-id-track-globally)
17724 (org-id-locations-load)))))
17726 ;;;; Agenda files
17728 ;;;###autoload
17729 (defun org-switchb (&optional arg)
17730 "Switch between Org buffers.
17731 With one prefix argument, restrict available buffers to files.
17732 With two prefix arguments, restrict available buffers to agenda files.
17734 Defaults to `iswitchb' for buffer name completion.
17735 Set `org-completion-use-ido' to make it use ido instead."
17736 (interactive "P")
17737 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17738 ((equal arg '(16)) (org-buffer-list 'agenda))
17739 (t (org-buffer-list))))
17740 (org-completion-use-iswitchb org-completion-use-iswitchb)
17741 (org-completion-use-ido org-completion-use-ido))
17742 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17743 (setq org-completion-use-iswitchb t))
17744 (org-pop-to-buffer-same-window
17745 (org-icompleting-read "Org buffer: "
17746 (mapcar 'list (mapcar 'buffer-name blist))
17747 nil t))))
17749 ;;; Define some older names previously used for this functionality
17750 ;;;###autoload
17751 (defalias 'org-ido-switchb 'org-switchb)
17752 ;;;###autoload
17753 (defalias 'org-iswitchb 'org-switchb)
17755 (defun org-buffer-list (&optional predicate exclude-tmp)
17756 "Return a list of Org buffers.
17757 PREDICATE can be `export', `files' or `agenda'.
17759 export restrict the list to Export buffers.
17760 files restrict the list to buffers visiting Org files.
17761 agenda restrict the list to buffers visiting agenda files.
17763 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17764 (let* ((bfn nil)
17765 (agenda-files (and (eq predicate 'agenda)
17766 (mapcar 'file-truename (org-agenda-files t))))
17767 (filter
17768 (cond
17769 ((eq predicate 'files)
17770 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17771 ((eq predicate 'export)
17772 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17773 ((eq predicate 'agenda)
17774 (lambda (b)
17775 (with-current-buffer b
17776 (and (derived-mode-p 'org-mode)
17777 (setq bfn (buffer-file-name b))
17778 (member (file-truename bfn) agenda-files)))))
17779 (t (lambda (b) (with-current-buffer b
17780 (or (derived-mode-p 'org-mode)
17781 (string-match "\*Org .*Export"
17782 (buffer-name b)))))))))
17783 (delq nil
17784 (mapcar
17785 (lambda(b)
17786 (if (and (funcall filter b)
17787 (or (not exclude-tmp)
17788 (not (string-match "tmp" (buffer-name b)))))
17790 nil))
17791 (buffer-list)))))
17793 (defun org-agenda-files (&optional unrestricted archives)
17794 "Get the list of agenda files.
17795 Optional UNRESTRICTED means return the full list even if a restriction
17796 is currently in place.
17797 When ARCHIVES is t, include all archive files that are really being
17798 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17799 `org-agenda-archives-mode' is t."
17800 (let ((files
17801 (cond
17802 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17803 ((stringp org-agenda-files) (org-read-agenda-file-list))
17804 ((listp org-agenda-files) org-agenda-files)
17805 (t (error "Invalid value of `org-agenda-files'")))))
17806 (setq files (apply 'append
17807 (mapcar (lambda (f)
17808 (if (file-directory-p f)
17809 (directory-files
17810 f t org-agenda-file-regexp)
17811 (list f)))
17812 files)))
17813 (when org-agenda-skip-unavailable-files
17814 (setq files (delq nil
17815 (mapcar (function
17816 (lambda (file)
17817 (and (file-readable-p file) file)))
17818 files))))
17819 (when (or (eq archives t)
17820 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17821 (setq files (org-add-archive-files files)))
17822 files))
17824 (defun org-agenda-file-p (&optional file)
17825 "Return non-nil, if FILE is an agenda file.
17826 If FILE is omitted, use the file associated with the current
17827 buffer."
17828 (member (or file (buffer-file-name))
17829 (org-agenda-files t)))
17831 (defun org-edit-agenda-file-list ()
17832 "Edit the list of agenda files.
17833 Depending on setup, this either uses customize to edit the variable
17834 `org-agenda-files', or it visits the file that is holding the list. In the
17835 latter case, the buffer is set up in a way that saving it automatically kills
17836 the buffer and restores the previous window configuration."
17837 (interactive)
17838 (if (stringp org-agenda-files)
17839 (let ((cw (current-window-configuration)))
17840 (find-file org-agenda-files)
17841 (org-set-local 'org-window-configuration cw)
17842 (org-add-hook 'after-save-hook
17843 (lambda ()
17844 (set-window-configuration
17845 (prog1 org-window-configuration
17846 (kill-buffer (current-buffer))))
17847 (org-install-agenda-files-menu)
17848 (message "New agenda file list installed"))
17849 nil 'local)
17850 (message "%s" (substitute-command-keys
17851 "Edit list and finish with \\[save-buffer]")))
17852 (customize-variable 'org-agenda-files)))
17854 (defun org-store-new-agenda-file-list (list)
17855 "Set new value for the agenda file list and save it correctly."
17856 (if (stringp org-agenda-files)
17857 (let ((fe (org-read-agenda-file-list t)) b u)
17858 (while (setq b (find-buffer-visiting org-agenda-files))
17859 (kill-buffer b))
17860 (with-temp-file org-agenda-files
17861 (insert
17862 (mapconcat
17863 (lambda (f) ;; Keep un-expanded entries.
17864 (if (setq u (assoc f fe))
17865 (cdr u)
17867 list "\n")
17868 "\n")))
17869 (let ((org-mode-hook nil) (org-inhibit-startup t)
17870 (org-insert-mode-line-in-empty-file nil))
17871 (setq org-agenda-files list)
17872 (customize-save-variable 'org-agenda-files org-agenda-files))))
17874 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17875 "Read the list of agenda files from a file.
17876 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17877 filenames, used by `org-store-new-agenda-file-list' to write back
17878 un-expanded file names."
17879 (when (file-directory-p org-agenda-files)
17880 (error "`org-agenda-files' cannot be a single directory"))
17881 (when (stringp org-agenda-files)
17882 (with-temp-buffer
17883 (insert-file-contents org-agenda-files)
17884 (mapcar
17885 (lambda (f)
17886 (let ((e (expand-file-name (substitute-in-file-name f)
17887 org-directory)))
17888 (if pair-with-expansion
17889 (cons e f)
17890 e)))
17891 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17893 ;;;###autoload
17894 (defun org-cycle-agenda-files ()
17895 "Cycle through the files in `org-agenda-files'.
17896 If the current buffer visits an agenda file, find the next one in the list.
17897 If the current buffer does not, find the first agenda file."
17898 (interactive)
17899 (let* ((fs (org-agenda-files t))
17900 (files (append fs (list (car fs))))
17901 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17902 file)
17903 (unless files (user-error "No agenda files"))
17904 (catch 'exit
17905 (while (setq file (pop files))
17906 (if (equal (file-truename file) tcf)
17907 (when (car files)
17908 (find-file (car files))
17909 (throw 'exit t))))
17910 (find-file (car fs)))
17911 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17913 (defun org-agenda-file-to-front (&optional to-end)
17914 "Move/add the current file to the top of the agenda file list.
17915 If the file is not present in the list, it is added to the front. If it is
17916 present, it is moved there. With optional argument TO-END, add/move to the
17917 end of the list."
17918 (interactive "P")
17919 (let ((org-agenda-skip-unavailable-files nil)
17920 (file-alist (mapcar (lambda (x)
17921 (cons (file-truename x) x))
17922 (org-agenda-files t)))
17923 (ctf (file-truename
17924 (or buffer-file-name
17925 (user-error "Please save the current buffer to a file"))))
17926 x had)
17927 (setq x (assoc ctf file-alist) had x)
17929 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17930 (if to-end
17931 (setq file-alist (append (delq x file-alist) (list x)))
17932 (setq file-alist (cons x (delq x file-alist))))
17933 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17934 (org-install-agenda-files-menu)
17935 (message "File %s to %s of agenda file list"
17936 (if had "moved" "added") (if to-end "end" "front"))))
17938 (defun org-remove-file (&optional file)
17939 "Remove current file from the list of files in variable `org-agenda-files'.
17940 These are the files which are being checked for agenda entries.
17941 Optional argument FILE means use this file instead of the current."
17942 (interactive)
17943 (let* ((org-agenda-skip-unavailable-files nil)
17944 (file (or file buffer-file-name
17945 (user-error "Current buffer does not visit a file")))
17946 (true-file (file-truename file))
17947 (afile (abbreviate-file-name file))
17948 (files (delq nil (mapcar
17949 (lambda (x)
17950 (if (equal true-file
17951 (file-truename x))
17952 nil x))
17953 (org-agenda-files t)))))
17954 (if (not (= (length files) (length (org-agenda-files t))))
17955 (progn
17956 (org-store-new-agenda-file-list files)
17957 (org-install-agenda-files-menu)
17958 (message "Removed file: %s" afile))
17959 (message "File was not in list: %s (not removed)" afile))))
17961 (defun org-file-menu-entry (file)
17962 (vector file (list 'find-file file) t))
17964 (defun org-check-agenda-file (file)
17965 "Make sure FILE exists. If not, ask user what to do."
17966 (when (not (file-exists-p file))
17967 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17968 (abbreviate-file-name file))
17969 (let ((r (downcase (read-char-exclusive))))
17970 (cond
17971 ((equal r ?r)
17972 (org-remove-file file)
17973 (throw 'nextfile t))
17974 (t (error "Abort"))))))
17976 (defun org-get-agenda-file-buffer (file)
17977 "Get a buffer visiting FILE. If the buffer needs to be created, add
17978 it to the list of buffers which might be released later."
17979 (let ((buf (org-find-base-buffer-visiting file)))
17980 (if buf
17981 buf ; just return it
17982 ;; Make a new buffer and remember it
17983 (setq buf (find-file-noselect file))
17984 (if buf (push buf org-agenda-new-buffers))
17985 buf)))
17987 (defun org-release-buffers (blist)
17988 "Release all buffers in list, asking the user for confirmation when needed.
17989 When a buffer is unmodified, it is just killed. When modified, it is saved
17990 \(if the user agrees) and then killed."
17991 (let (buf file)
17992 (while (setq buf (pop blist))
17993 (setq file (buffer-file-name buf))
17994 (when (and (buffer-modified-p buf)
17995 file
17996 (y-or-n-p (format "Save file %s? " file)))
17997 (with-current-buffer buf (save-buffer)))
17998 (kill-buffer buf))))
18000 (defun org-agenda-prepare-buffers (files)
18001 "Create buffers for all agenda files, protect archived trees and comments."
18002 (interactive)
18003 (let ((pa '(:org-archived t))
18004 (pc '(:org-comment t))
18005 (pall '(:org-archived t :org-comment t))
18006 (inhibit-read-only t)
18007 (org-inhibit-startup org-agenda-inhibit-startup)
18008 (rea (concat ":" org-archive-tag ":"))
18009 file re)
18010 (setq org-tag-alist-for-agenda nil
18011 org-tag-groups-alist-for-agenda nil)
18012 (save-excursion
18013 (save-restriction
18014 (while (setq file (pop files))
18015 (catch 'nextfile
18016 (if (bufferp file)
18017 (set-buffer file)
18018 (org-check-agenda-file file)
18019 (set-buffer (org-get-agenda-file-buffer file)))
18020 (widen)
18021 (org-set-regexps-and-options-for-tags)
18022 (goto-char (point-min))
18023 (let ((case-fold-search t))
18024 (when (search-forward "#+setupfile" nil t)
18025 ;; Don't set all regexps and options systematically as
18026 ;; this is only run for setting agenda tags from setup
18027 ;; file
18028 (org-set-regexps-and-options)))
18029 (org-refresh-category-properties)
18030 (org-refresh-properties org-effort-property 'org-effort)
18031 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18032 (setq org-todo-keywords-for-agenda
18033 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18034 (setq org-done-keywords-for-agenda
18035 (append org-done-keywords-for-agenda org-done-keywords))
18036 (setq org-todo-keyword-alist-for-agenda
18037 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18038 (setq org-drawers-for-agenda
18039 (append org-drawers-for-agenda org-drawers))
18040 (setq org-tag-alist-for-agenda
18041 (org-uniquify
18042 (append org-tag-alist-for-agenda
18043 org-tag-alist
18044 org-tag-persistent-alist)))
18045 (if org-group-tags
18046 (setq org-tag-groups-alist-for-agenda
18047 (org-uniquify-alist
18048 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18049 (org-with-silent-modifications
18050 (save-excursion
18051 (remove-text-properties (point-min) (point-max) pall)
18052 (when org-agenda-skip-archived-trees
18053 (goto-char (point-min))
18054 (while (re-search-forward rea nil t)
18055 (if (org-at-heading-p t)
18056 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18057 (goto-char (point-min))
18058 (setq re (format org-heading-keyword-regexp-format
18059 org-comment-string))
18060 (while (re-search-forward re nil t)
18061 (add-text-properties
18062 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18063 (setq org-todo-keywords-for-agenda
18064 (org-uniquify org-todo-keywords-for-agenda))
18065 (setq org-todo-keyword-alist-for-agenda
18066 (org-uniquify org-todo-keyword-alist-for-agenda))))
18069 ;;;; CDLaTeX minor mode
18071 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18072 "Keymap for the minor `org-cdlatex-mode'.")
18074 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18075 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18076 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18077 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18078 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18080 (defvar org-cdlatex-texmathp-advice-is-done nil
18081 "Flag remembering if we have applied the advice to texmathp already.")
18083 (define-minor-mode org-cdlatex-mode
18084 "Toggle the minor `org-cdlatex-mode'.
18085 This mode supports entering LaTeX environment and math in LaTeX fragments
18086 in Org-mode.
18087 \\{org-cdlatex-mode-map}"
18088 nil " OCDL" nil
18089 (when org-cdlatex-mode
18090 (require 'cdlatex)
18091 (run-hooks 'cdlatex-mode-hook)
18092 (cdlatex-compute-tables))
18093 (unless org-cdlatex-texmathp-advice-is-done
18094 (setq org-cdlatex-texmathp-advice-is-done t)
18095 (defadvice texmathp (around org-math-always-on activate)
18096 "Always return t in org-mode buffers.
18097 This is because we want to insert math symbols without dollars even outside
18098 the LaTeX math segments. If Orgmode thinks that point is actually inside
18099 an embedded LaTeX fragment, let texmathp do its job.
18100 \\[org-cdlatex-mode-map]"
18101 (interactive)
18102 (let (p)
18103 (cond
18104 ((not (derived-mode-p 'org-mode)) ad-do-it)
18105 ((eq this-command 'cdlatex-math-symbol)
18106 (setq ad-return-value t
18107 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18109 (let ((p (org-inside-LaTeX-fragment-p)))
18110 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18111 (setq ad-return-value t
18112 texmathp-why '("Org-mode embedded math" . 0))
18113 (if p ad-do-it)))))))))
18115 (defun turn-on-org-cdlatex ()
18116 "Unconditionally turn on `org-cdlatex-mode'."
18117 (org-cdlatex-mode 1))
18119 (defun org-try-cdlatex-tab ()
18120 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18121 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18122 - inside a LaTeX fragment, or
18123 - after the first word in a line, where an abbreviation expansion could
18124 insert a LaTeX environment."
18125 (when org-cdlatex-mode
18126 (cond
18127 ;; Before any word on the line: No expansion possible.
18128 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18129 ;; Just after first word on the line: Expand it. Make sure it
18130 ;; cannot happen on headlines, though.
18131 ((save-excursion
18132 (skip-chars-backward "a-zA-Z0-9*")
18133 (skip-chars-backward " \t")
18134 (and (bolp) (not (org-at-heading-p))))
18135 (cdlatex-tab) t)
18136 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18138 (defun org-cdlatex-underscore-caret (&optional arg)
18139 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18140 Revert to the normal definition outside of these fragments."
18141 (interactive "P")
18142 (if (org-inside-LaTeX-fragment-p)
18143 (call-interactively 'cdlatex-sub-superscript)
18144 (let (org-cdlatex-mode)
18145 (call-interactively (key-binding (vector last-input-event))))))
18147 (defun org-cdlatex-math-modify (&optional arg)
18148 "Execute `cdlatex-math-modify' in LaTeX fragments.
18149 Revert to the normal definition outside of these fragments."
18150 (interactive "P")
18151 (if (org-inside-LaTeX-fragment-p)
18152 (call-interactively 'cdlatex-math-modify)
18153 (let (org-cdlatex-mode)
18154 (call-interactively (key-binding (vector last-input-event))))))
18158 ;;;; LaTeX fragments
18160 (defvar org-latex-regexps
18161 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18162 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18163 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18164 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18165 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18166 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18167 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18168 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18169 "Regular expressions for matching embedded LaTeX.")
18171 (defun org-inside-LaTeX-fragment-p ()
18172 "Test if point is inside a LaTeX fragment.
18173 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18174 sequence appearing also before point.
18175 Even though the matchers for math are configurable, this function assumes
18176 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18177 delimiters are skipped when they have been removed by customization.
18178 The return value is nil, or a cons cell with the delimiter and the
18179 position of this delimiter.
18181 This function does a reasonably good job, but can locally be fooled by
18182 for example currency specifications. For example it will assume being in
18183 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18184 fragments that are properly closed, but during editing, we have to live
18185 with the uncertainty caused by missing closing delimiters. This function
18186 looks only before point, not after."
18187 (catch 'exit
18188 (let ((pos (point))
18189 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18190 (lim (progn
18191 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18192 (point)))
18193 dd-on str (start 0) m re)
18194 (goto-char pos)
18195 (when dodollar
18196 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18197 re (nth 1 (assoc "$" org-latex-regexps)))
18198 (while (string-match re str start)
18199 (cond
18200 ((= (match-end 0) (length str))
18201 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18202 ((= (match-end 0) (- (length str) 5))
18203 (throw 'exit nil))
18204 (t (setq start (match-end 0))))))
18205 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18206 (goto-char pos)
18207 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18208 (and (match-beginning 2) (throw 'exit nil))
18209 ;; count $$
18210 (while (re-search-backward "\\$\\$" lim t)
18211 (setq dd-on (not dd-on)))
18212 (goto-char pos)
18213 (if dd-on (cons "$$" m))))))
18215 (defun org-inside-latex-macro-p ()
18216 "Is point inside a LaTeX macro or its arguments?"
18217 (save-match-data
18218 (org-in-regexp
18219 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18221 (defvar org-latex-fragment-image-overlays nil
18222 "List of overlays carrying the images of latex fragments.")
18223 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18225 (defun org-remove-latex-fragment-image-overlays ()
18226 "Remove all overlays with LaTeX fragment images in current buffer."
18227 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18228 (setq org-latex-fragment-image-overlays nil))
18230 (defun org-preview-latex-fragment (&optional subtree)
18231 "Preview the LaTeX fragment at point, or all locally or globally.
18232 If the cursor is in a LaTeX fragment, create the image and overlay
18233 it over the source code. If there is no fragment at point, display
18234 all fragments in the current text, from one headline to the next. With
18235 prefix SUBTREE, display all fragments in the current subtree. With a
18236 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18237 the cursor is before the first headline,
18238 display all fragments in the buffer.
18239 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18240 (interactive "P")
18241 (unless buffer-file-name
18242 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18243 (when (display-graphic-p)
18244 (org-remove-latex-fragment-image-overlays)
18245 (save-excursion
18246 (save-restriction
18247 (let (beg end at msg)
18248 (cond
18249 ((or (equal subtree '(16))
18250 (not (save-excursion
18251 (re-search-backward org-outline-regexp-bol nil t))))
18252 (setq beg (point-min) end (point-max)
18253 msg "Creating images for buffer...%s"))
18254 ((equal subtree '(4))
18255 (org-back-to-heading)
18256 (setq beg (point) end (org-end-of-subtree t)
18257 msg "Creating images for subtree...%s"))
18259 (if (setq at (org-inside-LaTeX-fragment-p))
18260 (goto-char (max (point-min) (- (cdr at) 2)))
18261 (org-back-to-heading))
18262 (setq beg (point) end (progn (outline-next-heading) (point))
18263 msg (if at "Creating image...%s"
18264 "Creating images for entry...%s"))))
18265 (message msg "")
18266 (narrow-to-region beg end)
18267 (goto-char beg)
18268 (org-format-latex
18269 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18270 (file-name-nondirectory
18271 buffer-file-name)))
18272 default-directory 'overlays msg at 'forbuffer
18273 org-latex-create-formula-image-program)
18274 (message msg "done. Use `C-c C-c' to remove images."))))))
18276 (defun org-format-latex (prefix &optional dir overlays msg at
18277 forbuffer processing-type)
18278 "Replace LaTeX fragments with links to an image, and produce images.
18279 Some of the options can be changed using the variable
18280 `org-format-latex-options'."
18281 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18282 (let* ((prefixnodir (file-name-nondirectory prefix))
18283 (absprefix (expand-file-name prefix dir))
18284 (todir (file-name-directory absprefix))
18285 (opt org-format-latex-options)
18286 (optnew org-format-latex-options)
18287 (matchers (plist-get opt :matchers))
18288 (re-list org-latex-regexps)
18289 (cnt 0) txt hash link beg end re e checkdir
18290 string
18291 m n block-type block linkfile movefile ov)
18292 ;; Check the different regular expressions
18293 (while (setq e (pop re-list))
18294 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18295 block (if block-type "\n\n" ""))
18296 (when (member m matchers)
18297 (goto-char (point-min))
18298 (while (re-search-forward re nil t)
18299 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18300 (or (not overlays)
18301 (not (eq (get-char-property (match-beginning n)
18302 'org-overlay-type)
18303 'org-latex-overlay))))
18304 (cond
18305 ((eq processing-type 'verbatim))
18306 ((eq processing-type 'mathjax)
18307 ;; Prepare for MathJax processing.
18308 (setq string (match-string n))
18309 (when (member m '("$" "$1"))
18310 (save-excursion
18311 (delete-region (match-beginning n) (match-end n))
18312 (goto-char (match-beginning n))
18313 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18314 ((or (eq processing-type 'dvipng)
18315 (eq processing-type 'imagemagick))
18316 ;; Process to an image.
18317 (setq txt (match-string n)
18318 beg (match-beginning n) end (match-end n)
18319 cnt (1+ cnt))
18320 (let ((face (face-at-point))
18321 (fg (plist-get opt :foreground))
18322 (bg (plist-get opt :background))
18323 ;; Ensure full list is printed.
18324 print-length print-level)
18325 (when forbuffer
18326 ;; Get the colors from the face at point.
18327 (goto-char beg)
18328 (when (eq fg 'auto)
18329 (setq fg (face-attribute face :foreground nil 'default)))
18330 (when (eq bg 'auto)
18331 (setq bg (face-attribute face :background nil 'default)))
18332 (setq optnew (copy-sequence opt))
18333 (plist-put optnew :foreground fg)
18334 (plist-put optnew :background bg))
18335 (setq hash (sha1 (prin1-to-string
18336 (list org-format-latex-header
18337 org-latex-default-packages-alist
18338 org-latex-packages-alist
18339 org-format-latex-options
18340 forbuffer txt fg bg)))
18341 linkfile (format "%s_%s.png" prefix hash)
18342 movefile (format "%s_%s.png" absprefix hash)))
18343 (setq link (concat block "[[file:" linkfile "]]" block))
18344 (if msg (message msg cnt))
18345 (goto-char beg)
18346 (unless checkdir ; Ensure the directory exists.
18347 (setq checkdir t)
18348 (or (file-directory-p todir) (make-directory todir t)))
18349 (unless (file-exists-p movefile)
18350 (org-create-formula-image
18351 txt movefile optnew forbuffer processing-type))
18352 (if overlays
18353 (progn
18354 (mapc (lambda (o)
18355 (if (eq (overlay-get o 'org-overlay-type)
18356 'org-latex-overlay)
18357 (delete-overlay o)))
18358 (overlays-in beg end))
18359 (setq ov (make-overlay beg end))
18360 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18361 (if (featurep 'xemacs)
18362 (progn
18363 (overlay-put ov 'invisible t)
18364 (overlay-put
18365 ov 'end-glyph
18366 (make-glyph (vector 'png :file movefile))))
18367 (overlay-put
18368 ov 'display
18369 (list 'image :type 'png :file movefile :ascent 'center)))
18370 (push ov org-latex-fragment-image-overlays)
18371 (goto-char end))
18372 (delete-region beg end)
18373 (insert (org-add-props link
18374 (list 'org-latex-src
18375 (replace-regexp-in-string
18376 "\"" "" txt)
18377 'org-latex-src-embed-type
18378 (if block-type 'paragraph 'character))))))
18379 ((eq processing-type 'mathml)
18380 ;; Process to MathML
18381 (unless (save-match-data (org-format-latex-mathml-available-p))
18382 (user-error "LaTeX to MathML converter not configured"))
18383 (setq txt (match-string n)
18384 beg (match-beginning n) end (match-end n)
18385 cnt (1+ cnt))
18386 (if msg (message msg cnt))
18387 (goto-char beg)
18388 (delete-region beg end)
18389 (insert (org-format-latex-as-mathml
18390 txt block-type prefix dir)))
18392 (error "Unknown conversion type %s for LaTeX fragments"
18393 processing-type)))))))))
18395 (defun org-create-math-formula (latex-frag &optional mathml-file)
18396 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18397 Use `org-latex-to-mathml-convert-command'. If the conversion is
18398 sucessful, return the portion between \"<math...> </math>\"
18399 elements otherwise return nil. When MATHML-FILE is specified,
18400 write the results in to that file. When invoked as an
18401 interactive command, prompt for LATEX-FRAG, with initial value
18402 set to the current active region and echo the results for user
18403 inspection."
18404 (interactive (list (let ((frag (when (org-region-active-p)
18405 (buffer-substring-no-properties
18406 (region-beginning) (region-end)))))
18407 (read-string "LaTeX Fragment: " frag nil frag))))
18408 (unless latex-frag (error "Invalid LaTeX fragment"))
18409 (let* ((tmp-in-file (file-relative-name
18410 (make-temp-name (expand-file-name "ltxmathml-in"))))
18411 (ignore (write-region latex-frag nil tmp-in-file))
18412 (tmp-out-file (file-relative-name
18413 (make-temp-name (expand-file-name "ltxmathml-out"))))
18414 (cmd (format-spec
18415 org-latex-to-mathml-convert-command
18416 `((?j . ,(shell-quote-argument
18417 (expand-file-name org-latex-to-mathml-jar-file)))
18418 (?I . ,(shell-quote-argument tmp-in-file))
18419 (?o . ,(shell-quote-argument tmp-out-file)))))
18420 mathml shell-command-output)
18421 (when (org-called-interactively-p 'any)
18422 (unless (org-format-latex-mathml-available-p)
18423 (user-error "LaTeX to MathML converter not configured")))
18424 (message "Running %s" cmd)
18425 (setq shell-command-output (shell-command-to-string cmd))
18426 (setq mathml
18427 (when (file-readable-p tmp-out-file)
18428 (with-current-buffer (find-file-noselect tmp-out-file t)
18429 (goto-char (point-min))
18430 (when (re-search-forward
18431 (concat
18432 (regexp-quote
18433 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18434 "\\(.\\|\n\\)*"
18435 (regexp-quote "</math>")) nil t)
18436 (prog1 (match-string 0) (kill-buffer))))))
18437 (cond
18438 (mathml
18439 (setq mathml
18440 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18441 (when mathml-file
18442 (write-region mathml nil mathml-file))
18443 (when (org-called-interactively-p 'any)
18444 (message mathml)))
18445 ((message "LaTeX to MathML conversion failed")
18446 (message shell-command-output)))
18447 (delete-file tmp-in-file)
18448 (when (file-exists-p tmp-out-file)
18449 (delete-file tmp-out-file))
18450 mathml))
18452 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18453 prefix &optional dir)
18454 "Use `org-create-math-formula' but check local cache first."
18455 (let* ((absprefix (expand-file-name prefix dir))
18456 (print-length nil) (print-level nil)
18457 (formula-id (concat
18458 "formula-"
18459 (sha1
18460 (prin1-to-string
18461 (list latex-frag
18462 org-latex-to-mathml-convert-command)))))
18463 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18464 (formula-cache-dir (file-name-directory formula-cache)))
18466 (unless (file-directory-p formula-cache-dir)
18467 (make-directory formula-cache-dir t))
18469 (unless (file-exists-p formula-cache)
18470 (org-create-math-formula latex-frag formula-cache))
18472 (if (file-exists-p formula-cache)
18473 ;; Successful conversion. Return the link to MathML file.
18474 (org-add-props
18475 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18476 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18477 'org-latex-src-embed-type (if latex-frag-type
18478 'paragraph 'character)))
18479 ;; Failed conversion. Return the LaTeX fragment verbatim
18480 latex-frag)))
18482 (defun org-create-formula-image (string tofile options buffer &optional type)
18483 "Create an image from LaTeX source using dvipng or convert.
18484 This function calls either `org-create-formula-image-with-dvipng'
18485 or `org-create-formula-image-with-imagemagick' depending on the
18486 value of `org-latex-create-formula-image-program' or on the value
18487 of the optional TYPE variable.
18489 Note: ultimately these two function should be combined as they
18490 share a good deal of logic."
18491 (org-check-external-command
18492 "latex" "needed to convert LaTeX fragments to images")
18493 (funcall
18494 (case (or type org-latex-create-formula-image-program)
18495 ('dvipng
18496 (org-check-external-command
18497 "dvipng" "needed to convert LaTeX fragments to images")
18498 #'org-create-formula-image-with-dvipng)
18499 ('imagemagick
18500 (org-check-external-command
18501 "convert" "you need to install imagemagick")
18502 #'org-create-formula-image-with-imagemagick)
18503 (t (error
18504 "Invalid value of `org-latex-create-formula-image-program'")))
18505 string tofile options buffer))
18507 (declare-function org-export--get-global-options "ox" (&optional backend))
18508 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18509 (defun org-create-formula--latex-header ()
18510 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18511 (org-latex-guess-inputenc
18512 (org-splice-latex-header
18513 org-format-latex-header
18514 org-latex-default-packages-alist
18515 org-latex-packages-alist t
18516 (plist-get
18517 (org-combine-plists
18518 (org-export--get-global-options 'latex)
18519 (org-export--get-inbuffer-options 'latex))
18520 :latex-header))))
18522 ;; This function borrows from Ganesh Swami's latex2png.el
18523 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18524 "This calls dvipng."
18525 (require 'ox-latex)
18526 (let* ((tmpdir (if (featurep 'xemacs)
18527 (temp-directory)
18528 temporary-file-directory))
18529 (texfilebase (make-temp-name
18530 (expand-file-name "orgtex" tmpdir)))
18531 (texfile (concat texfilebase ".tex"))
18532 (dvifile (concat texfilebase ".dvi"))
18533 (pngfile (concat texfilebase ".png"))
18534 (fnh (if (featurep 'xemacs)
18535 (font-height (face-font 'default))
18536 (face-attribute 'default :height nil)))
18537 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18538 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18539 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18540 "Black"))
18541 (bg (or (plist-get options (if buffer :background :html-background))
18542 "Transparent")))
18543 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18544 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18545 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18546 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18547 (let ((latex-header (org-create-formula--latex-header)))
18548 (with-temp-file texfile
18549 (insert latex-header)
18550 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18551 (let ((dir default-directory))
18552 (condition-case nil
18553 (progn
18554 (cd tmpdir)
18555 (call-process "latex" nil nil nil texfile))
18556 (error nil))
18557 (cd dir))
18558 (if (not (file-exists-p dvifile))
18559 (progn (message "Failed to create dvi file from %s" texfile) nil)
18560 (condition-case nil
18561 (if (featurep 'xemacs)
18562 (call-process "dvipng" nil nil nil
18563 "-fg" fg "-bg" bg
18564 "-T" "tight"
18565 "-o" pngfile
18566 dvifile)
18567 (call-process "dvipng" nil nil nil
18568 "-fg" fg "-bg" bg
18569 "-D" dpi
18570 ;;"-x" scale "-y" scale
18571 "-T" "tight"
18572 "-o" pngfile
18573 dvifile))
18574 (error nil))
18575 (if (not (file-exists-p pngfile))
18576 (if org-format-latex-signal-error
18577 (error "Failed to create png file from %s" texfile)
18578 (message "Failed to create png file from %s" texfile)
18579 nil)
18580 ;; Use the requested file name and clean up
18581 (copy-file pngfile tofile 'replace)
18582 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18583 (if (file-exists-p (concat texfilebase e))
18584 (delete-file (concat texfilebase e))))
18585 pngfile))))
18587 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18588 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18589 "This calls convert, which is included into imagemagick."
18590 (require 'ox-latex)
18591 (let* ((tmpdir (if (featurep 'xemacs)
18592 (temp-directory)
18593 temporary-file-directory))
18594 (texfilebase (make-temp-name
18595 (expand-file-name "orgtex" tmpdir)))
18596 (texfile (concat texfilebase ".tex"))
18597 (pdffile (concat texfilebase ".pdf"))
18598 (pngfile (concat texfilebase ".png"))
18599 (fnh (if (featurep 'xemacs)
18600 (font-height (face-font 'default))
18601 (face-attribute 'default :height nil)))
18602 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18603 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18604 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18605 "black"))
18606 (bg (or (plist-get options (if buffer :background :html-background))
18607 "white")))
18608 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18609 (setq fg (org-latex-color-format fg)))
18610 (if (eq bg 'default) (setq bg (org-latex-color :background))
18611 (setq bg (org-latex-color-format
18612 (if (string= bg "Transparent") "white" bg))))
18613 (let ((latex-header (org-create-formula--latex-header)))
18614 (with-temp-file texfile
18615 (insert latex-header)
18616 (insert "\n\\begin{document}\n"
18617 "\\definecolor{fg}{rgb}{" fg "}\n"
18618 "\\definecolor{bg}{rgb}{" bg "}\n"
18619 "\n\\pagecolor{bg}\n"
18620 "\n{\\color{fg}\n"
18621 string
18622 "\n}\n"
18623 "\n\\end{document}\n")))
18624 (org-latex-compile texfile t)
18625 (if (not (file-exists-p pdffile))
18626 (progn (message "Failed to create pdf file from %s" texfile) nil)
18627 (condition-case nil
18628 (if (featurep 'xemacs)
18629 (call-process "convert" nil nil nil
18630 "-density" "96"
18631 "-trim"
18632 "-antialias"
18633 pdffile
18634 "-quality" "100"
18635 ;; "-sharpen" "0x1.0"
18636 pngfile)
18637 (call-process "convert" nil nil nil
18638 "-density" dpi
18639 "-trim"
18640 "-antialias"
18641 pdffile
18642 "-quality" "100"
18643 ;; "-sharpen" "0x1.0"
18644 pngfile))
18645 (error nil))
18646 (if (not (file-exists-p pngfile))
18647 (if org-format-latex-signal-error
18648 (error "Failed to create png file from %s" texfile)
18649 (message "Failed to create png file from %s" texfile)
18650 nil)
18651 ;; Use the requested file name and clean up
18652 (copy-file pngfile tofile 'replace)
18653 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18654 (if (file-exists-p (concat texfilebase e))
18655 (delete-file (concat texfilebase e))))
18656 pngfile))))
18658 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18659 "Fill a LaTeX header template TPL.
18660 In the template, the following place holders will be recognized:
18662 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18663 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18664 [PACKAGES] \\usepackage statements for PKG
18665 [NO-PACKAGES] do not include PKG
18666 [EXTRA] the string EXTRA
18667 [NO-EXTRA] do not include EXTRA
18669 For backward compatibility, if both the positive and the negative place
18670 holder is missing, the positive one (without the \"NO-\") will be
18671 assumed to be present at the end of the template.
18672 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18673 EXTRA is a string.
18674 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18675 (let (rpl (end ""))
18676 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18677 (setq rpl (if (or (match-end 1) (not def-pkg))
18678 "" (org-latex-packages-to-string def-pkg snippets-p t))
18679 tpl (replace-match rpl t t tpl))
18680 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18682 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18683 (setq rpl (if (or (match-end 1) (not pkg))
18684 "" (org-latex-packages-to-string pkg snippets-p t))
18685 tpl (replace-match rpl t t tpl))
18686 (if pkg (setq end
18687 (concat end "\n"
18688 (org-latex-packages-to-string pkg snippets-p)))))
18690 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18691 (setq rpl (if (or (match-end 1) (not extra))
18692 "" (concat extra "\n"))
18693 tpl (replace-match rpl t t tpl))
18694 (if (and extra (string-match "\\S-" extra))
18695 (setq end (concat end "\n" extra))))
18697 (if (string-match "\\S-" end)
18698 (concat tpl "\n" end)
18699 tpl)))
18701 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18702 "Turn an alist of packages into a string with the \\usepackage macros."
18703 (setq pkg (mapconcat (lambda(p)
18704 (cond
18705 ((stringp p) p)
18706 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18707 (format "%% Package %s omitted" (cadr p)))
18708 ((equal "" (car p))
18709 (format "\\usepackage{%s}" (cadr p)))
18711 (format "\\usepackage[%s]{%s}"
18712 (car p) (cadr p)))))
18714 "\n"))
18715 (if newline (concat pkg "\n") pkg))
18717 (defun org-dvipng-color (attr)
18718 "Return a RGB color specification for dvipng."
18719 (apply 'format "rgb %s %s %s"
18720 (mapcar 'org-normalize-color
18721 (if (featurep 'xemacs)
18722 (color-rgb-components
18723 (face-property 'default
18724 (cond ((eq attr :foreground) 'foreground)
18725 ((eq attr :background) 'background))))
18726 (color-values (face-attribute 'default attr nil))))))
18728 (defun org-dvipng-color-format (color-name)
18729 "Convert COLOR-NAME to a RGB color value for dvipng."
18730 (apply 'format "rgb %s %s %s"
18731 (mapcar 'org-normalize-color
18732 (color-values color-name))))
18734 (defun org-latex-color (attr)
18735 "Return a RGB color for the LaTeX color package."
18736 (apply 'format "%s,%s,%s"
18737 (mapcar 'org-normalize-color
18738 (if (featurep 'xemacs)
18739 (color-rgb-components
18740 (face-property 'default
18741 (cond ((eq attr :foreground) 'foreground)
18742 ((eq attr :background) 'background))))
18743 (color-values (face-attribute 'default attr nil))))))
18745 (defun org-latex-color-format (color-name)
18746 "Convert COLOR-NAME to a RGB color value."
18747 (apply 'format "%s,%s,%s"
18748 (mapcar 'org-normalize-color
18749 (color-values color-name))))
18751 (defun org-normalize-color (value)
18752 "Return string to be used as color value for an RGB component."
18753 (format "%g" (/ value 65535.0)))
18757 ;; Image display
18759 (defvar org-inline-image-overlays nil)
18760 (make-variable-buffer-local 'org-inline-image-overlays)
18762 (defun org-toggle-inline-images (&optional include-linked)
18763 "Toggle the display of inline images.
18764 INCLUDE-LINKED is passed to `org-display-inline-images'."
18765 (interactive "P")
18766 (if org-inline-image-overlays
18767 (progn
18768 (org-remove-inline-images)
18769 (message "Inline image display turned off"))
18770 (org-display-inline-images include-linked)
18771 (if (and (org-called-interactively-p)
18772 org-inline-image-overlays)
18773 (message "%d images displayed inline"
18774 (length org-inline-image-overlays))
18775 (message "No images to display inline"))))
18777 (defun org-redisplay-inline-images ()
18778 "Refresh the display of inline images."
18779 (interactive)
18780 (if (not org-inline-image-overlays)
18781 (org-toggle-inline-images)
18782 (org-toggle-inline-images)
18783 (org-toggle-inline-images)))
18785 (defun org-display-inline-images (&optional include-linked refresh beg end)
18786 "Display inline images.
18787 Normally only links without a description part are inlined, because this
18788 is how it will work for export. When INCLUDE-LINKED is set, also links
18789 with a description part will be inlined. This can be nice for a quick
18790 look at those images, but it does not reflect what exported files will look
18791 like.
18792 When REFRESH is set, refresh existing images between BEG and END.
18793 This will create new image displays only if necessary.
18794 BEG and END default to the buffer boundaries."
18795 (interactive "P")
18796 (when (display-graphic-p)
18797 (unless refresh
18798 (org-remove-inline-images)
18799 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18800 (save-excursion
18801 (save-restriction
18802 (widen)
18803 (setq beg (or beg (point-min)) end (or end (point-max)))
18804 (goto-char beg)
18805 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18806 (substring (org-image-file-name-regexp) 0 -2)
18807 "\\)\\]" (if include-linked "" "\\]")))
18808 (case-fold-search t)
18809 old file ov img type attrwidth width)
18810 (while (re-search-forward re end t)
18811 (setq old (get-char-property-and-overlay (match-beginning 1)
18812 'org-image-overlay)
18813 file (expand-file-name
18814 (concat (or (match-string 3) "") (match-string 4))))
18815 (when (image-type-available-p 'imagemagick)
18816 (setq attrwidth (if (or (listp org-image-actual-width)
18817 (null org-image-actual-width))
18818 (save-excursion
18819 (save-match-data
18820 (when (re-search-backward
18821 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18822 (save-excursion
18823 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18824 (string-to-number (match-string 1))))))
18825 width (cond ((eq org-image-actual-width t) nil)
18826 ((null org-image-actual-width) attrwidth)
18827 ((numberp org-image-actual-width)
18828 org-image-actual-width)
18829 ((listp org-image-actual-width)
18830 (or attrwidth (car org-image-actual-width))))
18831 type (if width 'imagemagick)))
18832 (when (file-exists-p file)
18833 (if (and (car-safe old) refresh)
18834 (image-refresh (overlay-get (cdr old) 'display))
18835 (setq img (save-match-data (create-image file type nil :width width)))
18836 (when img
18837 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18838 (overlay-put ov 'display img)
18839 (overlay-put ov 'face 'default)
18840 (overlay-put ov 'org-image-overlay t)
18841 (overlay-put ov 'modification-hooks
18842 (list 'org-display-inline-remove-overlay))
18843 (push ov org-inline-image-overlays))))))))))
18845 (define-obsolete-function-alias
18846 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18848 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18849 "Remove inline-display overlay if a corresponding region is modified."
18850 (let ((inhibit-modification-hooks t))
18851 (when (and ov after)
18852 (delete ov org-inline-image-overlays)
18853 (delete-overlay ov))))
18855 (defun org-remove-inline-images ()
18856 "Remove inline display of images."
18857 (interactive)
18858 (mapc 'delete-overlay org-inline-image-overlays)
18859 (setq org-inline-image-overlays nil))
18861 ;;;; Key bindings
18863 ;; Outline functions from `outline-mode-prefix-map'
18864 ;; that can be remapped in Org:
18865 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18866 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18867 (define-key org-mode-map [remap outline-forward-same-level]
18868 'org-forward-heading-same-level)
18869 (define-key org-mode-map [remap outline-backward-same-level]
18870 'org-backward-heading-same-level)
18871 (define-key org-mode-map [remap show-branches]
18872 'org-kill-note-or-show-branches)
18873 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18874 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18875 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18877 ;; Outline functions from `outline-mode-prefix-map' that can not
18878 ;; be remapped in Org:
18880 ;; - the column "key binding" shows whether the Outline function is still
18881 ;; available in Org mode on the same key that it has been bound to in
18882 ;; Outline mode:
18883 ;; - "overridden": key used for a different functionality in Org mode
18884 ;; - else: key still bound to the same Outline function in Org mode
18886 ;; | Outline function | key binding | Org replacement |
18887 ;; |------------------------------------+-------------+-----------------------|
18888 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18889 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18890 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18891 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18892 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18893 ;; | `show-entry' | overridden | no replacement |
18894 ;; | `show-children' | `C-c C-i' | visibility cycling |
18895 ;; | `show-branches' | `C-c C-k' | still same function |
18896 ;; | `show-subtree' | overridden | visibility cycling |
18897 ;; | `show-all' | overridden | no replacement |
18898 ;; | `hide-subtree' | overridden | visibility cycling |
18899 ;; | `hide-body' | overridden | no replacement |
18900 ;; | `hide-entry' | overridden | visibility cycling |
18901 ;; | `hide-leaves' | overridden | no replacement |
18902 ;; | `hide-sublevels' | overridden | no replacement |
18903 ;; | `hide-other' | overridden | no replacement |
18905 ;; Make `C-c C-x' a prefix key
18906 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18908 ;; TAB key with modifiers
18909 (org-defkey org-mode-map "\C-i" 'org-cycle)
18910 (org-defkey org-mode-map [(tab)] 'org-cycle)
18911 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18912 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18913 ;; The following line is necessary under Suse GNU/Linux
18914 (unless (featurep 'xemacs)
18915 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18916 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18917 (define-key org-mode-map [backtab] 'org-shifttab)
18919 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18920 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18921 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18923 ;; Cursor keys with modifiers
18924 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18925 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18926 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18927 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18929 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18930 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18931 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18932 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18934 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18935 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18936 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18937 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18939 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18940 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18941 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18942 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18944 ;; Babel keys
18945 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18946 (mapc (lambda (pair)
18947 (define-key org-babel-map (car pair) (cdr pair)))
18948 org-babel-key-bindings)
18950 ;;; Extra keys for tty access.
18951 ;; We only set them when really needed because otherwise the
18952 ;; menus don't show the simple keys
18954 (when (or org-use-extra-keys
18955 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18956 (not window-system))
18957 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18958 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18959 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18960 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18961 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18962 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18963 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18964 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18965 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18966 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18967 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18968 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18969 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18970 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18971 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18972 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18973 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18974 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18975 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18976 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18977 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18978 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18979 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18980 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18981 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18982 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18983 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18984 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18986 ;; All the other keys
18988 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18989 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18990 (if (boundp 'narrow-map)
18991 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18992 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18993 (if (boundp 'narrow-map)
18994 (org-defkey narrow-map "b" 'org-narrow-to-block)
18995 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18996 (if (boundp 'narrow-map)
18997 (org-defkey narrow-map "e" 'org-narrow-to-element)
18998 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18999 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19000 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19001 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19002 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19003 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19004 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19005 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19006 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19007 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19008 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19009 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19010 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19011 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19012 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19013 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19014 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19015 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19016 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19017 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19018 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19019 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19020 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19021 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19022 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19023 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19024 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19025 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19026 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19027 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19028 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19029 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19030 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19031 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19032 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19033 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19034 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19035 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19036 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19037 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19038 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19039 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19040 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19041 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19042 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19043 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19044 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19045 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19046 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19047 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19048 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19049 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19050 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19051 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19052 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19053 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19054 (org-defkey org-mode-map "\C-c^" 'org-sort)
19055 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19056 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19057 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19058 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19059 (org-defkey org-mode-map "\C-m" 'org-return)
19060 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19061 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19062 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19063 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19064 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19065 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19066 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19067 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19068 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19069 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19070 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19071 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19072 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19073 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19074 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19075 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19076 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19077 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19078 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19079 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19080 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19081 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19082 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19084 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19085 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19086 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19088 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19089 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19090 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19091 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19092 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19093 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19094 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19095 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19096 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19097 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19098 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19099 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19100 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19101 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19102 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19103 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19104 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19105 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19106 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19107 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19108 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19109 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19110 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19112 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19113 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19114 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19115 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19116 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19118 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19120 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19122 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19123 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19125 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19128 (when (featurep 'xemacs)
19129 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19132 (defconst org-speed-commands-default
19134 ("Outline Navigation")
19135 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19136 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19137 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19138 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19139 ("F" . org-next-block)
19140 ("B" . org-previous-block)
19141 ("u" . (org-speed-move-safe 'outline-up-heading))
19142 ("j" . org-goto)
19143 ("g" . (org-refile t))
19144 ("Outline Visibility")
19145 ("c" . org-cycle)
19146 ("C" . org-shifttab)
19147 (" " . org-display-outline-path)
19148 ("s" . org-narrow-to-subtree)
19149 ("=" . org-columns)
19150 ("Outline Structure Editing")
19151 ("U" . org-shiftmetaup)
19152 ("D" . org-shiftmetadown)
19153 ("r" . org-metaright)
19154 ("l" . org-metaleft)
19155 ("R" . org-shiftmetaright)
19156 ("L" . org-shiftmetaleft)
19157 ("i" . (progn (forward-char 1) (call-interactively
19158 'org-insert-heading-respect-content)))
19159 ("^" . org-sort)
19160 ("w" . org-refile)
19161 ("a" . org-archive-subtree-default-with-confirmation)
19162 ("@" . org-mark-subtree)
19163 ("#" . org-toggle-comment)
19164 ("Clock Commands")
19165 ("I" . org-clock-in)
19166 ("O" . org-clock-out)
19167 ("Meta Data Editing")
19168 ("t" . org-todo)
19169 ("," . (org-priority))
19170 ("0" . (org-priority ?\ ))
19171 ("1" . (org-priority ?A))
19172 ("2" . (org-priority ?B))
19173 ("3" . (org-priority ?C))
19174 (":" . org-set-tags-command)
19175 ("e" . org-set-effort)
19176 ("E" . org-inc-effort)
19177 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19178 (org-entry-put (point) "APPT_WARNTIME" m)))
19179 ("Agenda Views etc")
19180 ("v" . org-agenda)
19181 ("/" . org-sparse-tree)
19182 ("Misc")
19183 ("o" . org-open-at-point)
19184 ("?" . org-speed-command-help)
19185 ("<" . (org-agenda-set-restriction-lock 'subtree))
19186 (">" . (org-agenda-remove-restriction-lock))
19188 "The default speed commands.")
19190 (defun org-print-speed-command (e)
19191 (if (> (length (car e)) 1)
19192 (progn
19193 (princ "\n")
19194 (princ (car e))
19195 (princ "\n")
19196 (princ (make-string (length (car e)) ?-))
19197 (princ "\n"))
19198 (princ (car e))
19199 (princ " ")
19200 (if (symbolp (cdr e))
19201 (princ (symbol-name (cdr e)))
19202 (prin1 (cdr e)))
19203 (princ "\n")))
19205 (defun org-speed-command-help ()
19206 "Show the available speed commands."
19207 (interactive)
19208 (if (not org-use-speed-commands)
19209 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19210 (with-output-to-temp-buffer "*Help*"
19211 (princ "User-defined Speed commands\n===========================\n")
19212 (mapc 'org-print-speed-command org-speed-commands-user)
19213 (princ "\n")
19214 (princ "Built-in Speed commands\n=======================\n")
19215 (mapc 'org-print-speed-command org-speed-commands-default))
19216 (with-current-buffer "*Help*"
19217 (setq truncate-lines t))))
19219 (defun org-speed-move-safe (cmd)
19220 "Execute CMD, but make sure that the cursor always ends up in a headline.
19221 If not, return to the original position and throw an error."
19222 (interactive)
19223 (let ((pos (point)))
19224 (call-interactively cmd)
19225 (unless (and (bolp) (org-at-heading-p))
19226 (goto-char pos)
19227 (error "Boundary reached while executing %s" cmd))))
19229 (defvar org-self-insert-command-undo-counter 0)
19231 (defvar org-table-auto-blank-field) ; defined in org-table.el
19232 (defvar org-speed-command nil)
19234 (define-obsolete-function-alias
19235 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19237 (defun org-speed-command-activate (keys)
19238 "Hook for activating single-letter speed commands.
19239 `org-speed-commands-default' specifies a minimal command set.
19240 Use `org-speed-commands-user' for further customization."
19241 (when (or (and (bolp) (looking-at org-outline-regexp))
19242 (and (functionp org-use-speed-commands)
19243 (funcall org-use-speed-commands)))
19244 (cdr (assoc keys (append org-speed-commands-user
19245 org-speed-commands-default)))))
19247 (define-obsolete-function-alias
19248 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19250 (defun org-babel-speed-command-activate (keys)
19251 "Hook for activating single-letter code block commands."
19252 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19253 (cdr (assoc keys org-babel-key-bindings))))
19255 (defcustom org-speed-command-hook
19256 '(org-speed-command-default-hook org-babel-speed-command-hook)
19257 "Hook for activating speed commands at strategic locations.
19258 Hook functions are called in sequence until a valid handler is
19259 found.
19261 Each hook takes a single argument, a user-pressed command key
19262 which is also a `self-insert-command' from the global map.
19264 Within the hook, examine the cursor position and the command key
19265 and return nil or a valid handler as appropriate. Handler could
19266 be one of an interactive command, a function, or a form.
19268 Set `org-use-speed-commands' to non-nil value to enable this
19269 hook. The default setting is `org-speed-command-activate'."
19270 :group 'org-structure
19271 :version "24.1"
19272 :type 'hook)
19274 (defun org-self-insert-command (N)
19275 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19276 If the cursor is in a table looking at whitespace, the whitespace is
19277 overwritten, and the table is not marked as requiring realignment."
19278 (interactive "p")
19279 (org-check-before-invisible-edit 'insert)
19280 (cond
19281 ((and org-use-speed-commands
19282 (setq org-speed-command
19283 (run-hook-with-args-until-success
19284 'org-speed-command-hook (this-command-keys))))
19285 (cond
19286 ((commandp org-speed-command)
19287 (setq this-command org-speed-command)
19288 (call-interactively org-speed-command))
19289 ((functionp org-speed-command)
19290 (funcall org-speed-command))
19291 ((and org-speed-command (listp org-speed-command))
19292 (eval org-speed-command))
19293 (t (let (org-use-speed-commands)
19294 (call-interactively 'org-self-insert-command)))))
19295 ((and
19296 (org-table-p)
19297 (progn
19298 ;; check if we blank the field, and if that triggers align
19299 (and (featurep 'org-table) org-table-auto-blank-field
19300 (member last-command
19301 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19302 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19303 ;; got extra space, this field does not determine column width
19304 (let (org-table-may-need-update) (org-table-blank-field))
19305 ;; no extra space, this field may determine column width
19306 (org-table-blank-field)))
19308 (eq N 1)
19309 (looking-at "[^|\n]* |"))
19310 (let (org-table-may-need-update)
19311 (goto-char (1- (match-end 0)))
19312 (backward-delete-char 1)
19313 (goto-char (match-beginning 0))
19314 (self-insert-command N)))
19316 (setq org-table-may-need-update t)
19317 (self-insert-command N)
19318 (org-fix-tags-on-the-fly)
19319 (if org-self-insert-cluster-for-undo
19320 (if (not (eq last-command 'org-self-insert-command))
19321 (setq org-self-insert-command-undo-counter 1)
19322 (if (>= org-self-insert-command-undo-counter 20)
19323 (setq org-self-insert-command-undo-counter 1)
19324 (and (> org-self-insert-command-undo-counter 0)
19325 buffer-undo-list (listp buffer-undo-list)
19326 (not (cadr buffer-undo-list)) ; remove nil entry
19327 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19328 (setq org-self-insert-command-undo-counter
19329 (1+ org-self-insert-command-undo-counter))))))))
19331 (defun org-check-before-invisible-edit (kind)
19332 "Check is editing if kind KIND would be dangerous with invisible text around.
19333 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19334 ;; First, try to get out of here as quickly as possible, to reduce overhead
19335 (if (and org-catch-invisible-edits
19336 (or (not (boundp 'visible-mode)) (not visible-mode))
19337 (or (get-char-property (point) 'invisible)
19338 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19339 ;; OK, we need to take a closer look
19340 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19341 (invisible-before-point (if (bobp) nil (get-char-property
19342 (1- (point)) 'invisible)))
19343 (border-and-ok-direction
19345 ;; Check if we are acting predictably before invisible text
19346 (and invisible-at-point (not invisible-before-point)
19347 (memq kind '(insert delete-backward)))
19348 ;; Check if we are acting predictably after invisible text
19349 ;; This works not well, and I have turned it off. It seems
19350 ;; better to always show and stop after invisible text.
19351 ;; (and (not invisible-at-point) invisible-before-point
19352 ;; (memq kind '(insert delete)))
19354 (when (or (memq invisible-at-point '(outline org-hide-block t))
19355 (memq invisible-before-point '(outline org-hide-block t)))
19356 (if (eq org-catch-invisible-edits 'error)
19357 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19358 (if (and org-custom-properties-overlays
19359 (y-or-n-p "Display invisible properties in this buffer? "))
19360 (org-toggle-custom-properties-visibility)
19361 ;; Make the area visible
19362 (save-excursion
19363 (if invisible-before-point
19364 (goto-char (previous-single-char-property-change
19365 (point) 'invisible)))
19366 (org-cycle))
19367 (cond
19368 ((eq org-catch-invisible-edits 'show)
19369 ;; That's it, we do the edit after showing
19370 (message
19371 "Unfolding invisible region around point before editing")
19372 (sit-for 1))
19373 ((and (eq org-catch-invisible-edits 'smart)
19374 border-and-ok-direction)
19375 (message "Unfolding invisible region around point before editing"))
19377 ;; Don't do the edit, make the user repeat it in full visibility
19378 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19380 (defun org-fix-tags-on-the-fly ()
19381 (when (and (equal (char-after (point-at-bol)) ?*)
19382 (org-at-heading-p))
19383 (org-align-tags-here org-tags-column)))
19385 (defun org-delete-backward-char (N)
19386 "Like `delete-backward-char', insert whitespace at field end in tables.
19387 When deleting backwards, in tables this function will insert whitespace in
19388 front of the next \"|\" separator, to keep the table aligned. The table will
19389 still be marked for re-alignment if the field did fill the entire column,
19390 because, in this case the deletion might narrow the column."
19391 (interactive "p")
19392 (save-match-data
19393 (org-check-before-invisible-edit 'delete-backward)
19394 (if (and (org-table-p)
19395 (eq N 1)
19396 (string-match "|" (buffer-substring (point-at-bol) (point)))
19397 (looking-at ".*?|"))
19398 (let ((pos (point))
19399 (noalign (looking-at "[^|\n\r]* |"))
19400 (c org-table-may-need-update))
19401 (backward-delete-char N)
19402 (if (not overwrite-mode)
19403 (progn
19404 (skip-chars-forward "^|")
19405 (insert " ")
19406 (goto-char (1- 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 (backward-delete-char N)
19411 (org-fix-tags-on-the-fly))))
19413 (defun org-delete-char (N)
19414 "Like `delete-char', but insert whitespace at field end in tables.
19415 When deleting characters, in tables this function will insert whitespace in
19416 front of the next \"|\" separator, to keep the table aligned. The table will
19417 still be marked for re-alignment if the field did fill the entire column,
19418 because, in this case the deletion might narrow the column."
19419 (interactive "p")
19420 (save-match-data
19421 (org-check-before-invisible-edit 'delete)
19422 (if (and (org-table-p)
19423 (not (bolp))
19424 (not (= (char-after) ?|))
19425 (eq N 1))
19426 (if (looking-at ".*?|")
19427 (let ((pos (point))
19428 (noalign (looking-at "[^|\n\r]* |"))
19429 (c org-table-may-need-update))
19430 (replace-match
19431 (concat (substring (match-string 0) 1 -1) " |") nil t)
19432 (goto-char pos)
19433 ;; noalign: if there were two spaces at the end, this field
19434 ;; does not determine the width of the column.
19435 (if noalign (setq org-table-may-need-update c)))
19436 (delete-char N))
19437 (delete-char N)
19438 (org-fix-tags-on-the-fly))))
19440 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19441 (put 'org-self-insert-command 'delete-selection t)
19442 (put 'orgtbl-self-insert-command 'delete-selection t)
19443 (put 'org-delete-char 'delete-selection 'supersede)
19444 (put 'org-delete-backward-char 'delete-selection 'supersede)
19445 (put 'org-yank 'delete-selection 'yank)
19447 ;; Make `flyspell-mode' delay after some commands
19448 (put 'org-self-insert-command 'flyspell-delayed t)
19449 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19450 (put 'org-delete-char 'flyspell-delayed t)
19451 (put 'org-delete-backward-char 'flyspell-delayed t)
19453 ;; Make pabbrev-mode expand after org-mode commands
19454 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19455 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19457 ;; How to do this: Measure non-white length of current string
19458 ;; If equal to column width, we should realign.
19460 (defun org-remap (map &rest commands)
19461 "In MAP, remap the functions given in COMMANDS.
19462 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19463 (let (new old)
19464 (while commands
19465 (setq old (pop commands) new (pop commands))
19466 (if (fboundp 'command-remapping)
19467 (org-defkey map (vector 'remap old) new)
19468 (substitute-key-definition old new map global-map)))))
19470 (defun org-transpose-words ()
19471 "Transpose words for Org.
19472 This uses the `org-mode-transpose-word-syntax-table' syntax
19473 table, which interprets characters in `org-emphasis-alist' as
19474 word constituants."
19475 (interactive)
19476 (with-syntax-table org-mode-transpose-word-syntax-table
19477 (call-interactively 'transpose-words)))
19478 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19480 (when (eq org-enable-table-editor 'optimized)
19481 ;; If the user wants maximum table support, we need to hijack
19482 ;; some standard editing functions
19483 (org-remap org-mode-map
19484 'self-insert-command 'org-self-insert-command
19485 'delete-char 'org-delete-char
19486 'delete-backward-char 'org-delete-backward-char)
19487 (org-defkey org-mode-map "|" 'org-force-self-insert))
19489 (defvar org-ctrl-c-ctrl-c-hook nil
19490 "Hook for functions attaching themselves to `C-c C-c'.
19492 This can be used to add additional functionality to the C-c C-c
19493 key which executes context-dependent commands. This hook is run
19494 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19495 run after the last test.
19497 Each function will be called with no arguments. The function
19498 must check if the context is appropriate for it to act. If yes,
19499 it should do its thing and then return a non-nil value. If the
19500 context is wrong, just do nothing and return nil.")
19502 (defvar org-ctrl-c-ctrl-c-final-hook nil
19503 "Hook for functions attaching themselves to `C-c C-c'.
19505 This can be used to add additional functionality to the C-c C-c
19506 key which executes context-dependent commands. This hook is run
19507 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19508 before the first test.
19510 Each function will be called with no arguments. The function
19511 must check if the context is appropriate for it to act. If yes,
19512 it should do its thing and then return a non-nil value. If the
19513 context is wrong, just do nothing and return nil.")
19515 (defvar org-tab-first-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 as the first action when TAB is pressed, even before
19519 `org-cycle' messes around with the `outline-regexp' to cater for
19520 inline tasks and plain list item folding.
19521 If any function in this hook returns t, any other actions that
19522 would have been caused by TAB (such as table field motion or visibility
19523 cycling) will not occur.")
19525 (defvar org-tab-after-check-for-table-hook nil
19526 "Hook for functions to attach themselves to TAB.
19527 See `org-ctrl-c-ctrl-c-hook' for more information.
19528 This hook runs after it has been established that the cursor is not in a
19529 table, but before checking if the cursor is in a headline or if global cycling
19530 should be done.
19531 If any function in this hook returns t, not other actions like visibility
19532 cycling will be done.")
19534 (defvar org-tab-after-check-for-cycling-hook nil
19535 "Hook for functions to attach themselves to TAB.
19536 See `org-ctrl-c-ctrl-c-hook' for more information.
19537 This hook runs after it has been established that not table field motion and
19538 not visibility should be done because of current context. This is probably
19539 the place where a package like yasnippets can hook in.")
19541 (defvar org-tab-before-tab-emulation-hook nil
19542 "Hook for functions to attach themselves to TAB.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.
19544 This hook runs after every other options for TAB have been exhausted, but
19545 before indentation and \t insertion takes place.")
19547 (defvar org-metaleft-hook nil
19548 "Hook for functions attaching themselves to `M-left'.
19549 See `org-ctrl-c-ctrl-c-hook' for more information.")
19550 (defvar org-metaright-hook nil
19551 "Hook for functions attaching themselves to `M-right'.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19553 (defvar org-metaup-hook nil
19554 "Hook for functions attaching themselves to `M-up'.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-metadown-hook nil
19557 "Hook for functions attaching themselves to `M-down'.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftmetaleft-hook nil
19560 "Hook for functions attaching themselves to `M-S-left'.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-shiftmetaright-hook nil
19563 "Hook for functions attaching themselves to `M-S-right'.
19564 See `org-ctrl-c-ctrl-c-hook' for more information.")
19565 (defvar org-shiftmetaup-hook nil
19566 "Hook for functions attaching themselves to `M-S-up'.
19567 See `org-ctrl-c-ctrl-c-hook' for more information.")
19568 (defvar org-shiftmetadown-hook nil
19569 "Hook for functions attaching themselves to `M-S-down'.
19570 See `org-ctrl-c-ctrl-c-hook' for more information.")
19571 (defvar org-metareturn-hook nil
19572 "Hook for functions attaching themselves to `M-RET'.
19573 See `org-ctrl-c-ctrl-c-hook' for more information.")
19574 (defvar org-shiftup-hook nil
19575 "Hook for functions attaching themselves to `S-up'.
19576 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defvar org-shiftup-final-hook nil
19578 "Hook for functions attaching themselves to `S-up'.
19579 This one runs after all other options except shift-select have been excluded.
19580 See `org-ctrl-c-ctrl-c-hook' for more information.")
19581 (defvar org-shiftdown-hook nil
19582 "Hook for functions attaching themselves to `S-down'.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defvar org-shiftdown-final-hook nil
19585 "Hook for functions attaching themselves to `S-down'.
19586 This one runs after all other options except shift-select have been excluded.
19587 See `org-ctrl-c-ctrl-c-hook' for more information.")
19588 (defvar org-shiftleft-hook nil
19589 "Hook for functions attaching themselves to `S-left'.
19590 See `org-ctrl-c-ctrl-c-hook' for more information.")
19591 (defvar org-shiftleft-final-hook nil
19592 "Hook for functions attaching themselves to `S-left'.
19593 This one runs after all other options except shift-select have been excluded.
19594 See `org-ctrl-c-ctrl-c-hook' for more information.")
19595 (defvar org-shiftright-hook nil
19596 "Hook for functions attaching themselves to `S-right'.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.")
19598 (defvar org-shiftright-final-hook nil
19599 "Hook for functions attaching themselves to `S-right'.
19600 This one runs after all other options except shift-select have been excluded.
19601 See `org-ctrl-c-ctrl-c-hook' for more information.")
19603 (defun org-modifier-cursor-error ()
19604 "Throw an error, a modified cursor command was applied in wrong context."
19605 (user-error "This command is active in special context like tables, headlines or items"))
19607 (defun org-shiftselect-error ()
19608 "Throw an error because Shift-Cursor command was applied in wrong context."
19609 (if (and (boundp 'shift-select-mode) shift-select-mode)
19610 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19611 (user-error "This command works only in special context like headlines or timestamps")))
19613 (defun org-call-for-shift-select (cmd)
19614 (let ((this-command-keys-shift-translated t))
19615 (call-interactively cmd)))
19617 (defun org-shifttab (&optional arg)
19618 "Global visibility cycling or move to previous table field.
19619 Call `org-table-previous-field' within a table.
19620 When ARG is nil, cycle globally through visibility states.
19621 When ARG is a numeric prefix, show contents of this level."
19622 (interactive "P")
19623 (cond
19624 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19625 ((integerp arg)
19626 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19627 (message "Content view to level: %d" arg)
19628 (org-content (prefix-numeric-value arg2))
19629 (org-cycle-show-empty-lines t)
19630 (setq org-cycle-global-status 'overview)))
19631 (t (call-interactively 'org-global-cycle))))
19633 (defun org-shiftmetaleft ()
19634 "Promote subtree or delete table column.
19635 Calls `org-promote-subtree', `org-outdent-item-tree', or
19636 `org-table-delete-column', depending on context. See the
19637 individual commands for more information."
19638 (interactive)
19639 (cond
19640 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19641 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19642 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19643 ((if (not (org-region-active-p)) (org-at-item-p)
19644 (save-excursion (goto-char (region-beginning))
19645 (org-at-item-p)))
19646 (call-interactively 'org-outdent-item-tree))
19647 (t (org-modifier-cursor-error))))
19649 (defun org-shiftmetaright ()
19650 "Demote subtree or insert table column.
19651 Calls `org-demote-subtree', `org-indent-item-tree', or
19652 `org-table-insert-column', depending on context. See the
19653 individual commands for more information."
19654 (interactive)
19655 (cond
19656 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19657 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19658 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19659 ((if (not (org-region-active-p)) (org-at-item-p)
19660 (save-excursion (goto-char (region-beginning))
19661 (org-at-item-p)))
19662 (call-interactively 'org-indent-item-tree))
19663 (t (org-modifier-cursor-error))))
19665 (defun org-shiftmetaup (&optional arg)
19666 "Move subtree up or kill table row.
19667 Calls `org-move-subtree-up' or `org-table-kill-row' or
19668 `org-move-item-up' or `org-timestamp-up', depending on context.
19669 See the individual commands for more information."
19670 (interactive "P")
19671 (cond
19672 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19673 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19674 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19675 ((org-at-item-p) (call-interactively 'org-move-item-up))
19676 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19677 (call-interactively 'org-timestamp-up)))
19678 (t (call-interactively 'org-drag-line-backward))))
19680 (defun org-shiftmetadown (&optional arg)
19681 "Move subtree down or insert table row.
19682 Calls `org-move-subtree-down' or `org-table-insert-row' or
19683 `org-move-item-down' or `org-timestamp-up', depending on context.
19684 See the individual commands for more information."
19685 (interactive "P")
19686 (cond
19687 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19688 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19689 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19690 ((org-at-item-p) (call-interactively 'org-move-item-down))
19691 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19692 (call-interactively 'org-timestamp-down)))
19693 (t (call-interactively 'org-drag-line-forward))))
19695 (defsubst org-hidden-tree-error ()
19696 (user-error
19697 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19699 (defun org-metaleft (&optional arg)
19700 "Promote heading or move table column to left.
19701 Calls `org-do-promote' or `org-table-move-column', depending on context.
19702 With no specific context, calls the Emacs default `backward-word'.
19703 See the individual commands for more information."
19704 (interactive "P")
19705 (cond
19706 ((run-hook-with-args-until-success 'org-metaleft-hook))
19707 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19708 ((org-with-limited-levels
19709 (or (org-at-heading-p)
19710 (and (org-region-active-p)
19711 (save-excursion
19712 (goto-char (region-beginning))
19713 (org-at-heading-p)))))
19714 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19715 (call-interactively 'org-do-promote))
19716 ;; At an inline task.
19717 ((org-at-heading-p)
19718 (call-interactively 'org-inlinetask-promote))
19719 ((or (org-at-item-p)
19720 (and (org-region-active-p)
19721 (save-excursion
19722 (goto-char (region-beginning))
19723 (org-at-item-p))))
19724 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19725 (call-interactively 'org-outdent-item))
19726 (t (call-interactively 'backward-word))))
19728 (defun org-metaright (&optional arg)
19729 "Demote a subtree, a list item or move table column to right.
19730 In front of a drawer or a block keyword, indent it correctly.
19731 With no specific context, calls the Emacs default `forward-word'.
19732 See the individual commands for more information."
19733 (interactive "P")
19734 (cond
19735 ((run-hook-with-args-until-success 'org-metaright-hook))
19736 ((org-at-table-p) (call-interactively 'org-table-move-column))
19737 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19738 ((org-at-block-p) (call-interactively 'org-indent-block))
19739 ((org-with-limited-levels
19740 (or (org-at-heading-p)
19741 (and (org-region-active-p)
19742 (save-excursion
19743 (goto-char (region-beginning))
19744 (org-at-heading-p)))))
19745 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19746 (call-interactively 'org-do-demote))
19747 ;; At an inline task.
19748 ((org-at-heading-p)
19749 (call-interactively 'org-inlinetask-demote))
19750 ((or (org-at-item-p)
19751 (and (org-region-active-p)
19752 (save-excursion
19753 (goto-char (region-beginning))
19754 (org-at-item-p))))
19755 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19756 (call-interactively 'org-indent-item))
19757 (t (call-interactively 'forward-word))))
19759 (defun org-check-for-hidden (what)
19760 "Check if there are hidden headlines/items in the current visual line.
19761 WHAT can be either `headlines' or `items'. If the current line is
19762 an outline or item heading and it has a folded subtree below it,
19763 this function returns t, nil otherwise."
19764 (let ((re (cond
19765 ((eq what 'headlines) org-outline-regexp-bol)
19766 ((eq what 'items) (org-item-beginning-re))
19767 (t (error "This should not happen"))))
19768 beg end)
19769 (save-excursion
19770 (catch 'exit
19771 (unless (org-region-active-p)
19772 (setq beg (point-at-bol))
19773 (beginning-of-line 2)
19774 (while (and (not (eobp)) ;; this is like `next-line'
19775 (get-char-property (1- (point)) 'invisible))
19776 (beginning-of-line 2))
19777 (setq end (point))
19778 (goto-char beg)
19779 (goto-char (point-at-eol))
19780 (setq end (max end (point)))
19781 (while (re-search-forward re end t)
19782 (if (get-char-property (match-beginning 0) 'invisible)
19783 (throw 'exit t))))
19784 nil))))
19786 (defun org-metaup (&optional arg)
19787 "Move subtree up or move table row up.
19788 Calls `org-move-subtree-up' or `org-table-move-row' or
19789 `org-move-item-up', depending on context. See the individual commands
19790 for more information."
19791 (interactive "P")
19792 (cond
19793 ((run-hook-with-args-until-success 'org-metaup-hook))
19794 ((org-region-active-p)
19795 (let* ((a (min (region-beginning) (region-end)))
19796 (b (1- (max (region-beginning) (region-end))))
19797 (c (save-excursion (goto-char a)
19798 (move-beginning-of-line 0)))
19799 (d (save-excursion (goto-char a)
19800 (move-end-of-line 0) (point))))
19801 (transpose-regions a b c d)
19802 (goto-char c)))
19803 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19804 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19805 ((org-at-item-p) (call-interactively 'org-move-item-up))
19806 (t (org-drag-element-backward))))
19808 (defun org-metadown (&optional arg)
19809 "Move subtree down or move table row down.
19810 Calls `org-move-subtree-down' or `org-table-move-row' or
19811 `org-move-item-down', depending on context. See the individual
19812 commands for more information."
19813 (interactive "P")
19814 (cond
19815 ((run-hook-with-args-until-success 'org-metadown-hook))
19816 ((org-region-active-p)
19817 (let* ((a (min (region-beginning) (region-end)))
19818 (b (max (region-beginning) (region-end)))
19819 (c (save-excursion (goto-char b)
19820 (move-beginning-of-line 1)))
19821 (d (save-excursion (goto-char b)
19822 (move-end-of-line 1) (1+ (point)))))
19823 (transpose-regions a b c d)
19824 (goto-char d)))
19825 ((org-at-table-p) (call-interactively 'org-table-move-row))
19826 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19827 ((org-at-item-p) (call-interactively 'org-move-item-down))
19828 (t (org-drag-element-forward))))
19830 (defun org-shiftup (&optional arg)
19831 "Increase item in timestamp or increase priority of current headline.
19832 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19833 depending on context. See the individual commands for more information."
19834 (interactive "P")
19835 (cond
19836 ((run-hook-with-args-until-success 'org-shiftup-hook))
19837 ((and org-support-shift-select (org-region-active-p))
19838 (org-call-for-shift-select 'previous-line))
19839 ((org-at-timestamp-p t)
19840 (call-interactively (if org-edit-timestamp-down-means-later
19841 'org-timestamp-down 'org-timestamp-up)))
19842 ((and (not (eq org-support-shift-select 'always))
19843 org-enable-priority-commands
19844 (org-at-heading-p))
19845 (call-interactively 'org-priority-up))
19846 ((and (not org-support-shift-select) (org-at-item-p))
19847 (call-interactively 'org-previous-item))
19848 ((org-clocktable-try-shift 'up arg))
19849 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19850 (org-support-shift-select
19851 (org-call-for-shift-select 'previous-line))
19852 (t (org-shiftselect-error))))
19854 (defun org-shiftdown (&optional arg)
19855 "Decrease item in timestamp or decrease priority of current headline.
19856 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19857 depending on context. See the individual commands for more information."
19858 (interactive "P")
19859 (cond
19860 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19861 ((and org-support-shift-select (org-region-active-p))
19862 (org-call-for-shift-select 'next-line))
19863 ((org-at-timestamp-p t)
19864 (call-interactively (if org-edit-timestamp-down-means-later
19865 'org-timestamp-up 'org-timestamp-down)))
19866 ((and (not (eq org-support-shift-select 'always))
19867 org-enable-priority-commands
19868 (org-at-heading-p))
19869 (call-interactively 'org-priority-down))
19870 ((and (not org-support-shift-select) (org-at-item-p))
19871 (call-interactively 'org-next-item))
19872 ((org-clocktable-try-shift 'down arg))
19873 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19874 (org-support-shift-select
19875 (org-call-for-shift-select 'next-line))
19876 (t (org-shiftselect-error))))
19878 (defun org-shiftright (&optional arg)
19879 "Cycle the thing at point or in the current line, depending on context.
19880 Depending on context, this does one of the following:
19882 - switch a timestamp at point one day into the future
19883 - on a headline, switch to the next TODO keyword.
19884 - on an item, switch entire list to the next bullet type
19885 - on a property line, switch to the next allowed value
19886 - on a clocktable definition line, move time block into the future"
19887 (interactive "P")
19888 (cond
19889 ((run-hook-with-args-until-success 'org-shiftright-hook))
19890 ((and org-support-shift-select (org-region-active-p))
19891 (org-call-for-shift-select 'forward-char))
19892 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19893 ((and (not (eq org-support-shift-select 'always))
19894 (org-at-heading-p))
19895 (let ((org-inhibit-logging
19896 (not org-treat-S-cursor-todo-selection-as-state-change))
19897 (org-inhibit-blocking
19898 (not org-treat-S-cursor-todo-selection-as-state-change)))
19899 (org-call-with-arg 'org-todo 'right)))
19900 ((or (and org-support-shift-select
19901 (not (eq org-support-shift-select 'always))
19902 (org-at-item-bullet-p))
19903 (and (not org-support-shift-select) (org-at-item-p)))
19904 (org-call-with-arg 'org-cycle-list-bullet nil))
19905 ((and (not (eq org-support-shift-select 'always))
19906 (org-at-property-p))
19907 (call-interactively 'org-property-next-allowed-value))
19908 ((org-clocktable-try-shift 'right arg))
19909 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19910 (org-support-shift-select
19911 (org-call-for-shift-select 'forward-char))
19912 (t (org-shiftselect-error))))
19914 (defun org-shiftleft (&optional arg)
19915 "Cycle the thing at point or in the current line, depending on context.
19916 Depending on context, this does one of the following:
19918 - switch a timestamp at point one day into the past
19919 - on a headline, switch to the previous TODO keyword.
19920 - on an item, switch entire list to the previous bullet type
19921 - on a property line, switch to the previous allowed value
19922 - on a clocktable definition line, move time block into the past"
19923 (interactive "P")
19924 (cond
19925 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19926 ((and org-support-shift-select (org-region-active-p))
19927 (org-call-for-shift-select 'backward-char))
19928 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19929 ((and (not (eq org-support-shift-select 'always))
19930 (org-at-heading-p))
19931 (let ((org-inhibit-logging
19932 (not org-treat-S-cursor-todo-selection-as-state-change))
19933 (org-inhibit-blocking
19934 (not org-treat-S-cursor-todo-selection-as-state-change)))
19935 (org-call-with-arg 'org-todo 'left)))
19936 ((or (and org-support-shift-select
19937 (not (eq org-support-shift-select 'always))
19938 (org-at-item-bullet-p))
19939 (and (not org-support-shift-select) (org-at-item-p)))
19940 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19941 ((and (not (eq org-support-shift-select 'always))
19942 (org-at-property-p))
19943 (call-interactively 'org-property-previous-allowed-value))
19944 ((org-clocktable-try-shift 'left arg))
19945 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19946 (org-support-shift-select
19947 (org-call-for-shift-select 'backward-char))
19948 (t (org-shiftselect-error))))
19950 (defun org-shiftcontrolright ()
19951 "Switch to next TODO set."
19952 (interactive)
19953 (cond
19954 ((and org-support-shift-select (org-region-active-p))
19955 (org-call-for-shift-select 'forward-word))
19956 ((and (not (eq org-support-shift-select 'always))
19957 (org-at-heading-p))
19958 (org-call-with-arg 'org-todo 'nextset))
19959 (org-support-shift-select
19960 (org-call-for-shift-select 'forward-word))
19961 (t (org-shiftselect-error))))
19963 (defun org-shiftcontrolleft ()
19964 "Switch to previous TODO set."
19965 (interactive)
19966 (cond
19967 ((and org-support-shift-select (org-region-active-p))
19968 (org-call-for-shift-select 'backward-word))
19969 ((and (not (eq org-support-shift-select 'always))
19970 (org-at-heading-p))
19971 (org-call-with-arg 'org-todo 'previousset))
19972 (org-support-shift-select
19973 (org-call-for-shift-select 'backward-word))
19974 (t (org-shiftselect-error))))
19976 (defun org-shiftcontrolup (&optional n)
19977 "Change timestamps synchronously up in CLOCK log lines.
19978 Optional argument N tells to change by that many units."
19979 (interactive "P")
19980 (cond ((and (not org-support-shift-select)
19981 (org-at-clock-log-p)
19982 (org-at-timestamp-p t))
19983 (org-clock-timestamps-up n))
19984 (t (org-shiftselect-error))))
19986 (defun org-shiftcontroldown (&optional n)
19987 "Change timestamps synchronously down in CLOCK log lines.
19988 Optional argument N tells to change by that many units."
19989 (interactive "P")
19990 (cond ((and (not org-support-shift-select)
19991 (org-at-clock-log-p)
19992 (org-at-timestamp-p t))
19993 (org-clock-timestamps-down n))
19994 (t (org-shiftselect-error))))
19996 (defun org-ctrl-c-ret ()
19997 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19998 (interactive)
19999 (cond
20000 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20001 (t (call-interactively 'org-insert-heading))))
20003 (defun org-find-visible ()
20004 (let ((s (point)))
20005 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20006 (get-char-property s 'invisible)))
20008 (defun org-find-invisible ()
20009 (let ((s (point)))
20010 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20011 (not (get-char-property s 'invisible))))
20014 (defun org-copy-visible (beg end)
20015 "Copy the visible parts of the region."
20016 (interactive "r")
20017 (let (snippets s)
20018 (save-excursion
20019 (save-restriction
20020 (narrow-to-region beg end)
20021 (setq s (goto-char (point-min)))
20022 (while (not (= (point) (point-max)))
20023 (goto-char (org-find-invisible))
20024 (push (buffer-substring s (point)) snippets)
20025 (setq s (goto-char (org-find-visible))))))
20026 (kill-new (apply 'concat (nreverse snippets)))))
20028 (defun org-copy-special ()
20029 "Copy region in table or copy current subtree.
20030 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20031 See the individual commands for more information."
20032 (interactive)
20033 (call-interactively
20034 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20036 (defun org-cut-special ()
20037 "Cut region in table or cut current subtree.
20038 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20039 See the individual commands for more information."
20040 (interactive)
20041 (call-interactively
20042 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20044 (defun org-paste-special (arg)
20045 "Paste rectangular region into table, or past subtree relative to level.
20046 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20047 See the individual commands for more information."
20048 (interactive "P")
20049 (if (org-at-table-p)
20050 (org-table-paste-rectangle)
20051 (org-paste-subtree arg)))
20053 (defsubst org-in-fixed-width-region-p ()
20054 "Is point in a fixed-width region?"
20055 (save-match-data
20056 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20058 (defun org-edit-special (&optional arg)
20059 "Call a special editor for the element at point.
20060 When at a table, call the formula editor with `org-table-edit-formulas'.
20061 When in a source code block, call `org-edit-src-code'.
20062 When in a fixed-width region, call `org-edit-fixed-width-region'.
20063 When at an #+INCLUDE keyword, visit the included file.
20064 On a link, call `ffap' to visit the link at point.
20065 Otherwise, return a user error."
20066 (interactive "P")
20067 (let ((element (org-element-at-point)))
20068 (assert (not buffer-read-only) nil
20069 "Buffer is read-only: %s" (buffer-name))
20070 (case (org-element-type element)
20071 (src-block
20072 (if (not arg) (org-edit-src-code)
20073 (let* ((info (org-babel-get-src-block-info))
20074 (lang (nth 0 info))
20075 (params (nth 2 info))
20076 (session (cdr (assq :session params))))
20077 (if (not session) (org-edit-src-code)
20078 ;; At a src-block with a session and function called with
20079 ;; an ARG: switch to the buffer related to the inferior
20080 ;; process.
20081 (switch-to-buffer
20082 (funcall (intern (concat "org-babel-prep-session:" lang))
20083 session params))))))
20084 (keyword
20085 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20086 (find-file
20087 (org-remove-double-quotes
20088 (car (org-split-string (org-element-property :value element)))))
20089 (user-error "No special environment to edit here")))
20090 (table
20091 (if (eq (org-element-property :type element) 'table.el)
20092 (org-edit-src-code)
20093 (call-interactively 'org-table-edit-formulas)))
20094 ;; Only Org tables contain `table-row' type elements.
20095 (table-row (call-interactively 'org-table-edit-formulas))
20096 ((example-block export-block) (org-edit-src-code))
20097 (fixed-width (org-edit-fixed-width-region))
20098 (otherwise
20099 ;; No notable element at point. Though, we may be at a link,
20100 ;; which is an object. Thus, scan deeper.
20101 (if (eq (org-element-type (org-element-context element)) 'link)
20102 (call-interactively 'ffap)
20103 (user-error "No special environment to edit here"))))))
20105 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20106 (defun org-ctrl-c-ctrl-c (&optional arg)
20107 "Set tags in headline, or update according to changed information at point.
20109 This command does many different things, depending on context:
20111 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20112 this is what we do.
20114 - If the cursor is on a statistics cookie, update it.
20116 - If the cursor is in a headline, prompt for tags and insert them
20117 into the current line, aligned to `org-tags-column'. When called
20118 with prefix arg, realign all tags in the current buffer.
20120 - If the cursor is in one of the special #+KEYWORD lines, this
20121 triggers scanning the buffer for these lines and updating the
20122 information.
20124 - If the cursor is inside a table, realign the table. This command
20125 works even if the automatic table editor has been turned off.
20127 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20128 the entire table.
20130 - If the cursor is at a footnote reference or definition, jump to
20131 the corresponding definition or references, respectively.
20133 - If the cursor is a the beginning of a dynamic block, update it.
20135 - If the current buffer is a capture buffer, close note and file it.
20137 - If the cursor is on a <<<target>>>, update radio targets and
20138 corresponding links in this buffer.
20140 - If the cursor is on a numbered item in a plain list, renumber the
20141 ordered list.
20143 - If the cursor is on a checkbox, toggle it.
20145 - If the cursor is on a code block, evaluate it. The variable
20146 `org-confirm-babel-evaluate' can be used to control prompting
20147 before code block evaluation, by default every code block
20148 evaluation requires confirmation. Code block evaluation can be
20149 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20150 (interactive "P")
20151 (cond
20152 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20153 org-occur-highlights
20154 org-latex-fragment-image-overlays)
20155 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20156 (org-remove-occur-highlights)
20157 (org-remove-latex-fragment-image-overlays)
20158 (message "Temporary highlights/overlays removed from current buffer"))
20159 ((and (local-variable-p 'org-finish-function (current-buffer))
20160 (fboundp org-finish-function))
20161 (funcall org-finish-function))
20162 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20164 (let* ((context (org-element-context)) (type (org-element-type context)))
20165 ;; Test if point is within a blank line.
20166 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20167 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20168 (user-error "C-c C-c can do nothing useful at this location"))
20169 ;; For convenience: at the first line of a paragraph on the
20170 ;; same line as an item, apply function on that item instead.
20171 (when (eq type 'paragraph)
20172 (let ((parent (org-element-property :parent context)))
20173 (when (and (eq (org-element-type parent) 'item)
20174 (= (point-at-bol) (org-element-property :begin parent)))
20175 (setq context parent type 'item))))
20176 ;; Act according to type of element or object at point.
20177 (case type
20178 (clock (org-clock-update-time-maybe))
20179 (dynamic-block
20180 (save-excursion
20181 (goto-char (org-element-property :post-affiliated context))
20182 (org-update-dblock)))
20183 (footnote-definition
20184 (goto-char (org-element-property :post-affiliated context))
20185 (call-interactively 'org-footnote-action))
20186 (footnote-reference (call-interactively 'org-footnote-action))
20187 ((headline inlinetask)
20188 (save-excursion (goto-char (org-element-property :begin context))
20189 (call-interactively 'org-set-tags)))
20190 (item
20191 ;; At an item: a double C-u set checkbox to "[-]"
20192 ;; unconditionally, whereas a single one will toggle its
20193 ;; presence. Without an universal argument, if the item
20194 ;; has a checkbox, toggle it. Otherwise repair the list.
20195 (let* ((box (org-element-property :checkbox context))
20196 (struct (org-element-property :structure context))
20197 (old-struct (copy-tree struct))
20198 (parents (org-list-parents-alist struct))
20199 (prevs (org-list-prevs-alist struct))
20200 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20201 (org-list-set-checkbox
20202 (org-element-property :begin context) struct
20203 (cond ((equal arg '(16)) "[-]")
20204 ((and (not box) (equal arg '(4))) "[ ]")
20205 ((or (not box) (equal arg '(4))) nil)
20206 ((eq box 'on) "[ ]")
20207 (t "[X]")))
20208 ;; Mimic `org-list-write-struct' but with grabbing
20209 ;; a return value from `org-list-struct-fix-box'.
20210 (org-list-struct-fix-ind struct parents 2)
20211 (org-list-struct-fix-item-end struct)
20212 (org-list-struct-fix-bul struct prevs)
20213 (org-list-struct-fix-ind struct parents)
20214 (let ((block-item
20215 (org-list-struct-fix-box struct parents prevs orderedp)))
20216 (if (and box (equal struct old-struct))
20217 (if (equal arg '(16))
20218 (message "Checkboxes already reset")
20219 (user-error "Cannot toggle this checkbox: %s"
20220 (if (eq box 'on)
20221 "all subitems checked"
20222 "unchecked subitems")))
20223 (org-list-struct-apply-struct struct old-struct)
20224 (org-update-checkbox-count-maybe))
20225 (when block-item
20226 (message "Checkboxes were removed due to empty box at line %d"
20227 (org-current-line block-item))))))
20228 (keyword
20229 (let ((org-inhibit-startup-visibility-stuff t)
20230 (org-startup-align-all-tables nil))
20231 (when (boundp 'org-table-coordinate-overlays)
20232 (mapc 'delete-overlay org-table-coordinate-overlays)
20233 (setq org-table-coordinate-overlays nil))
20234 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20235 (message "Local setup has been refreshed"))
20236 (plain-list
20237 ;; At a plain list, with a double C-u argument, set
20238 ;; checkboxes of each item to "[-]", whereas a single one
20239 ;; will toggle their presence according to the state of the
20240 ;; first item in the list. Without an argument, repair the
20241 ;; list.
20242 (let* ((begin (org-element-property :contents-begin context))
20243 (beginm (move-marker (make-marker) begin))
20244 (struct (org-element-property :structure context))
20245 (old-struct (copy-tree struct))
20246 (first-box (save-excursion
20247 (goto-char begin)
20248 (looking-at org-list-full-item-re)
20249 (match-string-no-properties 3)))
20250 (new-box (cond ((equal arg '(16)) "[-]")
20251 ((equal arg '(4)) (unless first-box "[ ]"))
20252 ((equal first-box "[X]") "[ ]")
20253 (t "[X]"))))
20254 (cond
20255 (arg
20256 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20257 (org-list-get-all-items
20258 begin struct (org-list-prevs-alist struct))))
20259 ((and first-box (eq (point) begin))
20260 ;; For convenience, when point is at bol on the first
20261 ;; item of the list and no argument is provided, simply
20262 ;; toggle checkbox of that item, if any.
20263 (org-list-set-checkbox begin struct new-box)))
20264 (org-list-write-struct
20265 struct (org-list-parents-alist struct) old-struct)
20266 (org-update-checkbox-count-maybe)
20267 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20268 ((property-drawer node-property)
20269 (call-interactively 'org-property-action))
20270 ((radio-target target)
20271 (call-interactively 'org-update-radio-target-regexp))
20272 (statistics-cookie
20273 (call-interactively 'org-update-statistics-cookies))
20274 ((table table-cell table-row)
20275 ;; At a table, recalculate every field and align it. Also
20276 ;; send the table if necessary. If the table has
20277 ;; a `table.el' type, just give up. At a table row or
20278 ;; cell, maybe recalculate line but always align table.
20279 (if (eq (org-element-property :type context) 'table.el)
20280 (message "Use C-c ' to edit table.el tables")
20281 (let ((org-enable-table-editor t))
20282 (if (or (eq type 'table)
20283 ;; Check if point is at a TBLFM line.
20284 (and (eq type 'table-row)
20285 (= (point) (org-element-property :end context))))
20286 (save-excursion
20287 (if (org-at-TBLFM-p)
20288 (progn (require 'org-table)
20289 (org-table-calc-current-TBLFM))
20290 (goto-char (org-element-property :contents-begin context))
20291 (org-call-with-arg 'org-table-recalculate (or arg t))
20292 (orgtbl-send-table 'maybe)))
20293 (org-table-maybe-eval-formula)
20294 (cond (arg (call-interactively 'org-table-recalculate))
20295 ((org-table-maybe-recalculate-line))
20296 (t (org-table-align)))))))
20297 (timestamp (org-timestamp-change 0 'day))
20298 (otherwise
20299 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20300 (user-error
20301 "C-c C-c can do nothing useful at this location")))))))))
20303 (defun org-mode-restart ()
20304 "Restart Org-mode, to scan again for special lines.
20305 Also updates the keyword regular expressions."
20306 (interactive)
20307 (org-mode)
20308 (message "Org-mode restarted"))
20310 (defun org-kill-note-or-show-branches ()
20311 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20312 (interactive)
20313 (if (not org-finish-function)
20314 (progn
20315 (hide-subtree)
20316 (call-interactively 'show-branches))
20317 (let ((org-note-abort t))
20318 (funcall org-finish-function))))
20320 (defun org-open-line (n)
20321 "Insert a new row in tables, call `open-line' elsewhere."
20322 (interactive "*p")
20323 (if (org-at-table-p)
20324 (org-table-insert-row)
20325 (open-line n)))
20327 (defun org-return (&optional indent)
20328 "Goto next table row or insert a newline.
20329 Calls `org-table-next-row' or `newline', depending on context.
20330 See the individual commands for more information."
20331 (interactive)
20332 (let (org-ts-what)
20333 (cond
20334 ((or (bobp) (org-in-src-block-p))
20335 (if indent (newline-and-indent) (newline)))
20336 ((org-at-table-p)
20337 (org-table-justify-field-maybe)
20338 (call-interactively 'org-table-next-row))
20339 ;; when `newline-and-indent' is called within a list, make sure
20340 ;; text moved stays inside the item.
20341 ((and (org-in-item-p) indent)
20342 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20343 (progn
20344 (save-match-data (newline))
20345 (org-indent-line-to (length (match-string 0))))
20346 (let ((ind (org-get-indentation)))
20347 (newline)
20348 (if (org-looking-back org-list-end-re)
20349 (org-indent-line)
20350 (org-indent-line-to ind)))))
20351 ((and org-return-follows-link
20352 (org-at-timestamp-p t)
20353 (not (eq org-ts-what 'after)))
20354 (org-follow-timestamp-link))
20355 ((and org-return-follows-link
20356 (let ((tprop (get-text-property (point) 'face)))
20357 (or (eq tprop 'org-link)
20358 (and (listp tprop) (memq 'org-link tprop)))))
20359 (call-interactively 'org-open-at-point))
20360 ((and (org-at-heading-p)
20361 (looking-at
20362 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20363 (org-show-entry)
20364 (end-of-line 1)
20365 (newline))
20366 (t (if indent (newline-and-indent) (newline))))))
20368 (defun org-return-indent ()
20369 "Goto next table row or insert a newline and indent.
20370 Calls `org-table-next-row' or `newline-and-indent', depending on
20371 context. See the individual commands for more information."
20372 (interactive)
20373 (org-return t))
20375 (defun org-ctrl-c-star ()
20376 "Compute table, or change heading status of lines.
20377 Calls `org-table-recalculate' or `org-toggle-heading',
20378 depending on context."
20379 (interactive)
20380 (cond
20381 ((org-at-table-p)
20382 (call-interactively 'org-table-recalculate))
20384 ;; Convert all lines in region to list items
20385 (call-interactively 'org-toggle-heading))))
20387 (defun org-ctrl-c-minus ()
20388 "Insert separator line in table or modify bullet status of line.
20389 Also turns a plain line or a region of lines into list items.
20390 Calls `org-table-insert-hline', `org-toggle-item', or
20391 `org-cycle-list-bullet', depending on context."
20392 (interactive)
20393 (cond
20394 ((org-at-table-p)
20395 (call-interactively 'org-table-insert-hline))
20396 ((org-region-active-p)
20397 (call-interactively 'org-toggle-item))
20398 ((org-in-item-p)
20399 (call-interactively 'org-cycle-list-bullet))
20401 (call-interactively 'org-toggle-item))))
20403 (defun org-toggle-item (arg)
20404 "Convert headings or normal lines to items, items to normal lines.
20405 If there is no active region, only the current line is considered.
20407 If the first non blank line in the region is a headline, convert
20408 all headlines to items, shifting text accordingly.
20410 If it is an item, convert all items to normal lines.
20412 If it is normal text, change region into a list of items.
20413 With a prefix argument ARG, change the region in a single item."
20414 (interactive "P")
20415 (let ((shift-text
20416 (function
20417 ;; Shift text in current section to IND, from point to END.
20418 ;; The function leaves point to END line.
20419 (lambda (ind end)
20420 (let ((min-i 1000) (end (copy-marker end)))
20421 ;; First determine the minimum indentation (MIN-I) of
20422 ;; the text.
20423 (save-excursion
20424 (catch 'exit
20425 (while (< (point) end)
20426 (let ((i (org-get-indentation)))
20427 (cond
20428 ;; Skip blank lines and inline tasks.
20429 ((looking-at "^[ \t]*$"))
20430 ((looking-at org-outline-regexp-bol))
20431 ;; We can't find less than 0 indentation.
20432 ((zerop i) (throw 'exit (setq min-i 0)))
20433 ((< i min-i) (setq min-i i))))
20434 (forward-line))))
20435 ;; Then indent each line so that a line indented to
20436 ;; MIN-I becomes indented to IND. Ignore blank lines
20437 ;; and inline tasks in the process.
20438 (let ((delta (- ind min-i)))
20439 (while (< (point) end)
20440 (unless (or (looking-at "^[ \t]*$")
20441 (looking-at org-outline-regexp-bol))
20442 (org-indent-line-to (+ (org-get-indentation) delta)))
20443 (forward-line)))))))
20444 (skip-blanks
20445 (function
20446 ;; Return beginning of first non-blank line, starting from
20447 ;; line at POS.
20448 (lambda (pos)
20449 (save-excursion
20450 (goto-char pos)
20451 (skip-chars-forward " \r\t\n")
20452 (point-at-bol)))))
20453 beg end)
20454 ;; Determine boundaries of changes.
20455 (if (org-region-active-p)
20456 (setq beg (funcall skip-blanks (region-beginning))
20457 end (copy-marker (region-end)))
20458 (setq beg (funcall skip-blanks (point-at-bol))
20459 end (copy-marker (point-at-eol))))
20460 ;; Depending on the starting line, choose an action on the text
20461 ;; between BEG and END.
20462 (org-with-limited-levels
20463 (save-excursion
20464 (goto-char beg)
20465 (cond
20466 ;; Case 1. Start at an item: de-itemize. Note that it only
20467 ;; happens when a region is active: `org-ctrl-c-minus'
20468 ;; would call `org-cycle-list-bullet' otherwise.
20469 ((org-at-item-p)
20470 (while (< (point) end)
20471 (when (org-at-item-p)
20472 (skip-chars-forward " \t")
20473 (delete-region (point) (match-end 0)))
20474 (forward-line)))
20475 ;; Case 2. Start at an heading: convert to items.
20476 ((org-at-heading-p)
20477 (let* ((bul (org-list-bullet-string "-"))
20478 (bul-len (length bul))
20479 ;; Indentation of the first heading. It should be
20480 ;; relative to the indentation of its parent, if any.
20481 (start-ind (save-excursion
20482 (cond
20483 ((not org-adapt-indentation) 0)
20484 ((not (outline-previous-heading)) 0)
20485 (t (length (match-string 0))))))
20486 ;; Level of first heading. Further headings will be
20487 ;; compared to it to determine hierarchy in the list.
20488 (ref-level (org-reduced-level (org-outline-level))))
20489 (while (< (point) end)
20490 (let* ((level (org-reduced-level (org-outline-level)))
20491 (delta (max 0 (- level ref-level))))
20492 ;; If current headline is less indented than the first
20493 ;; one, set it as reference, in order to preserve
20494 ;; subtrees.
20495 (when (< level ref-level) (setq ref-level level))
20496 (replace-match bul t t)
20497 (org-indent-line-to (+ start-ind (* delta bul-len)))
20498 ;; Ensure all text down to END (or SECTION-END) belongs
20499 ;; to the newly created item.
20500 (let ((section-end (save-excursion
20501 (or (outline-next-heading) (point)))))
20502 (forward-line)
20503 (funcall shift-text
20504 (+ start-ind (* (1+ delta) bul-len))
20505 (min end section-end)))))))
20506 ;; Case 3. Normal line with ARG: make the first line of region
20507 ;; an item, and shift indentation of others lines to
20508 ;; set them as item's body.
20509 (arg (let* ((bul (org-list-bullet-string "-"))
20510 (bul-len (length bul))
20511 (ref-ind (org-get-indentation)))
20512 (skip-chars-forward " \t")
20513 (insert bul)
20514 (forward-line)
20515 (while (< (point) end)
20516 ;; Ensure that lines less indented than first one
20517 ;; still get included in item body.
20518 (funcall shift-text
20519 (+ ref-ind bul-len)
20520 (min end (save-excursion (or (outline-next-heading)
20521 (point)))))
20522 (forward-line))))
20523 ;; Case 4. Normal line without ARG: turn each non-item line
20524 ;; into an item.
20526 (while (< (point) end)
20527 (unless (or (org-at-heading-p) (org-at-item-p))
20528 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20529 (replace-match
20530 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20531 (forward-line))))))))
20533 (defun org-toggle-heading (&optional nstars)
20534 "Convert headings to normal text, or items or text to headings.
20535 If there is no active region, only convert the current line.
20537 With a \\[universal-argument] prefix, convert the whole list at
20538 point into heading.
20540 In a region:
20542 - If the first non blank line is a headline, remove the stars
20543 from all headlines in the region.
20545 - If it is a normal line, turn each and every normal line (i.e.,
20546 not an heading or an item) in the region into headings. If you
20547 want to convert only the first line of this region, use one
20548 universal prefix argument.
20550 - If it is a plain list item, turn all plain list items into headings.
20552 When converting a line into a heading, the number of stars is chosen
20553 such that the lines become children of the current entry. However,
20554 when a numeric prefix argument is given, its value determines the
20555 number of stars to add."
20556 (interactive "P")
20557 (let ((skip-blanks
20558 (function
20559 ;; Return beginning of first non-blank line, starting from
20560 ;; line at POS.
20561 (lambda (pos)
20562 (save-excursion
20563 (goto-char pos)
20564 (while (org-at-comment-p) (forward-line))
20565 (skip-chars-forward " \r\t\n")
20566 (point-at-bol)))))
20567 beg end toggled)
20568 ;; Determine boundaries of changes. If a universal prefix has
20569 ;; been given, put the list in a region. If region ends at a bol,
20570 ;; do not consider the last line to be in the region.
20572 (when (and current-prefix-arg (org-at-item-p))
20573 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20574 (org-mark-element))
20576 (if (org-region-active-p)
20577 (setq beg (funcall skip-blanks (region-beginning))
20578 end (copy-marker (save-excursion
20579 (goto-char (region-end))
20580 (if (bolp) (point) (point-at-eol)))))
20581 (setq beg (funcall skip-blanks (point-at-bol))
20582 end (copy-marker (point-at-eol))))
20583 ;; Ensure inline tasks don't count as headings.
20584 (org-with-limited-levels
20585 (save-excursion
20586 (goto-char beg)
20587 (cond
20588 ;; Case 1. Started at an heading: de-star headings.
20589 ((org-at-heading-p)
20590 (while (< (point) end)
20591 (when (org-at-heading-p t)
20592 (looking-at org-outline-regexp) (replace-match "")
20593 (setq toggled t))
20594 (forward-line)))
20595 ;; Case 2. Started at an item: change items into headlines.
20596 ;; One star will be added by `org-list-to-subtree'.
20597 ((org-at-item-p)
20598 (let* ((stars (make-string
20599 ;; subtract the star that will be added again by
20600 ;; `org-list-to-subtree'
20601 (if (numberp nstars) (1- nstars)
20602 (or (org-current-level) 0))
20603 ?*))
20604 (add-stars
20605 (cond (nstars "") ; stars from prefix only
20606 ((equal stars "") "") ; before first heading
20607 (org-odd-levels-only "*") ; inside heading, odd
20608 (t "")))) ; inside heading, oddeven
20609 (while (< (point) end)
20610 (when (org-at-item-p)
20611 ;; Pay attention to cases when region ends before list.
20612 (let* ((struct (org-list-struct))
20613 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20614 (save-restriction
20615 (narrow-to-region (point) list-end)
20616 (insert
20617 (org-list-to-subtree
20618 (org-list-parse-list t)
20619 '(:istart (concat stars add-stars (funcall get-stars depth))
20620 :icount (concat stars add-stars (funcall get-stars depth)))))))
20621 (setq toggled t))
20622 (forward-line))))
20623 ;; Case 3. Started at normal text: make every line an heading,
20624 ;; skipping headlines and items.
20625 (t (let* ((stars
20626 (make-string
20627 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20628 (add-stars
20629 (cond (nstars "") ; stars from prefix only
20630 ((equal stars "") "*") ; before first heading
20631 (org-odd-levels-only "**") ; inside heading, odd
20632 (t "*"))) ; inside heading, oddeven
20633 (rpl (concat stars add-stars " "))
20634 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20635 (while (< (point) (if (equal nstars '(4)) lend end))
20636 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20637 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20638 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20639 (forward-line)))))))
20640 (unless toggled (message "Cannot toggle heading from here"))))
20642 (defun org-meta-return (&optional arg)
20643 "Insert a new heading or wrap a region in a table.
20644 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20645 See the individual commands for more information."
20646 (interactive "P")
20647 (org-check-before-invisible-edit 'insert)
20648 (cond
20649 ((run-hook-with-args-until-success 'org-metareturn-hook))
20650 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20651 (newline-and-indent))
20652 ((org-at-table-p)
20653 (call-interactively 'org-table-wrap-region))
20654 (t (call-interactively 'org-insert-heading))))
20656 ;;; Menu entries
20658 (defsubst org-in-subtree-not-table-p ()
20659 "Are we in a subtree and not in a table?"
20660 (and (not (org-before-first-heading-p))
20661 (not (org-at-table-p))))
20663 ;; Define the Org-mode menus
20664 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20665 '("Tbl"
20666 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20667 ["Next Field" org-cycle (org-at-table-p)]
20668 ["Previous Field" org-shifttab (org-at-table-p)]
20669 ["Next Row" org-return (org-at-table-p)]
20670 "--"
20671 ["Blank Field" org-table-blank-field (org-at-table-p)]
20672 ["Edit Field" org-table-edit-field (org-at-table-p)]
20673 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20674 "--"
20675 ("Column"
20676 ["Move Column Left" org-metaleft (org-at-table-p)]
20677 ["Move Column Right" org-metaright (org-at-table-p)]
20678 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20679 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20680 ("Row"
20681 ["Move Row Up" org-metaup (org-at-table-p)]
20682 ["Move Row Down" org-metadown (org-at-table-p)]
20683 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20684 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20685 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20686 "--"
20687 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20688 ("Rectangle"
20689 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20690 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20691 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20692 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20693 "--"
20694 ("Calculate"
20695 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20696 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20697 ["Edit Formulas" org-edit-special (org-at-table-p)]
20698 "--"
20699 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20700 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20701 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20702 "--"
20703 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20704 "--"
20705 ["Sum Column/Rectangle" org-table-sum
20706 (or (org-at-table-p) (org-region-active-p))]
20707 ["Which Column?" org-table-current-column (org-at-table-p)])
20708 ["Debug Formulas"
20709 org-table-toggle-formula-debugger
20710 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20711 ["Show Col/Row Numbers"
20712 org-table-toggle-coordinate-overlays
20713 :style toggle
20714 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20715 "--"
20716 ["Create" org-table-create (and (not (org-at-table-p))
20717 org-enable-table-editor)]
20718 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20719 ["Import from File" org-table-import (not (org-at-table-p))]
20720 ["Export to File" org-table-export (org-at-table-p)]
20721 "--"
20722 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20724 (easy-menu-define org-org-menu org-mode-map "Org menu"
20725 '("Org"
20726 ("Show/Hide"
20727 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20728 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20729 ["Sparse Tree..." org-sparse-tree t]
20730 ["Reveal Context" org-reveal t]
20731 ["Show All" show-all t]
20732 "--"
20733 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20734 "--"
20735 ["New Heading" org-insert-heading t]
20736 ("Navigate Headings"
20737 ["Up" outline-up-heading t]
20738 ["Next" outline-next-visible-heading t]
20739 ["Previous" outline-previous-visible-heading t]
20740 ["Next Same Level" outline-forward-same-level t]
20741 ["Previous Same Level" outline-backward-same-level t]
20742 "--"
20743 ["Jump" org-goto t])
20744 ("Edit Structure"
20745 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20746 "--"
20747 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20748 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20749 "--"
20750 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20751 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20752 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20753 "--"
20754 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20755 "--"
20756 ["Copy visible text" org-copy-visible t]
20757 "--"
20758 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20759 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20760 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20761 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20762 "--"
20763 ["Sort Region/Children" org-sort t]
20764 "--"
20765 ["Convert to odd levels" org-convert-to-odd-levels t]
20766 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20767 ("Editing"
20768 ["Emphasis..." org-emphasize t]
20769 ["Edit Source Example" org-edit-special t]
20770 "--"
20771 ["Footnote new/jump" org-footnote-action t]
20772 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20773 ("Archive"
20774 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20775 "--"
20776 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20777 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20778 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20780 "--"
20781 ("Hyperlinks"
20782 ["Store Link (Global)" org-store-link t]
20783 ["Find existing link to here" org-occur-link-in-agenda-files t]
20784 ["Insert Link" org-insert-link t]
20785 ["Follow Link" org-open-at-point t]
20786 "--"
20787 ["Next link" org-next-link t]
20788 ["Previous link" org-previous-link t]
20789 "--"
20790 ["Descriptive Links"
20791 org-toggle-link-display
20792 :style radio
20793 :selected org-descriptive-links
20795 ["Literal Links"
20796 org-toggle-link-display
20797 :style radio
20798 :selected (not org-descriptive-links)])
20799 "--"
20800 ("TODO Lists"
20801 ["TODO/DONE/-" org-todo t]
20802 ("Select keyword"
20803 ["Next keyword" org-shiftright (org-at-heading-p)]
20804 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20805 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20806 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20807 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20808 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20809 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20810 "--"
20811 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20812 :selected org-enforce-todo-dependencies :style toggle :active t]
20813 "Settings for tree at point"
20814 ["Do Children sequentially" org-toggle-ordered-property :style radio
20815 :selected (org-entry-get nil "ORDERED")
20816 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20817 ["Do Children parallel" org-toggle-ordered-property :style radio
20818 :selected (not (org-entry-get nil "ORDERED"))
20819 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20820 "--"
20821 ["Set Priority" org-priority t]
20822 ["Priority Up" org-shiftup t]
20823 ["Priority Down" org-shiftdown t]
20824 "--"
20825 ["Get news from all feeds" org-feed-update-all t]
20826 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20827 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20828 ("TAGS and Properties"
20829 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20830 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20831 "--"
20832 ["Set property" org-set-property (not (org-before-first-heading-p))]
20833 ["Column view of properties" org-columns t]
20834 ["Insert Column View DBlock" org-insert-columns-dblock t])
20835 ("Dates and Scheduling"
20836 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20837 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20838 ("Change Date"
20839 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20840 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20841 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20842 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20843 ["Compute Time Range" org-evaluate-time-range t]
20844 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20845 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20846 "--"
20847 ["Custom time format" org-toggle-time-stamp-overlays
20848 :style radio :selected org-display-custom-times]
20849 "--"
20850 ["Goto Calendar" org-goto-calendar t]
20851 ["Date from Calendar" org-date-from-calendar t]
20852 "--"
20853 ["Start/Restart Timer" org-timer-start t]
20854 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20855 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20856 ["Insert Timer String" org-timer t]
20857 ["Insert Timer Item" org-timer-item t])
20858 ("Logging work"
20859 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20860 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20861 ["Clock out" org-clock-out t]
20862 ["Clock cancel" org-clock-cancel t]
20863 "--"
20864 ["Mark as default task" org-clock-mark-default-task t]
20865 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20866 ["Goto running clock" org-clock-goto t]
20867 "--"
20868 ["Display times" org-clock-display t]
20869 ["Create clock table" org-clock-report t]
20870 "--"
20871 ["Record DONE time"
20872 (progn (setq org-log-done (not org-log-done))
20873 (message "Switching to %s will %s record a timestamp"
20874 (car org-done-keywords)
20875 (if org-log-done "automatically" "not")))
20876 :style toggle :selected org-log-done])
20877 "--"
20878 ["Agenda Command..." org-agenda t]
20879 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20880 ("File List for Agenda")
20881 ("Special views current file"
20882 ["TODO Tree" org-show-todo-tree t]
20883 ["Check Deadlines" org-check-deadlines t]
20884 ["Timeline" org-timeline t]
20885 ["Tags/Property tree" org-match-sparse-tree t])
20886 "--"
20887 ["Export/Publish..." org-export-dispatch t]
20888 ("LaTeX"
20889 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20890 :selected org-cdlatex-mode]
20891 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20892 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20893 ["Modify math symbol" org-cdlatex-math-modify
20894 (org-inside-LaTeX-fragment-p)]
20895 ["Insert citation" org-reftex-citation t]
20896 "--"
20897 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20898 "--"
20899 ("MobileOrg"
20900 ["Push Files and Views" org-mobile-push t]
20901 ["Get Captured and Flagged" org-mobile-pull t]
20902 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20903 "--"
20904 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20905 "--"
20906 ("Documentation"
20907 ["Show Version" org-version t]
20908 ["Info Documentation" org-info t])
20909 ("Customize"
20910 ["Browse Org Group" org-customize t]
20911 "--"
20912 ["Expand This Menu" org-create-customize-menu
20913 (fboundp 'customize-menu-create)])
20914 ["Send bug report" org-submit-bug-report t]
20915 "--"
20916 ("Refresh/Reload"
20917 ["Refresh setup current buffer" org-mode-restart t]
20918 ["Reload Org (after update)" org-reload t]
20919 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20922 (defun org-info (&optional node)
20923 "Read documentation for Org-mode in the info system.
20924 With optional NODE, go directly to that node."
20925 (interactive)
20926 (info (format "(org)%s" (or node ""))))
20928 ;;;###autoload
20929 (defun org-submit-bug-report ()
20930 "Submit a bug report on Org-mode via mail.
20932 Don't hesitate to report any problems or inaccurate documentation.
20934 If you don't have setup sending mail from (X)Emacs, please copy the
20935 output buffer into your mail program, as it gives us important
20936 information about your Org-mode version and configuration."
20937 (interactive)
20938 (require 'reporter)
20939 (org-load-modules-maybe)
20940 (org-require-autoloaded-modules)
20941 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20942 (reporter-submit-bug-report
20943 "emacs-orgmode@gnu.org"
20944 (org-version nil 'full)
20945 (let (list)
20946 (save-window-excursion
20947 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20948 (delete-other-windows)
20949 (erase-buffer)
20950 (insert "You are about to submit a bug report to the Org-mode mailing list.
20952 We would like to add your full Org-mode and Outline configuration to the
20953 bug report. This greatly simplifies the work of the maintainer and
20954 other experts on the mailing list.
20956 HOWEVER, some variables you have customized may contain private
20957 information. The names of customers, colleagues, or friends, might
20958 appear in the form of file names, tags, todo states, or search strings.
20959 If you answer yes to the prompt, you might want to check and remove
20960 such private information before sending the email.")
20961 (add-text-properties (point-min) (point-max) '(face org-warning))
20962 (when (yes-or-no-p "Include your Org-mode configuration ")
20963 (mapatoms
20964 (lambda (v)
20965 (and (boundp v)
20966 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20967 (or (and (symbol-value v)
20968 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20969 (and
20970 (get v 'custom-type) (get v 'standard-value)
20971 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20972 (push v list)))))
20973 (kill-buffer (get-buffer "*Warn about privacy*"))
20974 list))
20975 nil nil
20976 "Remember to cover the basics, that is, what you expected to happen and
20977 what in fact did happen. You don't know how to make a good report? See
20979 http://orgmode.org/manual/Feedback.html#Feedback
20981 Your bug report will be posted to the Org-mode mailing list.
20982 ------------------------------------------------------------------------")
20983 (save-excursion
20984 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20985 (replace-match "\\1Bug: \\3 [\\2]")))))
20988 (defun org-install-agenda-files-menu ()
20989 (let ((bl (buffer-list)))
20990 (save-excursion
20991 (while bl
20992 (set-buffer (pop bl))
20993 (if (derived-mode-p 'org-mode) (setq bl nil)))
20994 (when (derived-mode-p 'org-mode)
20995 (easy-menu-change
20996 '("Org") "File List for Agenda"
20997 (append
20998 (list
20999 ["Edit File List" (org-edit-agenda-file-list) t]
21000 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21001 ["Remove Current File from List" org-remove-file t]
21002 ["Cycle through agenda files" org-cycle-agenda-files t]
21003 ["Occur in all agenda files" org-occur-in-agenda-files t]
21004 "--")
21005 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21007 ;;;; Documentation
21009 (defun org-require-autoloaded-modules ()
21010 (interactive)
21011 (mapc 'require
21012 '(org-agenda org-archive org-attach org-clock org-colview org-id
21013 org-remember org-table org-timer)))
21015 ;;;###autoload
21016 (defun org-reload (&optional uncompiled)
21017 "Reload all org lisp files.
21018 With prefix arg UNCOMPILED, load the uncompiled versions."
21019 (interactive "P")
21020 (require 'loadhist)
21021 (let* ((org-dir (org-find-library-dir "org"))
21022 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21023 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21024 (remove-re (mapconcat 'identity
21025 (mapcar (lambda (f) (concat "^" f "$"))
21026 (list (if (featurep 'xemacs)
21027 "org-colview"
21028 "org-colview-xemacs")
21029 "org" "org-loaddefs" "org-version"))
21030 "\\|"))
21031 (feats (delete-dups
21032 (mapcar 'file-name-sans-extension
21033 (mapcar 'file-name-nondirectory
21034 (delq nil
21035 (mapcar 'feature-file
21036 features))))))
21037 (lfeat (append
21038 (sort
21039 (setq feats
21040 (delq nil (mapcar
21041 (lambda (f)
21042 (if (and (string-match feature-re f)
21043 (not (string-match remove-re f)))
21044 f nil))
21045 feats)))
21046 'string-lessp)
21047 (list "org-version" "org")))
21048 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21049 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21050 load-uncore load-misses)
21051 (setq load-misses
21052 (delq 't
21053 (mapcar (lambda (f)
21054 (or (org-load-noerror-mustsuffix (concat org-dir f))
21055 (and (string= org-dir contrib-dir)
21056 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21057 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21058 (add-to-list 'load-uncore f 'append)
21061 lfeat)))
21062 (if load-uncore
21063 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21064 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21065 (if load-misses
21066 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21067 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21068 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21070 ;;;###autoload
21071 (defun org-customize ()
21072 "Call the customize function with org as argument."
21073 (interactive)
21074 (org-load-modules-maybe)
21075 (org-require-autoloaded-modules)
21076 (customize-browse 'org))
21078 (defun org-create-customize-menu ()
21079 "Create a full customization menu for Org-mode, insert it into the menu."
21080 (interactive)
21081 (org-load-modules-maybe)
21082 (org-require-autoloaded-modules)
21083 (if (fboundp 'customize-menu-create)
21084 (progn
21085 (easy-menu-change
21086 '("Org") "Customize"
21087 `(["Browse Org group" org-customize t]
21088 "--"
21089 ,(customize-menu-create 'org)
21090 ["Set" Custom-set t]
21091 ["Save" Custom-save t]
21092 ["Reset to Current" Custom-reset-current t]
21093 ["Reset to Saved" Custom-reset-saved t]
21094 ["Reset to Standard Settings" Custom-reset-standard t]))
21095 (message "\"Org\"-menu now contains full customization menu"))
21096 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21098 ;;;; Miscellaneous stuff
21100 ;;; Generally useful functions
21102 (defun org-get-at-bol (property)
21103 "Get text property PROPERTY at beginning of line."
21104 (get-text-property (point-at-bol) property))
21106 (defun org-find-text-property-in-string (prop s)
21107 "Return the first non-nil value of property PROP in string S."
21108 (or (get-text-property 0 prop s)
21109 (get-text-property (or (next-single-property-change 0 prop s) 0)
21110 prop s)))
21112 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21113 "Display the given MESSAGE as a warning."
21114 (if (fboundp 'display-warning)
21115 (display-warning 'org message
21116 (if (featurep 'xemacs) 'warning :warning))
21117 (let ((buf (get-buffer-create "*Org warnings*")))
21118 (with-current-buffer buf
21119 (goto-char (point-max))
21120 (insert "Warning (Org): " message)
21121 (unless (bolp)
21122 (newline)))
21123 (display-buffer buf)
21124 (sit-for 0))))
21126 (defun org-eval (form)
21127 "Eval FORM and return result."
21128 (condition-case error
21129 (eval form)
21130 (error (format "%%![Error: %s]" error))))
21132 (defun org-in-clocktable-p ()
21133 "Check if the cursor is in a clocktable."
21134 (let ((pos (point)) start)
21135 (save-excursion
21136 (end-of-line 1)
21137 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21138 (setq start (match-beginning 0))
21139 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21140 (>= (match-end 0) pos)
21141 start))))
21143 (defun org-in-commented-line ()
21144 "Is point in a line starting with `#'?"
21145 (equal (char-after (point-at-bol)) ?#))
21147 (defun org-in-indented-comment-line ()
21148 "Is point in a line starting with `#' after some white space?"
21149 (save-excursion
21150 (save-match-data
21151 (goto-char (point-at-bol))
21152 (looking-at "[ \t]*#"))))
21154 (defun org-in-verbatim-emphasis ()
21155 (save-match-data
21156 (and (org-in-regexp org-emph-re 2)
21157 (>= (point) (match-beginning 3))
21158 (<= (point) (match-end 4))
21159 (member (match-string 3) '("=" "~")))))
21161 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21162 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21163 (if (and marker (marker-buffer marker)
21164 (buffer-live-p (marker-buffer marker)))
21165 (progn
21166 (org-pop-to-buffer-same-window (marker-buffer marker))
21167 (if (or (> marker (point-max)) (< marker (point-min)))
21168 (widen))
21169 (goto-char marker)
21170 (org-show-context 'org-goto))
21171 (if bookmark
21172 (bookmark-jump bookmark)
21173 (error "Cannot find location"))))
21175 (defun org-quote-csv-field (s)
21176 "Quote field for inclusion in CSV material."
21177 (if (string-match "[\",]" s)
21178 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21181 (defun org-force-self-insert (N)
21182 "Needed to enforce self-insert under remapping."
21183 (interactive "p")
21184 (self-insert-command N))
21186 (defun org-string-width (s)
21187 "Compute width of string, ignoring invisible characters.
21188 This ignores character with invisibility property `org-link', and also
21189 characters with property `org-cwidth', because these will become invisible
21190 upon the next fontification round."
21191 (let (b l)
21192 (when (or (eq t buffer-invisibility-spec)
21193 (assq 'org-link buffer-invisibility-spec))
21194 (while (setq b (text-property-any 0 (length s)
21195 'invisible 'org-link s))
21196 (setq s (concat (substring s 0 b)
21197 (substring s (or (next-single-property-change
21198 b 'invisible s) (length s)))))))
21199 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21200 (setq s (concat (substring s 0 b)
21201 (substring s (or (next-single-property-change
21202 b 'org-cwidth s) (length s))))))
21203 (setq l (string-width s) b -1)
21204 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21205 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21208 (defun org-shorten-string (s maxlength)
21209 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21210 If the string is shorter or has length MAXLENGTH, just return the
21211 original string. If it is longer, the functions finds a space in the
21212 string, breaks this string off at that locations and adds three dots
21213 as ellipsis. Including the ellipsis, the string will not be longer
21214 than MAXLENGTH. If finding a good breaking point in the string does
21215 not work, the string is just chopped off in the middle of a word
21216 if necessary."
21217 (if (<= (length s) maxlength)
21219 (let* ((n (max (- maxlength 4) 1))
21220 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21221 (if (string-match re s)
21222 (concat (match-string 1 s) "...")
21223 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21225 (defun org-get-indentation (&optional line)
21226 "Get the indentation of the current line, interpreting tabs.
21227 When LINE is given, assume it represents a line and compute its indentation."
21228 (if line
21229 (if (string-match "^ *" (org-remove-tabs line))
21230 (match-end 0))
21231 (save-excursion
21232 (beginning-of-line 1)
21233 (skip-chars-forward " \t")
21234 (current-column))))
21236 (defun org-get-string-indentation (s)
21237 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21238 (let ((n -1) (i 0) (w tab-width) c)
21239 (catch 'exit
21240 (while (< (setq n (1+ n)) (length s))
21241 (setq c (aref s n))
21242 (cond ((= c ?\ ) (setq i (1+ i)))
21243 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21244 (t (throw 'exit t)))))
21247 (defun org-remove-tabs (s &optional width)
21248 "Replace tabulators in S with spaces.
21249 Assumes that s is a single line, starting in column 0."
21250 (setq width (or width tab-width))
21251 (while (string-match "\t" s)
21252 (setq s (replace-match
21253 (make-string
21254 (- (* width (/ (+ (match-beginning 0) width) width))
21255 (match-beginning 0)) ?\ )
21256 t t s)))
21259 (defun org-fix-indentation (line ind)
21260 "Fix indentation in LINE.
21261 IND is a cons cell with target and minimum indentation.
21262 If the current indentation in LINE is smaller than the minimum,
21263 leave it alone. If it is larger than ind, set it to the target."
21264 (let* ((l (org-remove-tabs line))
21265 (i (org-get-indentation l))
21266 (i1 (car ind)) (i2 (cdr ind)))
21267 (if (>= i i2) (setq l (substring line i2)))
21268 (if (> i1 0)
21269 (concat (make-string i1 ?\ ) l)
21270 l)))
21272 (defun org-remove-indentation (code &optional n)
21273 "Remove the maximum common indentation from the lines in CODE.
21274 N may optionally be the number of spaces to remove."
21275 (with-temp-buffer
21276 (insert code)
21277 (org-do-remove-indentation n)
21278 (buffer-string)))
21280 (defun org-do-remove-indentation (&optional n)
21281 "Remove the maximum common indentation from the buffer."
21282 (untabify (point-min) (point-max))
21283 (let ((min 10000) re)
21284 (if n
21285 (setq min n)
21286 (goto-char (point-min))
21287 (while (re-search-forward "^ *[^ \n]" nil t)
21288 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21289 (unless (or (= min 0) (= min 10000))
21290 (setq re (format "^ \\{%d\\}" min))
21291 (goto-char (point-min))
21292 (while (re-search-forward re nil t)
21293 (replace-match "")
21294 (end-of-line 1))
21295 min)))
21297 (defun org-fill-template (template alist)
21298 "Find each %key of ALIST in TEMPLATE and replace it."
21299 (let ((case-fold-search nil)
21300 entry key value)
21301 (setq alist (sort (copy-sequence alist)
21302 (lambda (a b) (< (length (car a)) (length (car b))))))
21303 (while (setq entry (pop alist))
21304 (setq template
21305 (replace-regexp-in-string
21306 (concat "%" (regexp-quote (car entry)))
21307 (or (cdr entry) "") template t t)))
21308 template))
21310 (defun org-base-buffer (buffer)
21311 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21312 (if (not buffer)
21313 buffer
21314 (or (buffer-base-buffer buffer)
21315 buffer)))
21317 (defun org-trim (s)
21318 "Remove whitespace at beginning and end of string."
21319 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21320 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21323 (defun org-wrap (string &optional width lines)
21324 "Wrap string to either a number of lines, or a width in characters.
21325 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21326 that costs. If there is a word longer than WIDTH, the text is actually
21327 wrapped to the length of that word.
21328 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21329 many lines, whatever width that takes.
21330 The return value is a list of lines, without newlines at the end."
21331 (let* ((words (org-split-string string "[ \t\n]+"))
21332 (maxword (apply 'max (mapcar 'org-string-width words)))
21333 w ll)
21334 (cond (width
21335 (org-do-wrap words (max maxword width)))
21336 (lines
21337 (setq w maxword)
21338 (setq ll (org-do-wrap words maxword))
21339 (if (<= (length ll) lines)
21341 (setq ll words)
21342 (while (> (length ll) lines)
21343 (setq w (1+ w))
21344 (setq ll (org-do-wrap words w)))
21345 ll))
21346 (t (error "Cannot wrap this")))))
21348 (defun org-do-wrap (words width)
21349 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21350 (let (lines line)
21351 (while words
21352 (setq line (pop words))
21353 (while (and words (< (+ (length line) (length (car words))) width))
21354 (setq line (concat line " " (pop words))))
21355 (setq lines (push line lines)))
21356 (nreverse lines)))
21358 (defun org-split-string (string &optional separators)
21359 "Splits STRING into substrings at SEPARATORS.
21360 No empty strings are returned if there are matches at the beginning
21361 and end of string."
21362 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21363 (start 0)
21364 notfirst
21365 (list nil))
21366 (while (and (string-match rexp string
21367 (if (and notfirst
21368 (= start (match-beginning 0))
21369 (< start (length string)))
21370 (1+ start) start))
21371 (< (match-beginning 0) (length string)))
21372 (setq notfirst t)
21373 (or (eq (match-beginning 0) 0)
21374 (and (eq (match-beginning 0) (match-end 0))
21375 (eq (match-beginning 0) start))
21376 (setq list
21377 (cons (substring string start (match-beginning 0))
21378 list)))
21379 (setq start (match-end 0)))
21380 (or (eq start (length string))
21381 (setq list
21382 (cons (substring string start)
21383 list)))
21384 (nreverse list)))
21386 (defun org-quote-vert (s)
21387 "Replace \"|\" with \"\\vert\"."
21388 (while (string-match "|" s)
21389 (setq s (replace-match "\\vert" t t s)))
21392 (defun org-uuidgen-p (s)
21393 "Is S an ID created by UUIDGEN?"
21394 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21396 (defun org-in-src-block-p (&optional inside)
21397 "Whether point is in a code source block.
21398 When INSIDE is non-nil, don't consider we are within a src block
21399 when point is at #+BEGIN_SRC or #+END_SRC."
21400 (let ((case-fold-search t) ov)
21401 (or (and (setq ov (overlays-at (point)))
21402 (memq 'org-block-background
21403 (overlay-properties (car ov))))
21404 (and (not inside)
21405 (save-match-data
21406 (save-excursion
21407 (beginning-of-line)
21408 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21410 (defun org-context ()
21411 "Return a list of contexts of the current cursor position.
21412 If several contexts apply, all are returned.
21413 Each context entry is a list with a symbol naming the context, and
21414 two positions indicating start and end of the context. Possible
21415 contexts are:
21417 :headline anywhere in a headline
21418 :headline-stars on the leading stars in a headline
21419 :todo-keyword on a TODO keyword (including DONE) in a headline
21420 :tags on the TAGS in a headline
21421 :priority on the priority cookie in a headline
21422 :item on the first line of a plain list item
21423 :item-bullet on the bullet/number of a plain list item
21424 :checkbox on the checkbox in a plain list item
21425 :table in an org-mode table
21426 :table-special on a special filed in a table
21427 :table-table in a table.el table
21428 :clocktable in a clocktable
21429 :src-block in a source block
21430 :link on a hyperlink
21431 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21432 :target on a <<target>>
21433 :radio-target on a <<<radio-target>>>
21434 :latex-fragment on a LaTeX fragment
21435 :latex-preview on a LaTeX fragment with overlaid preview image
21437 This function expects the position to be visible because it uses font-lock
21438 faces as a help to recognize the following contexts: :table-special, :link,
21439 and :keyword."
21440 (let* ((f (get-text-property (point) 'face))
21441 (faces (if (listp f) f (list f)))
21442 (case-fold-search t)
21443 (p (point)) clist o)
21444 ;; First the large context
21445 (cond
21446 ((org-at-heading-p t)
21447 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21448 (when (progn
21449 (beginning-of-line 1)
21450 (looking-at org-todo-line-tags-regexp))
21451 (push (org-point-in-group p 1 :headline-stars) clist)
21452 (push (org-point-in-group p 2 :todo-keyword) clist)
21453 (push (org-point-in-group p 4 :tags) clist))
21454 (goto-char p)
21455 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21456 (if (looking-at "\\[#[A-Z0-9]\\]")
21457 (push (org-point-in-group p 0 :priority) clist)))
21459 ((org-at-item-p)
21460 (push (org-point-in-group p 2 :item-bullet) clist)
21461 (push (list :item (point-at-bol)
21462 (save-excursion (org-end-of-item) (point)))
21463 clist)
21464 (and (org-at-item-checkbox-p)
21465 (push (org-point-in-group p 0 :checkbox) clist)))
21467 ((org-at-table-p)
21468 (push (list :table (org-table-begin) (org-table-end)) clist)
21469 (if (memq 'org-formula faces)
21470 (push (list :table-special
21471 (previous-single-property-change p 'face)
21472 (next-single-property-change p 'face)) clist)))
21473 ((org-at-table-p 'any)
21474 (push (list :table-table) clist)))
21475 (goto-char p)
21477 (let ((case-fold-search t))
21478 ;; New the "medium" contexts: clocktables, source blocks
21479 (cond ((org-in-clocktable-p)
21480 (push (list :clocktable
21481 (and (or (looking-at "#\\+BEGIN: clocktable")
21482 (search-backward "#+BEGIN: clocktable" nil t))
21483 (match-beginning 0))
21484 (and (re-search-forward "#\\+END:?" nil t)
21485 (match-end 0))) clist))
21486 ((org-in-src-block-p)
21487 (push (list :src-block
21488 (and (or (looking-at "#\\+BEGIN_SRC")
21489 (search-backward "#+BEGIN_SRC" nil t))
21490 (match-beginning 0))
21491 (and (search-forward "#+END_SRC" nil t)
21492 (match-beginning 0))) clist))))
21493 (goto-char p)
21495 ;; Now the small context
21496 (cond
21497 ((org-at-timestamp-p)
21498 (push (org-point-in-group p 0 :timestamp) clist))
21499 ((memq 'org-link faces)
21500 (push (list :link
21501 (previous-single-property-change p 'face)
21502 (next-single-property-change p 'face)) clist))
21503 ((memq 'org-special-keyword faces)
21504 (push (list :keyword
21505 (previous-single-property-change p 'face)
21506 (next-single-property-change p 'face)) clist))
21507 ((org-at-target-p)
21508 (push (org-point-in-group p 0 :target) clist)
21509 (goto-char (1- (match-beginning 0)))
21510 (if (looking-at org-radio-target-regexp)
21511 (push (org-point-in-group p 0 :radio-target) clist))
21512 (goto-char p))
21513 ((setq o (car (delq nil
21514 (mapcar
21515 (lambda (x)
21516 (if (memq x org-latex-fragment-image-overlays) x))
21517 (overlays-at (point))))))
21518 (push (list :latex-fragment
21519 (overlay-start o) (overlay-end o)) clist)
21520 (push (list :latex-preview
21521 (overlay-start o) (overlay-end o)) clist))
21522 ((org-inside-LaTeX-fragment-p)
21523 ;; FIXME: positions wrong.
21524 (push (list :latex-fragment (point) (point)) clist)))
21526 (setq clist (nreverse (delq nil clist)))
21527 clist))
21529 ;; FIXME: Compare with at-regexp-p Do we need both?
21530 (defun org-in-regexp (re &optional nlines visually)
21531 "Check if point is inside a match of regexp.
21532 Normally only the current line is checked, but you can include NLINES extra
21533 lines both before and after point into the search.
21534 If VISUALLY is set, require that the cursor is not after the match but
21535 really on, so that the block visually is on the match."
21536 (catch 'exit
21537 (let ((pos (point))
21538 (eol (point-at-eol (+ 1 (or nlines 0))))
21539 (inc (if visually 1 0)))
21540 (save-excursion
21541 (beginning-of-line (- 1 (or nlines 0)))
21542 (while (re-search-forward re eol t)
21543 (if (and (<= (match-beginning 0) pos)
21544 (>= (+ inc (match-end 0)) pos))
21545 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21547 (defun org-at-regexp-p (regexp)
21548 "Is point inside a match of REGEXP in the current line?"
21549 (catch 'exit
21550 (save-excursion
21551 (let ((pos (point)) (end (point-at-eol)))
21552 (beginning-of-line 1)
21553 (while (re-search-forward regexp end t)
21554 (if (and (<= (match-beginning 0) pos)
21555 (>= (match-end 0) pos))
21556 (throw 'exit t)))
21557 nil))))
21559 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21560 "Non-nil when point is between matches of START-RE and END-RE.
21562 Also return a non-nil value when point is on one of the matches.
21564 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21565 buffer positions. Default values are the positions of headlines
21566 surrounding the point.
21568 The functions returns a cons cell whose car (resp. cdr) is the
21569 position before START-RE (resp. after END-RE)."
21570 (save-match-data
21571 (let ((pos (point))
21572 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21573 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21574 beg end)
21575 (save-excursion
21576 ;; Point is on a block when on START-RE or if START-RE can be
21577 ;; found before it...
21578 (and (or (org-at-regexp-p start-re)
21579 (re-search-backward start-re limit-up t))
21580 (setq beg (match-beginning 0))
21581 ;; ... and END-RE after it...
21582 (goto-char (match-end 0))
21583 (re-search-forward end-re limit-down t)
21584 (> (setq end (match-end 0)) pos)
21585 ;; ... without another START-RE in-between.
21586 (goto-char (match-beginning 0))
21587 (not (re-search-backward start-re (1+ beg) t))
21588 ;; Return value.
21589 (cons beg end))))))
21591 (defun org-in-block-p (names)
21592 "Non-nil when point belongs to a block whose name belongs to NAMES.
21594 NAMES is a list of strings containing names of blocks.
21596 Return first block name matched, or nil. Beware that in case of
21597 nested blocks, the returned name may not belong to the closest
21598 block from point."
21599 (save-match-data
21600 (catch 'exit
21601 (let ((case-fold-search t)
21602 (lim-up (save-excursion (outline-previous-heading)))
21603 (lim-down (save-excursion (outline-next-heading))))
21604 (mapc (lambda (name)
21605 (let ((n (regexp-quote name)))
21606 (when (org-between-regexps-p
21607 (concat "^[ \t]*#\\+begin_" n)
21608 (concat "^[ \t]*#\\+end_" n)
21609 lim-up lim-down)
21610 (throw 'exit n))))
21611 names))
21612 nil)))
21614 (defun org-in-drawer-p ()
21615 "Is point within a drawer?"
21616 (save-match-data
21617 (let ((case-fold-search t)
21618 (lim-up (save-excursion (outline-previous-heading)))
21619 (lim-down (save-excursion (outline-next-heading))))
21620 (org-between-regexps-p
21621 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21622 "^[ \t]*:end:.*$"
21623 lim-up lim-down))))
21625 (defun org-occur-in-agenda-files (regexp &optional nlines)
21626 "Call `multi-occur' with buffers for all agenda files."
21627 (interactive "sOrg-files matching: \np")
21628 (let* ((files (org-agenda-files))
21629 (tnames (mapcar 'file-truename files))
21630 (extra org-agenda-text-search-extra-files)
21632 (when (eq (car extra) 'agenda-archives)
21633 (setq extra (cdr extra))
21634 (setq files (org-add-archive-files files)))
21635 (while (setq f (pop extra))
21636 (unless (member (file-truename f) tnames)
21637 (add-to-list 'files f 'append)
21638 (add-to-list 'tnames (file-truename f) 'append)))
21639 (multi-occur
21640 (mapcar (lambda (x)
21641 (with-current-buffer
21642 (or (get-file-buffer x) (find-file-noselect x))
21643 (widen)
21644 (current-buffer)))
21645 files)
21646 regexp)))
21648 (if (boundp 'occur-mode-find-occurrence-hook)
21649 ;; Emacs 23
21650 (add-hook 'occur-mode-find-occurrence-hook
21651 (lambda ()
21652 (when (derived-mode-p 'org-mode)
21653 (org-reveal))))
21654 ;; Emacs 22
21655 (defadvice occur-mode-goto-occurrence
21656 (after org-occur-reveal activate)
21657 (and (derived-mode-p 'org-mode) (org-reveal)))
21658 (defadvice occur-mode-goto-occurrence-other-window
21659 (after org-occur-reveal activate)
21660 (and (derived-mode-p 'org-mode) (org-reveal)))
21661 (defadvice occur-mode-display-occurrence
21662 (after org-occur-reveal activate)
21663 (when (derived-mode-p 'org-mode)
21664 (let ((pos (occur-mode-find-occurrence)))
21665 (with-current-buffer (marker-buffer pos)
21666 (save-excursion
21667 (goto-char pos)
21668 (org-reveal)))))))
21670 (defun org-occur-link-in-agenda-files ()
21671 "Create a link and search for it in the agendas.
21672 The link is not stored in `org-stored-links', it is just created
21673 for the search purpose."
21674 (interactive)
21675 (let ((link (condition-case nil
21676 (org-store-link nil)
21677 (error "Unable to create a link to here"))))
21678 (org-occur-in-agenda-files (regexp-quote link))))
21680 (defun org-reverse-string (string)
21681 "Return the reverse of STRING."
21682 (apply 'string (reverse (string-to-list string))))
21684 (defsubst org-uniquify (list)
21685 "Non-destructively remove duplicate elements from LIST."
21686 (let ((res (copy-sequence list))) (delete-dups res)))
21688 (defun org-uniquify-alist (alist)
21689 "Merge elements of ALIST with the same key.
21691 For example, in this alist:
21693 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21694 => '((a 1 3) (b 2))
21696 merge (a 1) and (a 3) into (a 1 3).
21698 The function returns the new ALIST."
21699 (let (rtn)
21700 (mapc
21701 (lambda (e)
21702 (let (n)
21703 (if (not (assoc (car e) rtn))
21704 (push e rtn)
21705 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21706 (setq rtn (assq-delete-all (car e) rtn))
21707 (push n rtn))))
21708 alist)
21709 rtn))
21711 (defun org-delete-all (elts list)
21712 "Remove all elements in ELTS from LIST."
21713 (while elts
21714 (setq list (delete (pop elts) list)))
21715 list)
21717 (defun org-count (cl-item cl-seq)
21718 "Count the number of occurrences of ITEM in SEQ.
21719 Taken from `count' in cl-seq.el with all keyword arguments removed."
21720 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21721 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21722 (while (< cl-start cl-end)
21723 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21724 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21725 (setq cl-start (1+ cl-start)))
21726 cl-count))
21728 (defun org-remove-if (predicate seq)
21729 "Remove everything from SEQ that fulfills PREDICATE."
21730 (let (res e)
21731 (while seq
21732 (setq e (pop seq))
21733 (if (not (funcall predicate e)) (push e res)))
21734 (nreverse res)))
21736 (defun org-remove-if-not (predicate seq)
21737 "Remove everything from SEQ that does not fulfill PREDICATE."
21738 (let (res e)
21739 (while seq
21740 (setq e (pop seq))
21741 (if (funcall predicate e) (push e res)))
21742 (nreverse res)))
21744 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21745 "Reduce two-argument FUNCTION across SEQ.
21746 Taken from `reduce' in cl-seq.el with all keyword arguments but
21747 \":initial-value\" removed."
21748 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21749 (cadr (memq :initial-value cl-keys)))
21750 (cl-seq (pop cl-seq))
21751 (t (funcall cl-func)))))
21752 (while cl-seq
21753 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21754 cl-accum))
21756 (defun org-back-over-empty-lines ()
21757 "Move backwards over whitespace, to the beginning of the first empty line.
21758 Returns the number of empty lines passed."
21759 (let ((pos (point)))
21760 (if (cdr (assoc 'heading org-blank-before-new-entry))
21761 (skip-chars-backward " \t\n\r")
21762 (unless (eobp)
21763 (forward-line -1)))
21764 (beginning-of-line 2)
21765 (goto-char (min (point) pos))
21766 (count-lines (point) pos)))
21768 (defun org-skip-whitespace ()
21769 (skip-chars-forward " \t\n\r"))
21771 (defun org-point-in-group (point group &optional context)
21772 "Check if POINT is in match-group GROUP.
21773 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21774 match. If the match group does not exist or point is not inside it,
21775 return nil."
21776 (and (match-beginning group)
21777 (>= point (match-beginning group))
21778 (<= point (match-end group))
21779 (if context
21780 (list context (match-beginning group) (match-end group))
21781 t)))
21783 (defun org-switch-to-buffer-other-window (&rest args)
21784 "Switch to buffer in a second window on the current frame.
21785 In particular, do not allow pop-up frames.
21786 Returns the newly created buffer."
21787 (org-no-popups
21788 (apply 'switch-to-buffer-other-window args)))
21790 (defun org-combine-plists (&rest plists)
21791 "Create a single property list from all plists in PLISTS.
21792 The process starts by copying the first list, and then setting properties
21793 from the other lists. Settings in the last list are the most significant
21794 ones and overrule settings in the other lists."
21795 (let ((rtn (copy-sequence (pop plists)))
21796 p v ls)
21797 (while plists
21798 (setq ls (pop plists))
21799 (while ls
21800 (setq p (pop ls) v (pop ls))
21801 (setq rtn (plist-put rtn p v))))
21802 rtn))
21804 (defun org-replace-escapes (string table)
21805 "Replace %-escapes in STRING with values in TABLE.
21806 TABLE is an association list with keys like \"%a\" and string values.
21807 The sequences in STRING may contain normal field width and padding information,
21808 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21809 so values can contain further %-escapes if they are define later in TABLE."
21810 (let ((tbl (copy-alist table))
21811 (case-fold-search nil)
21812 (pchg 0)
21813 e re rpl)
21814 (while (setq e (pop tbl))
21815 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21816 (when (and (cdr e) (string-match re (cdr e)))
21817 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21818 (safe "SREF"))
21819 (add-text-properties 0 3 (list 'sref sref) safe)
21820 (setcdr e (replace-match safe t t (cdr e)))))
21821 (while (string-match re string)
21822 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21823 (cdr e)))
21824 (setq string (replace-match rpl t t string))))
21825 (while (setq pchg (next-property-change pchg string))
21826 (let ((sref (get-text-property pchg 'sref string)))
21827 (when (and sref (string-match "SREF" string pchg))
21828 (setq string (replace-match sref t t string)))))
21829 string))
21831 (defun org-sublist (list start end)
21832 "Return a section of LIST, from START to END.
21833 Counting starts at 1."
21834 (let (rtn (c start))
21835 (setq list (nthcdr (1- start) list))
21836 (while (and list (<= c end))
21837 (push (pop list) rtn)
21838 (setq c (1+ c)))
21839 (nreverse rtn)))
21841 (defun org-find-base-buffer-visiting (file)
21842 "Like `find-buffer-visiting' but always return the base buffer and
21843 not an indirect buffer."
21844 (let ((buf (or (get-file-buffer file)
21845 (find-buffer-visiting file))))
21846 (if buf
21847 (or (buffer-base-buffer buf) buf)
21848 nil)))
21850 (defun org-image-file-name-regexp (&optional extensions)
21851 "Return regexp matching the file names of images.
21852 If EXTENSIONS is given, only match these."
21853 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21854 (image-file-name-regexp)
21855 (let ((image-file-name-extensions
21856 (or extensions
21857 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21858 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21859 (concat "\\."
21860 (regexp-opt (nconc (mapcar 'upcase
21861 image-file-name-extensions)
21862 image-file-name-extensions)
21864 "\\'"))))
21866 (defun org-file-image-p (file &optional extensions)
21867 "Return non-nil if FILE is an image."
21868 (save-match-data
21869 (string-match (org-image-file-name-regexp extensions) file)))
21871 (defun org-get-cursor-date (&optional with-time)
21872 "Return the date at cursor in as a time.
21873 This works in the calendar and in the agenda, anywhere else it just
21874 returns the current time.
21875 If WITH-TIME is non-nil, returns the time of the event at point (in
21876 the agenda) or the current time of the day."
21877 (let (date day defd tp tm hod mod)
21878 (when with-time
21879 (setq tp (get-text-property (point) 'time))
21880 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21881 (setq hod (string-to-number (match-string 1 tp))
21882 mod (string-to-number (match-string 2 tp))))
21883 (or tp (setq hod (nth 2 (decode-time (current-time)))
21884 mod (nth 1 (decode-time (current-time))))))
21885 (cond
21886 ((eq major-mode 'calendar-mode)
21887 (setq date (calendar-cursor-to-date)
21888 defd (encode-time 0 (or mod 0) (or hod 0)
21889 (nth 1 date) (nth 0 date) (nth 2 date))))
21890 ((eq major-mode 'org-agenda-mode)
21891 (setq day (get-text-property (point) 'day))
21892 (if day
21893 (setq date (calendar-gregorian-from-absolute day)
21894 defd (encode-time 0 (or mod 0) (or hod 0)
21895 (nth 1 date) (nth 0 date) (nth 2 date))))))
21896 (or defd (current-time))))
21898 (defun org-mark-subtree (&optional up)
21899 "Mark the current subtree.
21900 This puts point at the start of the current subtree, and mark at
21901 the end. If a numeric prefix UP is given, move up into the
21902 hierarchy of headlines by UP levels before marking the subtree."
21903 (interactive "P")
21904 (org-with-limited-levels
21905 (cond ((org-at-heading-p) (beginning-of-line))
21906 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21907 (t (outline-previous-visible-heading 1))))
21908 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21909 (if (org-called-interactively-p 'any)
21910 (call-interactively 'org-mark-element)
21911 (org-mark-element)))
21914 ;;; Indentation
21916 (defun org-indent-line ()
21917 "Indent line depending on context."
21918 (interactive)
21919 (let* ((pos (point))
21920 (itemp (org-at-item-p))
21921 (case-fold-search t)
21922 (org-drawer-regexp (or org-drawer-regexp "\000"))
21923 (inline-task-p (and (featurep 'org-inlinetask)
21924 (org-inlinetask-in-task-p)))
21925 (inline-re (and inline-task-p
21926 (org-inlinetask-outline-regexp)))
21927 column)
21928 (if (and orgstruct-is-++ (eq pos (point)))
21929 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21930 (indent-according-to-mode))
21931 (beginning-of-line 1)
21932 (cond
21933 ;; Headings
21934 ((looking-at org-outline-regexp) (setq column 0))
21935 ;; Footnote definition
21936 ((looking-at org-footnote-definition-re) (setq column 0))
21937 ;; Literal examples
21938 ((looking-at "[ \t]*:\\( \\|$\\)")
21939 (setq column (org-get-indentation))) ; do nothing
21940 ;; Lists
21941 ((ignore-errors (goto-char (org-in-item-p)))
21942 (setq column (if itemp
21943 (org-get-indentation)
21944 (org-list-item-body-column (point))))
21945 (goto-char pos))
21946 ;; Drawers
21947 ((and (looking-at "[ \t]*:END:")
21948 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21949 (save-excursion
21950 (goto-char (1- (match-beginning 1)))
21951 (setq column (current-column))))
21952 ;; Special blocks
21953 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21954 (save-excursion
21955 (re-search-backward
21956 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21957 (setq column (org-get-indentation (match-string 0))))
21958 ((and (not (looking-at "[ \t]*#\\+begin_"))
21959 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21960 (save-excursion
21961 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21962 (setq column
21963 (cond ((equal (downcase (match-string 1)) "src")
21964 ;; src blocks: let `org-edit-src-exit' handle them
21965 (org-get-indentation))
21966 ((equal (downcase (match-string 1)) "example")
21967 (max (org-get-indentation)
21968 (org-get-indentation (match-string 0))))
21970 (org-get-indentation (match-string 0))))))
21971 ;; This line has nothing special, look at the previous relevant
21972 ;; line to compute indentation
21974 (beginning-of-line 0)
21975 (while (and (not (bobp))
21976 (not (looking-at org-table-line-regexp))
21977 (not (looking-at org-drawer-regexp))
21978 ;; When point started in an inline task, do not move
21979 ;; above task starting line.
21980 (not (and inline-task-p (looking-at inline-re)))
21981 ;; Skip drawers, blocks, empty lines, verbatim,
21982 ;; comments, tables, footnotes definitions, lists,
21983 ;; inline tasks.
21984 (or (and (looking-at "[ \t]*:END:")
21985 (re-search-backward org-drawer-regexp nil t))
21986 (and (looking-at "[ \t]*#\\+end_")
21987 (re-search-backward "[ \t]*#\\+begin_"nil t))
21988 (looking-at "[ \t]*[\n:#|]")
21989 (looking-at org-footnote-definition-re)
21990 (and (not inline-task-p)
21991 (featurep 'org-inlinetask)
21992 (org-inlinetask-in-task-p)
21993 (or (org-inlinetask-goto-beginning) t))))
21994 (beginning-of-line 0))
21995 (cond
21996 ;; There was a list item above.
21997 ((save-excursion
21998 (and (ignore-errors (goto-char (org-in-item-p)))
21999 (goto-char
22000 (org-list-get-top-point (org-list-struct)))))
22001 (looking-at org-list-full-item-re)
22002 (setq column (length (match-string 0))))
22003 ;; There was an heading above.
22004 ((looking-at "\\*+[ \t]+")
22005 (if (not org-adapt-indentation)
22006 (setq column 0)
22007 (goto-char (match-end 0))
22008 (setq column (current-column))))
22009 ;; A drawer had started and is unfinished
22010 ((looking-at org-drawer-regexp)
22011 (goto-char (1- (match-beginning 1)))
22012 (setq column (current-column)))
22013 ;; Else, nothing noticeable found: get indentation and go on.
22014 (t (setq column (org-get-indentation))))))
22015 ;; Now apply indentation and move cursor accordingly
22016 (goto-char pos)
22017 (if (<= (current-column) (current-indentation))
22018 (org-indent-line-to column)
22019 (save-excursion (org-indent-line-to column)))
22020 ;; Special polishing for properties, see `org-property-format'
22021 (setq column (current-column))
22022 (beginning-of-line 1)
22023 (if (looking-at
22024 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
22025 (replace-match (concat (match-string 1)
22026 (format org-property-format
22027 (match-string 2) (match-string 3)))
22028 t t))
22029 (org-move-to-column column))))
22031 (defun org-indent-drawer ()
22032 "Indent the drawer at point."
22033 (interactive)
22034 (let ((p (point))
22035 (e (and (save-excursion (re-search-forward ":END:" nil t))
22036 (match-end 0)))
22037 (folded
22038 (save-excursion
22039 (end-of-line)
22040 (when (overlays-at (point))
22041 (member 'invisible (overlay-properties
22042 (car (overlays-at (point)))))))))
22043 (when folded (org-cycle))
22044 (indent-for-tab-command)
22045 (while (and (move-beginning-of-line 2) (< (point) e))
22046 (indent-for-tab-command))
22047 (goto-char p)
22048 (when folded (org-cycle)))
22049 (message "Drawer at point indented"))
22051 (defun org-indent-block ()
22052 "Indent the block at point."
22053 (interactive)
22054 (let ((p (point))
22055 (case-fold-search t)
22056 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22057 (match-end 0)))
22058 (folded
22059 (save-excursion
22060 (end-of-line)
22061 (when (overlays-at (point))
22062 (member 'invisible (overlay-properties
22063 (car (overlays-at (point)))))))))
22064 (when folded (org-cycle))
22065 (indent-for-tab-command)
22066 (while (and (move-beginning-of-line 2) (< (point) e))
22067 (indent-for-tab-command))
22068 (goto-char p)
22069 (when folded (org-cycle)))
22070 (message "Block at point indented"))
22072 (defun org-indent-region (start end)
22073 "Indent region."
22074 (interactive "r")
22075 (save-excursion
22076 (let ((line-end (org-current-line end)))
22077 (goto-char start)
22078 (while (< (org-current-line) line-end)
22079 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22080 (t (call-interactively 'org-indent-line)))
22081 (move-beginning-of-line 2)))))
22084 ;;; Filling
22086 ;; We use our own fill-paragraph and auto-fill functions.
22088 ;; `org-fill-paragraph' relies on adaptive filling and context
22089 ;; checking. Appropriate `fill-prefix' is computed with
22090 ;; `org-adaptive-fill-function'.
22092 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22093 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22094 ;; `org-adaptive-fill-function' value. Internally,
22095 ;; `org-comment-line-break-function' breaks the line.
22097 ;; `org-setup-filling' installs filling and auto-filling related
22098 ;; variables during `org-mode' initialization.
22100 (defun org-setup-filling ()
22101 (interactive)
22102 ;; Prevent auto-fill from inserting unwanted new items.
22103 (when (boundp 'fill-nobreak-predicate)
22104 (org-set-local
22105 'fill-nobreak-predicate
22106 (org-uniquify
22107 (append fill-nobreak-predicate
22108 '(org-fill-paragraph-separate-nobreak-p
22109 org-fill-line-break-nobreak-p
22110 org-fill-paragraph-with-timestamp-nobreak-p)))))
22111 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22112 (org-set-local 'auto-fill-inhibit-regexp nil)
22113 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22114 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22115 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22117 (defvar org-element-paragraph-separate) ; org-element.el
22118 (defun org-fill-paragraph-separate-nobreak-p ()
22119 "Non-nil when a line break at point would insert a new item."
22120 (looking-at (substring org-element-paragraph-separate 1)))
22122 (defun org-fill-line-break-nobreak-p ()
22123 "Non-nil when a line break at point would create an Org line break."
22124 (save-excursion
22125 (skip-chars-backward "[ \t]")
22126 (skip-chars-backward "\\\\")
22127 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22129 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22130 "Non-nil when a line break at point would insert a new item."
22131 (and (org-at-timestamp-p t)
22132 (not (looking-at org-ts-regexp-both))))
22134 (declare-function message-in-body-p "message" ())
22135 (defvar orgtbl-line-start-regexp) ; From org-table.el
22136 (defun org-adaptive-fill-function ()
22137 "Compute a fill prefix for the current line.
22138 Return fill prefix, as a string, or nil if current line isn't
22139 meant to be filled."
22140 (let (prefix)
22141 (catch 'exit
22142 (when (derived-mode-p 'message-mode)
22143 (save-excursion
22144 (beginning-of-line)
22145 (cond ((or (not (message-in-body-p))
22146 (looking-at orgtbl-line-start-regexp))
22147 (throw 'exit nil))
22148 ((looking-at message-cite-prefix-regexp)
22149 (throw 'exit (match-string-no-properties 0)))
22150 ((looking-at org-outline-regexp)
22151 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22152 (org-with-wide-buffer
22153 (let* ((p (line-beginning-position))
22154 (element (save-excursion
22155 (beginning-of-line)
22156 (or (ignore-errors (org-element-at-point))
22157 (user-error "An element cannot be parsed line %d"
22158 (line-number-at-pos (point))))))
22159 (type (org-element-type element))
22160 (post-affiliated (org-element-property :post-affiliated element)))
22161 (unless (and post-affiliated (< p post-affiliated))
22162 (case type
22163 (comment (looking-at "[ \t]*# ?") (match-string 0))
22164 (footnote-definition "")
22165 ((item plain-list)
22166 (make-string (org-list-item-body-column
22167 (or post-affiliated
22168 (org-element-property :begin element)))
22169 ? ))
22170 (paragraph
22171 ;; Fill prefix is usually the same as the current line,
22172 ;; except if the paragraph is at the beginning of an item.
22173 (let ((parent (org-element-property :parent element)))
22174 (cond ((eq (org-element-type parent) 'item)
22175 (make-string (org-list-item-body-column
22176 (org-element-property :begin parent))
22177 ? ))
22178 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22179 (match-string 0))
22180 (t ""))))
22181 (comment-block
22182 ;; Only fill contents if P is within block boundaries.
22183 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22184 (forward-line)
22185 (point)))
22186 (cend (save-excursion
22187 (goto-char (org-element-property :end element))
22188 (skip-chars-backward " \r\t\n")
22189 (line-beginning-position))))
22190 (when (and (>= p cbeg) (< p cend))
22191 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22192 (match-string 0)
22193 "")))))))))))
22195 (declare-function message-goto-body "message" ())
22196 (defvar message-cite-prefix-regexp) ; From message.el
22197 (defun org-fill-paragraph (&optional justify)
22198 "Fill element at point, when applicable.
22200 This function only applies to comment blocks, comments, example
22201 blocks and paragraphs. Also, as a special case, re-align table
22202 when point is at one.
22204 If JUSTIFY is non-nil (interactively, with prefix argument),
22205 justify as well. If `sentence-end-double-space' is non-nil, then
22206 period followed by one space does not end a sentence, so don't
22207 break a line there. The variable `fill-column' controls the
22208 width for filling.
22210 For convenience, when point is at a plain list, an item or
22211 a footnote definition, try to fill the first paragraph within."
22212 (interactive)
22213 (if (and (derived-mode-p 'message-mode)
22214 (or (not (message-in-body-p))
22215 (save-excursion (move-beginning-of-line 1)
22216 (looking-at message-cite-prefix-regexp))))
22217 ;; First ensure filling is correct in message-mode.
22218 (let ((fill-paragraph-function
22219 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22220 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22221 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22222 (paragraph-separate
22223 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22224 (fill-paragraph nil))
22225 (with-syntax-table org-mode-transpose-word-syntax-table
22226 ;; Move to end of line in order to get the first paragraph
22227 ;; within a plain list or a footnote definition.
22228 (let ((element (save-excursion
22229 (end-of-line)
22230 (or (ignore-errors (org-element-at-point))
22231 (user-error "An element cannot be parsed line %d"
22232 (line-number-at-pos (point)))))))
22233 ;; First check if point is in a blank line at the beginning of
22234 ;; the buffer. In that case, ignore filling.
22235 (case (org-element-type element)
22236 ;; Use major mode filling function is src blocks.
22237 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22238 ;; Align Org tables, leave table.el tables as-is.
22239 (table-row (org-table-align) t)
22240 (table
22241 (when (eq (org-element-property :type element) 'org)
22242 (save-excursion
22243 (goto-char (org-element-property :post-affiliated element))
22244 (org-table-align)))
22246 (paragraph
22247 ;; Paragraphs may contain `line-break' type objects.
22248 (let ((beg (max (point-min)
22249 (org-element-property :contents-begin element)))
22250 (end (min (point-max)
22251 (org-element-property :contents-end element))))
22252 ;; Do nothing if point is at an affiliated keyword.
22253 (if (< (line-end-position) beg) t
22254 (when (derived-mode-p 'message-mode)
22255 ;; In `message-mode', do not fill following citation
22256 ;; in current paragraph nor text before message body.
22257 (let ((body-start (save-excursion (message-goto-body))))
22258 (when body-start (setq beg (max body-start beg))))
22259 (when (save-excursion
22260 (re-search-forward
22261 (concat "^" message-cite-prefix-regexp) end t))
22262 (setq end (match-beginning 0))))
22263 ;; Fill paragraph, taking line breaks into account.
22264 ;; For that, slice the paragraph using line breaks as
22265 ;; separators, and fill the parts in reverse order to
22266 ;; avoid messing with markers.
22267 (save-excursion
22268 (goto-char end)
22269 (mapc
22270 (lambda (pos)
22271 (fill-region-as-paragraph pos (point) justify)
22272 (goto-char pos))
22273 ;; Find the list of ending positions for line breaks
22274 ;; in the current paragraph. Add paragraph
22275 ;; beginning to include first slice.
22276 (nreverse
22277 (cons beg
22278 (org-element-map
22279 (org-element--parse-objects
22280 beg end nil (org-element-restriction 'paragraph))
22281 'line-break
22282 (lambda (lb) (org-element-property :end lb)))))))
22283 t)))
22284 ;; Contents of `comment-block' type elements should be
22285 ;; filled as plain text, but only if point is within block
22286 ;; markers.
22287 (comment-block
22288 (let* ((case-fold-search t)
22289 (beg (save-excursion
22290 (goto-char (org-element-property :begin element))
22291 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22292 (forward-line)
22293 (point)))
22294 (end (save-excursion
22295 (goto-char (org-element-property :end element))
22296 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22297 (line-beginning-position))))
22298 (when (and (>= (point) beg) (< (point) end))
22299 (fill-region-as-paragraph
22300 (save-excursion
22301 (end-of-line)
22302 (re-search-backward "^[ \t]*$" beg 'move)
22303 (line-beginning-position))
22304 (save-excursion
22305 (beginning-of-line)
22306 (re-search-forward "^[ \t]*$" end 'move)
22307 (line-beginning-position))
22308 justify)))
22310 ;; Fill comments.
22311 (comment (fill-comment-paragraph justify))
22312 ;; Ignore every other element.
22313 (otherwise t))))))
22315 (defun org-auto-fill-function ()
22316 "Auto-fill function."
22317 ;; Check if auto-filling is meaningful.
22318 (let ((fc (current-fill-column)))
22319 (when (and fc (> (current-column) fc))
22320 (let* ((fill-prefix (org-adaptive-fill-function))
22321 ;; Enforce empty fill prefix, if required. Otherwise, it
22322 ;; will be computed again.
22323 (adaptive-fill-mode (not (equal fill-prefix ""))))
22324 (when fill-prefix (do-auto-fill))))))
22326 (defun org-comment-line-break-function (&optional soft)
22327 "Break line at point and indent, continuing comment if within one.
22328 The inserted newline is marked hard if variable
22329 `use-hard-newlines' is true, unless optional argument SOFT is
22330 non-nil."
22331 (if soft (insert-and-inherit ?\n) (newline 1))
22332 (save-excursion (forward-char -1) (delete-horizontal-space))
22333 (delete-horizontal-space)
22334 (indent-to-left-margin)
22335 (insert-before-markers-and-inherit fill-prefix))
22338 ;;; Comments
22340 ;; Org comments syntax is quite complex. It requires the entire line
22341 ;; to be just a comment. Also, even with the right syntax at the
22342 ;; beginning of line, some some elements (i.e. verse-block or
22343 ;; example-block) don't accept comments. Usual Emacs comment commands
22344 ;; cannot cope with those requirements. Therefore, Org replaces them.
22346 ;; Org still relies on `comment-dwim', but cannot trust
22347 ;; `comment-only-p'. So, `comment-region-function' and
22348 ;; `uncomment-region-function' both point
22349 ;; to`org-comment-or-uncomment-region'. Eventually,
22350 ;; `org-insert-comment' takes care of insertion of comments at the
22351 ;; beginning of line.
22353 ;; `org-setup-comments-handling' install comments related variables
22354 ;; during `org-mode' initialization.
22356 (defun org-setup-comments-handling ()
22357 (interactive)
22358 (org-set-local 'comment-use-syntax nil)
22359 (org-set-local 'comment-start "# ")
22360 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22361 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22362 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22363 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22365 (defun org-insert-comment ()
22366 "Insert an empty comment above current line.
22367 If the line is empty, insert comment at its beginning."
22368 (beginning-of-line)
22369 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22370 (org-indent-line)
22371 (insert "# "))
22373 (defvar comment-empty-lines) ; From newcomment.el.
22374 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22375 "Comment or uncomment each non-blank line in the region.
22376 Uncomment each non-blank line between BEG and END if it only
22377 contains commented lines. Otherwise, comment them."
22378 (save-restriction
22379 ;; Restrict region
22380 (narrow-to-region (save-excursion (goto-char beg)
22381 (skip-chars-forward " \r\t\n" end)
22382 (line-beginning-position))
22383 (save-excursion (goto-char end)
22384 (skip-chars-backward " \r\t\n" beg)
22385 (line-end-position)))
22386 (let ((uncommentp
22387 ;; UNCOMMENTP is non-nil when every non blank line between
22388 ;; BEG and END is a comment.
22389 (save-excursion
22390 (goto-char (point-min))
22391 (while (and (not (eobp))
22392 (let ((element (org-element-at-point)))
22393 (and (eq (org-element-type element) 'comment)
22394 (goto-char (min (point-max)
22395 (org-element-property
22396 :end element)))))))
22397 (eobp))))
22398 (if uncommentp
22399 ;; Only blank lines and comments in region: uncomment it.
22400 (save-excursion
22401 (goto-char (point-min))
22402 (while (not (eobp))
22403 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22404 (replace-match "" nil nil nil 1))
22405 (forward-line)))
22406 ;; Comment each line in region.
22407 (let ((min-indent (point-max)))
22408 ;; First find the minimum indentation across all lines.
22409 (save-excursion
22410 (goto-char (point-min))
22411 (while (and (not (eobp)) (not (zerop min-indent)))
22412 (unless (looking-at "[ \t]*$")
22413 (setq min-indent (min min-indent (current-indentation))))
22414 (forward-line)))
22415 ;; Then loop over all lines.
22416 (save-excursion
22417 (goto-char (point-min))
22418 (while (not (eobp))
22419 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22420 ;; Don't get fooled by invisible text (e.g. link path)
22421 ;; when moving to column MIN-INDENT.
22422 (let ((buffer-invisibility-spec nil))
22423 (org-move-to-column min-indent t))
22424 (insert comment-start))
22425 (forward-line))))))))
22428 ;;; Planning
22430 ;; This section contains tools to operate on timestamp objects, as
22431 ;; returned by, e.g. `org-element-context'.
22433 (defun org-timestamp-has-time-p (timestamp)
22434 "Non-nil when TIMESTAMP has a time specified."
22435 (org-element-property :hour-start timestamp))
22437 (defun org-timestamp-format (timestamp format &optional end utc)
22438 "Format a TIMESTAMP element into a string.
22440 FORMAT is a format specifier to be passed to
22441 `format-time-string'.
22443 When optional argument END is non-nil, use end of date-range or
22444 time-range, if possible.
22446 When optional argument UTC is non-nil, time will be expressed as
22447 Universal Time."
22448 (format-time-string
22449 format
22450 (apply 'encode-time
22451 (cons 0
22452 (mapcar
22453 (lambda (prop) (or (org-element-property prop timestamp) 0))
22454 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22455 '(:minute-start :hour-start :day-start :month-start
22456 :year-start)))))
22457 utc))
22459 (defun org-timestamp-split-range (timestamp &optional end)
22460 "Extract a timestamp object from a date or time range.
22462 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22463 the end of the range. Otherwise, extract its start.
22465 Return a new timestamp object sharing the same parent as
22466 TIMESTAMP."
22467 (let ((type (org-element-property :type timestamp)))
22468 (if (memq type '(active inactive diary)) timestamp
22469 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22470 ;; Set new type.
22471 (org-element-put-property
22472 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22473 ;; Copy start properties over end properties if END is
22474 ;; non-nil. Otherwise, copy end properties over `start' ones.
22475 (let ((p-alist '((:minute-start . :minute-end)
22476 (:hour-start . :hour-end)
22477 (:day-start . :day-end)
22478 (:month-start . :month-end)
22479 (:year-start . :year-end))))
22480 (dolist (p-cell p-alist)
22481 (org-element-put-property
22482 split-ts
22483 (funcall (if end 'car 'cdr) p-cell)
22484 (org-element-property
22485 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22486 ;; Eventually refresh `:raw-value'.
22487 (org-element-put-property split-ts :raw-value nil)
22488 (org-element-put-property
22489 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22491 (defun org-timestamp-translate (timestamp &optional boundary)
22492 "Apply `org-translate-time' on a TIMESTAMP object.
22493 When optional argument BOUNDARY is non-nil, it is either the
22494 symbol `start' or `end'. In this case, only translate the
22495 starting or ending part of TIMESTAMP if it is a date or time
22496 range. Otherwise, translate both parts."
22497 (if (and (not boundary)
22498 (memq (org-element-property :type timestamp)
22499 '(active-range inactive-range)))
22500 (concat
22501 (org-translate-time
22502 (org-element-property :raw-value
22503 (org-timestamp-split-range timestamp)))
22504 "--"
22505 (org-translate-time
22506 (org-element-property :raw-value
22507 (org-timestamp-split-range timestamp t))))
22508 (org-translate-time
22509 (org-element-property
22510 :raw-value
22511 (if (not boundary) timestamp
22512 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22516 ;;; Other stuff.
22518 (defun org-toggle-fixed-width-section (arg)
22519 "Toggle the fixed-width export.
22520 If there is no active region, the QUOTE keyword at the current headline is
22521 inserted or removed. When present, it causes the text between this headline
22522 and the next to be exported as fixed-width text, and unmodified.
22523 If there is an active region, this command adds or removes a colon as the
22524 first character of this line. If the first character of a line is a colon,
22525 this line is also exported in fixed-width font."
22526 (interactive "P")
22527 (let* ((cc 0)
22528 (regionp (org-region-active-p))
22529 (beg (if regionp (region-beginning) (point)))
22530 (end (if regionp (region-end)))
22531 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22532 (case-fold-search nil)
22533 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22534 off)
22535 (if regionp
22536 (save-excursion
22537 (goto-char beg)
22538 (setq cc (current-column))
22539 (beginning-of-line 1)
22540 (setq off (looking-at re))
22541 (while (> nlines 0)
22542 (setq nlines (1- nlines))
22543 (beginning-of-line 1)
22544 (cond
22545 (arg
22546 (org-move-to-column cc t)
22547 (insert ": \n")
22548 (forward-line -1))
22549 ((and off (looking-at re))
22550 (replace-match "" t t nil 1))
22551 ((not off) (org-move-to-column cc t) (insert ": ")))
22552 (forward-line 1)))
22553 (save-excursion
22554 (org-back-to-heading)
22555 (cond
22556 ((looking-at (format org-heading-keyword-regexp-format
22557 org-quote-string))
22558 (goto-char (match-end 1))
22559 (looking-at (concat " +" org-quote-string))
22560 (replace-match "" t t)
22561 (when (eolp) (insert " ")))
22562 ((looking-at org-outline-regexp)
22563 (goto-char (match-end 0))
22564 (insert org-quote-string " ")))))))
22566 (defun org-reftex-citation ()
22567 "Use reftex-citation to insert a citation into the buffer.
22568 This looks for a line like
22570 #+BIBLIOGRAPHY: foo plain option:-d
22572 and derives from it that foo.bib is the bibliography file relevant
22573 for this document. It then installs the necessary environment for RefTeX
22574 to work in this buffer and calls `reftex-citation' to insert a citation
22575 into the buffer.
22577 Export of such citations to both LaTeX and HTML is handled by the contributed
22578 package org-exp-bibtex by Taru Karttunen."
22579 (interactive)
22580 (let ((reftex-docstruct-symbol 'rds)
22581 (reftex-cite-format "\\cite{%l}")
22582 rds bib)
22583 (save-excursion
22584 (save-restriction
22585 (widen)
22586 (let ((case-fold-search t)
22587 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22588 (if (not (save-excursion
22589 (or (re-search-forward re nil t)
22590 (re-search-backward re nil t))))
22591 (error "No bibliography defined in file")
22592 (setq bib (concat (match-string 1) ".bib")
22593 rds (list (list 'bib bib)))))))
22594 (call-interactively 'reftex-citation)))
22596 ;;;; Functions extending outline functionality
22598 (defun org-beginning-of-line (&optional arg)
22599 "Go to the beginning of the current line. If that is invisible, continue
22600 to a visible line beginning. This makes the function of C-a more intuitive.
22601 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22602 first attempt, and only move to after the tags when the cursor is already
22603 beyond the end of the headline."
22604 (interactive "P")
22605 (let ((pos (point))
22606 (special (if (consp org-special-ctrl-a/e)
22607 (car org-special-ctrl-a/e)
22608 org-special-ctrl-a/e))
22609 refpos)
22610 (if (org-bound-and-true-p visual-line-mode)
22611 (beginning-of-visual-line 1)
22612 (beginning-of-line 1))
22613 (if (and arg (fboundp 'move-beginning-of-line))
22614 (call-interactively 'move-beginning-of-line)
22615 (if (bobp)
22617 (backward-char 1)
22618 (if (org-truely-invisible-p)
22619 (while (and (not (bobp)) (org-truely-invisible-p))
22620 (backward-char 1)
22621 (beginning-of-line 1))
22622 (forward-char 1))))
22623 (when special
22624 (cond
22625 ((and (looking-at org-complex-heading-regexp)
22626 (= (char-after (match-end 1)) ?\ ))
22627 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22628 (point-at-eol)))
22629 (goto-char
22630 (if (eq special t)
22631 (cond ((> pos refpos) refpos)
22632 ((= pos (point)) refpos)
22633 (t (point)))
22634 (cond ((> pos (point)) (point))
22635 ((not (eq last-command this-command)) (point))
22636 (t refpos)))))
22637 ((org-at-item-p)
22638 ;; Being at an item and not looking at an the item means point
22639 ;; was previously moved to beginning of a visual line, which
22640 ;; doesn't contain the item. Therefore, do nothing special,
22641 ;; just stay here.
22642 (when (looking-at org-list-full-item-re)
22643 ;; Set special position at first white space character after
22644 ;; bullet, and check-box, if any.
22645 (let ((after-bullet
22646 (let ((box (match-end 3)))
22647 (if (not box) (match-end 1)
22648 (let ((after (char-after box)))
22649 (if (and after (= after ? )) (1+ box) box))))))
22650 ;; Special case: Move point to special position when
22651 ;; currently after it or at beginning of line.
22652 (if (eq special t)
22653 (when (or (> pos after-bullet) (= (point) pos))
22654 (goto-char after-bullet))
22655 ;; Reversed case: Move point to special position when
22656 ;; point was already at beginning of line and command is
22657 ;; repeated.
22658 (when (and (= (point) pos) (eq last-command this-command))
22659 (goto-char after-bullet))))))))
22660 (org-no-warnings
22661 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22662 (setq disable-point-adjustment
22663 (or (not (invisible-p (point)))
22664 (not (invisible-p (max (point-min) (1- (point))))))))
22666 (defun org-end-of-line (&optional arg)
22667 "Go to the end of the line.
22668 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22669 tags on the first attempt, and only move to after the tags when
22670 the cursor is already beyond the end of the headline."
22671 (interactive "P")
22672 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22673 org-special-ctrl-a/e))
22674 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22675 'end-of-visual-line)
22676 ((fboundp 'move-end-of-line) 'move-end-of-line)
22677 (t 'end-of-line))))
22678 (if (or (not special) arg) (call-interactively move-fun)
22679 (let* ((element (save-excursion (beginning-of-line)
22680 (org-element-at-point)))
22681 (type (org-element-type element)))
22682 (cond
22683 ((memq type '(headline inlinetask))
22684 (let ((pos (point)))
22685 (beginning-of-line 1)
22686 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22687 (if (eq special t)
22688 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22689 (goto-char (match-beginning 1))
22690 (goto-char (match-end 0)))
22691 (if (or (< pos (match-end 0))
22692 (not (eq this-command last-command)))
22693 (goto-char (match-end 0))
22694 (goto-char (match-beginning 1))))
22695 (call-interactively move-fun))))
22696 ((org-element-property :hiddenp element)
22697 ;; If element is hidden, `move-end-of-line' would put point
22698 ;; after it. Use `end-of-line' to stay on current line.
22699 (call-interactively 'end-of-line))
22700 (t (call-interactively move-fun)))))
22701 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22702 (setq disable-point-adjustment
22703 (or (not (invisible-p (point)))
22704 (not (invisible-p (max (point-min) (1- (point))))))))
22706 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22707 (define-key org-mode-map "\C-e" 'org-end-of-line)
22709 (defun org-backward-sentence (&optional arg)
22710 "Go to beginning of sentence, or beginning of table field.
22711 This will call `backward-sentence' or `org-table-beginning-of-field',
22712 depending on context."
22713 (interactive "P")
22714 (cond
22715 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22716 (t (call-interactively 'backward-sentence))))
22718 (defun org-forward-sentence (&optional arg)
22719 "Go to end of sentence, or end of table field.
22720 This will call `forward-sentence' or `org-table-end-of-field',
22721 depending on context."
22722 (interactive "P")
22723 (cond
22724 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22725 (t (call-interactively 'forward-sentence))))
22727 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22728 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22730 (defun org-kill-line (&optional arg)
22731 "Kill line, to tags or end of line."
22732 (interactive "P")
22733 (cond
22734 ((or (not org-special-ctrl-k)
22735 (bolp)
22736 (not (org-at-heading-p)))
22737 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22738 org-ctrl-k-protect-subtree)
22739 (if (or (eq org-ctrl-k-protect-subtree 'error)
22740 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22741 (user-error "C-k aborted as it would kill a hidden subtree")))
22742 (call-interactively
22743 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22744 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22745 (kill-region (point) (match-beginning 1))
22746 (org-set-tags nil t))
22747 (t (kill-region (point) (point-at-eol)))))
22749 (define-key org-mode-map "\C-k" 'org-kill-line)
22751 (defun org-yank (&optional arg)
22752 "Yank. If the kill is a subtree, treat it specially.
22753 This command will look at the current kill and check if is a single
22754 subtree, or a series of subtrees[1]. If it passes the test, and if the
22755 cursor is at the beginning of a line or after the stars of a currently
22756 empty headline, then the yank is handled specially. How exactly depends
22757 on the value of the following variables, both set by default.
22759 org-yank-folded-subtrees
22760 When set, the subtree(s) will be folded after insertion, but only
22761 if doing so would now swallow text after the yanked text.
22763 org-yank-adjusted-subtrees
22764 When set, the subtree will be promoted or demoted in order to
22765 fit into the local outline tree structure, which means that the level
22766 will be adjusted so that it becomes the smaller one of the two
22767 *visible* surrounding headings.
22769 Any prefix to this command will cause `yank' to be called directly with
22770 no special treatment. In particular, a simple \\[universal-argument] prefix \
22771 will just
22772 plainly yank the text as it is.
22774 \[1] The test checks if the first non-white line is a heading
22775 and if there are no other headings with fewer stars."
22776 (interactive "P")
22777 (org-yank-generic 'yank arg))
22779 (defun org-yank-generic (command arg)
22780 "Perform some yank-like command.
22782 This function implements the behavior described in the `org-yank'
22783 documentation. However, it has been generalized to work for any
22784 interactive command with similar behavior."
22786 ;; pretend to be command COMMAND
22787 (setq this-command command)
22789 (if arg
22790 (call-interactively command)
22792 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22793 (and (org-kill-is-subtree-p)
22794 (or (bolp)
22795 (and (looking-at "[ \t]*$")
22796 (string-match
22797 "\\`\\*+\\'"
22798 (buffer-substring (point-at-bol) (point)))))))
22799 swallowp)
22800 (cond
22801 ((and subtreep org-yank-folded-subtrees)
22802 (let ((beg (point))
22803 end)
22804 (if (and subtreep org-yank-adjusted-subtrees)
22805 (org-paste-subtree nil nil 'for-yank)
22806 (call-interactively command))
22808 (setq end (point))
22809 (goto-char beg)
22810 (when (and (bolp) subtreep
22811 (not (setq swallowp
22812 (org-yank-folding-would-swallow-text beg end))))
22813 (org-with-limited-levels
22814 (or (looking-at org-outline-regexp)
22815 (re-search-forward org-outline-regexp-bol end t))
22816 (while (and (< (point) end) (looking-at org-outline-regexp))
22817 (hide-subtree)
22818 (org-cycle-show-empty-lines 'folded)
22819 (condition-case nil
22820 (outline-forward-same-level 1)
22821 (error (goto-char end))))))
22822 (when swallowp
22823 (message
22824 "Inserted text not folded because that would swallow text"))
22826 (goto-char end)
22827 (skip-chars-forward " \t\n\r")
22828 (beginning-of-line 1)
22829 (push-mark beg 'nomsg)))
22830 ((and subtreep org-yank-adjusted-subtrees)
22831 (let ((beg (point-at-bol)))
22832 (org-paste-subtree nil nil 'for-yank)
22833 (push-mark beg 'nomsg)))
22835 (call-interactively command))))))
22837 (defun org-yank-folding-would-swallow-text (beg end)
22838 "Would hide-subtree at BEG swallow any text after END?"
22839 (let (level)
22840 (org-with-limited-levels
22841 (save-excursion
22842 (goto-char beg)
22843 (when (or (looking-at org-outline-regexp)
22844 (re-search-forward org-outline-regexp-bol end t))
22845 (setq level (org-outline-level)))
22846 (goto-char end)
22847 (skip-chars-forward " \t\r\n\v\f")
22848 (if (or (eobp)
22849 (and (bolp) (looking-at org-outline-regexp)
22850 (<= (org-outline-level) level)))
22851 nil ; Nothing would be swallowed
22852 t))))) ; something would swallow
22854 (define-key org-mode-map "\C-y" 'org-yank)
22856 (defun org-truely-invisible-p ()
22857 "Check if point is at a character currently not visible.
22858 This version does not only check the character property, but also
22859 `visible-mode'."
22860 ;; Early versions of noutline don't have `outline-invisible-p'.
22861 (if (org-bound-and-true-p visible-mode)
22863 (outline-invisible-p)))
22865 (defun org-invisible-p2 ()
22866 "Check if point is at a character currently not visible."
22867 (save-excursion
22868 (if (and (eolp) (not (bobp))) (backward-char 1))
22869 ;; Early versions of noutline don't have `outline-invisible-p'.
22870 (outline-invisible-p)))
22872 (defun org-back-to-heading (&optional invisible-ok)
22873 "Call `outline-back-to-heading', but provide a better error message."
22874 (condition-case nil
22875 (outline-back-to-heading invisible-ok)
22876 (error (error "Before first headline at position %d in buffer %s"
22877 (point) (current-buffer)))))
22879 (defun org-before-first-heading-p ()
22880 "Before first heading?"
22881 (save-excursion
22882 (end-of-line)
22883 (null (re-search-backward org-outline-regexp-bol nil t))))
22885 (defun org-at-heading-p (&optional ignored)
22886 (outline-on-heading-p t))
22887 ;; Compatibility alias with Org versions < 7.8.03
22888 (defalias 'org-on-heading-p 'org-at-heading-p)
22890 (defun org-at-comment-p nil
22891 "Is cursor in a line starting with a # character?"
22892 (save-excursion
22893 (beginning-of-line)
22894 (looking-at "^#")))
22896 (defun org-at-drawer-p nil
22897 "Is cursor at a drawer keyword?"
22898 (save-excursion
22899 (move-beginning-of-line 1)
22900 (looking-at org-drawer-regexp)))
22902 (defun org-at-block-p nil
22903 "Is cursor at a block keyword?"
22904 (save-excursion
22905 (move-beginning-of-line 1)
22906 (looking-at org-block-regexp)))
22908 (defun org-point-at-end-of-empty-headline ()
22909 "If point is at the end of an empty headline, return t, else nil.
22910 If the heading only contains a TODO keyword, it is still still considered
22911 empty."
22912 (and (looking-at "[ \t]*$")
22913 (when org-todo-line-regexp
22914 (save-excursion
22915 (beginning-of-line 1)
22916 (let ((case-fold-search nil))
22917 (looking-at org-todo-line-regexp)
22918 (string= (match-string 3) ""))))))
22920 (defun org-at-heading-or-item-p ()
22921 (or (org-at-heading-p) (org-at-item-p)))
22923 (defun org-at-target-p ()
22924 (or (org-in-regexp org-radio-target-regexp)
22925 (org-in-regexp org-target-regexp)))
22926 ;; Compatibility alias with Org versions < 7.8.03
22927 (defalias 'org-on-target-p 'org-at-target-p)
22929 (defun org-up-heading-all (arg)
22930 "Move to the heading line of which the present line is a subheading.
22931 This function considers both visible and invisible heading lines.
22932 With argument, move up ARG levels."
22933 (if (fboundp 'outline-up-heading-all)
22934 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22935 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22937 (defun org-up-heading-safe ()
22938 "Move to the heading line of which the present line is a subheading.
22939 This version will not throw an error. It will return the level of the
22940 headline found, or nil if no higher level is found.
22942 Also, this function will be a lot faster than `outline-up-heading',
22943 because it relies on stars being the outline starters. This can really
22944 make a significant difference in outlines with very many siblings."
22945 (let (start-level re)
22946 (org-back-to-heading t)
22947 (setq start-level (funcall outline-level))
22948 (if (equal start-level 1)
22950 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22951 (if (re-search-backward re nil t)
22952 (funcall outline-level)))))
22954 (defun org-first-sibling-p ()
22955 "Is this heading the first child of its parents?"
22956 (interactive)
22957 (let ((re org-outline-regexp-bol)
22958 level l)
22959 (unless (org-at-heading-p t)
22960 (user-error "Not at a heading"))
22961 (setq level (funcall outline-level))
22962 (save-excursion
22963 (if (not (re-search-backward re nil t))
22965 (setq l (funcall outline-level))
22966 (< l level)))))
22968 (defun org-goto-sibling (&optional previous)
22969 "Goto the next sibling, even if it is invisible.
22970 When PREVIOUS is set, go to the previous sibling instead. Returns t
22971 when a sibling was found. When none is found, return nil and don't
22972 move point."
22973 (let ((fun (if previous 're-search-backward 're-search-forward))
22974 (pos (point))
22975 (re org-outline-regexp-bol)
22976 level l)
22977 (when (condition-case nil (org-back-to-heading t) (error nil))
22978 (setq level (funcall outline-level))
22979 (catch 'exit
22980 (or previous (forward-char 1))
22981 (while (funcall fun re nil t)
22982 (setq l (funcall outline-level))
22983 (when (< l level) (goto-char pos) (throw 'exit nil))
22984 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22985 (goto-char pos)
22986 nil))))
22988 (defun org-show-siblings ()
22989 "Show all siblings of the current headline."
22990 (save-excursion
22991 (while (org-goto-sibling) (org-flag-heading nil)))
22992 (save-excursion
22993 (while (org-goto-sibling 'previous)
22994 (org-flag-heading nil))))
22996 (defun org-goto-first-child ()
22997 "Goto the first child, even if it is invisible.
22998 Return t when a child was found. Otherwise don't move point and
22999 return nil."
23000 (let (level (pos (point)) (re org-outline-regexp-bol))
23001 (when (condition-case nil (org-back-to-heading t) (error nil))
23002 (setq level (outline-level))
23003 (forward-char 1)
23004 (if (and (re-search-forward re nil t) (> (outline-level) level))
23005 (progn (goto-char (match-beginning 0)) t)
23006 (goto-char pos) nil))))
23008 (defun org-show-hidden-entry ()
23009 "Show an entry where even the heading is hidden."
23010 (save-excursion
23011 (org-show-entry)))
23013 (defun org-flag-heading (flag &optional entry)
23014 "Flag the current heading. FLAG non-nil means make invisible.
23015 When ENTRY is non-nil, show the entire entry."
23016 (save-excursion
23017 (org-back-to-heading t)
23018 ;; Check if we should show the entire entry
23019 (if entry
23020 (progn
23021 (org-show-entry)
23022 (save-excursion
23023 (and (outline-next-heading)
23024 (org-flag-heading nil))))
23025 (outline-flag-region (max (point-min) (1- (point)))
23026 (save-excursion (outline-end-of-heading) (point))
23027 flag))))
23029 (defun org-get-next-sibling ()
23030 "Move to next heading of the same level, and return point.
23031 If there is no such heading, return nil.
23032 This is like outline-next-sibling, but invisible headings are ok."
23033 (let ((level (funcall outline-level)))
23034 (outline-next-heading)
23035 (while (and (not (eobp)) (> (funcall outline-level) level))
23036 (outline-next-heading))
23037 (if (or (eobp) (< (funcall outline-level) level))
23039 (point))))
23041 (defun org-get-last-sibling ()
23042 "Move to previous heading of the same level, and return point.
23043 If there is no such heading, return nil."
23044 (let ((opoint (point))
23045 (level (funcall outline-level)))
23046 (outline-previous-heading)
23047 (when (and (/= (point) opoint) (outline-on-heading-p t))
23048 (while (and (> (funcall outline-level) level)
23049 (not (bobp)))
23050 (outline-previous-heading))
23051 (if (< (funcall outline-level) level)
23053 (point)))))
23055 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23056 "Goto to the end of a subtree."
23057 ;; This contains an exact copy of the original function, but it uses
23058 ;; `org-back-to-heading', to make it work also in invisible
23059 ;; trees. And is uses an invisible-ok argument.
23060 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23061 ;; Furthermore, when used inside Org, finding the end of a large subtree
23062 ;; with many children and grandchildren etc, this can be much faster
23063 ;; than the outline version.
23064 (org-back-to-heading invisible-ok)
23065 (let ((first t)
23066 (level (funcall outline-level)))
23067 (if (and (derived-mode-p 'org-mode) (< level 1000))
23068 ;; A true heading (not a plain list item), in Org-mode
23069 ;; This means we can easily find the end by looking
23070 ;; only for the right number of stars. Using a regexp to do
23071 ;; this is so much faster than using a Lisp loop.
23072 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23073 (forward-char 1)
23074 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23075 ;; something else, do it the slow way
23076 (while (and (not (eobp))
23077 (or first (> (funcall outline-level) level)))
23078 (setq first nil)
23079 (outline-next-heading)))
23080 (unless to-heading
23081 (if (memq (preceding-char) '(?\n ?\^M))
23082 (progn
23083 ;; Go to end of line before heading
23084 (forward-char -1)
23085 (if (memq (preceding-char) '(?\n ?\^M))
23086 ;; leave blank line before heading
23087 (forward-char -1))))))
23088 (point))
23090 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23091 "Use Org version in org-mode, for dramatic speed-up."
23092 (if (derived-mode-p 'org-mode)
23093 (progn
23094 (org-end-of-subtree nil t)
23095 (unless (eobp) (backward-char 1)))
23096 ad-do-it))
23098 (defun org-end-of-meta-data-and-drawers ()
23099 "Jump to the first text after meta data and drawers in the current entry.
23100 This will move over empty lines, lines with planning time stamps,
23101 clocking lines, and drawers."
23102 (org-back-to-heading t)
23103 (let ((end (save-excursion (outline-next-heading) (point)))
23104 (re (concat "\\(" org-drawer-regexp "\\)"
23105 "\\|" "[ \t]*" org-keyword-time-regexp)))
23106 (forward-line 1)
23107 (while (re-search-forward re end t)
23108 (if (not (match-end 1))
23109 ;; empty or planning line
23110 (forward-line 1)
23111 ;; a drawer, find the end
23112 (re-search-forward "^[ \t]*:END:" end 'move)
23113 (forward-line 1)))
23114 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23115 (point)))
23117 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23118 "Move forward to the ARG'th subheading at same level as this one.
23119 Stop at the first and last subheadings of a superior heading.
23120 Normally this only looks at visible headings, but when INVISIBLE-OK is
23121 non-nil it will also look at invisible ones."
23122 (interactive "p")
23123 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23124 (if (and arg (< arg 0))
23125 (goto-char (point-min))
23126 (outline-next-heading))
23127 (org-at-heading-p)
23128 (let ((level (- (match-end 0) (match-beginning 0) 1))
23129 (f (if (and arg (< arg 0))
23130 're-search-backward
23131 're-search-forward))
23132 (count (if arg (abs arg) 1))
23133 (result (point)))
23134 (while (and (prog1 (> count 0)
23135 (forward-char (if (and arg (< arg 0)) -1 1)))
23136 (funcall f org-outline-regexp-bol nil 'move))
23137 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23138 (cond ((< l level) (setq count 0))
23139 ((and (= l level)
23140 (or invisible-ok
23141 (progn
23142 (goto-char (line-beginning-position))
23143 (not (outline-invisible-p)))))
23144 (setq count (1- count))
23145 (when (eq l level)
23146 (setq result (point)))))))
23147 (goto-char result))
23148 (beginning-of-line 1)))
23150 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23151 "Move backward to the ARG'th subheading at same level as this one.
23152 Stop at the first and last subheadings of a superior heading."
23153 (interactive "p")
23154 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23156 (defun org-next-block (arg &optional backward block-regexp)
23157 "Jump to the next block.
23158 With a prefix argument ARG, jump forward ARG many source blocks.
23159 When BACKWARD is non-nil, jump to the previous block.
23160 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23161 (interactive "p")
23162 (let ((re (or block-regexp org-block-regexp))
23163 (re-search-fn (or (and backward 're-search-backward)
23164 're-search-forward)))
23165 (if (looking-at re) (forward-char 1))
23166 (condition-case nil
23167 (funcall re-search-fn re nil nil arg)
23168 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23169 (goto-char (match-beginning 0)) (org-show-context)))
23171 (defun org-previous-block (arg &optional block-regexp)
23172 "Jump to the previous block.
23173 With a prefix argument ARG, jump backward ARG many source blocks.
23174 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23175 (interactive "p")
23176 (org-next-block arg t block-regexp))
23178 (defun org-forward-element ()
23179 "Move forward by one element.
23180 Move to the next element at the same level, when possible."
23181 (interactive)
23182 (cond ((eobp) (user-error "Cannot move further down"))
23183 ((org-with-limited-levels (org-at-heading-p))
23184 (let ((origin (point)))
23185 (goto-char (org-end-of-subtree nil t))
23186 (unless (org-with-limited-levels (org-at-heading-p))
23187 (goto-char origin)
23188 (user-error "Cannot move further down"))))
23190 (let* ((elem (org-element-at-point))
23191 (end (org-element-property :end elem))
23192 (parent (org-element-property :parent elem)))
23193 (if (and parent (= (org-element-property :contents-end parent) end))
23194 (goto-char (org-element-property :end parent))
23195 (goto-char end))))))
23197 (defun org-backward-element ()
23198 "Move backward by one element.
23199 Move to the previous element at the same level, when possible."
23200 (interactive)
23201 (cond ((bobp) (user-error "Cannot move further up"))
23202 ((org-with-limited-levels (org-at-heading-p))
23203 ;; At a headline, move to the previous one, if any, or stay
23204 ;; here.
23205 (let ((origin (point)))
23206 (org-with-limited-levels (org-backward-heading-same-level 1))
23207 ;; When current headline has no sibling above, move to its
23208 ;; parent.
23209 (when (= (point) origin)
23210 (or (org-with-limited-levels (org-up-heading-safe))
23211 (progn (goto-char origin)
23212 (user-error "Cannot move further up"))))))
23214 (let* ((trail (org-element-at-point 'keep-trail))
23215 (elem (car trail))
23216 (prev-elem (nth 1 trail))
23217 (beg (org-element-property :begin elem)))
23218 (cond
23219 ;; Move to beginning of current element if point isn't
23220 ;; there already.
23221 ((/= (point) beg) (goto-char beg))
23222 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23223 ((org-before-first-heading-p) (goto-char (point-min)))
23224 (t (org-back-to-heading)))))))
23226 (defun org-up-element ()
23227 "Move to upper element."
23228 (interactive)
23229 (if (org-with-limited-levels (org-at-heading-p))
23230 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23231 (let* ((elem (org-element-at-point))
23232 (parent (org-element-property :parent elem)))
23233 (if parent (goto-char (org-element-property :begin parent))
23234 (if (org-with-limited-levels (org-before-first-heading-p))
23235 (user-error "No surrounding element")
23236 (org-with-limited-levels (org-back-to-heading)))))))
23238 (defvar org-element-greater-elements)
23239 (defun org-down-element ()
23240 "Move to inner element."
23241 (interactive)
23242 (let ((element (org-element-at-point)))
23243 (cond
23244 ((memq (org-element-type element) '(plain-list table))
23245 (goto-char (org-element-property :contents-begin element))
23246 (forward-char))
23247 ((memq (org-element-type element) org-element-greater-elements)
23248 ;; If contents are hidden, first disclose them.
23249 (when (org-element-property :hiddenp element) (org-cycle))
23250 (goto-char (or (org-element-property :contents-begin element)
23251 (user-error "No content for this element"))))
23252 (t (user-error "No inner element")))))
23254 (defun org-drag-element-backward ()
23255 "Move backward element at point."
23256 (interactive)
23257 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23258 (let* ((trail (org-element-at-point 'keep-trail))
23259 (elem (car trail))
23260 (prev-elem (nth 1 trail)))
23261 ;; Error out if no previous element or previous element is
23262 ;; a parent of the current one.
23263 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23264 (user-error "Cannot drag element backward")
23265 (let ((pos (point)))
23266 (org-element-swap-A-B prev-elem elem)
23267 (goto-char (+ (org-element-property :begin prev-elem)
23268 (- pos (org-element-property :begin elem)))))))))
23270 (defun org-drag-element-forward ()
23271 "Move forward element at point."
23272 (interactive)
23273 (let* ((pos (point))
23274 (elem (org-element-at-point)))
23275 (when (= (point-max) (org-element-property :end elem))
23276 (user-error "Cannot drag element forward"))
23277 (goto-char (org-element-property :end elem))
23278 (let ((next-elem (org-element-at-point)))
23279 (when (or (org-element-nested-p elem next-elem)
23280 (and (eq (org-element-type next-elem) 'headline)
23281 (not (eq (org-element-type elem) 'headline))))
23282 (goto-char pos)
23283 (user-error "Cannot drag element forward"))
23284 ;; Compute new position of point: it's shifted by NEXT-ELEM
23285 ;; body's length (without final blanks) and by the length of
23286 ;; blanks between ELEM and NEXT-ELEM.
23287 (let ((size-next (- (save-excursion
23288 (goto-char (org-element-property :end next-elem))
23289 (skip-chars-backward " \r\t\n")
23290 (forward-line)
23291 ;; Small correction if buffer doesn't end
23292 ;; with a newline character.
23293 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23294 (org-element-property :begin next-elem)))
23295 (size-blank (- (org-element-property :end elem)
23296 (save-excursion
23297 (goto-char (org-element-property :end elem))
23298 (skip-chars-backward " \r\t\n")
23299 (forward-line)
23300 (point)))))
23301 (org-element-swap-A-B elem next-elem)
23302 (goto-char (+ pos size-next size-blank))))))
23304 (defun org-drag-line-forward (arg)
23305 "Drag the line at point ARG lines forward."
23306 (interactive "p")
23307 (dotimes (n (abs arg))
23308 (let ((c (current-column)))
23309 (if (< 0 arg)
23310 (progn
23311 (beginning-of-line 2)
23312 (transpose-lines 1)
23313 (beginning-of-line 0))
23314 (transpose-lines 1)
23315 (beginning-of-line -1))
23316 (org-move-to-column c))))
23318 (defun org-drag-line-backward (arg)
23319 "Drag the line at point ARG lines backward."
23320 (interactive "p")
23321 (org-drag-line-forward (- arg)))
23323 (defun org-mark-element ()
23324 "Put point at beginning of this element, mark at end.
23326 Interactively, if this command is repeated or (in Transient Mark
23327 mode) if the mark is active, it marks the next element after the
23328 ones already marked."
23329 (interactive)
23330 (let (deactivate-mark)
23331 (if (and (org-called-interactively-p 'any)
23332 (or (and (eq last-command this-command) (mark t))
23333 (and transient-mark-mode mark-active)))
23334 (set-mark
23335 (save-excursion
23336 (goto-char (mark))
23337 (goto-char (org-element-property :end (org-element-at-point)))))
23338 (let ((element (org-element-at-point)))
23339 (end-of-line)
23340 (push-mark (org-element-property :end element) t t)
23341 (goto-char (org-element-property :begin element))))))
23343 (defun org-narrow-to-element ()
23344 "Narrow buffer to current element."
23345 (interactive)
23346 (let ((elem (org-element-at-point)))
23347 (cond
23348 ((eq (car elem) 'headline)
23349 (narrow-to-region
23350 (org-element-property :begin elem)
23351 (org-element-property :end elem)))
23352 ((memq (car elem) org-element-greater-elements)
23353 (narrow-to-region
23354 (org-element-property :contents-begin elem)
23355 (org-element-property :contents-end elem)))
23357 (narrow-to-region
23358 (org-element-property :begin elem)
23359 (org-element-property :end elem))))))
23361 (defun org-transpose-element ()
23362 "Transpose current and previous elements, keeping blank lines between.
23363 Point is moved after both elements."
23364 (interactive)
23365 (org-skip-whitespace)
23366 (let ((end (org-element-property :end (org-element-at-point))))
23367 (org-drag-element-backward)
23368 (goto-char end)))
23370 (defun org-unindent-buffer ()
23371 "Un-indent the visible part of the buffer.
23372 Relative indentation (between items, inside blocks, etc.) isn't
23373 modified."
23374 (interactive)
23375 (unless (eq major-mode 'org-mode)
23376 (user-error "Cannot un-indent a buffer not in Org mode"))
23377 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23378 unindent-tree ; For byte-compiler.
23379 (unindent-tree
23380 (function
23381 (lambda (contents)
23382 (mapc
23383 (lambda (element)
23384 (if (memq (org-element-type element) '(headline section))
23385 (funcall unindent-tree (org-element-contents element))
23386 (save-excursion
23387 (save-restriction
23388 (narrow-to-region
23389 (org-element-property :begin element)
23390 (org-element-property :end element))
23391 (org-do-remove-indentation)))))
23392 (reverse contents))))))
23393 (funcall unindent-tree (org-element-contents parse-tree))))
23395 (defun org-show-subtree ()
23396 "Show everything after this heading at deeper levels."
23397 (interactive)
23398 (outline-flag-region
23399 (point)
23400 (save-excursion
23401 (org-end-of-subtree t t))
23402 nil))
23404 (defun org-show-entry ()
23405 "Show the body directly following this heading.
23406 Show the heading too, if it is currently invisible."
23407 (interactive)
23408 (save-excursion
23409 (condition-case nil
23410 (progn
23411 (org-back-to-heading t)
23412 (outline-flag-region
23413 (max (point-min) (1- (point)))
23414 (save-excursion
23415 (if (re-search-forward
23416 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23417 (match-beginning 1)
23418 (point-max)))
23419 nil)
23420 (org-cycle-hide-drawers 'children))
23421 (error nil))))
23423 (defun org-make-options-regexp (kwds &optional extra)
23424 "Make a regular expression for keyword lines."
23425 (concat
23426 "^#\\+\\("
23427 (mapconcat 'regexp-quote kwds "\\|")
23428 (if extra (concat "\\|" extra))
23429 "\\):[ \t]*\\(.*\\)"))
23431 ;; Make isearch reveal the necessary context
23432 (defun org-isearch-end ()
23433 "Reveal context after isearch exits."
23434 (when isearch-success ; only if search was successful
23435 (if (featurep 'xemacs)
23436 ;; Under XEmacs, the hook is run in the correct place,
23437 ;; we directly show the context.
23438 (org-show-context 'isearch)
23439 ;; In Emacs the hook runs *before* restoring the overlays.
23440 ;; So we have to use a one-time post-command-hook to do this.
23441 ;; (Emacs 22 has a special variable, see function `org-mode')
23442 (unless (and (boundp 'isearch-mode-end-hook-quit)
23443 isearch-mode-end-hook-quit)
23444 ;; Only when the isearch was not quitted.
23445 (org-add-hook 'post-command-hook 'org-isearch-post-command
23446 'append 'local)))
23447 (org-fix-ellipsis-at-bol)))
23449 (defun org-isearch-post-command ()
23450 "Remove self from hook, and show context."
23451 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23452 (org-show-context 'isearch))
23455 ;;;; Integration with and fixes for other packages
23457 ;;; Imenu support
23459 (defvar org-imenu-markers nil
23460 "All markers currently used by Imenu.")
23461 (make-variable-buffer-local 'org-imenu-markers)
23463 (defun org-imenu-new-marker (&optional pos)
23464 "Return a new marker for use by Imenu, and remember the marker."
23465 (let ((m (make-marker)))
23466 (move-marker m (or pos (point)))
23467 (push m org-imenu-markers)
23470 (defun org-imenu-get-tree ()
23471 "Produce the index for Imenu."
23472 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23473 (setq org-imenu-markers nil)
23474 (let* ((n org-imenu-depth)
23475 (re (concat "^" (org-get-limited-outline-regexp)))
23476 (subs (make-vector (1+ n) nil))
23477 (last-level 0)
23478 m level head0 head)
23479 (save-excursion
23480 (save-restriction
23481 (widen)
23482 (goto-char (point-max))
23483 (while (re-search-backward re nil t)
23484 (setq level (org-reduced-level (funcall outline-level)))
23485 (when (and (<= level n)
23486 (looking-at org-complex-heading-regexp)
23487 (setq head0 (org-match-string-no-properties 4)))
23488 (setq head (org-link-display-format head0)
23489 m (org-imenu-new-marker))
23490 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23491 (if (>= level last-level)
23492 (push (cons head m) (aref subs level))
23493 (push (cons head (aref subs (1+ level))) (aref subs level))
23494 (loop for i from (1+ level) to n do (aset subs i nil)))
23495 (setq last-level level)))))
23496 (aref subs 1)))
23498 (eval-after-load "imenu"
23499 '(progn
23500 (add-hook 'imenu-after-jump-hook
23501 (lambda ()
23502 (if (derived-mode-p 'org-mode)
23503 (org-show-context 'org-goto))))))
23505 (defun org-link-display-format (link)
23506 "Replace a link with its the description.
23507 If there is no description, use the link target."
23508 (save-match-data
23509 (if (string-match org-bracket-link-analytic-regexp link)
23510 (replace-match (if (match-end 5)
23511 (match-string 5 link)
23512 (concat (match-string 1 link)
23513 (match-string 3 link)))
23514 nil t link)
23515 link)))
23517 (defun org-toggle-link-display ()
23518 "Toggle the literal or descriptive display of links."
23519 (interactive)
23520 (if org-descriptive-links
23521 (progn (org-remove-from-invisibility-spec '(org-link))
23522 (org-restart-font-lock)
23523 (setq org-descriptive-links nil))
23524 (progn (add-to-invisibility-spec '(org-link))
23525 (org-restart-font-lock)
23526 (setq org-descriptive-links t))))
23528 ;; Speedbar support
23530 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23531 "Overlay marking the agenda restriction line in speedbar.")
23532 (overlay-put org-speedbar-restriction-lock-overlay
23533 'face 'org-agenda-restriction-lock)
23534 (overlay-put org-speedbar-restriction-lock-overlay
23535 'help-echo "Agendas are currently limited to this item.")
23536 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23538 (defun org-speedbar-set-agenda-restriction ()
23539 "Restrict future agenda commands to the location at point in speedbar.
23540 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23541 (interactive)
23542 (require 'org-agenda)
23543 (let (p m tp np dir txt)
23544 (cond
23545 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23546 'org-imenu t))
23547 (setq m (get-text-property p 'org-imenu-marker))
23548 (with-current-buffer (marker-buffer m)
23549 (goto-char m)
23550 (org-agenda-set-restriction-lock 'subtree)))
23551 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23552 'speedbar-function 'speedbar-find-file))
23553 (setq tp (previous-single-property-change
23554 (1+ p) 'speedbar-function)
23555 np (next-single-property-change
23556 tp 'speedbar-function)
23557 dir (speedbar-line-directory)
23558 txt (buffer-substring-no-properties (or tp (point-min))
23559 (or np (point-max))))
23560 (with-current-buffer (find-file-noselect
23561 (let ((default-directory dir))
23562 (expand-file-name txt)))
23563 (unless (derived-mode-p 'org-mode)
23564 (user-error "Cannot restrict to non-Org-mode file"))
23565 (org-agenda-set-restriction-lock 'file)))
23566 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23567 (move-overlay org-speedbar-restriction-lock-overlay
23568 (point-at-bol) (point-at-eol))
23569 (setq current-prefix-arg nil)
23570 (org-agenda-maybe-redo)))
23572 (eval-after-load "speedbar"
23573 '(progn
23574 (speedbar-add-supported-extension ".org")
23575 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23576 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23577 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23578 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23579 (add-hook 'speedbar-visiting-tag-hook
23580 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23582 ;;; Fixes and Hacks for problems with other packages
23584 ;; Make flyspell not check words in links, to not mess up our keymap
23585 (defvar org-element-affiliated-keywords) ; From org-element.el
23586 (defvar org-element-block-name-alist) ; From org-element.el
23587 (defun org-mode-flyspell-verify ()
23588 "Don't let flyspell put overlays at active buttons, or on
23589 {todo,all-time,additional-option-like}-keywords."
23590 (require 'org-element) ; For `org-element-affiliated-keywords'
23591 (let ((pos (max (1- (point)) (point-min)))
23592 (word (thing-at-point 'word)))
23593 (and (not (get-text-property pos 'keymap))
23594 (not (get-text-property pos 'org-no-flyspell))
23595 (not (member word org-todo-keywords-1))
23596 (not (member word org-all-time-keywords))
23597 (not (member word org-options-keywords))
23598 (not (member word (mapcar 'car org-startup-options)))
23599 (not (member-ignore-case word org-element-affiliated-keywords))
23600 (not (member-ignore-case word (org-get-export-keywords)))
23601 (not (member-ignore-case
23602 word (mapcar 'car org-element-block-name-alist)))
23603 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23605 (defun org-remove-flyspell-overlays-in (beg end)
23606 "Remove flyspell overlays in region."
23607 (and (org-bound-and-true-p flyspell-mode)
23608 (fboundp 'flyspell-delete-region-overlays)
23609 (flyspell-delete-region-overlays beg end))
23610 (add-text-properties beg end '(org-no-flyspell t)))
23612 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23613 (eval-after-load "bookmark"
23614 '(if (boundp 'bookmark-after-jump-hook)
23615 ;; We can use the hook
23616 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23617 ;; Hook not available, use advice
23618 (defadvice bookmark-jump (after org-make-visible activate)
23619 "Make the position visible."
23620 (org-bookmark-jump-unhide))))
23622 ;; Make sure saveplace shows the location if it was hidden
23623 (eval-after-load "saveplace"
23624 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23625 "Make the position visible."
23626 (org-bookmark-jump-unhide)))
23628 ;; Make sure ecb shows the location if it was hidden
23629 (eval-after-load "ecb"
23630 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23631 "Make hierarchy visible when jumping into location from ECB tree buffer."
23632 (if (derived-mode-p 'org-mode)
23633 (org-show-context))))
23635 (defun org-bookmark-jump-unhide ()
23636 "Unhide the current position, to show the bookmark location."
23637 (and (derived-mode-p 'org-mode)
23638 (or (outline-invisible-p)
23639 (save-excursion (goto-char (max (point-min) (1- (point))))
23640 (outline-invisible-p)))
23641 (org-show-context 'bookmark-jump)))
23643 ;; Make session.el ignore our circular variable
23644 (eval-after-load "session"
23645 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23647 ;;;; Finish up
23649 (provide 'org)
23651 (run-hooks 'org-load-hook)
23653 ;;; org.el ends here