Unescape :help-echo for links
[org-mode.git] / lisp / org.el
blob5412028178a924110b9efa738c2eba04f36cca88
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: Bastien Guerry <bzg at gnu 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/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro `org-with-limited-levels'.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches a headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (unless (boundp 'calendar-view-holidays-initially-flag)
107 (org-defvaralias 'calendar-view-holidays-initially-flag
108 'view-calendar-holidays-initially))
109 (unless (boundp 'calendar-view-diary-initially-flag)
110 (org-defvaralias 'calendar-view-diary-initially-flag
111 'view-diary-entries-initially))
112 (unless (boundp 'diary-fancy-buffer)
113 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
115 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
116 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
117 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
118 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "ox-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-table-set-constants "org-table" ())
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export-registered-backends) ; From ox.el
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VALUE stands for the
455 new value of the variable, after updating it:
457 \(progn
458 \(setq org-export-registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(or (memq backend val)
462 \(catch 'parentp
463 \(mapc
464 \(lambda (b)
465 \(and (org-export-derived-backend-p b (car backend))
466 \(throw 'parentp t)))
467 val)
468 nil)))
469 org-export-registered-backends))
470 \(let ((new-list (mapcar 'car org-export-registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default var new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export-registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (or (memq backend val)
495 (catch 'parentp
496 (mapc
497 (lambda (b)
498 (and (org-export-derived-backend-p b (car backend))
499 (throw 'parentp t)))
500 val)
501 nil)))
502 org-export-registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'car org-export-registered-backends)))
506 (dolist (backend val)
507 (cond
508 ((not (load (format "ox-%s" backend) t t))
509 (message "Problems while trying to load export back-end `%s'"
510 backend))
511 ((not (memq backend new-list)) (push backend new-list))))
512 ;; Set VAR to that list with fixed dependencies.
513 (set-default var new-list))))
514 :type '(set :greedy t
515 (const :tag " ascii Export buffer to ASCII format" ascii)
516 (const :tag " beamer Export buffer to Beamer presentation" beamer)
517 (const :tag " html Export buffer to HTML format" html)
518 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
519 (const :tag " latex Export buffer to LaTeX format" latex)
520 (const :tag " man Export buffer to MAN format" man)
521 (const :tag " md Export buffer to Markdown format" md)
522 (const :tag " odt Export buffer to ODT format" odt)
523 (const :tag " org Export buffer to Org format" org)
524 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
525 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
526 (const :tag "C deck Export buffer to deck.js presentations" deck)
527 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
528 (const :tag "C groff Export buffer to Groff format" groff)
529 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
530 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
531 (const :tag "C s5 Export buffer to s5 presentations" s5)
532 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
534 (eval-after-load 'ox
535 '(mapc
536 (lambda (backend)
537 (condition-case nil (require (intern (format "ox-%s" backend)))
538 (error (message "Problems while trying to load export back-end `%s'"
539 backend))))
540 org-export-backends))
542 (defcustom org-support-shift-select nil
543 "Non-nil means make shift-cursor commands select text when possible.
545 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
546 start selecting a region, or enlarge regions started in this way.
547 In Org-mode, in special contexts, these same keys are used for
548 other purposes, important enough to compete with shift selection.
549 Org tries to balance these needs by supporting `shift-select-mode'
550 outside these special contexts, under control of this variable.
552 The default of this variable is nil, to avoid confusing behavior. Shifted
553 cursor keys will then execute Org commands in the following contexts:
554 - on a headline, changing TODO state (left/right) and priority (up/down)
555 - on a time stamp, changing the time
556 - in a plain list item, changing the bullet type
557 - in a property definition line, switching between allowed values
558 - in the BEGIN line of a clock table (changing the time block).
559 Outside these contexts, the commands will throw an error.
561 When this variable is t and the cursor is not in a special
562 context, Org-mode will support shift-selection for making and
563 enlarging regions. To make this more effective, the bullet
564 cycling will no longer happen anywhere in an item line, but only
565 if the cursor is exactly on the bullet.
567 If you set this variable to the symbol `always', then the keys
568 will not be special in headlines, property lines, and item lines,
569 to make shift selection work there as well. If this is what you
570 want, you can use the following alternative commands: `C-c C-t'
571 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
572 can be used to switch TODO sets, `C-c -' to cycle item bullet
573 types, and properties can be edited by hand or in column view.
575 However, when the cursor is on a timestamp, shift-cursor commands
576 will still edit the time stamp - this is just too good to give up.
578 XEmacs user should have this variable set to nil, because
579 `shift-select-mode' is in Emacs 23 or later only."
580 :group 'org
581 :type '(choice
582 (const :tag "Never" nil)
583 (const :tag "When outside special context" t)
584 (const :tag "Everywhere except timestamps" always)))
586 (defcustom org-loop-over-headlines-in-active-region nil
587 "Shall some commands act upon headlines in the active region?
589 When set to `t', some commands will be performed in all headlines
590 within the active region.
592 When set to `start-level', some commands will be performed in all
593 headlines within the active region, provided that these headlines
594 are of the same level than the first one.
596 When set to a string, those commands will be performed on the
597 matching headlines within the active region. Such string must be
598 a tags/property/todo match as it is used in the agenda tags view.
600 The list of commands is: `org-schedule', `org-deadline',
601 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
602 `org-archive-to-archive-sibling'. The archiving commands skip
603 already archived entries."
604 :type '(choice (const :tag "Don't loop" nil)
605 (const :tag "All headlines in active region" t)
606 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
607 (string :tag "Tags/Property/Todo matcher"))
608 :version "24.1"
609 :group 'org-todo
610 :group 'org-archive)
612 (defgroup org-startup nil
613 "Options concerning startup of Org-mode."
614 :tag "Org Startup"
615 :group 'org)
617 (defcustom org-startup-folded t
618 "Non-nil means entering Org-mode will switch to OVERVIEW.
619 This can also be configured on a per-file basis by adding one of
620 the following lines anywhere in the buffer:
622 #+STARTUP: fold (or `overview', this is equivalent)
623 #+STARTUP: nofold (or `showall', this is equivalent)
624 #+STARTUP: content
625 #+STARTUP: showeverything
627 By default, this option is ignored when Org opens agenda files
628 for the first time. If you want the agenda to honor the startup
629 option, set `org-agenda-inhibit-startup' to nil."
630 :group 'org-startup
631 :type '(choice
632 (const :tag "nofold: show all" nil)
633 (const :tag "fold: overview" t)
634 (const :tag "content: all headlines" content)
635 (const :tag "show everything, even drawers" showeverything)))
637 (defcustom org-startup-truncated t
638 "Non-nil means entering Org-mode will set `truncate-lines'.
639 This is useful since some lines containing links can be very long and
640 uninteresting. Also tables look terrible when wrapped."
641 :group 'org-startup
642 :type 'boolean)
644 (defcustom org-startup-indented nil
645 "Non-nil means turn on `org-indent-mode' on startup.
646 This can also be configured on a per-file basis by adding one of
647 the following lines anywhere in the buffer:
649 #+STARTUP: indent
650 #+STARTUP: noindent"
651 :group 'org-structure
652 :type '(choice
653 (const :tag "Not" nil)
654 (const :tag "Globally (slow on startup in large files)" t)))
656 (defcustom org-use-sub-superscripts t
657 "Non-nil means interpret \"_\" and \"^\" for display.
658 When this option is turned on, you can use TeX-like syntax for sub- and
659 superscripts. Several characters after \"_\" or \"^\" will be
660 considered as a single item - so grouping with {} is normally not
661 needed. For example, the following things will be parsed as single
662 sub- or superscripts.
664 10^24 or 10^tau several digits will be considered 1 item.
665 10^-12 or 10^-tau a leading sign with digits or a word
666 x^2-y^3 will be read as x^2 - y^3, because items are
667 terminated by almost any nonword/nondigit char.
668 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
670 Still, ambiguity is possible - so when in doubt use {} to enclose
671 the sub/superscript. If you set this variable to the symbol
672 `{}', the braces are *required* in order to trigger
673 interpretations as sub/superscript. This can be helpful in
674 documents that need \"_\" frequently in plain text."
675 :group 'org-startup
676 :version "24.1"
677 :type '(choice
678 (const :tag "Always interpret" t)
679 (const :tag "Only with braces" {})
680 (const :tag "Never interpret" nil)))
682 (defcustom org-startup-with-beamer-mode nil
683 "Non-nil means turn on `org-beamer-mode' on startup.
684 This can also be configured on a per-file basis by adding one of
685 the following lines anywhere in the buffer:
687 #+STARTUP: beamer"
688 :group 'org-startup
689 :version "24.1"
690 :type 'boolean)
692 (defcustom org-startup-align-all-tables nil
693 "Non-nil means align all tables when visiting a file.
694 This is useful when the column width in tables is forced with <N> cookies
695 in table fields. Such tables will look correct only after the first re-align.
696 This can also be configured on a per-file basis by adding one of
697 the following lines anywhere in the buffer:
698 #+STARTUP: align
699 #+STARTUP: noalign"
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-startup-with-inline-images nil
704 "Non-nil means show inline images when loading a new Org file.
705 This can also be configured on a per-file basis by adding one of
706 the following lines anywhere in the buffer:
707 #+STARTUP: inlineimages
708 #+STARTUP: noinlineimages"
709 :group 'org-startup
710 :version "24.1"
711 :type 'boolean)
713 (defcustom org-startup-with-latex-preview nil
714 "Non-nil means preview LaTeX fragments when loading a new Org file.
716 This can also be configured on a per-file basis by adding one of
717 the followinglines anywhere in the buffer:
718 #+STARTUP: latexpreview
719 #+STARTUP: nolatexpreview"
720 :group 'org-startup
721 :version "24.4"
722 :package-version '(Org . "8.0")
723 :type 'boolean)
725 (defcustom org-insert-mode-line-in-empty-file nil
726 "Non-nil means insert the first line setting Org-mode in empty files.
727 When the function `org-mode' is called interactively in an empty file, this
728 normally means that the file name does not automatically trigger Org-mode.
729 To ensure that the file will always be in Org-mode in the future, a
730 line enforcing Org-mode will be inserted into the buffer, if this option
731 has been set."
732 :group 'org-startup
733 :type 'boolean)
735 (defcustom org-replace-disputed-keys nil
736 "Non-nil means use alternative key bindings for some keys.
737 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
738 These keys are also used by other packages like shift-selection-mode'
739 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
740 If you want to use Org-mode together with one of these other modes,
741 or more generally if you would like to move some Org-mode commands to
742 other keys, set this variable and configure the keys with the variable
743 `org-disputed-keys'.
745 This option is only relevant at load-time of Org-mode, and must be set
746 *before* org.el is loaded. Changing it requires a restart of Emacs to
747 become effective."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-use-extra-keys nil
752 "Non-nil means use extra key sequence definitions for certain commands.
753 This happens automatically if you run XEmacs or if `window-system'
754 is nil. This variable lets you do the same manually. You must
755 set it before loading org.
757 Example: on Carbon Emacs 22 running graphically, with an external
758 keyboard on a Powerbook, the default way of setting M-left might
759 not work for either Alt or ESC. Setting this variable will make
760 it work for ESC."
761 :group 'org-startup
762 :type 'boolean)
764 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
766 (defcustom org-disputed-keys
767 '(([(shift up)] . [(meta p)])
768 ([(shift down)] . [(meta n)])
769 ([(shift left)] . [(meta -)])
770 ([(shift right)] . [(meta +)])
771 ([(control shift right)] . [(meta shift +)])
772 ([(control shift left)] . [(meta shift -)]))
773 "Keys for which Org-mode and other modes compete.
774 This is an alist, cars are the default keys, second element specifies
775 the alternative to use when `org-replace-disputed-keys' is t.
777 Keys can be specified in any syntax supported by `define-key'.
778 The value of this option takes effect only at Org-mode's startup,
779 therefore you'll have to restart Emacs to apply it after changing."
780 :group 'org-startup
781 :type 'alist)
783 (defun org-key (key)
784 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
785 Or return the original if not disputed.
786 Also apply the translations defined in `org-xemacs-key-equivalents'."
787 (when org-replace-disputed-keys
788 (let* ((nkey (key-description key))
789 (x (org-find-if (lambda (x)
790 (equal (key-description (car x)) nkey))
791 org-disputed-keys)))
792 (setq key (if x (cdr x) key))))
793 (when (featurep 'xemacs)
794 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
795 key)
797 (defun org-find-if (predicate seq)
798 (catch 'exit
799 (while seq
800 (if (funcall predicate (car seq))
801 (throw 'exit (car seq))
802 (pop seq)))))
804 (defun org-defkey (keymap key def)
805 "Define a key, possibly translated, as returned by `org-key'."
806 (define-key keymap (org-key key) def))
808 (defcustom org-ellipsis nil
809 "The ellipsis to use in the Org-mode outline.
810 When nil, just use the standard three dots. When a string, use that instead,
811 When a face, use the standard 3 dots, but with the specified face.
812 The change affects only Org-mode (which will then use its own display table).
813 Changing this requires executing `M-x org-mode' in a buffer to become
814 effective."
815 :group 'org-startup
816 :type '(choice (const :tag "Default" nil)
817 (face :tag "Face" :value org-warning)
818 (string :tag "String" :value "...#")))
820 (defvar org-display-table nil
821 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
823 (defgroup org-keywords nil
824 "Keywords in Org-mode."
825 :tag "Org Keywords"
826 :group 'org)
828 (defcustom org-deadline-string "DEADLINE:"
829 "String to mark deadline entries.
830 A deadline is this string, followed by a time stamp. Should be a word,
831 terminated by a colon. You can insert a schedule keyword and
832 a timestamp with \\[org-deadline].
833 Changes become only effective after restarting Emacs."
834 :group 'org-keywords
835 :type 'string)
837 (defcustom org-scheduled-string "SCHEDULED:"
838 "String to mark scheduled TODO entries.
839 A schedule is this string, followed by a time stamp. Should be a word,
840 terminated by a colon. You can insert a schedule keyword and
841 a timestamp with \\[org-schedule].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-closed-string "CLOSED:"
847 "String used as the prefix for timestamps logging closing a TODO entry."
848 :group 'org-keywords
849 :type 'string)
851 (defcustom org-clock-string "CLOCK:"
852 "String used as prefix for timestamps clocking work hours on an item."
853 :group 'org-keywords
854 :type 'string)
856 (defcustom org-closed-keep-when-no-todo nil
857 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
858 :group 'org-todo
859 :group 'org-keywords
860 :version "24.4"
861 :package-version '(Org . "8.0")
862 :type 'boolean)
864 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
865 org-scheduled-string "\\|"
866 org-deadline-string "\\|"
867 org-closed-string "\\|"
868 org-clock-string "\\)")
869 "Matches a line with planning or clock info.")
871 (defcustom org-comment-string "COMMENT"
872 "Entries starting with this keyword will never be exported.
873 An entry can be toggled between COMMENT and normal with
874 \\[org-toggle-comment].
875 Changes become only effective after restarting Emacs."
876 :group 'org-keywords
877 :type 'string)
879 (defcustom org-quote-string "QUOTE"
880 "Entries starting with this keyword will be exported in fixed-width font.
881 Quoting applies only to the text in the entry following the headline, and does
882 not extend beyond the next headline, even if that is lower level.
883 An entry can be toggled between QUOTE and normal with
884 \\[org-toggle-fixed-width-section]."
885 :group 'org-keywords
886 :type 'string)
888 (defconst org-repeat-re
889 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
890 "Regular expression for specifying repeated events.
891 After a match, group 1 contains the repeat expression.")
893 (defgroup org-structure nil
894 "Options concerning the general structure of Org-mode files."
895 :tag "Org Structure"
896 :group 'org)
898 (defgroup org-reveal-location nil
899 "Options about how to make context of a location visible."
900 :tag "Org Reveal Location"
901 :group 'org-structure)
903 (defconst org-context-choice
904 '(choice
905 (const :tag "Always" t)
906 (const :tag "Never" nil)
907 (repeat :greedy t :tag "Individual contexts"
908 (cons
909 (choice :tag "Context"
910 (const agenda)
911 (const org-goto)
912 (const occur-tree)
913 (const tags-tree)
914 (const link-search)
915 (const mark-goto)
916 (const bookmark-jump)
917 (const isearch)
918 (const default))
919 (boolean))))
920 "Contexts for the reveal options.")
922 (defcustom org-show-hierarchy-above '((default . t))
923 "Non-nil means show full hierarchy when revealing a location.
924 Org-mode often shows locations in an org-mode file which might have
925 been invisible before. When this is set, the hierarchy of headings
926 above the exposed location is shown.
927 Turning this off for example for sparse trees makes them very compact.
928 Instead of t, this can also be an alist specifying this option for different
929 contexts. Valid contexts are
930 agenda when exposing an entry from the agenda
931 org-goto when using the command `org-goto' on key C-c C-j
932 occur-tree when using the command `org-occur' on key C-c /
933 tags-tree when constructing a sparse tree based on tags matches
934 link-search when exposing search matches associated with a link
935 mark-goto when exposing the jump goal of a mark
936 bookmark-jump when exposing a bookmark location
937 isearch when exiting from an incremental search
938 default default for all contexts not set explicitly"
939 :group 'org-reveal-location
940 :type org-context-choice)
942 (defcustom org-show-following-heading '((default . nil))
943 "Non-nil means show following heading when revealing a location.
944 Org-mode often shows locations in an org-mode file which might have
945 been invisible before. When this is set, the heading following the
946 match is shown.
947 Turning this off for example for sparse trees makes them very compact,
948 but makes it harder to edit the location of the match. In such a case,
949 use the command \\[org-reveal] to show more context.
950 Instead of t, this can also be an alist specifying this option for different
951 contexts. See `org-show-hierarchy-above' for valid contexts."
952 :group 'org-reveal-location
953 :type org-context-choice)
955 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
956 "Non-nil means show all sibling heading when revealing a location.
957 Org-mode often shows locations in an org-mode file which might have
958 been invisible before. When this is set, the sibling of the current entry
959 heading are all made visible. If `org-show-hierarchy-above' is t,
960 the same happens on each level of the hierarchy above the current entry.
962 By default this is on for the isearch context, off for all other contexts.
963 Turning this off for example for sparse trees makes them very compact,
964 but makes it harder to edit the location of the match. In such a case,
965 use the command \\[org-reveal] to show more context.
966 Instead of t, this can also be an alist specifying this option for different
967 contexts. See `org-show-hierarchy-above' for valid contexts."
968 :group 'org-reveal-location
969 :type org-context-choice
970 :version "24.4"
971 :package-version '(Org . "8.0"))
973 (defcustom org-show-entry-below '((default . nil))
974 "Non-nil means show the entry below a headline when revealing a location.
975 Org-mode often shows locations in an org-mode file which might have
976 been invisible before. When this is set, the text below the headline that is
977 exposed is also shown.
979 By default this is off for all contexts.
980 Instead of t, this can also be an alist specifying this option for different
981 contexts. See `org-show-hierarchy-above' for valid contexts."
982 :group 'org-reveal-location
983 :type org-context-choice)
985 (defcustom org-indirect-buffer-display 'other-window
986 "How should indirect tree buffers be displayed?
987 This applies to indirect buffers created with the commands
988 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
989 Valid values are:
990 current-window Display in the current window
991 other-window Just display in another window.
992 dedicated-frame Create one new frame, and re-use it each time.
993 new-frame Make a new frame each time. Note that in this case
994 previously-made indirect buffers are kept, and you need to
995 kill these buffers yourself."
996 :group 'org-structure
997 :group 'org-agenda-windows
998 :type '(choice
999 (const :tag "In current window" current-window)
1000 (const :tag "In current frame, other window" other-window)
1001 (const :tag "Each time a new frame" new-frame)
1002 (const :tag "One dedicated frame" dedicated-frame)))
1004 (defcustom org-use-speed-commands nil
1005 "Non-nil means activate single letter commands at beginning of a headline.
1006 This may also be a function to test for appropriate locations where speed
1007 commands should be active."
1008 :group 'org-structure
1009 :type '(choice
1010 (const :tag "Never" nil)
1011 (const :tag "At beginning of headline stars" t)
1012 (function)))
1014 (defcustom org-speed-commands-user nil
1015 "Alist of additional speed commands.
1016 This list will be checked before `org-speed-commands-default'
1017 when the variable `org-use-speed-commands' is non-nil
1018 and when the cursor is at the beginning of a headline.
1019 The car if each entry is a string with a single letter, which must
1020 be assigned to `self-insert-command' in the global map.
1021 The cdr is either a command to be called interactively, a function
1022 to be called, or a form to be evaluated.
1023 An entry that is just a list with a single string will be interpreted
1024 as a descriptive headline that will be added when listing the speed
1025 commands in the Help buffer using the `?' speed command."
1026 :group 'org-structure
1027 :type '(repeat :value ("k" . ignore)
1028 (choice :value ("k" . ignore)
1029 (list :tag "Descriptive Headline" (string :tag "Headline"))
1030 (cons :tag "Letter and Command"
1031 (string :tag "Command letter")
1032 (choice
1033 (function)
1034 (sexp))))))
1036 (defgroup org-cycle nil
1037 "Options concerning visibility cycling in Org-mode."
1038 :tag "Org Cycle"
1039 :group 'org-structure)
1041 (defcustom org-cycle-skip-children-state-if-no-children t
1042 "Non-nil means skip CHILDREN state in entries that don't have any."
1043 :group 'org-cycle
1044 :type 'boolean)
1046 (defcustom org-cycle-max-level nil
1047 "Maximum level which should still be subject to visibility cycling.
1048 Levels higher than this will, for cycling, be treated as text, not a headline.
1049 When `org-odd-levels-only' is set, a value of N in this variable actually
1050 means 2N-1 stars as the limiting headline.
1051 When nil, cycle all levels.
1052 Note that the limiting level of cycling is also influenced by
1053 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1054 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1055 than its value."
1056 :group 'org-cycle
1057 :type '(choice
1058 (const :tag "No limit" nil)
1059 (integer :tag "Maximum level")))
1061 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1062 "Names of drawers. Drawers are not opened by cycling on the headline above.
1063 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1064 this:
1065 :DRAWERNAME:
1066 .....
1067 :END:
1068 The drawer \"PROPERTIES\" is special for capturing properties through
1069 the property API.
1071 Drawers can be defined on the per-file basis with a line like:
1073 #+DRAWERS: HIDDEN STATE PROPERTIES"
1074 :group 'org-structure
1075 :group 'org-cycle
1076 :type '(repeat (string :tag "Drawer Name")))
1078 (defcustom org-hide-block-startup nil
1079 "Non-nil means entering Org-mode will fold all blocks.
1080 This can also be set in on a per-file basis with
1082 #+STARTUP: hideblocks
1083 #+STARTUP: showblocks"
1084 :group 'org-startup
1085 :group 'org-cycle
1086 :type 'boolean)
1088 (defcustom org-cycle-global-at-bob nil
1089 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1090 This makes it possible to do global cycling without having to use S-TAB or
1091 \\[universal-argument] TAB. For this special case to work, the first line
1092 of the buffer must not be a headline -- it may be empty or some other text.
1093 When used in this way, `org-cycle-hook' is disabled temporarily to make
1094 sure the cursor stays at the beginning of the buffer. When this option is
1095 nil, don't do anything special at the beginning of the buffer."
1096 :group 'org-cycle
1097 :type 'boolean)
1099 (defcustom org-cycle-level-after-item/entry-creation t
1100 "Non-nil means cycle entry level or item indentation in new empty entries.
1102 When the cursor is at the end of an empty headline, i.e., with only stars
1103 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1104 and then all possible ancestor states, before returning to the original state.
1105 This makes data entry extremely fast: M-RET to create a new headline,
1106 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1108 When the cursor is at the end of an empty plain list item, one TAB will
1109 make it a subitem, two or more tabs will back up to make this an item
1110 higher up in the item hierarchy."
1111 :group 'org-cycle
1112 :type 'boolean)
1114 (defcustom org-cycle-emulate-tab t
1115 "Where should `org-cycle' emulate TAB.
1116 nil Never
1117 white Only in completely white lines
1118 whitestart Only at the beginning of lines, before the first non-white char
1119 t Everywhere except in headlines
1120 exc-hl-bol Everywhere except at the start of a headline
1121 If TAB is used in a place where it does not emulate TAB, the current subtree
1122 visibility is cycled."
1123 :group 'org-cycle
1124 :type '(choice (const :tag "Never" nil)
1125 (const :tag "Only in completely white lines" white)
1126 (const :tag "Before first char in a line" whitestart)
1127 (const :tag "Everywhere except in headlines" t)
1128 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1130 (defcustom org-cycle-separator-lines 2
1131 "Number of empty lines needed to keep an empty line between collapsed trees.
1132 If you leave an empty line between the end of a subtree and the following
1133 headline, this empty line is hidden when the subtree is folded.
1134 Org-mode will leave (exactly) one empty line visible if the number of
1135 empty lines is equal or larger to the number given in this variable.
1136 So the default 2 means at least 2 empty lines after the end of a subtree
1137 are needed to produce free space between a collapsed subtree and the
1138 following headline.
1140 If the number is negative, and the number of empty lines is at least -N,
1141 all empty lines are shown.
1143 Special case: when 0, never leave empty lines in collapsed view."
1144 :group 'org-cycle
1145 :type 'integer)
1146 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1148 (defcustom org-pre-cycle-hook nil
1149 "Hook that is run before visibility cycling is happening.
1150 The function(s) in this hook must accept a single argument which indicates
1151 the new state that will be set right after running this hook. The
1152 argument is a symbol. Before a global state change, it can have the values
1153 `overview', `content', or `all'. Before a local state change, it can have
1154 the values `folded', `children', or `subtree'."
1155 :group 'org-cycle
1156 :type 'hook)
1158 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1159 org-cycle-hide-drawers
1160 org-cycle-hide-inline-tasks
1161 org-cycle-show-empty-lines
1162 org-optimize-window-after-visibility-change)
1163 "Hook that is run after `org-cycle' has changed the buffer visibility.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that was set by the most recent `org-cycle' command. The
1166 argument is a symbol. After a global state change, it can have the values
1167 `overview', `contents', or `all'. After a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defgroup org-edit-structure nil
1173 "Options concerning structure editing in Org-mode."
1174 :tag "Org Edit Structure"
1175 :group 'org-structure)
1177 (defcustom org-odd-levels-only nil
1178 "Non-nil means skip even levels and only use odd levels for the outline.
1179 This has the effect that two stars are being added/taken away in
1180 promotion/demotion commands. It also influences how levels are
1181 handled by the exporters.
1182 Changing it requires restart of `font-lock-mode' to become effective
1183 for fontification also in regions already fontified.
1184 You may also set this on a per-file basis by adding one of the following
1185 lines to the buffer:
1187 #+STARTUP: odd
1188 #+STARTUP: oddeven"
1189 :group 'org-edit-structure
1190 :group 'org-appearance
1191 :type 'boolean)
1193 (defcustom org-adapt-indentation t
1194 "Non-nil means adapt indentation to outline node level.
1196 When this variable is set, Org assumes that you write outlines by
1197 indenting text in each node to align with the headline (after the stars).
1198 The following issues are influenced by this variable:
1200 - When this is set and the *entire* text in an entry is indented, the
1201 indentation is increased by one space in a demotion command, and
1202 decreased by one in a promotion command. If any line in the entry
1203 body starts with text at column 0, indentation is not changed at all.
1205 - Property drawers and planning information is inserted indented when
1206 this variable s set. When nil, they will not be indented.
1208 - TAB indents a line relative to context. The lines below a headline
1209 will be indented when this variable is set.
1211 Note that this is all about true indentation, by adding and removing
1212 space characters. See also `org-indent.el' which does level-dependent
1213 indentation in a virtual way, i.e. at display time in Emacs."
1214 :group 'org-edit-structure
1215 :type 'boolean)
1217 (defcustom org-special-ctrl-a/e nil
1218 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1220 When t, `C-a' will bring back the cursor to the beginning of the
1221 headline text, i.e. after the stars and after a possible TODO
1222 keyword. In an item, this will be the position after bullet and
1223 check-box, if any. When the cursor is already at that position,
1224 another `C-a' will bring it to the beginning of the line.
1226 `C-e' will jump to the end of the headline, ignoring the presence
1227 of tags in the headline. A second `C-e' will then jump to the
1228 true end of the line, after any tags. This also means that, when
1229 this variable is non-nil, `C-e' also will never jump beyond the
1230 end of the heading of a folded section, i.e. not after the
1231 ellipses.
1233 When set to the symbol `reversed', the first `C-a' or `C-e' works
1234 normally, going to the true line boundary first. Only a directly
1235 following, identical keypress will bring the cursor to the
1236 special positions.
1238 This may also be a cons cell where the behavior for `C-a' and
1239 `C-e' is set separately."
1240 :group 'org-edit-structure
1241 :type '(choice
1242 (const :tag "off" nil)
1243 (const :tag "on: after stars/bullet and before tags first" t)
1244 (const :tag "reversed: true line boundary first" reversed)
1245 (cons :tag "Set C-a and C-e separately"
1246 (choice :tag "Special C-a"
1247 (const :tag "off" nil)
1248 (const :tag "on: after stars/bullet first" t)
1249 (const :tag "reversed: before stars/bullet first" reversed))
1250 (choice :tag "Special C-e"
1251 (const :tag "off" nil)
1252 (const :tag "on: before tags first" t)
1253 (const :tag "reversed: after tags first" reversed)))))
1254 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1256 (defcustom org-special-ctrl-k nil
1257 "Non-nil means `C-k' will behave specially in headlines.
1258 When nil, `C-k' will call the default `kill-line' command.
1259 When t, the following will happen while the cursor is in the headline:
1261 - When the cursor is at the beginning of a headline, kill the entire
1262 line and possible the folded subtree below the line.
1263 - When in the middle of the headline text, kill the headline up to the tags.
1264 - When after the headline text, kill the tags."
1265 :group 'org-edit-structure
1266 :type 'boolean)
1268 (defcustom org-ctrl-k-protect-subtree nil
1269 "Non-nil means, do not delete a hidden subtree with C-k.
1270 When set to the symbol `error', simply throw an error when C-k is
1271 used to kill (part-of) a headline that has hidden text behind it.
1272 Any other non-nil value will result in a query to the user, if it is
1273 OK to kill that hidden subtree. When nil, kill without remorse."
1274 :group 'org-edit-structure
1275 :version "24.1"
1276 :type '(choice
1277 (const :tag "Do not protect hidden subtrees" nil)
1278 (const :tag "Protect hidden subtrees with a security query" t)
1279 (const :tag "Never kill a hidden subtree with C-k" error)))
1281 (defcustom org-catch-invisible-edits nil
1282 "Check if in invisible region before inserting or deleting a character.
1283 Valid values are:
1285 nil Do not check, so just do invisible edits.
1286 error Throw an error and do nothing.
1287 show Make point visible, and do the requested edit.
1288 show-and-error Make point visible, then throw an error and abort the edit.
1289 smart Make point visible, and do insertion/deletion if it is
1290 adjacent to visible text and the change feels predictable.
1291 Never delete a previously invisible character or add in the
1292 middle or right after an invisible region. Basically, this
1293 allows insertion and backward-delete right before ellipses.
1294 FIXME: maybe in this case we should not even show?"
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not check" nil)
1299 (const :tag "Throw error when trying to edit" error)
1300 (const :tag "Unhide, but do not do the edit" show-and-error)
1301 (const :tag "Show invisible part and do the edit" show)
1302 (const :tag "Be smart and do the right thing" smart)))
1304 (defcustom org-yank-folded-subtrees t
1305 "Non-nil means when yanking subtrees, fold them.
1306 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1307 it starts with a heading and all other headings in it are either children
1308 or siblings, then fold all the subtrees. However, do this only if no
1309 text after the yank would be swallowed into a folded tree by this action."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-yank-adjusted-subtrees nil
1314 "Non-nil means when yanking subtrees, adjust the level.
1315 With this setting, `org-paste-subtree' is used to insert the subtree, see
1316 this function for details."
1317 :group 'org-edit-structure
1318 :type 'boolean)
1320 (defcustom org-M-RET-may-split-line '((default . t))
1321 "Non-nil means M-RET will split the line at the cursor position.
1322 When nil, it will go to the end of the line before making a
1323 new line.
1324 You may also set this option in a different way for different
1325 contexts. Valid contexts are:
1327 headline when creating a new headline
1328 item when creating a new item
1329 table in a table field
1330 default the value to be used for all contexts not explicitly
1331 customized"
1332 :group 'org-structure
1333 :group 'org-table
1334 :type '(choice
1335 (const :tag "Always" t)
1336 (const :tag "Never" nil)
1337 (repeat :greedy t :tag "Individual contexts"
1338 (cons
1339 (choice :tag "Context"
1340 (const headline)
1341 (const item)
1342 (const table)
1343 (const default))
1344 (boolean)))))
1347 (defcustom org-insert-heading-respect-content nil
1348 "Non-nil means insert new headings after the current subtree.
1349 When nil, the new heading is created directly after the current line.
1350 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1351 this variable on for the duration of the command."
1352 :group 'org-structure
1353 :type 'boolean)
1355 (defcustom org-blank-before-new-entry '((heading . auto)
1356 (plain-list-item . auto))
1357 "Should `org-insert-heading' leave a blank line before new heading/item?
1358 The value is an alist, with `heading' and `plain-list-item' as CAR,
1359 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1360 which case Org will look at the surrounding headings/items and try to
1361 make an intelligent decision whether to insert a blank line or not.
1363 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1364 the setting here is ignored and no empty line is inserted to avoid breaking
1365 the list structure."
1366 :group 'org-edit-structure
1367 :type '(list
1368 (cons (const heading)
1369 (choice (const :tag "Never" nil)
1370 (const :tag "Always" t)
1371 (const :tag "Auto" auto)))
1372 (cons (const plain-list-item)
1373 (choice (const :tag "Never" nil)
1374 (const :tag "Always" t)
1375 (const :tag "Auto" auto)))))
1377 (defcustom org-insert-heading-hook nil
1378 "Hook being run after inserting a new heading."
1379 :group 'org-edit-structure
1380 :type 'hook)
1382 (defcustom org-enable-fixed-width-editor t
1383 "Non-nil means lines starting with \":\" are treated as fixed-width.
1384 This currently only means they are never auto-wrapped.
1385 When nil, such lines will be treated like ordinary lines.
1386 See also the QUOTE keyword."
1387 :group 'org-edit-structure
1388 :type 'boolean)
1390 (defcustom org-goto-auto-isearch t
1391 "Non-nil means typing characters in `org-goto' starts incremental search.
1392 When nil, you can use these keybindings to navigate the buffer:
1394 q Quit the org-goto interface
1395 n Go to the next visible heading
1396 p Go to the previous visible heading
1397 f Go one heading forward on same level
1398 b Go one heading backward on same level
1399 u Go one heading up"
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defgroup org-sparse-trees nil
1404 "Options concerning sparse trees in Org-mode."
1405 :tag "Org Sparse Trees"
1406 :group 'org-structure)
1408 (defcustom org-highlight-sparse-tree-matches t
1409 "Non-nil means highlight all matches that define a sparse tree.
1410 The highlights will automatically disappear the next time the buffer is
1411 changed by an edit command."
1412 :group 'org-sparse-trees
1413 :type 'boolean)
1415 (defcustom org-remove-highlights-with-change t
1416 "Non-nil means any change to the buffer will remove temporary highlights.
1417 Such highlights are created by `org-occur' and `org-clock-display'.
1418 When nil, `C-c C-c needs to be used to get rid of the highlights.
1419 The highlights created by `org-preview-latex-fragment' always need
1420 `C-c C-c' to be removed."
1421 :group 'org-sparse-trees
1422 :group 'org-time
1423 :type 'boolean)
1426 (defcustom org-occur-hook '(org-first-headline-recenter)
1427 "Hook that is run after `org-occur' has constructed a sparse tree.
1428 This can be used to recenter the window to show as much of the structure
1429 as possible."
1430 :group 'org-sparse-trees
1431 :type 'hook)
1433 (defgroup org-imenu-and-speedbar nil
1434 "Options concerning imenu and speedbar in Org-mode."
1435 :tag "Org Imenu and Speedbar"
1436 :group 'org-structure)
1438 (defcustom org-imenu-depth 2
1439 "The maximum level for Imenu access to Org-mode headlines.
1440 This also applied for speedbar access."
1441 :group 'org-imenu-and-speedbar
1442 :type 'integer)
1444 (defgroup org-table nil
1445 "Options concerning tables in Org-mode."
1446 :tag "Org Table"
1447 :group 'org)
1449 (defcustom org-enable-table-editor 'optimized
1450 "Non-nil means lines starting with \"|\" are handled by the table editor.
1451 When nil, such lines will be treated like ordinary lines.
1453 When equal to the symbol `optimized', the table editor will be optimized to
1454 do the following:
1455 - Automatic overwrite mode in front of whitespace in table fields.
1456 This makes the structure of the table stay in tact as long as the edited
1457 field does not exceed the column width.
1458 - Minimize the number of realigns. Normally, the table is aligned each time
1459 TAB or RET are pressed to move to another field. With optimization this
1460 happens only if changes to a field might have changed the column width.
1461 Optimization requires replacing the functions `self-insert-command',
1462 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1463 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1464 very good at guessing when a re-align will be necessary, but you can always
1465 force one with \\[org-ctrl-c-ctrl-c].
1467 If you would like to use the optimized version in Org-mode, but the
1468 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1470 This variable can be used to turn on and off the table editor during a session,
1471 but in order to toggle optimization, a restart is required.
1473 See also the variable `org-table-auto-blank-field'."
1474 :group 'org-table
1475 :type '(choice
1476 (const :tag "off" nil)
1477 (const :tag "on" t)
1478 (const :tag "on, optimized" optimized)))
1480 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1481 (version<= emacs-version "24.1"))
1482 "Non-nil means cluster self-insert commands for undo when possible.
1483 If this is set, then, like in the Emacs command loop, 20 consecutive
1484 characters will be undone together.
1485 This is configurable, because there is some impact on typing performance."
1486 :group 'org-table
1487 :type 'boolean)
1489 (defcustom org-table-tab-recognizes-table.el t
1490 "Non-nil means TAB will automatically notice a table.el table.
1491 When it sees such a table, it moves point into it and - if necessary -
1492 calls `table-recognize-table'."
1493 :group 'org-table-editing
1494 :type 'boolean)
1496 (defgroup org-link nil
1497 "Options concerning links in Org-mode."
1498 :tag "Org Link"
1499 :group 'org)
1501 (defvar org-link-abbrev-alist-local nil
1502 "Buffer-local version of `org-link-abbrev-alist', which see.
1503 The value of this is taken from the #+LINK lines.")
1504 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1506 (defcustom org-link-abbrev-alist nil
1507 "Alist of link abbreviations.
1508 The car of each element is a string, to be replaced at the start of a link.
1509 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1510 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1512 [[linkkey:tag][description]]
1514 The 'linkkey' must be a word word, starting with a letter, followed
1515 by letters, numbers, '-' or '_'.
1517 If REPLACE is a string, the tag will simply be appended to create the link.
1518 If the string contains \"%s\", the tag will be inserted there. If the string
1519 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1520 at that point (see the function `url-hexify-string'). If the string contains
1521 the specifier \"%(my-function)\", then the custom function `my-function' will
1522 be invoked: this function takes the tag as its only argument and must return
1523 a string.
1525 REPLACE may also be a function that will be called with the tag as the
1526 only argument to create the link, which should be returned as a string.
1528 See the manual for examples."
1529 :group 'org-link
1530 :type '(repeat
1531 (cons
1532 (string :tag "Protocol")
1533 (choice
1534 (string :tag "Format")
1535 (function)))))
1537 (defcustom org-descriptive-links t
1538 "Non-nil means Org will display descriptive links.
1539 E.g. [[http://orgmode.org][Org website]] will be displayed as
1540 \"Org Website\", hiding the link itself and just displaying its
1541 description. When set to `nil', Org will display the full links
1542 literally.
1544 You can interactively set the value of this variable by calling
1545 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1546 :group 'org-link
1547 :type 'boolean)
1549 (defcustom org-link-file-path-type 'adaptive
1550 "How the path name in file links should be stored.
1551 Valid values are:
1553 relative Relative to the current directory, i.e. the directory of the file
1554 into which the link is being inserted.
1555 absolute Absolute path, if possible with ~ for home directory.
1556 noabbrev Absolute path, no abbreviation of home directory.
1557 adaptive Use relative path for files in the current directory and sub-
1558 directories of it. For other files, use an absolute path."
1559 :group 'org-link
1560 :type '(choice
1561 (const relative)
1562 (const absolute)
1563 (const noabbrev)
1564 (const adaptive)))
1566 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1567 "Types of links that should be activated in Org-mode files.
1568 This is a list of symbols, each leading to the activation of a certain link
1569 type. In principle, it does not hurt to turn on most link types - there may
1570 be a small gain when turning off unused link types. The types are:
1572 bracket The recommended [[link][description]] or [[link]] links with hiding.
1573 angle Links in angular brackets that may contain whitespace like
1574 <bbdb:Carsten Dominik>.
1575 plain Plain links in normal text, no whitespace, like http://google.com.
1576 radio Text that is matched by a radio target, see manual for details.
1577 tag Tag settings in a headline (link to tag search).
1578 date Time stamps (link to calendar).
1579 footnote Footnote labels.
1581 Changing this variable requires a restart of Emacs to become effective."
1582 :group 'org-link
1583 :type '(set :greedy t
1584 (const :tag "Double bracket links" bracket)
1585 (const :tag "Angular bracket links" angle)
1586 (const :tag "Plain text links" plain)
1587 (const :tag "Radio target matches" radio)
1588 (const :tag "Tags" tag)
1589 (const :tag "Timestamps" date)
1590 (const :tag "Footnotes" footnote)))
1592 (defcustom org-make-link-description-function nil
1593 "Function to use for generating link descriptions from links.
1594 When nil, the link location will be used. This function must take
1595 two parameters: the first one is the link, the second one is the
1596 description generated by `org-insert-link'. The function should
1597 return the description to use."
1598 :group 'org-link
1599 :type 'function)
1601 (defgroup org-link-store nil
1602 "Options concerning storing links in Org-mode."
1603 :tag "Org Store Link"
1604 :group 'org-link)
1606 (defcustom org-url-hexify-p t
1607 "When non-nil, hexify URL when creating a link."
1608 :type 'boolean
1609 :version "24.3"
1610 :group 'org-link-store)
1612 (defcustom org-email-link-description-format "Email %c: %.30s"
1613 "Format of the description part of a link to an email or usenet message.
1614 The following %-escapes will be replaced by corresponding information:
1616 %F full \"From\" field
1617 %f name, taken from \"From\" field, address if no name
1618 %T full \"To\" field
1619 %t first name in \"To\" field, address if no name
1620 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1621 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1622 %s subject
1623 %d date
1624 %m message-id.
1626 You may use normal field width specification between the % and the letter.
1627 This is for example useful to limit the length of the subject.
1629 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1630 :group 'org-link-store
1631 :type 'string)
1633 (defcustom org-from-is-user-regexp
1634 (let (r1 r2)
1635 (when (and user-mail-address (not (string= user-mail-address "")))
1636 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1637 (when (and user-full-name (not (string= user-full-name "")))
1638 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1639 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1640 "Regexp matched against the \"From:\" header of an email or usenet message.
1641 It should match if the message is from the user him/herself."
1642 :group 'org-link-store
1643 :type 'regexp)
1645 (defcustom org-context-in-file-links t
1646 "Non-nil means file links from `org-store-link' contain context.
1647 A search string will be added to the file name with :: as separator and
1648 used to find the context when the link is activated by the command
1649 `org-open-at-point'. When this option is t, the entire active region
1650 will be placed in the search string of the file link. If set to a
1651 positive integer, only the first n lines of context will be stored.
1653 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1654 negates this setting for the duration of the command."
1655 :group 'org-link-store
1656 :type '(choice boolean integer))
1658 (defcustom org-keep-stored-link-after-insertion nil
1659 "Non-nil means keep link in list for entire session.
1661 The command `org-store-link' adds a link pointing to the current
1662 location to an internal list. These links accumulate during a session.
1663 The command `org-insert-link' can be used to insert links into any
1664 Org-mode file (offering completion for all stored links). When this
1665 option is nil, every link which has been inserted once using \\[org-insert-link]
1666 will be removed from the list, to make completing the unused links
1667 more efficient."
1668 :group 'org-link-store
1669 :type 'boolean)
1671 (defgroup org-link-follow nil
1672 "Options concerning following links in Org-mode."
1673 :tag "Org Follow Link"
1674 :group 'org-link)
1676 (defcustom org-link-translation-function nil
1677 "Function to translate links with different syntax to Org syntax.
1678 This can be used to translate links created for example by the Planner
1679 or emacs-wiki packages to Org syntax.
1680 The function must accept two parameters, a TYPE containing the link
1681 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1682 which is everything after the link protocol. It should return a cons
1683 with possibly modified values of type and path.
1684 Org contains a function for this, so if you set this variable to
1685 `org-translate-link-from-planner', you should be able follow many
1686 links created by planner."
1687 :group 'org-link-follow
1688 :type 'function)
1690 (defcustom org-follow-link-hook nil
1691 "Hook that is run after a link has been followed."
1692 :group 'org-link-follow
1693 :type 'hook)
1695 (defcustom org-tab-follows-link nil
1696 "Non-nil means on links TAB will follow the link.
1697 Needs to be set before org.el is loaded.
1698 This really should not be used, it does not make sense, and the
1699 implementation is bad."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-return-follows-link nil
1704 "Non-nil means on links RET will follow the link.
1705 In tables, the special behavior of RET has precedence."
1706 :group 'org-link-follow
1707 :type 'boolean)
1709 (defcustom org-mouse-1-follows-link
1710 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1711 "Non-nil means mouse-1 on a link will follow the link.
1712 A longer mouse click will still set point. Does not work on XEmacs.
1713 Needs to be set before org.el is loaded."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-mark-ring-length 4
1718 "Number of different positions to be recorded in the ring.
1719 Changing this requires a restart of Emacs to work correctly."
1720 :group 'org-link-follow
1721 :type 'integer)
1723 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1724 "Non-nil means internal links in Org files must exactly match a headline.
1725 When nil, the link search tries to match a phrase with all words
1726 in the search text."
1727 :group 'org-link-follow
1728 :version "24.1"
1729 :type '(choice
1730 (const :tag "Use fuzzy text search" nil)
1731 (const :tag "Match only exact headline" t)
1732 (const :tag "Match exact headline or query to create it"
1733 query-to-create)))
1735 (defcustom org-link-frame-setup
1736 '((vm . vm-visit-folder-other-frame)
1737 (vm-imap . vm-visit-imap-folder-other-frame)
1738 (gnus . org-gnus-no-new-news)
1739 (file . find-file-other-window)
1740 (wl . wl-other-frame))
1741 "Setup the frame configuration for following links.
1742 When following a link with Emacs, it may often be useful to display
1743 this link in another window or frame. This variable can be used to
1744 set this up for the different types of links.
1745 For VM, use any of
1746 `vm-visit-folder'
1747 `vm-visit-folder-other-window'
1748 `vm-visit-folder-other-frame'
1749 For Gnus, use any of
1750 `gnus'
1751 `gnus-other-frame'
1752 `org-gnus-no-new-news'
1753 For FILE, use any of
1754 `find-file'
1755 `find-file-other-window'
1756 `find-file-other-frame'
1757 For Wanderlust use any of
1758 `wl'
1759 `wl-other-frame'
1760 For the calendar, use the variable `calendar-setup'.
1761 For BBDB, it is currently only possible to display the matches in
1762 another window."
1763 :group 'org-link-follow
1764 :type '(list
1765 (cons (const vm)
1766 (choice
1767 (const vm-visit-folder)
1768 (const vm-visit-folder-other-window)
1769 (const vm-visit-folder-other-frame)))
1770 (cons (const gnus)
1771 (choice
1772 (const gnus)
1773 (const gnus-other-frame)
1774 (const org-gnus-no-new-news)))
1775 (cons (const file)
1776 (choice
1777 (const find-file)
1778 (const find-file-other-window)
1779 (const find-file-other-frame)))
1780 (cons (const wl)
1781 (choice
1782 (const wl)
1783 (const wl-other-frame)))))
1785 (defcustom org-display-internal-link-with-indirect-buffer nil
1786 "Non-nil means use indirect buffer to display infile links.
1787 Activating internal links (from one location in a file to another location
1788 in the same file) normally just jumps to the location. When the link is
1789 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1790 is displayed in
1791 another window. When this option is set, the other window actually displays
1792 an indirect buffer clone of the current buffer, to avoid any visibility
1793 changes to the current buffer."
1794 :group 'org-link-follow
1795 :type 'boolean)
1797 (defcustom org-open-non-existing-files nil
1798 "Non-nil means `org-open-file' will open non-existing files.
1799 When nil, an error will be generated.
1800 This variable applies only to external applications because they
1801 might choke on non-existing files. If the link is to a file that
1802 will be opened in Emacs, the variable is ignored."
1803 :group 'org-link-follow
1804 :type 'boolean)
1806 (defcustom org-open-directory-means-index-dot-org nil
1807 "Non-nil means a link to a directory really means to index.org.
1808 When nil, following a directory link will run dired or open a finder/explorer
1809 window on that directory."
1810 :group 'org-link-follow
1811 :type 'boolean)
1813 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1814 "Function and arguments to call for following mailto links.
1815 This is a list with the first element being a Lisp function, and the
1816 remaining elements being arguments to the function. In string arguments,
1817 %a will be replaced by the address, and %s will be replaced by the subject
1818 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1822 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1823 (const :tag "message-mail" (message-mail "%a" "%s"))
1824 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1826 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1827 "Non-nil means ask for confirmation before executing shell links.
1828 Shell links can be dangerous: just think about a link
1830 [[shell:rm -rf ~/*][Google Search]]
1832 This link would show up in your Org-mode document as \"Google Search\",
1833 but really it would remove your entire home directory.
1834 Therefore we advise against setting this variable to nil.
1835 Just change it to `y-or-n-p' if you want to confirm with a
1836 single keystroke rather than having to type \"yes\"."
1837 :group 'org-link-follow
1838 :type '(choice
1839 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1840 (const :tag "with y-or-n (faster)" y-or-n-p)
1841 (const :tag "no confirmation (dangerous)" nil)))
1842 (put 'org-confirm-shell-link-function
1843 'safe-local-variable
1844 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1846 (defcustom org-confirm-shell-link-not-regexp ""
1847 "A regexp to skip confirmation for shell links."
1848 :group 'org-link-follow
1849 :version "24.1"
1850 :type 'regexp)
1852 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1853 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1854 Elisp links can be dangerous: just think about a link
1856 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1858 This link would show up in your Org-mode document as \"Google Search\",
1859 but really it would remove your entire home directory.
1860 Therefore we advise against setting this variable to nil.
1861 Just change it to `y-or-n-p' if you want to confirm with a
1862 single keystroke rather than having to type \"yes\"."
1863 :group 'org-link-follow
1864 :type '(choice
1865 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1866 (const :tag "with y-or-n (faster)" y-or-n-p)
1867 (const :tag "no confirmation (dangerous)" nil)))
1868 (put 'org-confirm-shell-link-function
1869 'safe-local-variable
1870 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1872 (defcustom org-confirm-elisp-link-not-regexp ""
1873 "A regexp to skip confirmation for Elisp links."
1874 :group 'org-link-follow
1875 :version "24.1"
1876 :type 'regexp)
1878 (defconst org-file-apps-defaults-gnu
1879 '((remote . emacs)
1880 (system . mailcap)
1881 (t . mailcap))
1882 "Default file applications on a UNIX or GNU/Linux system.
1883 See `org-file-apps'.")
1885 (defconst org-file-apps-defaults-macosx
1886 '((remote . emacs)
1887 (t . "open %s")
1888 (system . "open %s")
1889 ("ps.gz" . "gv %s")
1890 ("eps.gz" . "gv %s")
1891 ("dvi" . "xdvi %s")
1892 ("fig" . "xfig %s"))
1893 "Default file applications on a MacOS X system.
1894 The system \"open\" is known as a default, but we use X11 applications
1895 for some files for which the OS does not have a good default.
1896 See `org-file-apps'.")
1898 (defconst org-file-apps-defaults-windowsnt
1899 (list
1900 '(remote . emacs)
1901 (cons t
1902 (list (if (featurep 'xemacs)
1903 'mswindows-shell-execute
1904 'w32-shell-execute)
1905 "open" 'file))
1906 (cons 'system
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file)))
1911 "Default file applications on a Windows NT system.
1912 The system \"open\" is used for most files.
1913 See `org-file-apps'.")
1915 (defcustom org-file-apps
1916 '((auto-mode . emacs)
1917 ("\\.mm\\'" . default)
1918 ("\\.x?html?\\'" . default)
1919 ("\\.pdf\\'" . default))
1920 "External applications for opening `file:path' items in a document.
1921 Org-mode uses system defaults for different file types, but
1922 you can use this variable to set the application for a given file
1923 extension. The entries in this list are cons cells where the car identifies
1924 files and the cdr the corresponding command. Possible values for the
1925 file identifier are
1926 \"string\" A string as a file identifier can be interpreted in different
1927 ways, depending on its contents:
1929 - Alphanumeric characters only:
1930 Match links with this file extension.
1931 Example: (\"pdf\" . \"evince %s\")
1932 to open PDFs with evince.
1934 - Regular expression: Match links where the
1935 filename matches the regexp. If you want to
1936 use groups here, use shy groups.
1938 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1939 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1940 to open *.html and *.xhtml with firefox.
1942 - Regular expression which contains (non-shy) groups:
1943 Match links where the whole link, including \"::\", and
1944 anything after that, matches the regexp.
1945 In a custom command string, %1, %2, etc. are replaced with
1946 the parts of the link that were matched by the groups.
1947 For backwards compatibility, if a command string is given
1948 that does not use any of the group matches, this case is
1949 handled identically to the second one (i.e. match against
1950 file name only).
1951 In a custom lisp form, you can access the group matches with
1952 (match-string n link).
1954 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1955 to open [[file:document.pdf::5]] with evince at page 5.
1957 `directory' Matches a directory
1958 `remote' Matches a remote file, accessible through tramp or efs.
1959 Remote files most likely should be visited through Emacs
1960 because external applications cannot handle such paths.
1961 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1962 so all files Emacs knows how to handle. Using this with
1963 command `emacs' will open most files in Emacs. Beware that this
1964 will also open html files inside Emacs, unless you add
1965 (\"html\" . default) to the list as well.
1966 t Default for files not matched by any of the other options.
1967 `system' The system command to open files, like `open' on Windows
1968 and Mac OS X, and mailcap under GNU/Linux. This is the command
1969 that will be selected if you call `C-c C-o' with a double
1970 \\[universal-argument] \\[universal-argument] prefix.
1972 Possible values for the command are:
1973 `emacs' The file will be visited by the current Emacs process.
1974 `default' Use the default application for this file type, which is the
1975 association for t in the list, most likely in the system-specific
1976 part.
1977 This can be used to overrule an unwanted setting in the
1978 system-specific variable.
1979 `system' Use the system command for opening files, like \"open\".
1980 This command is specified by the entry whose car is `system'.
1981 Most likely, the system-specific version of this variable
1982 does define this command, but you can overrule/replace it
1983 here.
1984 string A command to be executed by a shell; %s will be replaced
1985 by the path to the file.
1986 sexp A Lisp form which will be evaluated. The file path will
1987 be available in the Lisp variable `file'.
1988 For more examples, see the system specific constants
1989 `org-file-apps-defaults-macosx'
1990 `org-file-apps-defaults-windowsnt'
1991 `org-file-apps-defaults-gnu'."
1992 :group 'org-link-follow
1993 :type '(repeat
1994 (cons (choice :value ""
1995 (string :tag "Extension")
1996 (const :tag "System command to open files" system)
1997 (const :tag "Default for unrecognized files" t)
1998 (const :tag "Remote file" remote)
1999 (const :tag "Links to a directory" directory)
2000 (const :tag "Any files that have Emacs modes"
2001 auto-mode))
2002 (choice :value ""
2003 (const :tag "Visit with Emacs" emacs)
2004 (const :tag "Use default" default)
2005 (const :tag "Use the system command" system)
2006 (string :tag "Command")
2007 (sexp :tag "Lisp form")))))
2009 (defcustom org-doi-server-url "http://dx.doi.org/"
2010 "The URL of the DOI server."
2011 :type 'string
2012 :version "24.3"
2013 :group 'org-link-follow)
2015 (defgroup org-refile nil
2016 "Options concerning refiling entries in Org-mode."
2017 :tag "Org Refile"
2018 :group 'org)
2020 (defcustom org-directory "~/org"
2021 "Directory with org files.
2022 This is just a default location to look for Org files. There is no need
2023 at all to put your files into this directory. It is only used in the
2024 following situations:
2026 1. When a capture template specifies a target file that is not an
2027 absolute path. The path will then be interpreted relative to
2028 `org-directory'
2029 2. When a capture note is filed away in an interactive way (when exiting the
2030 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2031 with `org-directory' as the default path."
2032 :group 'org-refile
2033 :group 'org-remember
2034 :group 'org-capture
2035 :type 'directory)
2037 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2038 "Default target for storing notes.
2039 Used as a fall back file for org-remember.el and org-capture.el, for
2040 templates that do not specify a target file."
2041 :group 'org-refile
2042 :group 'org-remember
2043 :group 'org-capture
2044 :type '(choice
2045 (const :tag "Default from remember-data-file" nil)
2046 file))
2048 (defcustom org-goto-interface 'outline
2049 "The default interface to be used for `org-goto'.
2050 Allowed values are:
2051 outline The interface shows an outline of the relevant file
2052 and the correct heading is found by moving through
2053 the outline or by searching with incremental search.
2054 outline-path-completion Headlines in the current buffer are offered via
2055 completion. This is the interface also used by
2056 the refile command."
2057 :group 'org-refile
2058 :type '(choice
2059 (const :tag "Outline" outline)
2060 (const :tag "Outline-path-completion" outline-path-completion)))
2062 (defcustom org-goto-max-level 5
2063 "Maximum target level when running `org-goto' with refile interface."
2064 :group 'org-refile
2065 :type 'integer)
2067 (defcustom org-reverse-note-order nil
2068 "Non-nil means store new notes at the beginning of a file or entry.
2069 When nil, new notes will be filed to the end of a file or entry.
2070 This can also be a list with cons cells of regular expressions that
2071 are matched against file names, and values."
2072 :group 'org-remember
2073 :group 'org-capture
2074 :group 'org-refile
2075 :type '(choice
2076 (const :tag "Reverse always" t)
2077 (const :tag "Reverse never" nil)
2078 (repeat :tag "By file name regexp"
2079 (cons regexp boolean))))
2081 (defcustom org-log-refile nil
2082 "Information to record when a task is refiled.
2084 Possible values are:
2086 nil Don't add anything
2087 time Add a time stamp to the task
2088 note Prompt for a note and add it with template `org-log-note-headings'
2090 This option can also be set with on a per-file-basis with
2092 #+STARTUP: nologrefile
2093 #+STARTUP: logrefile
2094 #+STARTUP: lognoterefile
2096 You can have local logging settings for a subtree by setting the LOGGING
2097 property to one or more of these keywords.
2099 When bulk-refiling from the agenda, the value `note' is forbidden and
2100 will temporarily be changed to `time'."
2101 :group 'org-refile
2102 :group 'org-progress
2103 :version "24.1"
2104 :type '(choice
2105 (const :tag "No logging" nil)
2106 (const :tag "Record timestamp" time)
2107 (const :tag "Record timestamp with note." note)))
2109 (defcustom org-refile-targets nil
2110 "Targets for refiling entries with \\[org-refile].
2111 This is a list of cons cells. Each cell contains:
2112 - a specification of the files to be considered, either a list of files,
2113 or a symbol whose function or variable value will be used to retrieve
2114 a file name or a list of file names. If you use `org-agenda-files' for
2115 that, all agenda files will be scanned for targets. Nil means consider
2116 headings in the current buffer.
2117 - A specification of how to find candidate refile targets. This may be
2118 any of:
2119 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2120 This tag has to be present in all target headlines, inheritance will
2121 not be considered.
2122 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2123 todo keyword.
2124 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2125 headlines that are refiling targets.
2126 - a cons cell (:level . N). Any headline of level N is considered a target.
2127 Note that, when `org-odd-levels-only' is set, level corresponds to
2128 order in hierarchy, not to the number of stars.
2129 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2130 Note that, when `org-odd-levels-only' is set, level corresponds to
2131 order in hierarchy, not to the number of stars.
2133 Each element of this list generates a set of possible targets.
2134 The union of these sets is presented (with completion) to
2135 the user by `org-refile'.
2137 You can set the variable `org-refile-target-verify-function' to a function
2138 to verify each headline found by the simple criteria above.
2140 When this variable is nil, all top-level headlines in the current buffer
2141 are used, equivalent to the value `((nil . (:level . 1))'."
2142 :group 'org-refile
2143 :type '(repeat
2144 (cons
2145 (choice :value org-agenda-files
2146 (const :tag "All agenda files" org-agenda-files)
2147 (const :tag "Current buffer" nil)
2148 (function) (variable) (file))
2149 (choice :tag "Identify target headline by"
2150 (cons :tag "Specific tag" (const :value :tag) (string))
2151 (cons :tag "TODO keyword" (const :value :todo) (string))
2152 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2153 (cons :tag "Level number" (const :value :level) (integer))
2154 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2156 (defcustom org-refile-target-verify-function nil
2157 "Function to verify if the headline at point should be a refile target.
2158 The function will be called without arguments, with point at the
2159 beginning of the headline. It should return t and leave point
2160 where it is if the headline is a valid target for refiling.
2162 If the target should not be selected, the function must return nil.
2163 In addition to this, it may move point to a place from where the search
2164 should be continued. For example, the function may decide that the entire
2165 subtree of the current entry should be excluded and move point to the end
2166 of the subtree."
2167 :group 'org-refile
2168 :type 'function)
2170 (defcustom org-refile-use-cache nil
2171 "Non-nil means cache refile targets to speed up the process.
2172 The cache for a particular file will be updated automatically when
2173 the buffer has been killed, or when any of the marker used for flagging
2174 refile targets no longer points at a live buffer.
2175 If you have added new entries to a buffer that might themselves be targets,
2176 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2177 find that easier, `C-u C-u C-u C-c C-w'."
2178 :group 'org-refile
2179 :version "24.1"
2180 :type 'boolean)
2182 (defcustom org-refile-use-outline-path nil
2183 "Non-nil means provide refile targets as paths.
2184 So a level 3 headline will be available as level1/level2/level3.
2186 When the value is `file', also include the file name (without directory)
2187 into the path. In this case, you can also stop the completion after
2188 the file name, to get entries inserted as top level in the file.
2190 When `full-file-path', include the full file path."
2191 :group 'org-refile
2192 :type '(choice
2193 (const :tag "Not" nil)
2194 (const :tag "Yes" t)
2195 (const :tag "Start with file name" file)
2196 (const :tag "Start with full file path" full-file-path)))
2198 (defcustom org-outline-path-complete-in-steps t
2199 "Non-nil means complete the outline path in hierarchical steps.
2200 When Org-mode uses the refile interface to select an outline path
2201 \(see variable `org-refile-use-outline-path'), the completion of
2202 the path can be done is a single go, or if can be done in steps down
2203 the headline hierarchy. Going in steps is probably the best if you
2204 do not use a special completion package like `ido' or `icicles'.
2205 However, when using these packages, going in one step can be very
2206 fast, while still showing the whole path to the entry."
2207 :group 'org-refile
2208 :type 'boolean)
2210 (defcustom org-refile-allow-creating-parent-nodes nil
2211 "Non-nil means allow to create new nodes as refile targets.
2212 New nodes are then created by adding \"/new node name\" to the completion
2213 of an existing node. When the value of this variable is `confirm',
2214 new node creation must be confirmed by the user (recommended)
2215 When nil, the completion must match an existing entry.
2217 Note that, if the new heading is not seen by the criteria
2218 listed in `org-refile-targets', multiple instances of the same
2219 heading would be created by trying again to file under the new
2220 heading."
2221 :group 'org-refile
2222 :type '(choice
2223 (const :tag "Never" nil)
2224 (const :tag "Always" t)
2225 (const :tag "Prompt for confirmation" confirm)))
2227 (defcustom org-refile-active-region-within-subtree nil
2228 "Non-nil means also refile active region within a subtree.
2230 By default `org-refile' doesn't allow refiling regions if they
2231 don't contain a set of subtrees, but it might be convenient to
2232 do so sometimes: in that case, the first line of the region is
2233 converted to a headline before refiling."
2234 :group 'org-refile
2235 :version "24.1"
2236 :type 'boolean)
2238 (defgroup org-todo nil
2239 "Options concerning TODO items in Org-mode."
2240 :tag "Org TODO"
2241 :group 'org)
2243 (defgroup org-progress nil
2244 "Options concerning Progress logging in Org-mode."
2245 :tag "Org Progress"
2246 :group 'org-time)
2248 (defvar org-todo-interpretation-widgets
2249 '((:tag "Sequence (cycling hits every state)" sequence)
2250 (:tag "Type (cycling directly to DONE)" type))
2251 "The available interpretation symbols for customizing `org-todo-keywords'.
2252 Interested libraries should add to this list.")
2254 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2255 "List of TODO entry keyword sequences and their interpretation.
2256 \\<org-mode-map>This is a list of sequences.
2258 Each sequence starts with a symbol, either `sequence' or `type',
2259 indicating if the keywords should be interpreted as a sequence of
2260 action steps, or as different types of TODO items. The first
2261 keywords are states requiring action - these states will select a headline
2262 for inclusion into the global TODO list Org-mode produces. If one of
2263 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2264 signify that no further action is necessary. If \"|\" is not found,
2265 the last keyword is treated as the only DONE state of the sequence.
2267 The command \\[org-todo] cycles an entry through these states, and one
2268 additional state where no keyword is present. For details about this
2269 cycling, see the manual.
2271 TODO keywords and interpretation can also be set on a per-file basis with
2272 the special #+SEQ_TODO and #+TYP_TODO lines.
2274 Each keyword can optionally specify a character for fast state selection
2275 \(in combination with the variable `org-use-fast-todo-selection')
2276 and specifiers for state change logging, using the same syntax that
2277 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2278 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2279 indicates to record a time stamp each time this state is selected.
2281 Each keyword may also specify if a timestamp or a note should be
2282 recorded when entering or leaving the state, by adding additional
2283 characters in the parenthesis after the keyword. This looks like this:
2284 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2285 record only the time of the state change. With X and Y being either
2286 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2287 Y when leaving the state if and only if the *target* state does not
2288 define X. You may omit any of the fast-selection key or X or /Y,
2289 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2291 For backward compatibility, this variable may also be just a list
2292 of keywords. In this case the interpretation (sequence or type) will be
2293 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2294 :group 'org-todo
2295 :group 'org-keywords
2296 :type '(choice
2297 (repeat :tag "Old syntax, just keywords"
2298 (string :tag "Keyword"))
2299 (repeat :tag "New syntax"
2300 (cons
2301 (choice
2302 :tag "Interpretation"
2303 ;;Quick and dirty way to see
2304 ;;`org-todo-interpretations'. This takes the
2305 ;;place of item arguments
2306 :convert-widget
2307 (lambda (widget)
2308 (widget-put widget
2309 :args (mapcar
2310 #'(lambda (x)
2311 (widget-convert
2312 (cons 'const x)))
2313 org-todo-interpretation-widgets))
2314 widget))
2315 (repeat
2316 (string :tag "Keyword"))))))
2318 (defvar org-todo-keywords-1 nil
2319 "All TODO and DONE keywords active in a buffer.")
2320 (make-variable-buffer-local 'org-todo-keywords-1)
2321 (defvar org-todo-keywords-for-agenda nil)
2322 (defvar org-done-keywords-for-agenda nil)
2323 (defvar org-drawers-for-agenda nil)
2324 (defvar org-todo-keyword-alist-for-agenda nil)
2325 (defvar org-tag-alist-for-agenda nil
2326 "Alist of all tags from all agenda files.")
2327 (defvar org-tag-groups-alist-for-agenda nil
2328 "Alist of all groups tags from all current agenda files.")
2329 (defvar org-tag-groups-alist nil)
2330 (make-variable-buffer-local 'org-tag-groups-alist)
2331 (defvar org-agenda-contributing-files nil)
2332 (defvar org-not-done-keywords nil)
2333 (make-variable-buffer-local 'org-not-done-keywords)
2334 (defvar org-done-keywords nil)
2335 (make-variable-buffer-local 'org-done-keywords)
2336 (defvar org-todo-heads nil)
2337 (make-variable-buffer-local 'org-todo-heads)
2338 (defvar org-todo-sets nil)
2339 (make-variable-buffer-local 'org-todo-sets)
2340 (defvar org-todo-log-states nil)
2341 (make-variable-buffer-local 'org-todo-log-states)
2342 (defvar org-todo-kwd-alist nil)
2343 (make-variable-buffer-local 'org-todo-kwd-alist)
2344 (defvar org-todo-key-alist nil)
2345 (make-variable-buffer-local 'org-todo-key-alist)
2346 (defvar org-todo-key-trigger nil)
2347 (make-variable-buffer-local 'org-todo-key-trigger)
2349 (defcustom org-todo-interpretation 'sequence
2350 "Controls how TODO keywords are interpreted.
2351 This variable is in principle obsolete and is only used for
2352 backward compatibility, if the interpretation of todo keywords is
2353 not given already in `org-todo-keywords'. See that variable for
2354 more information."
2355 :group 'org-todo
2356 :group 'org-keywords
2357 :type '(choice (const sequence)
2358 (const type)))
2360 (defcustom org-use-fast-todo-selection t
2361 "Non-nil means use the fast todo selection scheme with C-c C-t.
2362 This variable describes if and under what circumstances the cycling
2363 mechanism for TODO keywords will be replaced by a single-key, direct
2364 selection scheme.
2366 When nil, fast selection is never used.
2368 When the symbol `prefix', it will be used when `org-todo' is called
2369 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2370 `C-u t' in an agenda buffer.
2372 When t, fast selection is used by default. In this case, the prefix
2373 argument forces cycling instead.
2375 In all cases, the special interface is only used if access keys have
2376 actually been assigned by the user, i.e. if keywords in the configuration
2377 are followed by a letter in parenthesis, like TODO(t)."
2378 :group 'org-todo
2379 :type '(choice
2380 (const :tag "Never" nil)
2381 (const :tag "By default" t)
2382 (const :tag "Only with C-u C-c C-t" prefix)))
2384 (defcustom org-provide-todo-statistics t
2385 "Non-nil means update todo statistics after insert and toggle.
2386 ALL-HEADLINES means update todo statistics by including headlines
2387 with no TODO keyword as well, counting them as not done.
2388 A list of TODO keywords means the same, but skip keywords that are
2389 not in this list.
2391 When this is set, todo statistics is updated in the parent of the
2392 current entry each time a todo state is changed."
2393 :group 'org-todo
2394 :type '(choice
2395 (const :tag "Yes, only for TODO entries" t)
2396 (const :tag "Yes, including all entries" 'all-headlines)
2397 (repeat :tag "Yes, for TODOs in this list"
2398 (string :tag "TODO keyword"))
2399 (other :tag "No TODO statistics" nil)))
2401 (defcustom org-hierarchical-todo-statistics t
2402 "Non-nil means TODO statistics covers just direct children.
2403 When nil, all entries in the subtree are considered.
2404 This has only an effect if `org-provide-todo-statistics' is set.
2405 To set this to nil for only a single subtree, use a COOKIE_DATA
2406 property and include the word \"recursive\" into the value."
2407 :group 'org-todo
2408 :type 'boolean)
2410 (defcustom org-after-todo-state-change-hook nil
2411 "Hook which is run after the state of a TODO item was changed.
2412 The new state (a string with a TODO keyword, or nil) is available in the
2413 Lisp variable `org-state'."
2414 :group 'org-todo
2415 :type 'hook)
2417 (defvar org-blocker-hook nil
2418 "Hook for functions that are allowed to block a state change.
2420 Functions in this hook should not modify the buffer.
2421 Each function gets as its single argument a property list,
2422 see `org-trigger-hook' for more information about this list.
2424 If any of the functions in this hook returns nil, the state change
2425 is blocked.")
2427 (defvar org-trigger-hook nil
2428 "Hook for functions that are triggered by a state change.
2430 Each function gets as its single argument a property list with at
2431 least the following elements:
2433 (:type type-of-change :position pos-at-entry-start
2434 :from old-state :to new-state)
2436 Depending on the type, more properties may be present.
2438 This mechanism is currently implemented for:
2440 TODO state changes
2441 ------------------
2442 :type todo-state-change
2443 :from previous state (keyword as a string), or nil, or a symbol
2444 'todo' or 'done', to indicate the general type of state.
2445 :to new state, like in :from")
2447 (defcustom org-enforce-todo-dependencies nil
2448 "Non-nil means undone TODO entries will block switching the parent to DONE.
2449 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2450 be blocked if any prior sibling is not yet done.
2451 Finally, if the parent is blocked because of ordered siblings of its own,
2452 the child will also be blocked."
2453 :set (lambda (var val)
2454 (set var val)
2455 (if val
2456 (add-hook 'org-blocker-hook
2457 'org-block-todo-from-children-or-siblings-or-parent)
2458 (remove-hook 'org-blocker-hook
2459 'org-block-todo-from-children-or-siblings-or-parent)))
2460 :group 'org-todo
2461 :type 'boolean)
2463 (defcustom org-enforce-todo-checkbox-dependencies nil
2464 "Non-nil means unchecked boxes will block switching the parent to DONE.
2465 When this is nil, checkboxes have no influence on switching TODO states.
2466 When non-nil, you first need to check off all check boxes before the TODO
2467 entry can be switched to DONE.
2468 This variable needs to be set before org.el is loaded, and you need to
2469 restart Emacs after a change to make the change effective. The only way
2470 to change is while Emacs is running is through the customize interface."
2471 :set (lambda (var val)
2472 (set var val)
2473 (if val
2474 (add-hook 'org-blocker-hook
2475 'org-block-todo-from-checkboxes)
2476 (remove-hook 'org-blocker-hook
2477 'org-block-todo-from-checkboxes)))
2478 :group 'org-todo
2479 :type 'boolean)
2481 (defcustom org-treat-insert-todo-heading-as-state-change nil
2482 "Non-nil means inserting a TODO heading is treated as state change.
2483 So when the command \\[org-insert-todo-heading] is used, state change
2484 logging will apply if appropriate. When nil, the new TODO item will
2485 be inserted directly, and no logging will take place."
2486 :group 'org-todo
2487 :type 'boolean)
2489 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2490 "Non-nil means switching TODO states with S-cursor counts as state change.
2491 This is the default behavior. However, setting this to nil allows a
2492 convenient way to select a TODO state and bypass any logging associated
2493 with that."
2494 :group 'org-todo
2495 :type 'boolean)
2497 (defcustom org-todo-state-tags-triggers nil
2498 "Tag changes that should be triggered by TODO state changes.
2499 This is a list. Each entry is
2501 (state-change (tag . flag) .......)
2503 State-change can be a string with a state, and empty string to indicate the
2504 state that has no TODO keyword, or it can be one of the symbols `todo'
2505 or `done', meaning any not-done or done state, respectively."
2506 :group 'org-todo
2507 :group 'org-tags
2508 :type '(repeat
2509 (cons (choice :tag "When changing to"
2510 (const :tag "Not-done state" todo)
2511 (const :tag "Done state" done)
2512 (string :tag "State"))
2513 (repeat
2514 (cons :tag "Tag action"
2515 (string :tag "Tag")
2516 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2518 (defcustom org-log-done nil
2519 "Information to record when a task moves to the DONE state.
2521 Possible values are:
2523 nil Don't add anything, just change the keyword
2524 time Add a time stamp to the task
2525 note Prompt for a note and add it with template `org-log-note-headings'
2527 This option can also be set with on a per-file-basis with
2529 #+STARTUP: nologdone
2530 #+STARTUP: logdone
2531 #+STARTUP: lognotedone
2533 You can have local logging settings for a subtree by setting the LOGGING
2534 property to one or more of these keywords."
2535 :group 'org-todo
2536 :group 'org-progress
2537 :type '(choice
2538 (const :tag "No logging" nil)
2539 (const :tag "Record CLOSED timestamp" time)
2540 (const :tag "Record CLOSED timestamp with note." note)))
2542 ;; Normalize old uses of org-log-done.
2543 (cond
2544 ((eq org-log-done t) (setq org-log-done 'time))
2545 ((and (listp org-log-done) (memq 'done org-log-done))
2546 (setq org-log-done 'note)))
2548 (defcustom org-log-reschedule nil
2549 "Information to record when the scheduling date of a tasks is modified.
2551 Possible values are:
2553 nil Don't add anything, just change the date
2554 time Add a time stamp to the task
2555 note Prompt for a note and add it with template `org-log-note-headings'
2557 This option can also be set with on a per-file-basis with
2559 #+STARTUP: nologreschedule
2560 #+STARTUP: logreschedule
2561 #+STARTUP: lognotereschedule"
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "No logging" nil)
2566 (const :tag "Record timestamp" time)
2567 (const :tag "Record timestamp with note." note)))
2569 (defcustom org-log-redeadline nil
2570 "Information to record when the deadline date of a tasks is modified.
2572 Possible values are:
2574 nil Don't add anything, just change the date
2575 time Add a time stamp to the task
2576 note Prompt for a note and add it with template `org-log-note-headings'
2578 This option can also be set with on a per-file-basis with
2580 #+STARTUP: nologredeadline
2581 #+STARTUP: logredeadline
2582 #+STARTUP: lognoteredeadline
2584 You can have local logging settings for a subtree by setting the LOGGING
2585 property to one or more of these keywords."
2586 :group 'org-todo
2587 :group 'org-progress
2588 :type '(choice
2589 (const :tag "No logging" nil)
2590 (const :tag "Record timestamp" time)
2591 (const :tag "Record timestamp with note." note)))
2593 (defcustom org-log-note-clock-out nil
2594 "Non-nil means record a note when clocking out of an item.
2595 This can also be configured on a per-file basis by adding one of
2596 the following lines anywhere in the buffer:
2598 #+STARTUP: lognoteclock-out
2599 #+STARTUP: nolognoteclock-out"
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type 'boolean)
2604 (defcustom org-log-done-with-time t
2605 "Non-nil means the CLOSED time stamp will contain date and time.
2606 When nil, only the date will be recorded."
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-note-headings
2611 '((done . "CLOSING NOTE %t")
2612 (state . "State %-12s from %-12S %t")
2613 (note . "Note taken on %t")
2614 (reschedule . "Rescheduled from %S on %t")
2615 (delschedule . "Not scheduled, was %S on %t")
2616 (redeadline . "New deadline from %S on %t")
2617 (deldeadline . "Removed deadline, was %S on %t")
2618 (refile . "Refiled on %t")
2619 (clock-out . ""))
2620 "Headings for notes added to entries.
2621 The value is an alist, with the car being a symbol indicating the note
2622 context, and the cdr is the heading to be used. The heading may also be the
2623 empty string.
2624 %t in the heading will be replaced by a time stamp.
2625 %T will be an active time stamp instead the default inactive one
2626 %d will be replaced by a short-format time stamp.
2627 %D will be replaced by an active short-format time stamp.
2628 %s will be replaced by the new TODO state, in double quotes.
2629 %S will be replaced by the old TODO state, in double quotes.
2630 %u will be replaced by the user name.
2631 %U will be replaced by the full user name.
2633 In fact, it is not a good idea to change the `state' entry, because
2634 agenda log mode depends on the format of these entries."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(list :greedy t
2638 (cons (const :tag "Heading when closing an item" done) string)
2639 (cons (const :tag
2640 "Heading when changing todo state (todo sequence only)"
2641 state) string)
2642 (cons (const :tag "Heading when just taking a note" note) string)
2643 (cons (const :tag "Heading when clocking out" clock-out) string)
2644 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2645 (cons (const :tag "Heading when rescheduling" reschedule) string)
2646 (cons (const :tag "Heading when changing deadline" redeadline) string)
2647 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2648 (cons (const :tag "Heading when refiling" refile) string)))
2650 (unless (assq 'note org-log-note-headings)
2651 (push '(note . "%t") org-log-note-headings))
2653 (defcustom org-log-into-drawer nil
2654 "Non-nil means insert state change notes and time stamps into a drawer.
2655 When nil, state changes notes will be inserted after the headline and
2656 any scheduling and clock lines, but not inside a drawer.
2658 The value of this variable should be the name of the drawer to use.
2659 LOGBOOK is proposed as the default drawer for this purpose, you can
2660 also set this to a string to define the drawer of your choice.
2662 A value of t is also allowed, representing \"LOGBOOK\".
2664 A value of t or nil can also be set with on a per-file-basis with
2666 #+STARTUP: logdrawer
2667 #+STARTUP: nologdrawer
2669 If this variable is set, `org-log-state-notes-insert-after-drawers'
2670 will be ignored.
2672 You can set the property LOG_INTO_DRAWER to overrule this setting for
2673 a subtree."
2674 :group 'org-todo
2675 :group 'org-progress
2676 :type '(choice
2677 (const :tag "Not into a drawer" nil)
2678 (const :tag "LOGBOOK" t)
2679 (string :tag "Other")))
2681 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2683 (defun org-log-into-drawer ()
2684 "Return the value of `org-log-into-drawer', but let properties overrule.
2685 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2686 used instead of the default value."
2687 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2688 (cond
2689 ((not p) org-log-into-drawer)
2690 ((equal p "nil") nil)
2691 ((equal p "t") "LOGBOOK")
2692 (t p))))
2694 (defcustom org-log-state-notes-insert-after-drawers nil
2695 "Non-nil means insert state change notes after any drawers in entry.
2696 Only the drawers that *immediately* follow the headline and the
2697 deadline/scheduled line are skipped.
2698 When nil, insert notes right after the heading and perhaps the line
2699 with deadline/scheduling if present.
2701 This variable will have no effect if `org-log-into-drawer' is
2702 set."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type 'boolean)
2707 (defcustom org-log-states-order-reversed t
2708 "Non-nil means the latest state note will be directly after heading.
2709 When nil, the state change notes will be ordered according to time.
2711 This option can also be set with on a per-file-basis with
2713 #+STARTUP: logstatesreversed
2714 #+STARTUP: nologstatesreversed"
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type 'boolean)
2719 (defcustom org-todo-repeat-to-state nil
2720 "The TODO state to which a repeater should return the repeating task.
2721 By default this is the first task in a TODO sequence, or the previous state
2722 in a TODO_TYP set. But you can specify another task here.
2723 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2724 :group 'org-todo
2725 :version "24.1"
2726 :type '(choice (const :tag "Head of sequence" nil)
2727 (string :tag "Specific state")))
2729 (defcustom org-log-repeat 'time
2730 "Non-nil means record moving through the DONE state when triggering repeat.
2731 An auto-repeating task is immediately switched back to TODO when
2732 marked DONE. If you are not logging state changes (by adding \"@\"
2733 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2734 record a closing note, there will be no record of the task moving
2735 through DONE. This variable forces taking a note anyway.
2737 nil Don't force a record
2738 time Record a time stamp
2739 note Prompt for a note and add it with template `org-log-note-headings'
2741 This option can also be set with on a per-file-basis with
2743 #+STARTUP: nologrepeat
2744 #+STARTUP: logrepeat
2745 #+STARTUP: lognoterepeat
2747 You can have local logging settings for a subtree by setting the LOGGING
2748 property to one or more of these keywords."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type '(choice
2752 (const :tag "Don't force a record" nil)
2753 (const :tag "Force recording the DONE state" time)
2754 (const :tag "Force recording a note with the DONE state" note)))
2757 (defgroup org-priorities nil
2758 "Priorities in Org-mode."
2759 :tag "Org Priorities"
2760 :group 'org-todo)
2762 (defcustom org-enable-priority-commands t
2763 "Non-nil means priority commands are active.
2764 When nil, these commands will be disabled, so that you never accidentally
2765 set a priority."
2766 :group 'org-priorities
2767 :type 'boolean)
2769 (defcustom org-highest-priority ?A
2770 "The highest priority of TODO items. A character like ?A, ?B etc.
2771 Must have a smaller ASCII number than `org-lowest-priority'."
2772 :group 'org-priorities
2773 :type 'character)
2775 (defcustom org-lowest-priority ?C
2776 "The lowest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a larger ASCII number than `org-highest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-default-priority ?B
2782 "The default priority of TODO items.
2783 This is the priority an item gets if no explicit priority is given.
2784 When starting to cycle on an empty priority the first step in the cycle
2785 depends on `org-priority-start-cycle-with-default'. The resulting first
2786 step priority must not exceed the range from `org-highest-priority' to
2787 `org-lowest-priority' which means that `org-default-priority' has to be
2788 in this range exclusive or inclusive the range boundaries. Else the
2789 first step refuses to set the default and the second will fall back
2790 to (depending on the command used) the highest or lowest priority."
2791 :group 'org-priorities
2792 :type 'character)
2794 (defcustom org-priority-start-cycle-with-default t
2795 "Non-nil means start with default priority when starting to cycle.
2796 When this is nil, the first step in the cycle will be (depending on the
2797 command used) one higher or lower than the default priority.
2798 See also `org-default-priority'."
2799 :group 'org-priorities
2800 :type 'boolean)
2802 (defcustom org-get-priority-function nil
2803 "Function to extract the priority from a string.
2804 The string is normally the headline. If this is nil Org computes the
2805 priority from the priority cookie like [#A] in the headline. It returns
2806 an integer, increasing by 1000 for each priority level.
2807 The user can set a different function here, which should take a string
2808 as an argument and return the numeric priority."
2809 :group 'org-priorities
2810 :version "24.1"
2811 :type 'function)
2813 (defgroup org-time nil
2814 "Options concerning time stamps and deadlines in Org-mode."
2815 :tag "Org Time"
2816 :group 'org)
2818 (defcustom org-insert-labeled-timestamps-at-point nil
2819 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2820 When nil, these labeled time stamps are forces into the second line of an
2821 entry, just after the headline. When scheduling from the global TODO list,
2822 the time stamp will always be forced into the second line."
2823 :group 'org-time
2824 :type 'boolean)
2826 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2827 "Formats for `format-time-string' which are used for time stamps.
2828 It is not recommended to change this constant.")
2830 (defcustom org-time-stamp-rounding-minutes '(0 5)
2831 "Number of minutes to round time stamps to.
2832 These are two values, the first applies when first creating a time stamp.
2833 The second applies when changing it with the commands `S-up' and `S-down'.
2834 When changing the time stamp, this means that it will change in steps
2835 of N minutes, as given by the second value.
2837 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2838 numbers should be factors of 60, so for example 5, 10, 15.
2840 When this is larger than 1, you can still force an exact time stamp by using
2841 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2842 and by using a prefix arg to `S-up/down' to specify the exact number
2843 of minutes to shift."
2844 :group 'org-time
2845 :get #'(lambda (var) ; Make sure both elements are there
2846 (if (integerp (default-value var))
2847 (list (default-value var) 5)
2848 (default-value var)))
2849 :type '(list
2850 (integer :tag "when inserting times")
2851 (integer :tag "when modifying times")))
2853 ;; Normalize old customizations of this variable.
2854 (when (integerp org-time-stamp-rounding-minutes)
2855 (setq org-time-stamp-rounding-minutes
2856 (list org-time-stamp-rounding-minutes
2857 org-time-stamp-rounding-minutes)))
2859 (defcustom org-display-custom-times nil
2860 "Non-nil means overlay custom formats over all time stamps.
2861 The formats are defined through the variable `org-time-stamp-custom-formats'.
2862 To turn this on on a per-file basis, insert anywhere in the file:
2863 #+STARTUP: customtime"
2864 :group 'org-time
2865 :set 'set-default
2866 :type 'sexp)
2867 (make-variable-buffer-local 'org-display-custom-times)
2869 (defcustom org-time-stamp-custom-formats
2870 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2871 "Custom formats for time stamps. See `format-time-string' for the syntax.
2872 These are overlaid over the default ISO format if the variable
2873 `org-display-custom-times' is set. Time like %H:%M should be at the
2874 end of the second format. The custom formats are also honored by export
2875 commands, if custom time display is turned on at the time of export."
2876 :group 'org-time
2877 :type 'sexp)
2879 (defun org-time-stamp-format (&optional long inactive)
2880 "Get the right format for a time string."
2881 (let ((f (if long (cdr org-time-stamp-formats)
2882 (car org-time-stamp-formats))))
2883 (if inactive
2884 (concat "[" (substring f 1 -1) "]")
2885 f)))
2887 (defcustom org-time-clocksum-format
2888 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2889 "The format string used when creating CLOCKSUM lines.
2890 This is also used when Org mode generates a time duration.
2892 The value can be a single format string containing two
2893 %-sequences, which will be filled with the number of hours and
2894 minutes in that order.
2896 Alternatively, the value can be a plist associating any of the
2897 keys :years, :months, :weeks, :days, :hours or :minutes with
2898 format strings. The time duration is formatted using only the
2899 time components that are needed and concatenating the results.
2900 If a time unit in absent, it falls back to the next smallest
2901 unit.
2903 The keys :require-years, :require-months, :require-days,
2904 :require-weeks, :require-hours, :require-minutes are also
2905 meaningful. A non-nil value for these keys indicates that the
2906 corresponding time component should always be included, even if
2907 its value is 0.
2910 For example,
2912 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2913 :require-minutes t)
2915 means durations longer than a day will be expressed in days,
2916 hours and minutes, and durations less than a day will always be
2917 expressed in hours and minutes (even for durations less than an
2918 hour).
2920 The value
2922 \(:days \"%dd\" :minutes \"%dm\")
2924 means durations longer than a day will be expressed in days and
2925 minutes, and durations less than a day will be expressed entirely
2926 in minutes (even for durations longer than an hour)."
2927 :group 'org-time
2928 :group 'org-clock
2929 :version "24.4"
2930 :package-version '(Org . "8.0")
2931 :type '(choice (string :tag "Format string")
2932 (set :tag "Plist"
2933 (group :inline t (const :tag "Years" :years)
2934 (string :tag "Format string"))
2935 (group :inline t
2936 (const :tag "Always show years" :require-years)
2937 (const t))
2938 (group :inline t (const :tag "Months" :months)
2939 (string :tag "Format string"))
2940 (group :inline t
2941 (const :tag "Always show months" :require-months)
2942 (const t))
2943 (group :inline t (const :tag "Weeks" :weeks)
2944 (string :tag "Format string"))
2945 (group :inline t
2946 (const :tag "Always show weeks" :require-weeks)
2947 (const t))
2948 (group :inline t (const :tag "Days" :days)
2949 (string :tag "Format string"))
2950 (group :inline t
2951 (const :tag "Always show days" :require-days)
2952 (const t))
2953 (group :inline t (const :tag "Hours" :hours)
2954 (string :tag "Format string"))
2955 (group :inline t
2956 (const :tag "Always show hours" :require-hours)
2957 (const t))
2958 (group :inline t (const :tag "Minutes" :minutes)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show minutes" :require-minutes)
2962 (const t)))))
2964 (defcustom org-time-clocksum-use-fractional nil
2965 "When non-nil, \\[org-clock-display] uses fractional times.
2966 See `org-time-clocksum-format' for more on time clock formats."
2967 :group 'org-time
2968 :group 'org-clock
2969 :version "24.3"
2970 :type 'boolean)
2972 (defcustom org-time-clocksum-use-effort-durations nil
2973 "When non-nil, \\[org-clock-display] uses effort durations.
2974 E.g. by default, one day is considered to be a 8 hours effort,
2975 so a task that has been clocked for 16 hours will be displayed
2976 as during 2 days in the clock display or in the clocktable.
2978 See `org-effort-durations' on how to set effort durations
2979 and `org-time-clocksum-format' for more on time clock formats."
2980 :group 'org-time
2981 :group 'org-clock
2982 :version "24.4"
2983 :package-version '(Org . "8.0")
2984 :type 'boolean)
2986 (defcustom org-time-clocksum-fractional-format "%.2f"
2987 "The format string used when creating CLOCKSUM lines,
2988 or when Org mode generates a time duration, if
2989 `org-time-clocksum-use-fractional' is enabled.
2991 The value can be a single format string containing one
2992 %-sequence, which will be filled with the number of hours as
2993 a float.
2995 Alternatively, the value can be a plist associating any of the
2996 keys :years, :months, :weeks, :days, :hours or :minutes with
2997 a format string. The time duration is formatted using the
2998 largest time unit which gives a non-zero integer part. If all
2999 specified formats have zero integer part, the smallest time unit
3000 is used."
3001 :group 'org-time
3002 :type '(choice (string :tag "Format string")
3003 (set (group :inline t (const :tag "Years" :years)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Months" :months)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Weeks" :weeks)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Days" :days)
3010 (string :tag "Format string"))
3011 (group :inline t (const :tag "Hours" :hours)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Minutes" :minutes)
3014 (string :tag "Format string")))))
3016 (defcustom org-deadline-warning-days 14
3017 "Number of days before expiration during which a deadline becomes active.
3018 This variable governs the display in sparse trees and in the agenda.
3019 When 0 or negative, it means use this number (the absolute value of it)
3020 even if a deadline has a different individual lead time specified.
3022 Custom commands can set this variable in the options section."
3023 :group 'org-time
3024 :group 'org-agenda-daily/weekly
3025 :type 'integer)
3027 (defcustom org-scheduled-delay-days 0
3028 "Number of days before a scheduled item becomes active.
3029 This variable governs the display in sparse trees and in the agenda.
3030 The default value (i.e. 0) means: don't delay scheduled item.
3031 When negative, it means use this number (the absolute value of it)
3032 even if a scheduled item has a different individual delay time
3033 specified.
3035 Custom commands can set this variable in the options section."
3036 :group 'org-time
3037 :group 'org-agenda-daily/weekly
3038 :version "24.4"
3039 :package-version '(Org . "8.0")
3040 :type 'integer)
3042 (defcustom org-read-date-prefer-future t
3043 "Non-nil means assume future for incomplete date input from user.
3044 This affects the following situations:
3045 1. The user gives a month but not a year.
3046 For example, if it is April and you enter \"feb 2\", this will be read
3047 as Feb 2, *next* year. \"May 5\", however, will be this year.
3048 2. The user gives a day, but no month.
3049 For example, if today is the 15th, and you enter \"3\", Org-mode will
3050 read this as the third of *next* month. However, if you enter \"17\",
3051 it will be considered as *this* month.
3053 If you set this variable to the symbol `time', then also the following
3054 will work:
3056 3. If the user gives a time.
3057 If the time is before now, it will be interpreted as tomorrow.
3059 Currently none of this works for ISO week specifications.
3061 When this option is nil, the current day, month and year will always be
3062 used as defaults.
3064 See also `org-agenda-jump-prefer-future'."
3065 :group 'org-time
3066 :type '(choice
3067 (const :tag "Never" nil)
3068 (const :tag "Check month and day" t)
3069 (const :tag "Check month, day, and time" time)))
3071 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3072 "Should the agenda jump command prefer the future for incomplete dates?
3073 The default is to do the same as configured in `org-read-date-prefer-future'.
3074 But you can also set a deviating value here.
3075 This may t or nil, or the symbol `org-read-date-prefer-future'."
3076 :group 'org-agenda
3077 :group 'org-time
3078 :version "24.1"
3079 :type '(choice
3080 (const :tag "Use org-read-date-prefer-future"
3081 org-read-date-prefer-future)
3082 (const :tag "Never" nil)
3083 (const :tag "Always" t)))
3085 (defcustom org-read-date-force-compatible-dates t
3086 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3088 Depending on the system Emacs is running on, certain dates cannot
3089 be represented with the type used internally to represent time.
3090 Dates between 1970-1-1 and 2038-1-1 can always be represented
3091 correctly. Some systems allow for earlier dates, some for later,
3092 some for both. One way to find out it to insert any date into an
3093 Org buffer, putting the cursor on the year and hitting S-up and
3094 S-down to test the range.
3096 When this variable is set to t, the date/time prompt will not let
3097 you specify dates outside the 1970-2037 range, so it is certain that
3098 these dates will work in whatever version of Emacs you are
3099 running, and also that you can move a file from one Emacs implementation
3100 to another. WHenever Org is forcing the year for you, it will display
3101 a message and beep.
3103 When this variable is nil, Org will check if the date is
3104 representable in the specific Emacs implementation you are using.
3105 If not, it will force a year, usually the current year, and beep
3106 to remind you. Currently this setting is not recommended because
3107 the likelihood that you will open your Org files in an Emacs that
3108 has limited date range is not negligible.
3110 A workaround for this problem is to use diary sexp dates for time
3111 stamps outside of this range."
3112 :group 'org-time
3113 :version "24.1"
3114 :type 'boolean)
3116 (defcustom org-read-date-display-live t
3117 "Non-nil means display current interpretation of date prompt live.
3118 This display will be in an overlay, in the minibuffer."
3119 :group 'org-time
3120 :type 'boolean)
3122 (defcustom org-read-date-popup-calendar t
3123 "Non-nil means pop up a calendar when prompting for a date.
3124 In the calendar, the date can be selected with mouse-1. However, the
3125 minibuffer will also be active, and you can simply enter the date as well.
3126 When nil, only the minibuffer will be available."
3127 :group 'org-time
3128 :type 'boolean)
3129 (org-defvaralias 'org-popup-calendar-for-date-prompt
3130 'org-read-date-popup-calendar)
3132 (make-obsolete-variable
3133 'org-read-date-minibuffer-setup-hook
3134 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3135 (defcustom org-read-date-minibuffer-setup-hook nil
3136 "Hook to be used to set up keys for the date/time interface.
3137 Add key definitions to `minibuffer-local-map', which will be a
3138 temporary copy.
3140 WARNING: This option is obsolete, you should use
3141 `org-read-date-minibuffer-local-map' to set up keys."
3142 :group 'org-time
3143 :type 'hook)
3145 (defcustom org-extend-today-until 0
3146 "The hour when your day really ends. Must be an integer.
3147 This has influence for the following applications:
3148 - When switching the agenda to \"today\". It it is still earlier than
3149 the time given here, the day recognized as TODAY is actually yesterday.
3150 - When a date is read from the user and it is still before the time given
3151 here, the current date and time will be assumed to be yesterday, 23:59.
3152 Also, timestamps inserted in capture templates follow this rule.
3154 IMPORTANT: This is a feature whose implementation is and likely will
3155 remain incomplete. Really, it is only here because past midnight seems to
3156 be the favorite working time of John Wiegley :-)"
3157 :group 'org-time
3158 :type 'integer)
3160 (defcustom org-use-effective-time nil
3161 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3162 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3163 \"effective time\" of any timestamps between midnight and 8am will be
3164 23:59 of the previous day."
3165 :group 'org-time
3166 :version "24.1"
3167 :type 'boolean)
3169 (defcustom org-use-last-clock-out-time-as-effective-time nil
3170 "When non-nil, use the last clock out time for `org-todo'.
3171 Note that this option has precedence over the combined use of
3172 `org-use-effective-time' and `org-extend-today-until'."
3173 :group 'org-time
3174 :version "24.4"
3175 :package-version '(Org . "8.0")
3176 :type 'boolean)
3178 (defcustom org-edit-timestamp-down-means-later nil
3179 "Non-nil means S-down will increase the time in a time stamp.
3180 When nil, S-up will increase."
3181 :group 'org-time
3182 :type 'boolean)
3184 (defcustom org-calendar-follow-timestamp-change t
3185 "Non-nil means make the calendar window follow timestamp changes.
3186 When a timestamp is modified and the calendar window is visible, it will be
3187 moved to the new date."
3188 :group 'org-time
3189 :type 'boolean)
3191 (defgroup org-tags nil
3192 "Options concerning tags in Org-mode."
3193 :tag "Org Tags"
3194 :group 'org)
3196 (defcustom org-tag-alist nil
3197 "List of tags allowed in Org-mode files.
3198 When this list is nil, Org-mode will base TAG input on what is already in the
3199 buffer.
3200 The value of this variable is an alist, the car of each entry must be a
3201 keyword as a string, the cdr may be a character that is used to select
3202 that tag through the fast-tag-selection interface.
3203 See the manual for details."
3204 :group 'org-tags
3205 :type '(repeat
3206 (choice
3207 (cons (string :tag "Tag name")
3208 (character :tag "Access char"))
3209 (list :tag "Start radio group"
3210 (const :startgroup)
3211 (option (string :tag "Group description")))
3212 (list :tag "Group tags delimiter"
3213 (const :grouptags))
3214 (list :tag "End radio group"
3215 (const :endgroup)
3216 (option (string :tag "Group description")))
3217 (const :tag "New line" (:newline)))))
3219 (defcustom org-tag-persistent-alist nil
3220 "List of tags that will always appear in all Org-mode files.
3221 This is in addition to any in buffer settings or customizations
3222 of `org-tag-alist'.
3223 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3224 The value of this variable is an alist, the car of each entry must be a
3225 keyword as a string, the cdr may be a character that is used to select
3226 that tag through the fast-tag-selection interface.
3227 See the manual for details.
3228 To disable these tags on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: noptag"
3230 :group 'org-tags
3231 :type '(repeat
3232 (choice
3233 (cons (string :tag "Tag name")
3234 (character :tag "Access char"))
3235 (const :tag "Start radio group" (:startgroup))
3236 (const :tag "Group tags delimiter" (:grouptags))
3237 (const :tag "End radio group" (:endgroup))
3238 (const :tag "New line" (:newline)))))
3240 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3241 "If non-nil, always offer completion for all tags of all agenda files.
3242 Instead of customizing this variable directly, you might want to
3243 set it locally for capture buffers, because there no list of
3244 tags in that file can be created dynamically (there are none).
3246 (add-hook 'org-capture-mode-hook
3247 (lambda ()
3248 (set (make-local-variable
3249 'org-complete-tags-always-offer-all-agenda-tags)
3250 t)))"
3251 :group 'org-tags
3252 :version "24.1"
3253 :type 'boolean)
3255 (defvar org-file-tags nil
3256 "List of tags that can be inherited by all entries in the file.
3257 The tags will be inherited if the variable `org-use-tag-inheritance'
3258 says they should be.
3259 This variable is populated from #+FILETAGS lines.")
3261 (defcustom org-use-fast-tag-selection 'auto
3262 "Non-nil means use fast tag selection scheme.
3263 This is a special interface to select and deselect tags with single keys.
3264 When nil, fast selection is never used.
3265 When the symbol `auto', fast selection is used if and only if selection
3266 characters for tags have been configured, either through the variable
3267 `org-tag-alist' or through a #+TAGS line in the buffer.
3268 When t, fast selection is always used and selection keys are assigned
3269 automatically if necessary."
3270 :group 'org-tags
3271 :type '(choice
3272 (const :tag "Always" t)
3273 (const :tag "Never" nil)
3274 (const :tag "When selection characters are configured" 'auto)))
3276 (defcustom org-fast-tag-selection-single-key nil
3277 "Non-nil means fast tag selection exits after first change.
3278 When nil, you have to press RET to exit it.
3279 During fast tag selection, you can toggle this flag with `C-c'.
3280 This variable can also have the value `expert'. In this case, the window
3281 displaying the tags menu is not even shown, until you press C-c again."
3282 :group 'org-tags
3283 :type '(choice
3284 (const :tag "No" nil)
3285 (const :tag "Yes" t)
3286 (const :tag "Expert" expert)))
3288 (defvar org-fast-tag-selection-include-todo nil
3289 "Non-nil means fast tags selection interface will also offer TODO states.
3290 This is an undocumented feature, you should not rely on it.")
3292 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3293 "The column to which tags should be indented in a headline.
3294 If this number is positive, it specifies the column. If it is negative,
3295 it means that the tags should be flushright to that column. For example,
3296 -80 works well for a normal 80 character screen.
3297 When 0, place tags directly after headline text, with only one space in
3298 between."
3299 :group 'org-tags
3300 :type 'integer)
3302 (defcustom org-auto-align-tags t
3303 "Non-nil keeps tags aligned when modifying headlines.
3304 Some operations (i.e. demoting) change the length of a headline and
3305 therefore shift the tags around. With this option turned on, after
3306 each such operation the tags are again aligned to `org-tags-column'."
3307 :group 'org-tags
3308 :type 'boolean)
3310 (defcustom org-use-tag-inheritance t
3311 "Non-nil means tags in levels apply also for sublevels.
3312 When nil, only the tags directly given in a specific line apply there.
3313 This may also be a list of tags that should be inherited, or a regexp that
3314 matches tags that should be inherited. Additional control is possible
3315 with the variable `org-tags-exclude-from-inheritance' which gives an
3316 explicit list of tags to be excluded from inheritance, even if the value of
3317 `org-use-tag-inheritance' would select it for inheritance.
3319 If this option is t, a match early-on in a tree can lead to a large
3320 number of matches in the subtree when constructing the agenda or creating
3321 a sparse tree. If you only want to see the first match in a tree during
3322 a search, check out the variable `org-tags-match-list-sublevels'."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "Not" nil)
3326 (const :tag "Always" t)
3327 (repeat :tag "Specific tags" (string :tag "Tag"))
3328 (regexp :tag "Tags matched by regexp")))
3330 (defcustom org-tags-exclude-from-inheritance nil
3331 "List of tags that should never be inherited.
3332 This is a way to exclude a few tags from inheritance. For way to do
3333 the opposite, to actively allow inheritance for selected tags,
3334 see the variable `org-use-tag-inheritance'."
3335 :group 'org-tags
3336 :type '(repeat (string :tag "Tag")))
3338 (defun org-tag-inherit-p (tag)
3339 "Check if TAG is one that should be inherited."
3340 (cond
3341 ((member tag org-tags-exclude-from-inheritance) nil)
3342 ((eq org-use-tag-inheritance t) t)
3343 ((not org-use-tag-inheritance) nil)
3344 ((stringp org-use-tag-inheritance)
3345 (string-match org-use-tag-inheritance tag))
3346 ((listp org-use-tag-inheritance)
3347 (member tag org-use-tag-inheritance))
3348 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3350 (defcustom org-tags-match-list-sublevels t
3351 "Non-nil means list also sublevels of headlines matching a search.
3352 This variable applies to tags/property searches, and also to stuck
3353 projects because this search is based on a tags match as well.
3355 When set to the symbol `indented', sublevels are indented with
3356 leading dots.
3358 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3359 the sublevels of a headline matching a tag search often also match
3360 the same search. Listing all of them can create very long lists.
3361 Setting this variable to nil causes subtrees of a match to be skipped.
3363 This variable is semi-obsolete and probably should always be true. It
3364 is better to limit inheritance to certain tags using the variables
3365 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3366 :group 'org-tags
3367 :type '(choice
3368 (const :tag "No, don't list them" nil)
3369 (const :tag "Yes, do list them" t)
3370 (const :tag "List them, indented with leading dots" indented)))
3372 (defcustom org-tags-sort-function nil
3373 "When set, tags are sorted using this function as a comparator."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No sorting" nil)
3377 (const :tag "Alphabetical" string<)
3378 (const :tag "Reverse alphabetical" string>)
3379 (function :tag "Custom function" nil)))
3381 (defvar org-tags-history nil
3382 "History of minibuffer reads for tags.")
3383 (defvar org-last-tags-completion-table nil
3384 "The last used completion table for tags.")
3385 (defvar org-after-tags-change-hook nil
3386 "Hook that is run after the tags in a line have changed.")
3388 (defgroup org-properties nil
3389 "Options concerning properties in Org-mode."
3390 :tag "Org Properties"
3391 :group 'org)
3393 (defcustom org-property-format "%-10s %s"
3394 "How property key/value pairs should be formatted by `indent-line'.
3395 When `indent-line' hits a property definition, it will format the line
3396 according to this format, mainly to make sure that the values are
3397 lined-up with respect to each other."
3398 :group 'org-properties
3399 :type 'string)
3401 (defcustom org-properties-postprocess-alist nil
3402 "Alist of properties and functions to adjust inserted values.
3403 Elements of this alist must be of the form
3405 ([string] [function])
3407 where [string] must be a property name and [function] must be a
3408 lambda expression: this lambda expression must take one argument,
3409 the value to adjust, and return the new value as a string.
3411 For example, this element will allow the property \"Remaining\"
3412 to be updated wrt the relation between the \"Effort\" property
3413 and the clock summary:
3415 ((\"Remaining\" (lambda(value)
3416 (let ((clocksum (org-clock-sum-current-item))
3417 (effort (org-duration-string-to-minutes
3418 (org-entry-get (point) \"Effort\"))))
3419 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3420 :group 'org-properties
3421 :version "24.1"
3422 :type '(alist :key-type (string :tag "Property")
3423 :value-type (function :tag "Function")))
3425 (defcustom org-use-property-inheritance nil
3426 "Non-nil means properties apply also for sublevels.
3428 This setting is chiefly used during property searches. Turning it on can
3429 cause significant overhead when doing a search, which is why it is not
3430 on by default.
3432 When nil, only the properties directly given in the current entry count.
3433 When t, every property is inherited. The value may also be a list of
3434 properties that should have inheritance, or a regular expression matching
3435 properties that should be inherited.
3437 However, note that some special properties use inheritance under special
3438 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3439 and the properties ending in \"_ALL\" when they are used as descriptor
3440 for valid values of a property.
3442 Note for programmers:
3443 When querying an entry with `org-entry-get', you can control if inheritance
3444 should be used. By default, `org-entry-get' looks only at the local
3445 properties. You can request inheritance by setting the inherit argument
3446 to t (to force inheritance) or to `selective' (to respect the setting
3447 in this variable)."
3448 :group 'org-properties
3449 :type '(choice
3450 (const :tag "Not" nil)
3451 (const :tag "Always" t)
3452 (repeat :tag "Specific properties" (string :tag "Property"))
3453 (regexp :tag "Properties matched by regexp")))
3455 (defun org-property-inherit-p (property)
3456 "Check if PROPERTY is one that should be inherited."
3457 (cond
3458 ((eq org-use-property-inheritance t) t)
3459 ((not org-use-property-inheritance) nil)
3460 ((stringp org-use-property-inheritance)
3461 (string-match org-use-property-inheritance property))
3462 ((listp org-use-property-inheritance)
3463 (member property org-use-property-inheritance))
3464 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3466 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3467 "The default column format, if no other format has been defined.
3468 This variable can be set on the per-file basis by inserting a line
3470 #+COLUMNS: %25ITEM ....."
3471 :group 'org-properties
3472 :type 'string)
3474 (defcustom org-columns-ellipses ".."
3475 "The ellipses to be used when a field in column view is truncated.
3476 When this is the empty string, as many characters as possible are shown,
3477 but then there will be no visual indication that the field has been truncated.
3478 When this is a string of length N, the last N characters of a truncated
3479 field are replaced by this string. If the column is narrower than the
3480 ellipses string, only part of the ellipses string will be shown."
3481 :group 'org-properties
3482 :type 'string)
3484 (defcustom org-columns-modify-value-for-display-function nil
3485 "Function that modifies values for display in column view.
3486 For example, it can be used to cut out a certain part from a time stamp.
3487 The function must take 2 arguments:
3489 column-title The title of the column (*not* the property name)
3490 value The value that should be modified.
3492 The function should return the value that should be displayed,
3493 or nil if the normal value should be used."
3494 :group 'org-properties
3495 :type 'function)
3497 (defcustom org-effort-property "Effort"
3498 "The property that is being used to keep track of effort estimates.
3499 Effort estimates given in this property need to have the format H:MM."
3500 :group 'org-properties
3501 :group 'org-progress
3502 :type '(string :tag "Property"))
3504 (defconst org-global-properties-fixed
3505 '(("VISIBILITY_ALL" . "folded children content all")
3506 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3507 "List of property/value pairs that can be inherited by any entry.
3509 These are fixed values, for the preset properties. The user variable
3510 that can be used to add to this list is `org-global-properties'.
3512 The entries in this list are cons cells where the car is a property
3513 name and cdr is a string with the value. If the value represents
3514 multiple items like an \"_ALL\" property, separate the items by
3515 spaces.")
3517 (defcustom org-global-properties nil
3518 "List of property/value pairs that can be inherited by any entry.
3520 This list will be combined with the constant `org-global-properties-fixed'.
3522 The entries in this list are cons cells where the car is a property
3523 name and cdr is a string with the value.
3525 You can set buffer-local values for the same purpose in the variable
3526 `org-file-properties' this by adding lines like
3528 #+PROPERTY: NAME VALUE"
3529 :group 'org-properties
3530 :type '(repeat
3531 (cons (string :tag "Property")
3532 (string :tag "Value"))))
3534 (defvar org-file-properties nil
3535 "List of property/value pairs that can be inherited by any entry.
3536 Valid for the current buffer.
3537 This variable is populated from #+PROPERTY lines.")
3538 (make-variable-buffer-local 'org-file-properties)
3540 (defgroup org-agenda nil
3541 "Options concerning agenda views in Org-mode."
3542 :tag "Org Agenda"
3543 :group 'org)
3545 (defvar org-category nil
3546 "Variable used by org files to set a category for agenda display.
3547 Such files should use a file variable to set it, for example
3549 # -*- mode: org; org-category: \"ELisp\"
3551 or contain a special line
3553 #+CATEGORY: ELisp
3555 If the file does not specify a category, then file's base name
3556 is used instead.")
3557 (make-variable-buffer-local 'org-category)
3558 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3560 (defcustom org-agenda-files nil
3561 "The files to be used for agenda display.
3562 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3563 \\[org-remove-file]. You can also use customize to edit the list.
3565 If an entry is a directory, all files in that directory that are matched by
3566 `org-agenda-file-regexp' will be part of the file list.
3568 If the value of the variable is not a list but a single file name, then
3569 the list of agenda files is actually stored and maintained in that file, one
3570 agenda file per line. In this file paths can be given relative to
3571 `org-directory'. Tilde expansion and environment variable substitution
3572 are also made."
3573 :group 'org-agenda
3574 :type '(choice
3575 (repeat :tag "List of files and directories" file)
3576 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3578 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3579 "Regular expression to match files for `org-agenda-files'.
3580 If any element in the list in that variable contains a directory instead
3581 of a normal file, all files in that directory that are matched by this
3582 regular expression will be included."
3583 :group 'org-agenda
3584 :type 'regexp)
3586 (defcustom org-agenda-text-search-extra-files nil
3587 "List of extra files to be searched by text search commands.
3588 These files will be search in addition to the agenda files by the
3589 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3590 Note that these files will only be searched for text search commands,
3591 not for the other agenda views like todo lists, tag searches or the weekly
3592 agenda. This variable is intended to list notes and possibly archive files
3593 that should also be searched by these two commands.
3594 In fact, if the first element in the list is the symbol `agenda-archives',
3595 than all archive files of all agenda files will be added to the search
3596 scope."
3597 :group 'org-agenda
3598 :type '(set :greedy t
3599 (const :tag "Agenda Archives" agenda-archives)
3600 (repeat :inline t (file))))
3602 (org-defvaralias 'org-agenda-multi-occur-extra-files
3603 'org-agenda-text-search-extra-files)
3605 (defcustom org-agenda-skip-unavailable-files nil
3606 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3607 A nil value means to remove them, after a query, from the list."
3608 :group 'org-agenda
3609 :type 'boolean)
3611 (defcustom org-calendar-to-agenda-key [?c]
3612 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3613 The command `org-calendar-goto-agenda' will be bound to this key. The
3614 default is the character `c' because then `c' can be used to switch back and
3615 forth between agenda and calendar."
3616 :group 'org-agenda
3617 :type 'sexp)
3619 (defcustom org-calendar-insert-diary-entry-key [?i]
3620 "The key to be installed in `calendar-mode-map' for adding diary entries.
3621 This option is irrelevant until `org-agenda-diary-file' has been configured
3622 to point to an Org-mode file. When that is the case, the command
3623 `org-agenda-diary-entry' will be bound to the key given here, by default
3624 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3625 if you want to continue doing this, you need to change this to a different
3626 key."
3627 :group 'org-agenda
3628 :type 'sexp)
3630 (defcustom org-agenda-diary-file 'diary-file
3631 "File to which to add new entries with the `i' key in agenda and calendar.
3632 When this is the symbol `diary-file', the functionality in the Emacs
3633 calendar will be used to add entries to the `diary-file'. But when this
3634 points to a file, `org-agenda-diary-entry' will be used instead."
3635 :group 'org-agenda
3636 :type '(choice
3637 (const :tag "The standard Emacs diary file" diary-file)
3638 (file :tag "Special Org file diary entries")))
3640 (eval-after-load "calendar"
3641 '(progn
3642 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3643 'org-calendar-goto-agenda)
3644 (add-hook 'calendar-mode-hook
3645 (lambda ()
3646 (unless (eq org-agenda-diary-file 'diary-file)
3647 (define-key calendar-mode-map
3648 org-calendar-insert-diary-entry-key
3649 'org-agenda-diary-entry))))))
3651 (defgroup org-latex nil
3652 "Options for embedding LaTeX code into Org-mode."
3653 :tag "Org LaTeX"
3654 :group 'org)
3656 (defcustom org-format-latex-options
3657 '(:foreground default :background default :scale 1.0
3658 :html-foreground "Black" :html-background "Transparent"
3659 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3660 "Options for creating images from LaTeX fragments.
3661 This is a property list with the following properties:
3662 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3663 `default' means use the foreground of the default face.
3664 `auto' means use the foreground from the text face.
3665 :background the background color, or \"Transparent\".
3666 `default' means use the background of the default face.
3667 `auto' means use the background from the text face.
3668 :scale a scaling factor for the size of the images, to get more pixels
3669 :html-foreground, :html-background, :html-scale
3670 the same numbers for HTML export.
3671 :matchers a list indicating which matchers should be used to
3672 find LaTeX fragments. Valid members of this list are:
3673 \"begin\" find environments
3674 \"$1\" find single characters surrounded by $.$
3675 \"$\" find math expressions surrounded by $...$
3676 \"$$\" find math expressions surrounded by $$....$$
3677 \"\\(\" find math expressions surrounded by \\(...\\)
3678 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3679 :group 'org-latex
3680 :type 'plist)
3682 (defcustom org-format-latex-signal-error t
3683 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3684 When nil, just push out a message."
3685 :group 'org-latex
3686 :version "24.1"
3687 :type 'boolean)
3689 (defcustom org-latex-to-mathml-jar-file nil
3690 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3691 Use this to specify additional executable file say a jar file.
3693 When using MathToWeb as the converter, specify the full-path to
3694 your mathtoweb.jar file."
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "None" nil)
3699 (file :tag "JAR file" :must-match t)))
3701 (defcustom org-latex-to-mathml-convert-command nil
3702 "Command to convert LaTeX fragments to MathML.
3703 Replace format-specifiers in the command as noted below and use
3704 `shell-command' to convert LaTeX to MathML.
3705 %j: Executable file in fully expanded form as specified by
3706 `org-latex-to-mathml-jar-file'.
3707 %I: Input LaTeX file in fully expanded form
3708 %o: Output MathML file
3709 This command is used by `org-create-math-formula'.
3711 When using MathToWeb as the converter, set this to
3712 \"java -jar %j -unicode -force -df %o %I\"."
3713 :group 'org-latex
3714 :version "24.1"
3715 :type '(choice
3716 (const :tag "None" nil)
3717 (string :tag "\nShell command")))
3719 (defcustom org-latex-create-formula-image-program 'dvipng
3720 "Program to convert LaTeX fragments with.
3722 dvipng Process the LaTeX fragments to dvi file, then convert
3723 dvi files to png files using dvipng.
3724 This will also include processing of non-math environments.
3725 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3726 to convert pdf files to png files"
3727 :group 'org-latex
3728 :version "24.1"
3729 :type '(choice
3730 (const :tag "dvipng" dvipng)
3731 (const :tag "imagemagick" imagemagick)))
3733 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3734 "Path to store latex preview images.
3735 A relative path here creates many directories relative to the
3736 processed org files paths. An absolute path puts all preview
3737 images at the same place."
3738 :group 'org-latex
3739 :version "24.3"
3740 :type 'string)
3742 (defun org-format-latex-mathml-available-p ()
3743 "Return t if `org-latex-to-mathml-convert-command' is usable."
3744 (save-match-data
3745 (when (and (boundp 'org-latex-to-mathml-convert-command)
3746 org-latex-to-mathml-convert-command)
3747 (let ((executable (car (split-string
3748 org-latex-to-mathml-convert-command))))
3749 (when (executable-find executable)
3750 (if (string-match
3751 "%j" org-latex-to-mathml-convert-command)
3752 (file-readable-p org-latex-to-mathml-jar-file)
3753 t))))))
3755 (defcustom org-format-latex-header "\\documentclass{article}
3756 \\usepackage[usenames]{color}
3757 \\usepackage{amsmath}
3758 \\usepackage[mathscr]{eucal}
3759 \\pagestyle{empty} % do not remove
3760 \[PACKAGES]
3761 \[DEFAULT-PACKAGES]
3762 % The settings below are copied from fullpage.sty
3763 \\setlength{\\textwidth}{\\paperwidth}
3764 \\addtolength{\\textwidth}{-3cm}
3765 \\setlength{\\oddsidemargin}{1.5cm}
3766 \\addtolength{\\oddsidemargin}{-2.54cm}
3767 \\setlength{\\evensidemargin}{\\oddsidemargin}
3768 \\setlength{\\textheight}{\\paperheight}
3769 \\addtolength{\\textheight}{-\\headheight}
3770 \\addtolength{\\textheight}{-\\headsep}
3771 \\addtolength{\\textheight}{-\\footskip}
3772 \\addtolength{\\textheight}{-3cm}
3773 \\setlength{\\topmargin}{1.5cm}
3774 \\addtolength{\\topmargin}{-2.54cm}"
3775 "The document header used for processing LaTeX fragments.
3776 It is imperative that this header make sure that no page number
3777 appears on the page. The package defined in the variables
3778 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3779 will either replace the placeholder \"[PACKAGES]\" in this
3780 header, or they will be appended."
3781 :group 'org-latex
3782 :type 'string)
3784 (defun org-set-packages-alist (var val)
3785 "Set the packages alist and make sure it has 3 elements per entry."
3786 (set var (mapcar (lambda (x)
3787 (if (and (consp x) (= (length x) 2))
3788 (list (car x) (nth 1 x) t)
3790 val)))
3792 (defun org-get-packages-alist (var)
3793 "Get the packages alist and make sure it has 3 elements per entry."
3794 (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 (default-value var)))
3800 (defcustom org-latex-default-packages-alist
3801 '(("AUTO" "inputenc" t)
3802 ("T1" "fontenc" t)
3803 ("" "fixltx2e" nil)
3804 ("" "graphicx" t)
3805 ("" "longtable" nil)
3806 ("" "float" nil)
3807 ("" "wrapfig" nil)
3808 ("" "soul" t)
3809 ("" "textcomp" t)
3810 ("" "marvosym" t)
3811 ("" "wasysym" t)
3812 ("" "latexsym" t)
3813 ("" "amssymb" t)
3814 ("" "hyperref" nil)
3815 "\\tolerance=1000")
3816 "Alist of default packages to be inserted in the header.
3818 Change this only if one of the packages here causes an
3819 incompatibility with another package you are using.
3821 The packages in this list are needed by one part or another of
3822 Org mode to function properly:
3824 - inputenc, fontenc: for basic font and character selection
3825 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3826 symbols used for interpreting the entities in `org-entities'.
3827 You can skip some of these packages if you don't use any of the
3828 symbols in it.
3829 - graphicx: for including images
3830 - float, wrapfig: for figure placement
3831 - longtable: for long tables
3832 - hyperref: for cross references
3834 Therefore you should not modify this variable unless you know
3835 what you are doing. The one reason to change it anyway is that
3836 you might be loading some other package that conflicts with one
3837 of the default packages. Each cell is of the format
3838 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3839 the package also needs to be included when compiling LaTeX
3840 snippets into images for inclusion into non-LaTeX output."
3841 :group 'org-latex
3842 :group 'org-export-latex
3843 :set 'org-set-packages-alist
3844 :get 'org-get-packages-alist
3845 :version "24.1"
3846 :type '(repeat
3847 (choice
3848 (list :tag "options/package pair"
3849 (string :tag "options")
3850 (string :tag "package")
3851 (boolean :tag "Snippet"))
3852 (string :tag "A line of LaTeX"))))
3854 (defcustom org-latex-packages-alist nil
3855 "Alist of packages to be inserted in every LaTeX header.
3857 These will be inserted after `org-latex-default-packages-alist'.
3858 Each cell is of the format:
3860 \(\"options\" \"package\" snippet-flag)
3862 SNIPPET-FLAG, when t, indicates that this package is also needed
3863 when turning LaTeX snippets into images for inclusion into
3864 non-LaTeX output.
3866 Make sure that you only list packages here which:
3868 - you want in every file
3869 - do not conflict with the setup in `org-format-latex-header'.
3870 - do not conflict with the default packages in
3871 `org-latex-default-packages-alist'."
3872 :group 'org-latex
3873 :group 'org-export-latex
3874 :set 'org-set-packages-alist
3875 :get 'org-get-packages-alist
3876 :type '(repeat
3877 (choice
3878 (list :tag "options/package pair"
3879 (string :tag "options")
3880 (string :tag "package")
3881 (boolean :tag "Snippet"))
3882 (string :tag "A line of LaTeX"))))
3884 (defgroup org-appearance nil
3885 "Settings for Org-mode appearance."
3886 :tag "Org Appearance"
3887 :group 'org)
3889 (defcustom org-level-color-stars-only nil
3890 "Non-nil means fontify only the stars in each headline.
3891 When nil, the entire headline is fontified.
3892 Changing it requires restart of `font-lock-mode' to become effective
3893 also in regions already fontified."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-hide-leading-stars nil
3898 "Non-nil means hide the first N-1 stars in a headline.
3899 This works by using the face `org-hide' for these stars. This
3900 face is white for a light background, and black for a dark
3901 background. You may have to customize the face `org-hide' to
3902 make this work.
3903 Changing it requires restart of `font-lock-mode' to become effective
3904 also in regions already fontified.
3905 You may also set this on a per-file basis by adding one of the following
3906 lines to the buffer:
3908 #+STARTUP: hidestars
3909 #+STARTUP: showstars"
3910 :group 'org-appearance
3911 :type 'boolean)
3913 (defcustom org-hidden-keywords nil
3914 "List of symbols corresponding to keywords to be hidden the org buffer.
3915 For example, a value '(title) for this list will make the document's title
3916 appear in the buffer without the initial #+TITLE: keyword."
3917 :group 'org-appearance
3918 :version "24.1"
3919 :type '(set (const :tag "#+AUTHOR" author)
3920 (const :tag "#+DATE" date)
3921 (const :tag "#+EMAIL" email)
3922 (const :tag "#+TITLE" title)))
3924 (defcustom org-custom-properties nil
3925 "List of properties (as strings) with a special meaning.
3926 The default use of these custom properties is to let the user
3927 hide them with `org-toggle-custom-properties-visibility'."
3928 :group 'org-properties
3929 :group 'org-appearance
3930 :version "24.3"
3931 :type '(repeat (string :tag "Property Name")))
3933 (defcustom org-fontify-done-headline nil
3934 "Non-nil means change the face of a headline if it is marked DONE.
3935 Normally, only the TODO/DONE keyword indicates the state of a headline.
3936 When this is non-nil, the headline after the keyword is set to the
3937 `org-headline-done' as an additional indication."
3938 :group 'org-appearance
3939 :type 'boolean)
3941 (defcustom org-fontify-emphasized-text t
3942 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3943 Changing this variable requires a restart of Emacs to take effect."
3944 :group 'org-appearance
3945 :type 'boolean)
3947 (defcustom org-fontify-whole-heading-line nil
3948 "Non-nil means fontify the whole line for headings.
3949 This is useful when setting a background color for the
3950 org-level-* faces."
3951 :group 'org-appearance
3952 :type 'boolean)
3954 (defcustom org-highlight-latex-and-related nil
3955 "Non-nil means highlight LaTeX related syntax in the buffer.
3956 When non nil, the value should be a list containing any of the
3957 following symbols:
3958 `latex' Highlight LaTeX snippets and environments.
3959 `script' Highlight subscript and superscript.
3960 `entities' Highlight entities."
3961 :group 'org-appearance
3962 :version "24.4"
3963 :package-version '(Org . "8.0")
3964 :type '(choice
3965 (const :tag "No highlighting" nil)
3966 (set :greedy t :tag "Highlight"
3967 (const :tag "LaTeX snippets and environments" latex)
3968 (const :tag "Subscript and superscript" script)
3969 (const :tag "Entities" entities))))
3971 (defcustom org-hide-emphasis-markers nil
3972 "Non-nil mean font-lock should hide the emphasis marker characters."
3973 :group 'org-appearance
3974 :type 'boolean)
3976 (defcustom org-pretty-entities nil
3977 "Non-nil means show entities as UTF8 characters.
3978 When nil, the \\name form remains in the buffer."
3979 :group 'org-appearance
3980 :version "24.1"
3981 :type 'boolean)
3983 (defcustom org-pretty-entities-include-sub-superscripts t
3984 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3985 :group 'org-appearance
3986 :version "24.1"
3987 :type 'boolean)
3989 (defvar org-emph-re nil
3990 "Regular expression for matching emphasis.
3991 After a match, the match groups contain these elements:
3992 0 The match of the full regular expression, including the characters
3993 before and after the proper match
3994 1 The character before the proper match, or empty at beginning of line
3995 2 The proper match, including the leading and trailing markers
3996 3 The leading marker like * or /, indicating the type of highlighting
3997 4 The text between the emphasis markers, not including the markers
3998 5 The character after the match, empty at the end of a line")
3999 (defvar org-verbatim-re nil
4000 "Regular expression for matching verbatim text.")
4001 (defvar org-emphasis-regexp-components) ; defined just below
4002 (defvar org-emphasis-alist) ; defined just below
4003 (defun org-set-emph-re (var val)
4004 "Set variable and compute the emphasis regular expression."
4005 (set var val)
4006 (when (and (boundp 'org-emphasis-alist)
4007 (boundp 'org-emphasis-regexp-components)
4008 org-emphasis-alist org-emphasis-regexp-components)
4009 (let* ((e org-emphasis-regexp-components)
4010 (pre (car e))
4011 (post (nth 1 e))
4012 (border (nth 2 e))
4013 (body (nth 3 e))
4014 (nl (nth 4 e))
4015 (body1 (concat body "*?"))
4016 (markers (mapconcat 'car org-emphasis-alist ""))
4017 (vmarkers (mapconcat
4018 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4019 org-emphasis-alist "")))
4020 ;; make sure special characters appear at the right position in the class
4021 (if (string-match "\\^" markers)
4022 (setq markers (concat (replace-match "" t t markers) "^")))
4023 (if (string-match "-" markers)
4024 (setq markers (concat (replace-match "" t t markers) "-")))
4025 (if (string-match "\\^" vmarkers)
4026 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4027 (if (string-match "-" vmarkers)
4028 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4029 (if (> nl 0)
4030 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4031 (int-to-string nl) "\\}")))
4032 ;; Make the regexp
4033 (setq org-emph-re
4034 (concat "\\([" pre "]\\|^\\)"
4035 "\\("
4036 "\\([" markers "]\\)"
4037 "\\("
4038 "[^" border "]\\|"
4039 "[^" border "]"
4040 body1
4041 "[^" border "]"
4042 "\\)"
4043 "\\3\\)"
4044 "\\([" post "]\\|$\\)"))
4045 (setq org-verbatim-re
4046 (concat "\\([" pre "]\\|^\\)"
4047 "\\("
4048 "\\([" vmarkers "]\\)"
4049 "\\("
4050 "[^" border "]\\|"
4051 "[^" border "]"
4052 body1
4053 "[^" border "]"
4054 "\\)"
4055 "\\3\\)"
4056 "\\([" post "]\\|$\\)")))))
4058 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4059 ;; set this option proved cumbersome. See this message/thread:
4060 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4061 (defvar org-emphasis-regexp-components
4062 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4063 "Components used to build the regular expression for emphasis.
4064 This is a list with five entries. Terminology: In an emphasis string
4065 like \" *strong word* \", we call the initial space PREMATCH, the final
4066 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4067 and \"trong wor\" is the body. The different components in this variable
4068 specify what is allowed/forbidden in each part:
4070 pre Chars allowed as prematch. Beginning of line will be allowed too.
4071 post Chars allowed as postmatch. End of line will be allowed too.
4072 border The chars *forbidden* as border characters.
4073 body-regexp A regexp like \".\" to match a body character. Don't use
4074 non-shy groups here, and don't allow newline here.
4075 newline The maximum number of newlines allowed in an emphasis exp.
4077 You need to reload Org or to restart Emacs after customizing this.")
4079 (defcustom org-emphasis-alist
4080 `(("*" bold)
4081 ("/" italic)
4082 ("_" underline)
4083 ("=" org-code verbatim)
4084 ("~" org-verbatim verbatim)
4085 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4086 "Alist of characters and faces to emphasize text.
4087 Text starting and ending with a special character will be emphasized,
4088 for example *bold*, _underlined_ and /italic/. This variable sets the
4089 marker characters and the face to be used by font-lock for highlighting
4090 in Org-mode Emacs buffers.
4092 You need to reload Org or to restart Emacs after customizing this."
4093 :group 'org-appearance
4094 :set 'org-set-emph-re
4095 :version "24.4"
4096 :package-version '(Org . "8.0")
4097 :type '(repeat
4098 (list
4099 (string :tag "Marker character")
4100 (choice
4101 (face :tag "Font-lock-face")
4102 (plist :tag "Face property list"))
4103 (option (const verbatim)))))
4105 (defvar org-protecting-blocks
4106 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4107 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4108 This is needed for font-lock setup.")
4110 ;;; Miscellaneous options
4112 (defgroup org-completion nil
4113 "Completion in Org-mode."
4114 :tag "Org Completion"
4115 :group 'org)
4117 (defcustom org-completion-use-ido nil
4118 "Non-nil means use ido completion wherever possible.
4119 Note that `ido-mode' must be active for this variable to be relevant.
4120 If you decide to turn this variable on, you might well want to turn off
4121 `org-outline-path-complete-in-steps'.
4122 See also `org-completion-use-iswitchb'."
4123 :group 'org-completion
4124 :type 'boolean)
4126 (defcustom org-completion-use-iswitchb nil
4127 "Non-nil means use iswitchb completion wherever possible.
4128 Note that `iswitchb-mode' must be active for this variable to be relevant.
4129 If you decide to turn this variable on, you might well want to turn off
4130 `org-outline-path-complete-in-steps'.
4131 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4132 :group 'org-completion
4133 :type 'boolean)
4135 (defcustom org-completion-fallback-command 'hippie-expand
4136 "The expansion command called by \\[pcomplete] in normal context.
4137 Normal means, no org-mode-specific context."
4138 :group 'org-completion
4139 :type 'function)
4141 ;;; Functions and variables from their packages
4142 ;; Declared here to avoid compiler warnings
4144 ;; XEmacs only
4145 (defvar outline-mode-menu-heading)
4146 (defvar outline-mode-menu-show)
4147 (defvar outline-mode-menu-hide)
4148 (defvar zmacs-regions) ; XEmacs regions
4150 ;; Emacs only
4151 (defvar mark-active)
4153 ;; Various packages
4154 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4155 (declare-function calendar-forward-day "cal-move" (arg))
4156 (declare-function calendar-goto-date "cal-move" (date))
4157 (declare-function calendar-goto-today "cal-move" ())
4158 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4159 (defvar calc-embedded-close-formula)
4160 (defvar calc-embedded-open-formula)
4161 (declare-function cdlatex-tab "ext:cdlatex" ())
4162 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4163 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4164 (defvar font-lock-unfontify-region-function)
4165 (declare-function iswitchb-read-buffer "iswitchb"
4166 (prompt &optional default require-match start matches-set))
4167 (defvar iswitchb-temp-buflist)
4168 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4169 (defvar org-agenda-tags-todo-honor-ignore-options)
4170 (declare-function org-agenda-skip "org-agenda" ())
4171 (declare-function
4172 org-agenda-format-item "org-agenda"
4173 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4174 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4175 (declare-function org-agenda-change-all-lines "org-agenda"
4176 (newhead hdmarker &optional fixface just-this))
4177 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4178 (declare-function org-agenda-maybe-redo "org-agenda" ())
4179 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4180 (beg end))
4181 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4182 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4183 "org-agenda" (&optional end))
4184 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4185 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4186 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4187 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4188 (declare-function org-indent-mode "org-indent" (&optional arg))
4189 (declare-function parse-time-string "parse-time" (string))
4190 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4191 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4192 (defvar remember-data-file)
4193 (defvar texmathp-why)
4194 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4195 (declare-function table--at-cell-p "table" (position &optional object at-column))
4197 (defvar org-latex-regexps)
4199 ;;; Autoload and prepare some org modules
4201 ;; Some table stuff that needs to be defined here, because it is used
4202 ;; by the functions setting up org-mode or checking for table context.
4204 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4205 "Detect an org-type or table-type table.")
4206 (defconst org-table-line-regexp "^[ \t]*|"
4207 "Detect an org-type table line.")
4208 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4209 "Detect an org-type table line.")
4210 (defconst org-table-hline-regexp "^[ \t]*|-"
4211 "Detect an org-type table hline.")
4212 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4213 "Detect a table-type table hline.")
4214 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4215 "Detect the first line outside a table when searching from within it.
4216 This works for both table types.")
4218 ;; Autoload the functions in org-table.el that are needed by functions here.
4220 (eval-and-compile
4221 (org-autoload "org-table"
4222 '(org-table-begin org-table-blank-field org-table-end)))
4224 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4225 "Detect a #+TBLFM line.")
4227 ;;;###autoload
4228 (defun turn-on-orgtbl ()
4229 "Unconditionally turn on `orgtbl-mode'."
4230 (require 'org-table)
4231 (orgtbl-mode 1))
4233 (defun org-at-table-p (&optional table-type)
4234 "Return t if the cursor is inside an org-type table.
4235 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4236 (if org-enable-table-editor
4237 (save-excursion
4238 (beginning-of-line 1)
4239 (looking-at (if table-type org-table-any-line-regexp
4240 org-table-line-regexp)))
4241 nil))
4242 (defsubst org-table-p () (org-at-table-p))
4244 (defun org-at-table.el-p ()
4245 "Return t if and only if we are at a table.el table."
4246 (and (org-at-table-p 'any)
4247 (save-excursion
4248 (goto-char (org-table-begin 'any))
4249 (looking-at org-table1-hline-regexp))))
4251 (defun org-table-recognize-table.el ()
4252 "If there is a table.el table nearby, recognize it and move into it."
4253 (if org-table-tab-recognizes-table.el
4254 (if (org-at-table.el-p)
4255 (progn
4256 (beginning-of-line 1)
4257 (if (looking-at org-table-dataline-regexp)
4259 (if (looking-at org-table1-hline-regexp)
4260 (progn
4261 (beginning-of-line 2)
4262 (if (looking-at org-table-any-border-regexp)
4263 (beginning-of-line -1)))))
4264 (if (re-search-forward "|" (org-table-end t) t)
4265 (progn
4266 (require 'table)
4267 (if (table--at-cell-p (point))
4269 (message "recognizing table.el table...")
4270 (table-recognize-table)
4271 (message "recognizing table.el table...done")))
4272 (error "This should not happen"))
4274 nil)
4275 nil))
4277 (defun org-at-table-hline-p ()
4278 "Return t if the cursor is inside a hline in a table."
4279 (if org-enable-table-editor
4280 (save-excursion
4281 (beginning-of-line 1)
4282 (looking-at org-table-hline-regexp))
4283 nil))
4285 (defvar org-table-clean-did-remove-column nil)
4286 (defun org-table-map-tables (function &optional quietly)
4287 "Apply FUNCTION to the start of all tables in the buffer."
4288 (save-excursion
4289 (save-restriction
4290 (widen)
4291 (goto-char (point-min))
4292 (while (re-search-forward org-table-any-line-regexp nil t)
4293 (unless quietly
4294 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4295 (beginning-of-line 1)
4296 (when (and (looking-at org-table-line-regexp)
4297 ;; Exclude tables in src/example/verbatim/clocktable blocks
4298 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4299 (save-excursion (funcall function))
4300 (or (looking-at org-table-line-regexp)
4301 (forward-char 1)))
4302 (re-search-forward org-table-any-border-regexp nil 1))))
4303 (unless quietly (message "Mapping tables: done")))
4305 ;; Declare and autoload functions from ox.el and al.
4307 (declare-function org-export-get-environment "ox"
4308 (&optional backend subtreep ext-plist))
4309 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4311 ;; Declare and autoload functions from org-agenda.el
4313 (eval-and-compile
4314 (org-autoload "org-agenda"
4315 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4317 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4318 (declare-function org-clock-update-mode-line "org-clock" ())
4319 (declare-function org-resolve-clocks "org-clock"
4320 (&optional also-non-dangling-p prompt last-valid))
4322 (defun org-at-TBLFM-p (&optional pos)
4323 "Return t when point (or POS) is in #+TBLFM line."
4324 (save-excursion
4325 (let ((pos pos)))
4326 (goto-char (or pos (point)))
4327 (beginning-of-line 1)
4328 (looking-at org-TBLFM-regexp)))
4330 (defvar org-clock-start-time)
4331 (defvar org-clock-marker (make-marker)
4332 "Marker recording the last clock-in.")
4333 (defvar org-clock-hd-marker (make-marker)
4334 "Marker recording the last clock-in, but the headline position.")
4335 (defvar org-clock-heading ""
4336 "The heading of the current clock entry.")
4337 (defun org-clock-is-active ()
4338 "Return non-nil if clock is currently running.
4339 The return value is actually the clock marker."
4340 (marker-buffer org-clock-marker))
4342 (eval-and-compile
4343 (org-autoload "org-clock" '(org-clock-remove-overlays
4344 org-clock-update-time-maybe
4345 org-clocktable-shift)))
4347 (defun org-check-running-clock ()
4348 "Check if the current buffer contains the running clock.
4349 If yes, offer to stop it and to save the buffer with the changes."
4350 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4351 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4352 (buffer-name))))
4353 (org-clock-out)
4354 (when (y-or-n-p "Save changed buffer?")
4355 (save-buffer))))
4357 (defun org-clocktable-try-shift (dir n)
4358 "Check if this line starts a clock table, if yes, shift the time block."
4359 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4360 (org-clocktable-shift dir n)))
4362 ;;;###autoload
4363 (defun org-clock-persistence-insinuate ()
4364 "Set up hooks for clock persistence."
4365 (require 'org-clock)
4366 (add-hook 'org-mode-hook 'org-clock-load)
4367 (add-hook 'kill-emacs-hook 'org-clock-save))
4369 ;; Define the variable already here, to make sure we have it.
4370 (defvar org-indent-mode nil
4371 "Non-nil if Org-Indent mode is enabled.
4372 Use the command `org-indent-mode' to change this variable.")
4374 ;; Autoload archiving code
4375 ;; The stuff that is needed for cycling and tags has to be defined here.
4377 (defgroup org-archive nil
4378 "Options concerning archiving in Org-mode."
4379 :tag "Org Archive"
4380 :group 'org-structure)
4382 (defcustom org-archive-location "%s_archive::"
4383 "The location where subtrees should be archived.
4385 The value of this variable is a string, consisting of two parts,
4386 separated by a double-colon. The first part is a filename and
4387 the second part is a headline.
4389 When the filename is omitted, archiving happens in the same file.
4390 %s in the filename will be replaced by the current file
4391 name (without the directory part). Archiving to a different file
4392 is useful to keep archived entries from contributing to the
4393 Org-mode Agenda.
4395 The archived entries will be filed as subtrees of the specified
4396 headline. When the headline is omitted, the subtrees are simply
4397 filed away at the end of the file, as top-level entries. Also in
4398 the heading you can use %s to represent the file name, this can be
4399 useful when using the same archive for a number of different files.
4401 Here are a few examples:
4402 \"%s_archive::\"
4403 If the current file is Projects.org, archive in file
4404 Projects.org_archive, as top-level trees. This is the default.
4406 \"::* Archived Tasks\"
4407 Archive in the current file, under the top-level headline
4408 \"* Archived Tasks\".
4410 \"~/org/archive.org::\"
4411 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4413 \"~/org/archive.org::* From %s\"
4414 Archive in file ~/org/archive.org (absolute path), under headlines
4415 \"From FILENAME\" where file name is the current file name.
4417 \"~/org/datetree.org::datetree/* Finished Tasks\"
4418 The \"datetree/\" string is special, signifying to archive
4419 items to the datetree. Items are placed in either the CLOSED
4420 date of the item, or the current date if there is no CLOSED date.
4421 The heading will be a subentry to the current date. There doesn't
4422 need to be a heading, but there always needs to be a slash after
4423 datetree. For example, to store archived items directly in the
4424 datetree, use \"~/org/datetree.org::datetree/\".
4426 \"basement::** Finished Tasks\"
4427 Archive in file ./basement (relative path), as level 3 trees
4428 below the level 2 heading \"** Finished Tasks\".
4430 You may set this option on a per-file basis by adding to the buffer a
4431 line like
4433 #+ARCHIVE: basement::** Finished Tasks
4435 You may also define it locally for a subtree by setting an ARCHIVE property
4436 in the entry. If such a property is found in an entry, or anywhere up
4437 the hierarchy, it will be used."
4438 :group 'org-archive
4439 :type 'string)
4441 (defcustom org-archive-tag "ARCHIVE"
4442 "The tag that marks a subtree as archived.
4443 An archived subtree does not open during visibility cycling, and does
4444 not contribute to the agenda listings.
4445 After changing this, font-lock must be restarted in the relevant buffers to
4446 get the proper fontification."
4447 :group 'org-archive
4448 :group 'org-keywords
4449 :type 'string)
4451 (defcustom org-agenda-skip-archived-trees t
4452 "Non-nil means the agenda will skip any items located in archived trees.
4453 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4454 variable is no longer recommended, you should leave it at the value t.
4455 Instead, use the key `v' to cycle the archives-mode in the agenda."
4456 :group 'org-archive
4457 :group 'org-agenda-skip
4458 :type 'boolean)
4460 (defcustom org-columns-skip-archived-trees t
4461 "Non-nil means ignore archived trees when creating column view."
4462 :group 'org-archive
4463 :group 'org-properties
4464 :type 'boolean)
4466 (defcustom org-cycle-open-archived-trees nil
4467 "Non-nil means `org-cycle' will open archived trees.
4468 An archived tree is a tree marked with the tag ARCHIVE.
4469 When nil, archived trees will stay folded. You can still open them with
4470 normal outline commands like `show-all', but not with the cycling commands."
4471 :group 'org-archive
4472 :group 'org-cycle
4473 :type 'boolean)
4475 (defcustom org-sparse-tree-open-archived-trees nil
4476 "Non-nil means sparse tree construction shows matches in archived trees.
4477 When nil, matches in these trees are highlighted, but the trees are kept in
4478 collapsed state."
4479 :group 'org-archive
4480 :group 'org-sparse-trees
4481 :type 'boolean)
4483 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4484 "The default date type when building a sparse tree.
4485 When this is nil, a date is a scheduled or a deadline timestamp.
4486 Otherwise, these types are allowed:
4488 all: all timestamps
4489 active: only active timestamps (<...>)
4490 inactive: only inactive timestamps (<...)
4491 scheduled: only scheduled timestamps
4492 deadline: only deadline timestamps"
4493 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4494 (const :tag "All timestamps" all)
4495 (const :tag "Only active timestamps" active)
4496 (const :tag "Only inactive timestamps" inactive)
4497 (const :tag "Only scheduled timestamps" scheduled)
4498 (const :tag "Only deadline timestamps" deadline)
4499 (const :tag "Only closed timestamps" closed))
4500 :version "24.3"
4501 :group 'org-sparse-trees)
4503 (defun org-cycle-hide-archived-subtrees (state)
4504 "Re-hide all archived subtrees after a visibility state change."
4505 (when (and (not org-cycle-open-archived-trees)
4506 (not (memq state '(overview folded))))
4507 (save-excursion
4508 (let* ((globalp (memq state '(contents all)))
4509 (beg (if globalp (point-min) (point)))
4510 (end (if globalp (point-max) (org-end-of-subtree t))))
4511 (org-hide-archived-subtrees beg end)
4512 (goto-char beg)
4513 (if (looking-at (concat ".*:" org-archive-tag ":"))
4514 (message "%s" (substitute-command-keys
4515 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4517 (defun org-force-cycle-archived ()
4518 "Cycle subtree even if it is archived."
4519 (interactive)
4520 (setq this-command 'org-cycle)
4521 (let ((org-cycle-open-archived-trees t))
4522 (call-interactively 'org-cycle)))
4524 (defun org-hide-archived-subtrees (beg end)
4525 "Re-hide all archived subtrees after a visibility state change."
4526 (save-excursion
4527 (let* ((re (concat ":" org-archive-tag ":")))
4528 (goto-char beg)
4529 (while (re-search-forward re end t)
4530 (when (org-at-heading-p)
4531 (org-flag-subtree t)
4532 (org-end-of-subtree t))))))
4534 (declare-function outline-end-of-heading "outline" ())
4535 (declare-function outline-flag-region "outline" (from to flag))
4536 (defun org-flag-subtree (flag)
4537 (save-excursion
4538 (org-back-to-heading t)
4539 (outline-end-of-heading)
4540 (outline-flag-region (point)
4541 (progn (org-end-of-subtree t) (point))
4542 flag)))
4544 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4546 (eval-and-compile
4547 (org-autoload "org-archive"
4548 '(org-add-archive-files)))
4550 ;; Autoload Column View Code
4552 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4553 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4554 (declare-function org-columns-compute "org-colview" (property))
4556 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4557 '(org-columns-number-to-string
4558 org-columns-get-format-and-top-level
4559 org-columns-compute
4560 org-columns-remove-overlays))
4562 ;; Autoload ID code
4564 (declare-function org-id-store-link "org-id")
4565 (declare-function org-id-locations-load "org-id")
4566 (declare-function org-id-locations-save "org-id")
4567 (defvar org-id-track-globally)
4568 (org-autoload "org-id"
4569 '(org-id-new
4570 org-id-copy
4571 org-id-get-with-outline-path-completion
4572 org-id-get-with-outline-drilling))
4574 ;;; Variables for pre-computed regular expressions, all buffer local
4576 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4577 "Matches first line of a hidden block.")
4578 (make-variable-buffer-local 'org-drawer-regexp)
4579 (defvar org-todo-regexp nil
4580 "Matches any of the TODO state keywords.")
4581 (make-variable-buffer-local 'org-todo-regexp)
4582 (defvar org-not-done-regexp nil
4583 "Matches any of the TODO state keywords except the last one.")
4584 (make-variable-buffer-local 'org-not-done-regexp)
4585 (defvar org-not-done-heading-regexp nil
4586 "Matches a TODO headline that is not done.")
4587 (make-variable-buffer-local 'org-not-done-regexp)
4588 (defvar org-todo-line-regexp nil
4589 "Matches a headline and puts TODO state into group 2 if present.")
4590 (make-variable-buffer-local 'org-todo-line-regexp)
4591 (defvar org-complex-heading-regexp nil
4592 "Matches a headline and puts everything into groups:
4593 group 1: the stars
4594 group 2: The todo keyword, maybe
4595 group 3: Priority cookie
4596 group 4: True headline
4597 group 5: Tags")
4598 (make-variable-buffer-local 'org-complex-heading-regexp)
4599 (defvar org-complex-heading-regexp-format nil
4600 "Printf format to make regexp to match an exact headline.
4601 This regexp will match the headline of any node which has the
4602 exact headline text that is put into the format, but may have any
4603 TODO state, priority and tags.")
4604 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4605 (defvar org-todo-line-tags-regexp nil
4606 "Matches a headline and puts TODO state into group 2 if present.
4607 Also put tags into group 4 if tags are present.")
4608 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4609 (defvar org-ds-keyword-length 12
4610 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4611 (make-variable-buffer-local 'org-ds-keyword-length)
4612 (defvar org-deadline-regexp nil
4613 "Matches the DEADLINE keyword.")
4614 (make-variable-buffer-local 'org-deadline-regexp)
4615 (defvar org-deadline-time-regexp nil
4616 "Matches the DEADLINE keyword together with a time stamp.")
4617 (make-variable-buffer-local 'org-deadline-time-regexp)
4618 (defvar org-deadline-time-hour-regexp nil
4619 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4620 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4621 (defvar org-deadline-line-regexp nil
4622 "Matches the DEADLINE keyword and the rest of the line.")
4623 (make-variable-buffer-local 'org-deadline-line-regexp)
4624 (defvar org-scheduled-regexp nil
4625 "Matches the SCHEDULED keyword.")
4626 (make-variable-buffer-local 'org-scheduled-regexp)
4627 (defvar org-scheduled-time-regexp nil
4628 "Matches the SCHEDULED keyword together with a time stamp.")
4629 (make-variable-buffer-local 'org-scheduled-time-regexp)
4630 (defvar org-scheduled-time-hour-regexp nil
4631 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4632 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4633 (defvar org-closed-time-regexp nil
4634 "Matches the CLOSED keyword together with a time stamp.")
4635 (make-variable-buffer-local 'org-closed-time-regexp)
4637 (defvar org-keyword-time-regexp nil
4638 "Matches any of the 4 keywords, together with the time stamp.")
4639 (make-variable-buffer-local 'org-keyword-time-regexp)
4640 (defvar org-keyword-time-not-clock-regexp nil
4641 "Matches any of the 3 keywords, together with the time stamp.")
4642 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4643 (defvar org-maybe-keyword-time-regexp nil
4644 "Matches a timestamp, possibly preceded by a keyword.")
4645 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4646 (defvar org-all-time-keywords nil
4647 "List of time keywords.")
4648 (make-variable-buffer-local 'org-all-time-keywords)
4650 (defconst org-plain-time-of-day-regexp
4651 (concat
4652 "\\(\\<[012]?[0-9]"
4653 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4654 "\\(--?"
4655 "\\(\\<[012]?[0-9]"
4656 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4657 "\\)?")
4658 "Regular expression to match a plain time or time range.
4659 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4660 groups carry important information:
4661 0 the full match
4662 1 the first time, range or not
4663 8 the second time, if it is a range.")
4665 (defconst org-plain-time-extension-regexp
4666 (concat
4667 "\\(\\<[012]?[0-9]"
4668 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4669 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4670 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4671 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4672 groups carry important information:
4673 0 the full match
4674 7 hours of duration
4675 9 minutes of duration")
4677 (defconst org-stamp-time-of-day-regexp
4678 (concat
4679 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4680 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4681 "\\(--?"
4682 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4683 "Regular expression to match a timestamp time or time range.
4684 After a match, the following groups carry important information:
4685 0 the full match
4686 1 date plus weekday, for back referencing to make sure both times are on the same day
4687 2 the first time, range or not
4688 4 the second time, if it is a range.")
4690 (defconst org-startup-options
4691 '(("fold" org-startup-folded t)
4692 ("overview" org-startup-folded t)
4693 ("nofold" org-startup-folded nil)
4694 ("showall" org-startup-folded nil)
4695 ("showeverything" org-startup-folded showeverything)
4696 ("content" org-startup-folded content)
4697 ("indent" org-startup-indented t)
4698 ("noindent" org-startup-indented nil)
4699 ("hidestars" org-hide-leading-stars t)
4700 ("showstars" org-hide-leading-stars nil)
4701 ("odd" org-odd-levels-only t)
4702 ("oddeven" org-odd-levels-only nil)
4703 ("align" org-startup-align-all-tables t)
4704 ("noalign" org-startup-align-all-tables nil)
4705 ("inlineimages" org-startup-with-inline-images t)
4706 ("noinlineimages" org-startup-with-inline-images nil)
4707 ("latexpreview" org-startup-with-latex-preview t)
4708 ("nolatexpreview" org-startup-with-latex-preview nil)
4709 ("customtime" org-display-custom-times t)
4710 ("logdone" org-log-done time)
4711 ("lognotedone" org-log-done note)
4712 ("nologdone" org-log-done nil)
4713 ("lognoteclock-out" org-log-note-clock-out t)
4714 ("nolognoteclock-out" org-log-note-clock-out nil)
4715 ("logrepeat" org-log-repeat state)
4716 ("lognoterepeat" org-log-repeat note)
4717 ("logdrawer" org-log-into-drawer t)
4718 ("nologdrawer" org-log-into-drawer nil)
4719 ("logstatesreversed" org-log-states-order-reversed t)
4720 ("nologstatesreversed" org-log-states-order-reversed nil)
4721 ("nologrepeat" org-log-repeat nil)
4722 ("logreschedule" org-log-reschedule time)
4723 ("lognotereschedule" org-log-reschedule note)
4724 ("nologreschedule" org-log-reschedule nil)
4725 ("logredeadline" org-log-redeadline time)
4726 ("lognoteredeadline" org-log-redeadline note)
4727 ("nologredeadline" org-log-redeadline nil)
4728 ("logrefile" org-log-refile time)
4729 ("lognoterefile" org-log-refile note)
4730 ("nologrefile" org-log-refile nil)
4731 ("fninline" org-footnote-define-inline t)
4732 ("nofninline" org-footnote-define-inline nil)
4733 ("fnlocal" org-footnote-section nil)
4734 ("fnauto" org-footnote-auto-label t)
4735 ("fnprompt" org-footnote-auto-label nil)
4736 ("fnconfirm" org-footnote-auto-label confirm)
4737 ("fnplain" org-footnote-auto-label plain)
4738 ("fnadjust" org-footnote-auto-adjust t)
4739 ("nofnadjust" org-footnote-auto-adjust nil)
4740 ("constcgs" constants-unit-system cgs)
4741 ("constSI" constants-unit-system SI)
4742 ("noptag" org-tag-persistent-alist nil)
4743 ("hideblocks" org-hide-block-startup t)
4744 ("nohideblocks" org-hide-block-startup nil)
4745 ("beamer" org-startup-with-beamer-mode t)
4746 ("entitiespretty" org-pretty-entities t)
4747 ("entitiesplain" org-pretty-entities nil))
4748 "Variable associated with STARTUP options for org-mode.
4749 Each element is a list of three items: the startup options (as written
4750 in the #+STARTUP line), the corresponding variable, and the value to set
4751 this variable to if the option is found. An optional forth element PUSH
4752 means to push this value onto the list in the variable.")
4754 (defun org-update-property-plist (key val props)
4755 "Update PROPS with KEY and VAL."
4756 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4757 (key (if appending (substring key 0 (- (length key) 1)) key))
4758 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4759 (previous (cdr (assoc key props))))
4760 (if appending
4761 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4762 (cons (cons key val) remainder))))
4764 (defconst org-block-regexp
4765 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4766 "Regular expression for hiding blocks.")
4767 (defconst org-heading-keyword-regexp-format
4768 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4769 "Printf format for a regexp matching a headline with some keyword.
4770 This regexp will match the headline of any node which has the
4771 exact keyword that is put into the format. The keyword isn't in
4772 any group by default, but the stars and the body are.")
4773 (defconst org-heading-keyword-maybe-regexp-format
4774 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4775 "Printf format for a regexp matching a headline, possibly with some keyword.
4776 This regexp can match any headline with the specified keyword, or
4777 without a keyword. The keyword isn't in any group by default,
4778 but the stars and the body are.")
4780 (defcustom org-group-tags t
4781 "When non-nil (the default), use group tags.
4782 This can be turned on/off through `org-toggle-tags-groups'."
4783 :group 'org-tags
4784 :group 'org-startup
4785 :type 'boolean)
4787 (defun org-toggle-tags-groups ()
4788 "Toggle support for group tags.
4789 Support for group tags is controlled by the option
4790 `org-group-tags', which is non-nil by default."
4791 (interactive)
4792 (setq org-group-tags (not org-group-tags))
4793 (cond ((and (derived-mode-p 'org-agenda-mode)
4794 org-group-tags)
4795 (org-agenda-redo))
4796 ((derived-mode-p 'org-mode)
4797 (let ((org-inhibit-startup t)) (org-mode))))
4798 (message "Groups tags support has been turned %s"
4799 (if org-group-tags "on" "off")))
4801 (defun org-set-regexps-and-options-for-tags ()
4802 "Precompute regular expressions used for tags in the current buffer."
4803 (when (derived-mode-p 'org-mode)
4804 (org-set-local 'org-file-tags nil)
4805 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4806 (splitre "[ \t]+")
4807 (start 0)
4808 tags ftags key value)
4809 (save-excursion
4810 (save-restriction
4811 (widen)
4812 (goto-char (point-min))
4813 (while (re-search-forward re nil t)
4814 (setq key (upcase (org-match-string-no-properties 1))
4815 value (org-match-string-no-properties 2))
4816 (if (stringp value) (setq value (org-trim value)))
4817 (cond
4818 ((equal key "TAGS")
4819 (setq tags (append tags (if tags '("\\n") nil)
4820 (org-split-string value splitre))))
4821 ((equal key "FILETAGS")
4822 (when (string-match "\\S-" value)
4823 (setq ftags
4824 (append
4825 ftags
4826 (apply 'append
4827 (mapcar (lambda (x) (org-split-string x ":"))
4828 (org-split-string value)))))))))))
4829 ;; Process the file tags.
4830 (and ftags (org-set-local 'org-file-tags
4831 (mapcar 'org-add-prop-inherited ftags)))
4832 (org-set-local 'org-tag-groups-alist nil)
4833 ;; Process the tags.
4834 ;; FIXME
4835 (when tags
4836 (let (e tgs g)
4837 (while (setq e (pop tags))
4838 (cond
4839 ((equal e "{")
4840 (progn (push '(:startgroup) tgs)
4841 (when (equal (nth 1 tags) ":")
4842 (push (list (replace-regexp-in-string
4843 "(.+)$" "" (nth 0 tags)))
4844 org-tag-groups-alist)
4845 (setq g 0))))
4846 ((equal e ":") (push '(:grouptags) tgs))
4847 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4848 ((equal e "\\n") (push '(:newline) tgs))
4849 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4850 (push (cons (match-string 1 e)
4851 (string-to-char (match-string 2 e))) tgs)
4852 (if (and g (> g 0))
4853 (setcar org-tag-groups-alist
4854 (append (car org-tag-groups-alist)
4855 (list (match-string 1 e)))))
4856 (if g (setq g (1+ g))))
4857 (t (push (list e) tgs)
4858 (if (and g (> g 0))
4859 (setcar org-tag-groups-alist
4860 (append (car org-tag-groups-alist) (list e))))
4861 (if g (setq g (1+ g))))))
4862 (org-set-local 'org-tag-alist nil)
4863 (while (setq e (pop tgs))
4864 (or (and (stringp (car e))
4865 (assoc (car e) org-tag-alist))
4866 (push e org-tag-alist))))))))
4868 (defun org-set-regexps-and-options ()
4869 "Precompute regular expressions used in the current buffer."
4870 (when (derived-mode-p 'org-mode)
4871 (org-set-local 'org-todo-kwd-alist nil)
4872 (org-set-local 'org-todo-key-alist nil)
4873 (org-set-local 'org-todo-key-trigger nil)
4874 (org-set-local 'org-todo-keywords-1 nil)
4875 (org-set-local 'org-done-keywords nil)
4876 (org-set-local 'org-todo-heads nil)
4877 (org-set-local 'org-todo-sets nil)
4878 (org-set-local 'org-todo-log-states nil)
4879 (org-set-local 'org-file-properties nil)
4880 (let ((re (org-make-options-regexp
4881 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4882 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4883 "SETUPFILE" "OPTIONS")
4884 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4885 (splitre "[ \t]+")
4886 (scripts org-use-sub-superscripts)
4887 kwds kws0 kwsa key log value cat arch const links hw dws
4888 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4889 (start 0))
4890 (save-excursion
4891 (save-restriction
4892 (widen)
4893 (goto-char (point-min))
4894 (while (or (and ext-setup-or-nil
4895 (let (ret)
4896 (with-temp-buffer
4897 (insert ext-setup-or-nil)
4898 (let ((major-mode 'org-mode))
4899 (org-set-regexps-and-options-for-tags)
4900 (setq ret (list org-file-tags org-tag-alist
4901 org-tag-groups-alist))))
4902 (setq org-file-tags (nth 0 ret)
4903 org-tag-alist (nth 1 ret)
4904 org-tag-groups-alist (nth 2 ret))))
4905 (and ext-setup-or-nil
4906 (string-match re ext-setup-or-nil start)
4907 (setq start (match-end 0)))
4908 (and (setq ext-setup-or-nil nil start 0)
4909 (re-search-forward re nil t)))
4910 (setq key (upcase (match-string 1 ext-setup-or-nil))
4911 value (org-match-string-no-properties 2 ext-setup-or-nil))
4912 (if (stringp value) (setq value (org-trim value)))
4913 (cond
4914 ((equal key "CATEGORY")
4915 (setq cat value))
4916 ((member key '("SEQ_TODO" "TODO"))
4917 (push (cons 'sequence (org-split-string value splitre)) kwds))
4918 ((equal key "TYP_TODO")
4919 (push (cons 'type (org-split-string value splitre)) kwds))
4920 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4921 ;; general TODO-like setup
4922 (push (cons (intern (downcase (match-string 1 key)))
4923 (org-split-string value splitre)) kwds))
4924 ((equal key "COLUMNS")
4925 (org-set-local 'org-columns-default-format value))
4926 ((equal key "LINK")
4927 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4928 (push (cons (match-string 1 value)
4929 (org-trim (match-string 2 value)))
4930 links)))
4931 ((equal key "PRIORITIES")
4932 (setq prio (org-split-string value " +")))
4933 ((equal key "PROPERTY")
4934 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4935 (setq props (org-update-property-plist (match-string 1 value)
4936 (match-string 2 value)
4937 props))))
4938 ((equal key "DRAWERS")
4939 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4940 ((equal key "CONSTANTS")
4941 (org-table-set-constants))
4942 ((equal key "STARTUP")
4943 (let ((opts (org-split-string value splitre))
4944 l var val)
4945 (while (setq l (pop opts))
4946 (when (setq l (assoc l org-startup-options))
4947 (setq var (nth 1 l) val (nth 2 l))
4948 (if (not (nth 3 l))
4949 (set (make-local-variable var) val)
4950 (if (not (listp (symbol-value var)))
4951 (set (make-local-variable var) nil))
4952 (set (make-local-variable var) (symbol-value var))
4953 (add-to-list var val))))))
4954 ((equal key "ARCHIVE")
4955 (setq arch value)
4956 (remove-text-properties 0 (length arch)
4957 '(face t fontified t) arch))
4958 ((equal key "OPTIONS")
4959 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4960 (setq scripts (read (match-string 2 value)))))
4961 ((and (equal key "SETUPFILE")
4962 ;; Prevent checking in Gnus messages
4963 (not buffer-read-only))
4964 (setq setup-contents (org-file-contents
4965 (expand-file-name
4966 (org-remove-double-quotes value))
4967 'noerror))
4968 (if (not ext-setup-or-nil)
4969 (setq ext-setup-or-nil setup-contents start 0)
4970 (setq ext-setup-or-nil
4971 (concat (substring ext-setup-or-nil 0 start)
4972 "\n" setup-contents "\n"
4973 (substring ext-setup-or-nil start)))))))
4974 ;; search for property blocks
4975 (goto-char (point-min))
4976 (while (re-search-forward org-block-regexp nil t)
4977 (when (equal "PROPERTY" (upcase (match-string 1)))
4978 (setq value (replace-regexp-in-string
4979 "[\n\r]" " " (match-string 4)))
4980 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4981 (setq props (org-update-property-plist (match-string 1 value)
4982 (match-string 2 value)
4983 props)))))))
4984 (org-set-local 'org-use-sub-superscripts scripts)
4985 (when cat
4986 (org-set-local 'org-category (intern cat))
4987 (push (cons "CATEGORY" cat) props))
4988 (when prio
4989 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4990 (setq prio (mapcar 'string-to-char prio))
4991 (org-set-local 'org-highest-priority (nth 0 prio))
4992 (org-set-local 'org-lowest-priority (nth 1 prio))
4993 (org-set-local 'org-default-priority (nth 2 prio)))
4994 (and props (org-set-local 'org-file-properties (nreverse props)))
4995 (and drawers (org-set-local 'org-drawers drawers))
4996 (and arch (org-set-local 'org-archive-location arch))
4997 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4998 ;; Process the TODO keywords
4999 (unless kwds
5000 ;; Use the global values as if they had been given locally.
5001 (setq kwds (default-value 'org-todo-keywords))
5002 (if (stringp (car kwds))
5003 (setq kwds (list (cons org-todo-interpretation
5004 (default-value 'org-todo-keywords)))))
5005 (setq kwds (reverse kwds)))
5006 (setq kwds (nreverse kwds))
5007 (let (inter kws kw)
5008 (while (setq kws (pop kwds))
5009 (let ((kws (or
5010 (run-hook-with-args-until-success
5011 'org-todo-setup-filter-hook kws)
5012 kws)))
5013 (setq inter (pop kws) sep (member "|" kws)
5014 kws0 (delete "|" (copy-sequence kws))
5015 kwsa nil
5016 kws1 (mapcar
5017 (lambda (x)
5018 ;; 1 2
5019 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5020 (progn
5021 (setq kw (match-string 1 x)
5022 key (and (match-end 2) (match-string 2 x))
5023 log (org-extract-log-state-settings x))
5024 (push (cons kw (and key (string-to-char key))) kwsa)
5025 (and log (push log org-todo-log-states))
5027 (error "Invalid TODO keyword %s" x)))
5028 kws0)
5029 kwsa (if kwsa (append '((:startgroup))
5030 (nreverse kwsa)
5031 '((:endgroup))))
5032 hw (car kws1)
5033 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5034 tail (list inter hw (car dws) (org-last dws))))
5035 (add-to-list 'org-todo-heads hw 'append)
5036 (push kws1 org-todo-sets)
5037 (setq org-done-keywords (append org-done-keywords dws nil))
5038 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5039 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5040 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5041 (setq org-todo-sets (nreverse org-todo-sets)
5042 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5043 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5044 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5045 ;; Compute the regular expressions and other local variables.
5046 ;; Using `org-outline-regexp-bol' would complicate them much,
5047 ;; because of the fixed white space at the end of that string.
5048 (if (not org-done-keywords)
5049 (setq org-done-keywords (and org-todo-keywords-1
5050 (list (org-last org-todo-keywords-1)))))
5051 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5052 (length org-scheduled-string)
5053 (length org-clock-string)
5054 (length org-closed-string)))
5055 org-drawer-regexp
5056 (concat "^[ \t]*:\\("
5057 (mapconcat 'regexp-quote org-drawers "\\|")
5058 "\\):[ \t]*$")
5059 org-not-done-keywords
5060 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5061 org-todo-regexp
5062 (concat "\\("
5063 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5064 "\\)")
5065 org-not-done-regexp
5066 (concat "\\("
5067 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5068 "\\)")
5069 org-not-done-heading-regexp
5070 (format org-heading-keyword-regexp-format org-not-done-regexp)
5071 org-todo-line-regexp
5072 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5073 org-complex-heading-regexp
5074 (concat "^\\(\\*+\\)"
5075 "\\(?: +" org-todo-regexp "\\)?"
5076 "\\(?: +\\(\\[#.\\]\\)\\)?"
5077 "\\(?: +\\(.*?\\)\\)??"
5078 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5079 "[ \t]*$")
5080 org-complex-heading-regexp-format
5081 (concat "^\\(\\*+\\)"
5082 "\\(?: +" org-todo-regexp "\\)?"
5083 "\\(?: +\\(\\[#.\\]\\)\\)?"
5084 "\\(?: +"
5085 ;; Stats cookies can be stuck to body.
5086 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5087 "\\(%s\\)"
5088 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5089 "\\)"
5090 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5091 "[ \t]*$")
5092 org-todo-line-tags-regexp
5093 (concat "^\\(\\*+\\)"
5094 "\\(?: +" org-todo-regexp "\\)?"
5095 "\\(?: +\\(.*?\\)\\)??"
5096 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5097 "[ \t]*$")
5098 org-deadline-regexp (concat "\\<" org-deadline-string)
5099 org-deadline-time-regexp
5100 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5101 org-deadline-time-hour-regexp
5102 (concat "\\<" org-deadline-string
5103 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5104 org-deadline-line-regexp
5105 (concat "\\<\\(" org-deadline-string "\\).*")
5106 org-scheduled-regexp
5107 (concat "\\<" org-scheduled-string)
5108 org-scheduled-time-regexp
5109 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5110 org-scheduled-time-hour-regexp
5111 (concat "\\<" org-scheduled-string
5112 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5113 org-closed-time-regexp
5114 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5115 org-keyword-time-regexp
5116 (concat "\\<\\(" org-scheduled-string
5117 "\\|" org-deadline-string
5118 "\\|" org-closed-string
5119 "\\|" org-clock-string "\\)"
5120 " *[[<]\\([^]>]+\\)[]>]")
5121 org-keyword-time-not-clock-regexp
5122 (concat "\\<\\(" org-scheduled-string
5123 "\\|" org-deadline-string
5124 "\\|" org-closed-string
5125 "\\)"
5126 " *[[<]\\([^]>]+\\)[]>]")
5127 org-maybe-keyword-time-regexp
5128 (concat "\\(\\<\\(" org-scheduled-string
5129 "\\|" org-deadline-string
5130 "\\|" org-closed-string
5131 "\\|" org-clock-string "\\)\\)?"
5132 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5133 org-all-time-keywords
5134 (mapcar (lambda (w) (substring w 0 -1))
5135 (list org-scheduled-string org-deadline-string
5136 org-clock-string org-closed-string)))
5137 (org-compute-latex-and-related-regexp)
5138 (org-set-font-lock-defaults))))
5140 (defun org-file-contents (file &optional noerror)
5141 "Return the contents of FILE, as a string."
5142 (if (or (not file)
5143 (not (file-readable-p file)))
5144 (if noerror
5145 (message "Cannot read file \"%s\"" file)
5146 (error "Cannot read file \"%s\"" file))
5147 (with-temp-buffer
5148 (insert-file-contents file)
5149 (buffer-string))))
5151 (defun org-extract-log-state-settings (x)
5152 "Extract the log state setting from a TODO keyword string.
5153 This will extract info from a string like \"WAIT(w@/!)\"."
5154 (let (kw key log1 log2)
5155 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5156 (setq kw (match-string 1 x)
5157 key (and (match-end 2) (match-string 2 x))
5158 log1 (and (match-end 3) (match-string 3 x))
5159 log2 (and (match-end 4) (match-string 4 x)))
5160 (and (or log1 log2)
5161 (list kw
5162 (and log1 (if (equal log1 "!") 'time 'note))
5163 (and log2 (if (equal log2 "!") 'time 'note)))))))
5165 (defun org-remove-keyword-keys (list)
5166 "Remove a pair of parenthesis at the end of each string in LIST."
5167 (mapcar (lambda (x)
5168 (if (string-match "(.*)$" x)
5169 (substring x 0 (match-beginning 0))
5171 list))
5173 (defun org-assign-fast-keys (alist)
5174 "Assign fast keys to a keyword-key alist.
5175 Respect keys that are already there."
5176 (let (new e (alt ?0))
5177 (while (setq e (pop alist))
5178 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5179 (cdr e)) ;; Key already assigned.
5180 (push e new)
5181 (let ((clist (string-to-list (downcase (car e))))
5182 (used (append new alist)))
5183 (when (= (car clist) ?@)
5184 (pop clist))
5185 (while (and clist (rassoc (car clist) used))
5186 (pop clist))
5187 (unless clist
5188 (while (rassoc alt used)
5189 (incf alt)))
5190 (push (cons (car e) (or (car clist) alt)) new))))
5191 (nreverse new)))
5193 ;;; Some variables used in various places
5195 (defvar org-window-configuration nil
5196 "Used in various places to store a window configuration.")
5197 (defvar org-selected-window nil
5198 "Used in various places to store a window configuration.")
5199 (defvar org-finish-function nil
5200 "Function to be called when `C-c C-c' is used.
5201 This is for getting out of special buffers like capture.")
5204 ;; FIXME: Occasionally check by commenting these, to make sure
5205 ;; no other functions uses these, forgetting to let-bind them.
5206 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5207 (defvar org-last-state)
5208 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5210 ;; Defined somewhere in this file, but used before definition.
5211 (defvar org-entities) ;; defined in org-entities.el
5212 (defvar org-struct-menu)
5213 (defvar org-org-menu)
5214 (defvar org-tbl-menu)
5216 ;;;; Define the Org-mode
5218 ;; We use a before-change function to check if a table might need
5219 ;; an update.
5220 (defvar org-table-may-need-update t
5221 "Indicates that a table might need an update.
5222 This variable is set by `org-before-change-function'.
5223 `org-table-align' sets it back to nil.")
5224 (defun org-before-change-function (beg end)
5225 "Every change indicates that a table might need an update."
5226 (setq org-table-may-need-update t))
5227 (defvar org-mode-map)
5228 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5229 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5230 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5231 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5232 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5233 (defvar org-table-buffer-is-an nil)
5235 (defvar bidi-paragraph-direction)
5236 (defvar buffer-face-mode-face)
5238 (require 'outline)
5239 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5240 (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"))
5241 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5243 ;; Other stuff we need.
5244 (require 'time-date)
5245 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5246 (require 'easymenu)
5247 (require 'overlay)
5249 ;; (require 'org-macs) moved higher up in the file before it is first used
5250 (require 'org-entities)
5251 ;; (require 'org-compat) moved higher up in the file before it is first used
5252 (require 'org-faces)
5253 (require 'org-list)
5254 (require 'org-pcomplete)
5255 (require 'org-src)
5256 (require 'org-footnote)
5257 (require 'org-macro)
5259 ;; babel
5260 (require 'ob)
5262 ;;;###autoload
5263 (define-derived-mode org-mode outline-mode "Org"
5264 "Outline-based notes management and organizer, alias
5265 \"Carsten's outline-mode for keeping track of everything.\"
5267 Org-mode develops organizational tasks around a NOTES file which
5268 contains information about projects as plain text. Org-mode is
5269 implemented on top of outline-mode, which is ideal to keep the content
5270 of large files well structured. It supports ToDo items, deadlines and
5271 time stamps, which magically appear in the diary listing of the Emacs
5272 calendar. Tables are easily created with a built-in table editor.
5273 Plain text URL-like links connect to websites, emails (VM), Usenet
5274 messages (Gnus), BBDB entries, and any files related to the project.
5275 For printing and sharing of notes, an Org-mode file (or a part of it)
5276 can be exported as a structured ASCII or HTML file.
5278 The following commands are available:
5280 \\{org-mode-map}"
5282 ;; Get rid of Outline menus, they are not needed
5283 ;; Need to do this here because define-derived-mode sets up
5284 ;; the keymap so late. Still, it is a waste to call this each time
5285 ;; we switch another buffer into org-mode.
5286 (if (featurep 'xemacs)
5287 (when (boundp 'outline-mode-menu-heading)
5288 ;; Assume this is Greg's port, it uses easymenu
5289 (easy-menu-remove outline-mode-menu-heading)
5290 (easy-menu-remove outline-mode-menu-show)
5291 (easy-menu-remove outline-mode-menu-hide))
5292 (define-key org-mode-map [menu-bar headings] 'undefined)
5293 (define-key org-mode-map [menu-bar hide] 'undefined)
5294 (define-key org-mode-map [menu-bar show] 'undefined))
5296 (org-load-modules-maybe)
5297 (easy-menu-add org-org-menu)
5298 (easy-menu-add org-tbl-menu)
5299 (org-install-agenda-files-menu)
5300 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5301 (add-to-invisibility-spec '(org-cwidth))
5302 (add-to-invisibility-spec '(org-hide-block . t))
5303 (when (featurep 'xemacs)
5304 (org-set-local 'line-move-ignore-invisible t))
5305 (org-set-local 'outline-regexp org-outline-regexp)
5306 (org-set-local 'outline-level 'org-outline-level)
5307 (setq bidi-paragraph-direction 'left-to-right)
5308 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5309 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5310 (when (and org-ellipsis
5311 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5312 (fboundp 'make-glyph-code))
5313 (unless org-display-table
5314 (setq org-display-table (make-display-table)))
5315 (set-display-table-slot
5316 org-display-table 4
5317 (vconcat (mapcar
5318 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5319 org-ellipsis)))
5320 (if (stringp org-ellipsis) org-ellipsis "..."))))
5321 (setq buffer-display-table org-display-table))
5322 (org-set-regexps-and-options-for-tags)
5323 (org-set-regexps-and-options)
5324 (when (and org-tag-faces (not org-tags-special-faces-re))
5325 ;; tag faces set outside customize.... force initialization.
5326 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5327 ;; Calc embedded
5328 (org-set-local 'calc-embedded-open-mode "# ")
5329 ;; Modify a few syntax entries
5330 (modify-syntax-entry ?@ "w")
5331 (modify-syntax-entry ?\" "\"")
5332 (if org-startup-truncated (setq truncate-lines t))
5333 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5334 (org-set-local 'font-lock-unfontify-region-function
5335 'org-unfontify-region)
5336 ;; Activate before-change-function
5337 (org-set-local 'org-table-may-need-update t)
5338 (org-add-hook 'before-change-functions 'org-before-change-function nil
5339 'local)
5340 ;; Check for running clock before killing a buffer
5341 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5342 ;; Initialize macros templates.
5343 (org-macro-initialize-templates)
5344 ;; Initialize radio targets.
5345 (org-update-radio-target-regexp)
5346 ;; Indentation.
5347 (org-set-local 'indent-line-function 'org-indent-line)
5348 (org-set-local 'indent-region-function 'org-indent-region)
5349 ;; Filling and auto-filling.
5350 (org-setup-filling)
5351 ;; Comments.
5352 (org-setup-comments-handling)
5353 ;; Beginning/end of defun
5354 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5355 (org-set-local 'end-of-defun-function 'org-forward-element)
5356 ;; Next error for sparse trees
5357 (org-set-local 'next-error-function 'org-occur-next-match)
5358 ;; Make sure dependence stuff works reliably, even for users who set it
5359 ;; too late :-(
5360 (if org-enforce-todo-dependencies
5361 (add-hook 'org-blocker-hook
5362 'org-block-todo-from-children-or-siblings-or-parent)
5363 (remove-hook 'org-blocker-hook
5364 'org-block-todo-from-children-or-siblings-or-parent))
5365 (if org-enforce-todo-checkbox-dependencies
5366 (add-hook 'org-blocker-hook
5367 'org-block-todo-from-checkboxes)
5368 (remove-hook 'org-blocker-hook
5369 'org-block-todo-from-checkboxes))
5371 ;; Align options lines
5372 (org-set-local
5373 'align-mode-rules-list
5374 '((org-in-buffer-settings
5375 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5376 (modes . '(org-mode)))))
5378 ;; Imenu
5379 (org-set-local 'imenu-create-index-function
5380 'org-imenu-get-tree)
5382 ;; Make isearch reveal context
5383 (if (or (featurep 'xemacs)
5384 (not (boundp 'outline-isearch-open-invisible-function)))
5385 ;; Emacs 21 and XEmacs make use of the hook
5386 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5387 ;; Emacs 22 deals with this through a special variable
5388 (org-set-local 'outline-isearch-open-invisible-function
5389 (lambda (&rest ignore) (org-show-context 'isearch)))
5390 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5392 ;; Setup the pcomplete hooks
5393 (set (make-local-variable 'pcomplete-command-completion-function)
5394 'org-pcomplete-initial)
5395 (set (make-local-variable 'pcomplete-command-name-function)
5396 'org-command-at-point)
5397 (set (make-local-variable 'pcomplete-default-completion-function)
5398 'ignore)
5399 (set (make-local-variable 'pcomplete-parse-arguments-function)
5400 'org-parse-arguments)
5401 (set (make-local-variable 'pcomplete-termination-string) "")
5402 (when (>= emacs-major-version 23)
5403 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5405 ;; If empty file that did not turn on org-mode automatically, make it to.
5406 (if (and org-insert-mode-line-in-empty-file
5407 (org-called-interactively-p 'any)
5408 (= (point-min) (point-max)))
5409 (insert "# -*- mode: org -*-\n\n"))
5410 (unless org-inhibit-startup
5411 (org-unmodified
5412 (and org-startup-with-beamer-mode (org-beamer-mode))
5413 (when org-startup-align-all-tables
5414 (org-table-map-tables 'org-table-align 'quietly))
5415 (when org-startup-with-inline-images
5416 (org-display-inline-images))
5417 (when org-startup-with-latex-preview
5418 (org-preview-latex-fragment))
5419 (unless org-inhibit-startup-visibility-stuff
5420 (org-set-startup-visibility))))
5421 ;; Try to set org-hide correctly
5422 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5424 ;; Update `customize-package-emacs-version-alist'
5425 (add-to-list 'customize-package-emacs-version-alist
5426 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5427 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5428 ("8.0" . "24.4")))
5430 (defvar org-mode-transpose-word-syntax-table
5431 (let ((st (make-syntax-table)))
5432 (mapc (lambda(c) (modify-syntax-entry
5433 (string-to-char (car c)) "w p" st))
5434 org-emphasis-alist)
5435 st))
5437 (when (fboundp 'abbrev-table-put)
5438 (abbrev-table-put org-mode-abbrev-table
5439 :parents (list text-mode-abbrev-table)))
5441 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5443 (defsubst org-fix-ellipsis-at-bol ()
5444 (save-excursion (goto-char (window-start)) (recenter 0)))
5446 (defun org-find-invisible-foreground ()
5447 (let ((candidates (remove
5448 "unspecified-bg"
5449 (nconc
5450 (list (face-background 'default)
5451 (face-background 'org-default))
5452 (mapcar
5453 (lambda (alist)
5454 (when (boundp alist)
5455 (cdr (assoc 'background-color (symbol-value alist)))))
5456 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5457 (list (face-foreground 'org-hide))))))
5458 (car (remove nil candidates))))
5460 (defun org-current-time (&optional rounding-minutes past)
5461 "Current time, possibly rounded to ROUNDING-MINUTES.
5462 When ROUNDING-MINUTES is not an integer, fall back on the car of
5463 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5464 the rounding returns a past time."
5465 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5466 (car org-time-stamp-rounding-minutes)))
5467 (time (decode-time)) res)
5468 (if (< r 1)
5469 (current-time)
5470 (setq res
5471 (apply 'encode-time
5472 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5473 (nthcdr 2 time))))
5474 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5475 (seconds-to-time (- (org-float-time res) (* r 60)))
5476 res))))
5478 (defun org-today ()
5479 "Return today date, considering `org-extend-today-until'."
5480 (time-to-days
5481 (time-subtract (current-time)
5482 (list 0 (* 3600 org-extend-today-until) 0))))
5484 ;;;; Font-Lock stuff, including the activators
5486 (defvar org-mouse-map (make-sparse-keymap))
5487 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5488 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5489 (when org-mouse-1-follows-link
5490 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5491 (when org-tab-follows-link
5492 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5493 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5495 (require 'font-lock)
5497 (defconst org-non-link-chars "]\t\n\r<>")
5498 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5499 "shell" "elisp" "doi" "message"))
5500 (defvar org-link-types-re nil
5501 "Matches a link that has a url-like prefix like \"http:\"")
5502 (defvar org-link-re-with-space nil
5503 "Matches a link with spaces, optional angular brackets around it.")
5504 (defvar org-link-re-with-space2 nil
5505 "Matches a link with spaces, optional angular brackets around it.")
5506 (defvar org-link-re-with-space3 nil
5507 "Matches a link with spaces, only for internal part in bracket links.")
5508 (defvar org-angle-link-re nil
5509 "Matches link with angular brackets, spaces are allowed.")
5510 (defvar org-plain-link-re nil
5511 "Matches plain link, without spaces.")
5512 (defvar org-bracket-link-regexp nil
5513 "Matches a link in double brackets.")
5514 (defvar org-bracket-link-analytic-regexp nil
5515 "Regular expression used to analyze links.
5516 Here is what the match groups contain after a match:
5517 1: http:
5518 2: http
5519 3: path
5520 4: [desc]
5521 5: desc")
5522 (defvar org-bracket-link-analytic-regexp++ nil
5523 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5524 (defvar org-any-link-re nil
5525 "Regular expression matching any link.")
5527 (defconst org-match-sexp-depth 3
5528 "Number of stacked braces for sub/superscript matching.")
5530 (defun org-create-multibrace-regexp (left right n)
5531 "Create a regular expression which will match a balanced sexp.
5532 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5533 as single character strings.
5534 The regexp returned will match the entire expression including the
5535 delimiters. It will also define a single group which contains the
5536 match except for the outermost delimiters. The maximum depth of
5537 stacked delimiters is N. Escaping delimiters is not possible."
5538 (let* ((nothing (concat "[^" left right "]*?"))
5539 (or "\\|")
5540 (re nothing)
5541 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5542 (while (> n 1)
5543 (setq n (1- n)
5544 re (concat re or next)
5545 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5546 (concat left "\\(" re "\\)" right)))
5548 (defvar org-match-substring-regexp
5549 (concat
5550 "\\(\\S-\\)\\([_^]\\)\\("
5551 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5552 "\\|"
5553 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5554 "\\|"
5555 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5556 "The regular expression matching a sub- or superscript.")
5558 (defvar org-match-substring-with-braces-regexp
5559 (concat
5560 "\\(\\S-\\)\\([_^]\\)\\("
5561 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5562 "\\)")
5563 "The regular expression matching a sub- or superscript, forcing braces.")
5565 (defun org-make-link-regexps ()
5566 "Update the link regular expressions.
5567 This should be called after the variable `org-link-types' has changed."
5568 (setq org-link-types-re
5569 (concat
5570 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5571 org-link-re-with-space
5572 (concat
5573 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5574 "\\([^" org-non-link-chars " ]"
5575 "[^" org-non-link-chars "]*"
5576 "[^" org-non-link-chars " ]\\)>?")
5577 org-link-re-with-space2
5578 (concat
5579 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5580 "\\([^" org-non-link-chars " ]"
5581 "[^\t\n\r]*"
5582 "[^" org-non-link-chars " ]\\)>?")
5583 org-link-re-with-space3
5584 (concat
5585 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5586 "\\([^" org-non-link-chars " ]"
5587 "[^\t\n\r]*\\)")
5588 org-angle-link-re
5589 (concat
5590 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5591 "\\([^" org-non-link-chars " ]"
5592 "[^" org-non-link-chars "]*"
5593 "\\)>")
5594 org-plain-link-re
5595 (concat
5596 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5597 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5598 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5599 org-bracket-link-regexp
5600 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5601 org-bracket-link-analytic-regexp
5602 (concat
5603 "\\[\\["
5604 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5605 "\\([^]]+\\)"
5606 "\\]"
5607 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5608 "\\]")
5609 org-bracket-link-analytic-regexp++
5610 (concat
5611 "\\[\\["
5612 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5613 "\\([^]]+\\)"
5614 "\\]"
5615 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5616 "\\]")
5617 org-any-link-re
5618 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5619 org-angle-link-re "\\)\\|\\("
5620 org-plain-link-re "\\)")))
5622 (org-make-link-regexps)
5624 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5625 "Regular expression for fast time stamp matching.")
5626 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5627 "Regular expression for fast time stamp matching.")
5628 (defconst org-ts-regexp0
5629 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5630 "Regular expression matching time strings for analysis.
5631 This one does not require the space after the date, so it can be used
5632 on a string that terminates immediately after the date.")
5633 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5634 "Regular expression matching time strings for analysis.")
5635 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5636 "Regular expression matching time stamps, with groups.")
5637 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5638 "Regular expression matching time stamps (also [..]), with groups.")
5639 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5640 "Regular expression matching a time stamp range.")
5641 (defconst org-tr-regexp-both
5642 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5643 "Regular expression matching a time stamp range.")
5644 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5645 org-ts-regexp "\\)?")
5646 "Regular expression matching a time stamp or time stamp range.")
5647 (defconst org-tsr-regexp-both
5648 (concat org-ts-regexp-both "\\(--?-?"
5649 org-ts-regexp-both "\\)?")
5650 "Regular expression matching a time stamp or time stamp range.
5651 The time stamps may be either active or inactive.")
5653 (defvar org-emph-face nil)
5655 (defun org-do-emphasis-faces (limit)
5656 "Run through the buffer and add overlays to emphasized strings."
5657 (let (rtn a)
5658 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5659 (if (not (= (char-after (match-beginning 3))
5660 (char-after (match-beginning 4))))
5661 (progn
5662 (setq rtn t)
5663 (setq a (assoc (match-string 3) org-emphasis-alist))
5664 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5665 'face
5666 (nth 1 a))
5667 (and (nth 4 a)
5668 (org-remove-flyspell-overlays-in
5669 (match-beginning 0) (match-end 0)))
5670 (add-text-properties (match-beginning 2) (match-end 2)
5671 '(font-lock-multiline t org-emphasis t))
5672 (when org-hide-emphasis-markers
5673 (add-text-properties (match-end 4) (match-beginning 5)
5674 '(invisible org-link))
5675 (add-text-properties (match-beginning 3) (match-end 3)
5676 '(invisible org-link)))))
5677 (backward-char 1))
5678 rtn))
5680 (defun org-emphasize (&optional char)
5681 "Insert or change an emphasis, i.e. a font like bold or italic.
5682 If there is an active region, change that region to a new emphasis.
5683 If there is no region, just insert the marker characters and position
5684 the cursor between them.
5685 CHAR should be the marker character. If it is a space, it means to
5686 remove the emphasis of the selected region.
5687 If CHAR is not given (for example in an interactive call) it will be
5688 prompted for."
5689 (interactive)
5690 (let ((erc org-emphasis-regexp-components)
5691 (prompt "")
5692 (string "") beg end move c s)
5693 (if (org-region-active-p)
5694 (setq beg (region-beginning) end (region-end)
5695 string (buffer-substring beg end))
5696 (setq move t))
5698 (unless char
5699 (message "Emphasis marker or tag: [%s]"
5700 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5701 (setq char (read-char-exclusive)))
5702 (if (equal char ?\ )
5703 (setq s "" move nil)
5704 (unless (assoc (char-to-string char) org-emphasis-alist)
5705 (user-error "No such emphasis marker: \"%c\"" char))
5706 (setq s (char-to-string char)))
5707 (while (and (> (length string) 1)
5708 (equal (substring string 0 1) (substring string -1))
5709 (assoc (substring string 0 1) org-emphasis-alist))
5710 (setq string (substring string 1 -1)))
5711 (setq string (concat s string s))
5712 (if beg (delete-region beg end))
5713 (unless (or (bolp)
5714 (string-match (concat "[" (nth 0 erc) "\n]")
5715 (char-to-string (char-before (point)))))
5716 (insert " "))
5717 (unless (or (eobp)
5718 (string-match (concat "[" (nth 1 erc) "\n]")
5719 (char-to-string (char-after (point)))))
5720 (insert " ") (backward-char 1))
5721 (insert string)
5722 (and move (backward-char 1))))
5724 (defconst org-nonsticky-props
5725 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5727 (defsubst org-rear-nonsticky-at (pos)
5728 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5730 (defun org-activate-plain-links (limit)
5731 "Run through the buffer and add overlays to links."
5732 (let (f hl)
5733 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5734 (not (org-in-src-block-p)))
5735 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5736 (setq f (get-text-property (match-beginning 0) 'face))
5737 (setq hl (org-match-string-no-properties 0))
5738 (if (or (eq f 'org-tag)
5739 (and (listp f) (memq 'org-tag f)))
5741 (add-text-properties (match-beginning 0) (match-end 0)
5742 (list 'mouse-face 'highlight
5743 'face 'org-link
5744 'htmlize-link `(:uri ,hl)
5745 'keymap org-mouse-map))
5746 (org-rear-nonsticky-at (match-end 0)))
5747 t)))
5749 (defun org-activate-code (limit)
5750 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5751 (progn
5752 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5753 (remove-text-properties (match-beginning 0) (match-end 0)
5754 '(display t invisible t intangible t))
5755 t)))
5757 (defcustom org-src-fontify-natively nil
5758 "When non-nil, fontify code in code blocks."
5759 :type 'boolean
5760 :version "24.1"
5761 :group 'org-appearance
5762 :group 'org-babel)
5764 (defcustom org-allow-promoting-top-level-subtree nil
5765 "When non-nil, allow promoting a top level subtree.
5766 The leading star of the top level headline will be replaced
5767 by a #."
5768 :type 'boolean
5769 :version "24.1"
5770 :group 'org-appearance)
5772 (defun org-fontify-meta-lines-and-blocks (limit)
5773 (condition-case nil
5774 (org-fontify-meta-lines-and-blocks-1 limit)
5775 (error (message "org-mode fontification error"))))
5777 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5778 "Fontify #+ lines and blocks."
5779 (let ((case-fold-search t))
5780 (if (re-search-forward
5781 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5782 limit t)
5783 (let ((beg (match-beginning 0))
5784 (block-start (match-end 0))
5785 (block-end nil)
5786 (lang (match-string 7))
5787 (beg1 (line-beginning-position 2))
5788 (dc1 (downcase (match-string 2)))
5789 (dc3 (downcase (match-string 3)))
5790 end end1 quoting block-type ovl)
5791 (cond
5792 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5793 ;; a single line of backend-specific content
5794 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5795 (remove-text-properties (match-beginning 0) (match-end 0)
5796 '(display t invisible t intangible t))
5797 (add-text-properties (match-beginning 1) (match-end 3)
5798 '(font-lock-fontified t face org-meta-line))
5799 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5800 '(font-lock-fontified t face org-block))
5801 ; for backend-specific code
5803 ((and (match-end 4) (equal dc3 "+begin"))
5804 ;; Truly a block
5805 (setq block-type (downcase (match-string 5))
5806 quoting (member block-type org-protecting-blocks))
5807 (when (re-search-forward
5808 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5809 nil t) ;; on purpose, we look further than LIMIT
5810 (setq end (min (point-max) (match-end 0))
5811 end1 (min (point-max) (1- (match-beginning 0))))
5812 (setq block-end (match-beginning 0))
5813 (when quoting
5814 (remove-text-properties beg end
5815 '(display t invisible t intangible t)))
5816 (add-text-properties
5817 beg end
5818 '(font-lock-fontified t font-lock-multiline t))
5819 (add-text-properties beg beg1 '(face org-meta-line))
5820 (add-text-properties end1 (min (point-max) (1+ end))
5821 '(face org-meta-line)) ; for end_src
5822 (cond
5823 ((and lang (not (string= lang "")) org-src-fontify-natively)
5824 (org-src-font-lock-fontify-block lang block-start block-end)
5825 ;; remove old background overlays
5826 (mapc (lambda (ov)
5827 (if (eq (overlay-get ov 'face) 'org-block-background)
5828 (delete-overlay ov)))
5829 (overlays-at (/ (+ beg1 block-end) 2)))
5830 ;; add a background overlay
5831 (setq ovl (make-overlay beg1 block-end))
5832 (overlay-put ovl 'face 'org-block-background)
5833 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5834 (quoting
5835 (add-text-properties beg1 (min (point-max) (1+ end1))
5836 '(face org-block))) ; end of source block
5837 ((not org-fontify-quote-and-verse-blocks))
5838 ((string= block-type "quote")
5839 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5840 ((string= block-type "verse")
5841 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5842 (add-text-properties beg beg1 '(face org-block-begin-line))
5843 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5844 '(face org-block-end-line))
5846 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5847 (add-text-properties
5848 beg (match-end 3)
5849 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5850 '(font-lock-fontified t invisible t)
5851 '(font-lock-fontified t face org-document-info-keyword)))
5852 (add-text-properties
5853 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5854 (if (string-equal dc1 "+title:")
5855 '(font-lock-fontified t face org-document-title)
5856 '(font-lock-fontified t face org-document-info))))
5857 ((or (equal dc1 "+results")
5858 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5859 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5860 "+call:" "+header:" "+headers:" "+name:"))
5861 (and (match-end 4) (equal dc3 "+attr")))
5862 (add-text-properties
5863 beg (match-end 0)
5864 '(font-lock-fontified t face org-meta-line))
5866 ((member dc3 '(" " ""))
5867 (add-text-properties
5868 beg (match-end 0)
5869 '(font-lock-fontified t face font-lock-comment-face)))
5870 ((not (member (char-after beg) '(?\ ?\t)))
5871 ;; just any other in-buffer setting, but not indented
5872 (add-text-properties
5873 beg (match-end 0)
5874 '(font-lock-fontified t face org-meta-line))
5876 (t nil))))))
5878 (defun org-activate-angle-links (limit)
5879 "Run through the buffer and add overlays to links."
5880 (if (and (re-search-forward org-angle-link-re limit t)
5881 (not (org-in-src-block-p)))
5882 (progn
5883 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5884 (add-text-properties (match-beginning 0) (match-end 0)
5885 (list 'mouse-face 'highlight
5886 'keymap org-mouse-map))
5887 (org-rear-nonsticky-at (match-end 0))
5888 t)))
5890 (defun org-activate-footnote-links (limit)
5891 "Run through the buffer and add overlays to footnotes."
5892 (let ((fn (org-footnote-next-reference-or-definition limit)))
5893 (when fn
5894 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5895 (org-remove-flyspell-overlays-in beg end)
5896 (add-text-properties beg end
5897 (list 'mouse-face 'highlight
5898 'keymap org-mouse-map
5899 'help-echo
5900 (if (= (point-at-bol) beg)
5901 "Footnote definition"
5902 "Footnote reference")
5903 'font-lock-fontified t
5904 'font-lock-multiline t
5905 'face 'org-footnote))))))
5907 (defun org-activate-bracket-links (limit)
5908 "Run through the buffer and add overlays to bracketed links."
5909 (if (and (re-search-forward org-bracket-link-regexp limit t)
5910 (not (org-in-src-block-p)))
5911 (let* ((hl (org-match-string-no-properties 1))
5912 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5913 (ip (org-maybe-intangible
5914 (list 'invisible 'org-link
5915 'keymap org-mouse-map 'mouse-face 'highlight
5916 'font-lock-multiline t 'help-echo help
5917 'htmlize-link `(:uri ,hl))))
5918 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5919 'font-lock-multiline t 'help-echo help
5920 'htmlize-link `(:uri ,hl))))
5921 ;; We need to remove the invisible property here. Table narrowing
5922 ;; may have made some of this invisible.
5923 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5924 (remove-text-properties (match-beginning 0) (match-end 0)
5925 '(invisible nil))
5926 (if (match-end 3)
5927 (progn
5928 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5929 (org-rear-nonsticky-at (match-beginning 3))
5930 (add-text-properties (match-beginning 3) (match-end 3) vp)
5931 (org-rear-nonsticky-at (match-end 3))
5932 (add-text-properties (match-end 3) (match-end 0) ip)
5933 (org-rear-nonsticky-at (match-end 0)))
5934 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5935 (org-rear-nonsticky-at (match-beginning 1))
5936 (add-text-properties (match-beginning 1) (match-end 1) vp)
5937 (org-rear-nonsticky-at (match-end 1))
5938 (add-text-properties (match-end 1) (match-end 0) ip)
5939 (org-rear-nonsticky-at (match-end 0)))
5940 t)))
5942 (defun org-activate-dates (limit)
5943 "Run through the buffer and add overlays to dates."
5944 (if (and (re-search-forward org-tsr-regexp-both limit t)
5945 (not (equal (char-before (match-beginning 0)) 91)))
5946 (progn
5947 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5948 (add-text-properties (match-beginning 0) (match-end 0)
5949 (list 'mouse-face 'highlight
5950 'keymap org-mouse-map))
5951 (org-rear-nonsticky-at (match-end 0))
5952 (when org-display-custom-times
5953 (if (match-end 3)
5954 (org-display-custom-time (match-beginning 3) (match-end 3)))
5955 (org-display-custom-time (match-beginning 1) (match-end 1)))
5956 t)))
5958 (defvar org-target-link-regexp nil
5959 "Regular expression matching radio targets in plain text.")
5960 (make-variable-buffer-local 'org-target-link-regexp)
5961 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5962 "Regular expression matching a link target.")
5963 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5964 "Regular expression matching a radio target.")
5965 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5966 "Regular expression matching any target.")
5968 (defun org-activate-target-links (limit)
5969 "Run through the buffer and add overlays to target matches."
5970 (when org-target-link-regexp
5971 (let ((case-fold-search t))
5972 (if (re-search-forward org-target-link-regexp limit t)
5973 (progn
5974 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5975 (add-text-properties (match-beginning 0) (match-end 0)
5976 (list 'mouse-face 'highlight
5977 'keymap org-mouse-map
5978 'help-echo "Radio target link"
5979 'org-linked-text t))
5980 (org-rear-nonsticky-at (match-end 0))
5981 t)))))
5983 (defun org-update-radio-target-regexp ()
5984 "Find all radio targets in this file and update the regular expression."
5985 (interactive)
5986 (when (memq 'radio org-activate-links)
5987 (setq org-target-link-regexp
5988 (org-make-target-link-regexp (org-all-targets 'radio)))
5989 (org-restart-font-lock)))
5991 (defun org-hide-wide-columns (limit)
5992 (let (s e)
5993 (setq s (text-property-any (point) (or limit (point-max))
5994 'org-cwidth t))
5995 (when s
5996 (setq e (next-single-property-change s 'org-cwidth))
5997 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5998 (goto-char e)
5999 t)))
6001 (defvar org-latex-and-related-regexp nil
6002 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6003 (defvar org-match-substring-regexp)
6004 (defvar org-match-substring-with-braces-regexp)
6006 (defun org-compute-latex-and-related-regexp ()
6007 "Compute regular expression for LaTeX, entities and sub/superscript.
6008 Result depends on variable `org-highlight-latex-and-related'."
6009 (org-set-local
6010 'org-latex-and-related-regexp
6011 (let* ((re-sub
6012 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6013 ((eq org-use-sub-superscripts '{})
6014 (list org-match-substring-with-braces-regexp))
6015 (org-use-sub-superscripts (list org-match-substring-regexp))))
6016 (re-latex
6017 (when (memq 'latex org-highlight-latex-and-related)
6018 (let ((matchers (plist-get org-format-latex-options :matchers)))
6019 (delq nil
6020 (mapcar (lambda (x)
6021 (and (member (car x) matchers) (nth 1 x)))
6022 org-latex-regexps)))))
6023 (re-entities
6024 (when (memq 'entities org-highlight-latex-and-related)
6025 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6026 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6028 (defun org-do-latex-and-related (limit)
6029 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6030 LIMIT bounds the search for syntax to highlight. Stop at first
6031 highlighted object, if any. Return t if some highlighting was
6032 done, nil otherwise."
6033 (when (org-string-nw-p org-latex-and-related-regexp)
6034 (catch 'found
6035 (while (re-search-forward org-latex-and-related-regexp limit t)
6036 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6037 'face))
6038 '(org-code org-verbatim underline))
6039 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6040 '(?_ ?^))
6042 0)))
6043 (font-lock-prepend-text-property
6044 (+ offset (match-beginning 0)) (match-end 0)
6045 'face 'org-latex-and-related)
6046 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6047 '(font-lock-multiline t)))
6048 (throw 'found t)))
6049 nil)))
6051 (defun org-restart-font-lock ()
6052 "Restart `font-lock-mode', to force refontification."
6053 (when (and (boundp 'font-lock-mode) font-lock-mode)
6054 (font-lock-mode -1)
6055 (font-lock-mode 1)))
6057 (defun org-all-targets (&optional radio)
6058 "Return a list of all targets in this file.
6059 When optional argument RADIO is non-nil, only find radio
6060 targets."
6061 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6062 (save-excursion
6063 (goto-char (point-min))
6064 (while (re-search-forward re nil t)
6065 ;; Make sure point is really within the object.
6066 (backward-char)
6067 (let ((obj (org-element-context)))
6068 (when (memq (org-element-type obj) '(radio-target target))
6069 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6070 rtn)))
6072 (defun org-make-target-link-regexp (targets)
6073 "Make regular expression matching all strings in TARGETS.
6074 The regular expression finds the targets also if there is a line break
6075 between words."
6076 (and targets
6077 (concat
6078 "\\<\\("
6079 (mapconcat
6080 (lambda (x)
6081 (setq x (regexp-quote x))
6082 (while (string-match " +" x)
6083 (setq x (replace-match "\\s-+" t t x)))
6085 targets
6086 "\\|")
6087 "\\)\\>")))
6089 (defun org-activate-tags (limit)
6090 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6091 (progn
6092 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6093 (add-text-properties (match-beginning 1) (match-end 1)
6094 (list 'mouse-face 'highlight
6095 'keymap org-mouse-map))
6096 (org-rear-nonsticky-at (match-end 1))
6097 t)))
6099 (defun org-outline-level ()
6100 "Compute the outline level of the heading at point.
6101 If this is called at a normal headline, the level is the number of stars.
6102 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6103 (save-excursion
6104 (if (not (condition-case nil
6105 (org-back-to-heading t)
6106 (error nil)))
6108 (looking-at org-outline-regexp)
6109 (1- (- (match-end 0) (match-beginning 0))))))
6111 (defvar org-font-lock-keywords nil)
6113 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6114 "Regular expression matching a property line.")
6116 (defvar org-font-lock-hook nil
6117 "Functions to be called for special font lock stuff.")
6119 (defvar org-font-lock-set-keywords-hook nil
6120 "Functions that can manipulate `org-font-lock-extra-keywords'.
6121 This is called after `org-font-lock-extra-keywords' is defined, but before
6122 it is installed to be used by font lock. This can be useful if something
6123 needs to be inserted at a specific position in the font-lock sequence.")
6125 (defun org-font-lock-hook (limit)
6126 "Run `org-font-lock-hook' within LIMIT."
6127 (run-hook-with-args 'org-font-lock-hook limit))
6129 (defun org-set-font-lock-defaults ()
6130 "Set font lock defaults for the current buffer."
6131 (let* ((em org-fontify-emphasized-text)
6132 (lk org-activate-links)
6133 (org-font-lock-extra-keywords
6134 (list
6135 ;; Call the hook
6136 '(org-font-lock-hook)
6137 ;; Headlines
6138 `(,(if org-fontify-whole-heading-line
6139 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6140 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6141 (1 (org-get-level-face 1))
6142 (2 (org-get-level-face 2))
6143 (3 (org-get-level-face 3)))
6144 ;; Table lines
6145 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6146 (1 'org-table t))
6147 ;; Table internals
6148 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6149 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6150 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6151 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6152 ;; Drawers
6153 (list org-drawer-regexp '(0 'org-special-keyword t))
6154 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6155 ;; Properties
6156 (list org-property-re
6157 '(1 'org-special-keyword t)
6158 '(3 'org-property-value t))
6159 ;; Links
6160 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6161 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6162 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6163 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6164 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6165 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6166 (if (memq 'footnote lk) '(org-activate-footnote-links))
6167 ;; Targets.
6168 (list org-any-target-regexp '(0 'org-target t))
6169 ;; Diary sexps.
6170 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6171 ;; Macro
6172 '("{{{.+}}}" (0 'org-macro t))
6173 '(org-hide-wide-columns (0 nil append))
6174 ;; TODO keyword
6175 (list (format org-heading-keyword-regexp-format
6176 org-todo-regexp)
6177 '(2 (org-get-todo-face 2) t))
6178 ;; DONE
6179 (if org-fontify-done-headline
6180 (list (format org-heading-keyword-regexp-format
6181 (concat
6182 "\\(?:"
6183 (mapconcat 'regexp-quote org-done-keywords "\\|")
6184 "\\)"))
6185 '(2 'org-headline-done t))
6186 nil)
6187 ;; Priorities
6188 '(org-font-lock-add-priority-faces)
6189 ;; Tags
6190 '(org-font-lock-add-tag-faces)
6191 ;; Tags groups
6192 (if (and org-group-tags org-tag-groups-alist)
6193 (list (concat org-outline-regexp-bol ".+\\(:"
6194 (regexp-opt (mapcar 'car org-tag-groups-alist))
6195 ":\\).*$")
6196 '(1 'org-tag-group prepend)))
6197 ;; Special keywords
6198 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6199 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6200 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6201 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6202 ;; Emphasis
6203 (if em
6204 (if (featurep 'xemacs)
6205 '(org-do-emphasis-faces (0 nil append))
6206 '(org-do-emphasis-faces)))
6207 ;; Checkboxes
6208 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6209 1 'org-checkbox prepend)
6210 (if (cdr (assq 'checkbox org-list-automatic-rules))
6211 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6212 (0 (org-get-checkbox-statistics-face) t)))
6213 ;; Description list items
6214 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6215 1 'org-list-dt prepend)
6216 ;; ARCHIVEd headings
6217 (list (concat
6218 org-outline-regexp-bol
6219 "\\(.*:" org-archive-tag ":.*\\)")
6220 '(1 'org-archived prepend))
6221 ;; Specials
6222 '(org-do-latex-and-related)
6223 '(org-fontify-entities)
6224 '(org-raise-scripts)
6225 ;; Code
6226 '(org-activate-code (1 'org-code t))
6227 ;; COMMENT
6228 (list (format org-heading-keyword-regexp-format
6229 (concat "\\("
6230 org-comment-string "\\|" org-quote-string
6231 "\\)"))
6232 '(2 'org-special-keyword t))
6233 ;; Blocks and meta lines
6234 '(org-fontify-meta-lines-and-blocks))))
6235 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6236 (run-hooks 'org-font-lock-set-keywords-hook)
6237 ;; Now set the full font-lock-keywords
6238 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6239 (org-set-local 'font-lock-defaults
6240 '(org-font-lock-keywords t nil nil backward-paragraph))
6241 (kill-local-variable 'font-lock-keywords) nil))
6243 (defun org-toggle-pretty-entities ()
6244 "Toggle the composition display of entities as UTF8 characters."
6245 (interactive)
6246 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6247 (org-restart-font-lock)
6248 (if org-pretty-entities
6249 (message "Entities are now displayed as UTF8 characters")
6250 (save-restriction
6251 (widen)
6252 (org-decompose-region (point-min) (point-max))
6253 (message "Entities are now displayed as plain text"))))
6255 (defvar org-custom-properties-overlays nil
6256 "List of overlays used for custom properties.")
6257 (make-variable-buffer-local 'org-custom-properties-overlays)
6259 (defun org-toggle-custom-properties-visibility ()
6260 "Display or hide properties in `org-custom-properties'."
6261 (interactive)
6262 (if org-custom-properties-overlays
6263 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6264 (setq org-custom-properties-overlays nil))
6265 (unless (not org-custom-properties)
6266 (save-excursion
6267 (save-restriction
6268 (widen)
6269 (goto-char (point-min))
6270 (while (re-search-forward org-property-re nil t)
6271 (mapc (lambda(p)
6272 (when (equal p (substring (match-string 1) 1 -1))
6273 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6274 (overlay-put o 'invisible t)
6275 (overlay-put o 'org-custom-property t)
6276 (push o org-custom-properties-overlays))))
6277 org-custom-properties)))))))
6279 (defun org-fontify-entities (limit)
6280 "Find an entity to fontify."
6281 (let (ee)
6282 (when org-pretty-entities
6283 (catch 'match
6284 (while (re-search-forward
6285 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6286 limit t)
6287 (if (and (not (org-in-indented-comment-line))
6288 (setq ee (org-entity-get (match-string 1)))
6289 (= (length (nth 6 ee)) 1))
6290 (let*
6291 ((end (if (equal (match-string 2) "{}")
6292 (match-end 2)
6293 (match-end 1))))
6294 (add-text-properties
6295 (match-beginning 0) end
6296 (list 'font-lock-fontified t))
6297 (compose-region (match-beginning 0) end
6298 (nth 6 ee) nil)
6299 (backward-char 1)
6300 (throw 'match t))))
6301 nil))))
6303 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6304 "Fontify string S like in Org-mode."
6305 (with-temp-buffer
6306 (insert s)
6307 (let ((org-odd-levels-only odd-levels))
6308 (org-mode)
6309 (font-lock-fontify-buffer)
6310 (buffer-string))))
6312 (defvar org-m nil)
6313 (defvar org-l nil)
6314 (defvar org-f nil)
6315 (defun org-get-level-face (n)
6316 "Get the right face for match N in font-lock matching of headlines."
6317 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6318 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6319 (if org-cycle-level-faces
6320 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6321 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6322 (cond
6323 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6324 ((eq n 2) org-f)
6325 (t (if org-level-color-stars-only nil org-f))))
6328 (defun org-get-todo-face (kwd)
6329 "Get the right face for a TODO keyword KWD.
6330 If KWD is a number, get the corresponding match group."
6331 (if (numberp kwd) (setq kwd (match-string kwd)))
6332 (or (org-face-from-face-or-color
6333 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6334 (and (member kwd org-done-keywords) 'org-done)
6335 'org-todo))
6337 (defun org-face-from-face-or-color (context inherit face-or-color)
6338 "Create a face list that inherits INHERIT, but sets the foreground color.
6339 When FACE-OR-COLOR is not a string, just return it."
6340 (if (stringp face-or-color)
6341 (list :inherit inherit
6342 (cdr (assoc context org-faces-easy-properties))
6343 face-or-color)
6344 face-or-color))
6346 (defun org-font-lock-add-tag-faces (limit)
6347 "Add the special tag faces."
6348 (when (and org-tag-faces org-tags-special-faces-re)
6349 (while (re-search-forward org-tags-special-faces-re limit t)
6350 (add-text-properties (match-beginning 1) (match-end 1)
6351 (list 'face (org-get-tag-face 1)
6352 'font-lock-fontified t))
6353 (backward-char 1))))
6355 (defun org-font-lock-add-priority-faces (limit)
6356 "Add the special priority faces."
6357 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6358 (when (save-match-data (org-at-heading-p))
6359 (add-text-properties
6360 (match-beginning 0) (match-end 0)
6361 (list 'face (or (org-face-from-face-or-color
6362 'priority 'org-priority
6363 (cdr (assoc (char-after (match-beginning 1))
6364 org-priority-faces)))
6365 'org-priority)
6366 'font-lock-fontified t)))))
6368 (defun org-get-tag-face (kwd)
6369 "Get the right face for a TODO keyword KWD.
6370 If KWD is a number, get the corresponding match group."
6371 (if (numberp kwd) (setq kwd (match-string kwd)))
6372 (or (org-face-from-face-or-color
6373 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6374 'org-tag))
6376 (defun org-unfontify-region (beg end &optional maybe_loudly)
6377 "Remove fontification and activation overlays from links."
6378 (font-lock-default-unfontify-region beg end)
6379 (let* ((buffer-undo-list t)
6380 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6381 (inhibit-modification-hooks t)
6382 deactivate-mark buffer-file-name buffer-file-truename)
6383 (org-decompose-region beg end)
6384 (remove-text-properties beg end
6385 '(mouse-face t keymap t org-linked-text t
6386 invisible t intangible t
6387 org-no-flyspell t org-emphasis t))
6388 (org-remove-font-lock-display-properties beg end)))
6390 (defconst org-script-display '(((raise -0.3) (height 0.7))
6391 ((raise 0.3) (height 0.7))
6392 ((raise -0.5))
6393 ((raise 0.5)))
6394 "Display properties for showing superscripts and subscripts.")
6396 (defun org-remove-font-lock-display-properties (beg end)
6397 "Remove specific display properties that have been added by font lock.
6398 The will remove the raise properties that are used to show superscripts
6399 and subscripts."
6400 (let (next prop)
6401 (while (< beg end)
6402 (setq next (next-single-property-change beg 'display nil end)
6403 prop (get-text-property beg 'display))
6404 (if (member prop org-script-display)
6405 (put-text-property beg next 'display nil))
6406 (setq beg next))))
6408 (defun org-raise-scripts (limit)
6409 "Add raise properties to sub/superscripts."
6410 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6411 (if (re-search-forward
6412 (if (eq org-use-sub-superscripts t)
6413 org-match-substring-regexp
6414 org-match-substring-with-braces-regexp)
6415 limit t)
6416 (let* ((pos (point)) table-p comment-p
6417 (mpos (match-beginning 3))
6418 (emph-p (get-text-property mpos 'org-emphasis))
6419 (link-p (get-text-property mpos 'mouse-face))
6420 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6421 (goto-char (point-at-bol))
6422 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6423 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6424 (goto-char pos)
6425 ;; Handle a_b^c
6426 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6427 (if (or comment-p emph-p link-p keyw-p)
6429 (put-text-property (match-beginning 3) (match-end 0)
6430 'display
6431 (if (equal (char-after (match-beginning 2)) ?^)
6432 (nth (if table-p 3 1) org-script-display)
6433 (nth (if table-p 2 0) org-script-display)))
6434 (add-text-properties (match-beginning 2) (match-end 2)
6435 (list 'invisible t
6436 'org-dwidth t 'org-dwidth-n 1))
6437 (if (and (eq (char-after (match-beginning 3)) ?{)
6438 (eq (char-before (match-end 3)) ?}))
6439 (progn
6440 (add-text-properties
6441 (match-beginning 3) (1+ (match-beginning 3))
6442 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6443 (add-text-properties
6444 (1- (match-end 3)) (match-end 3)
6445 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6446 t)))))
6448 ;;;; Visibility cycling, including org-goto and indirect buffer
6450 ;;; Cycling
6452 (defvar org-cycle-global-status nil)
6453 (make-variable-buffer-local 'org-cycle-global-status)
6454 (put 'org-cycle-global-status 'org-state t)
6455 (defvar org-cycle-subtree-status nil)
6456 (make-variable-buffer-local 'org-cycle-subtree-status)
6457 (put 'org-cycle-subtree-status 'org-state t)
6459 (defvar org-inlinetask-min-level)
6461 ;;;###autoload
6462 (defun org-cycle (&optional arg)
6463 "TAB-action and visibility cycling for Org-mode.
6465 This is the command invoked in Org-mode by the TAB key. Its main purpose
6466 is outline visibility cycling, but it also invokes other actions
6467 in special contexts.
6469 - When this function is called with a prefix argument, rotate the entire
6470 buffer through 3 states (global cycling)
6471 1. OVERVIEW: Show only top-level headlines.
6472 2. CONTENTS: Show all headlines of all levels, but no body text.
6473 3. SHOW ALL: Show everything.
6474 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6475 determined by the variable `org-startup-folded', and by any VISIBILITY
6476 properties in the buffer.
6477 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6478 including any drawers.
6480 - When inside a table, re-align the table and move to the next field.
6482 - When point is at the beginning of a headline, rotate the subtree started
6483 by this line through 3 different states (local cycling)
6484 1. FOLDED: Only the main headline is shown.
6485 2. CHILDREN: The main headline and the direct children are shown.
6486 From this state, you can move to one of the children
6487 and zoom in further.
6488 3. SUBTREE: Show the entire subtree, including body text.
6489 If there is no subtree, switch directly from CHILDREN to FOLDED.
6491 - When point is at the beginning of an empty headline and the variable
6492 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6493 of the headline by demoting and promoting it to likely levels. This
6494 speeds up creation document structure by pressing TAB once or several
6495 times right after creating a new headline.
6497 - When there is a numeric prefix, go up to a heading with level ARG, do
6498 a `show-subtree' and return to the previous cursor position. If ARG
6499 is negative, go up that many levels.
6501 - When point is not at the beginning of a headline, execute the global
6502 binding for TAB, which is re-indenting the line. See the option
6503 `org-cycle-emulate-tab' for details.
6505 - Special case: if point is at the beginning of the buffer and there is
6506 no headline in line 1, this function will act as if called with prefix arg
6507 (C-u TAB, same as S-TAB) also when called without prefix arg.
6508 But only if also the variable `org-cycle-global-at-bob' is t."
6509 (interactive "P")
6510 (org-load-modules-maybe)
6511 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6512 (and org-cycle-level-after-item/entry-creation
6513 (or (org-cycle-level)
6514 (org-cycle-item-indentation))))
6515 (let* (message-log-max ; Don't populate the *Messages* buffer
6516 (limit-level
6517 (or org-cycle-max-level
6518 (and (boundp 'org-inlinetask-min-level)
6519 org-inlinetask-min-level
6520 (1- org-inlinetask-min-level))))
6521 (nstars (and limit-level
6522 (if org-odd-levels-only
6523 (and limit-level (1- (* limit-level 2)))
6524 limit-level)))
6525 (org-outline-regexp
6526 (if (not (derived-mode-p 'org-mode))
6527 outline-regexp
6528 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6529 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6530 (not (looking-at org-outline-regexp))))
6531 (org-cycle-hook
6532 (if bob-special
6533 (delq 'org-optimize-window-after-visibility-change
6534 (copy-sequence org-cycle-hook))
6535 org-cycle-hook))
6536 (pos (point)))
6538 (if (or bob-special (equal arg '(4)))
6539 ;; special case: use global cycling
6540 (setq arg t))
6542 (cond
6544 ((equal arg '(16))
6545 (setq last-command 'dummy)
6546 (org-set-startup-visibility)
6547 (message "Startup visibility, plus VISIBILITY properties"))
6549 ((equal arg '(64))
6550 (show-all)
6551 (message "Entire buffer visible, including drawers"))
6553 ;; Table: enter it or move to the next field.
6554 ((org-at-table-p 'any)
6555 (if (org-at-table.el-p)
6556 (message "Use C-c ' to edit table.el tables")
6557 (if arg (org-table-edit-field t)
6558 (org-table-justify-field-maybe)
6559 (call-interactively 'org-table-next-field))))
6561 ((run-hook-with-args-until-success
6562 'org-tab-after-check-for-table-hook))
6564 ;; Global cycling: delegate to `org-cycle-internal-global'.
6565 ((eq arg t) (org-cycle-internal-global))
6567 ;; Drawers: delegate to `org-flag-drawer'.
6568 ((and org-drawers org-drawer-regexp
6569 (save-excursion
6570 (beginning-of-line 1)
6571 (looking-at org-drawer-regexp)))
6572 (org-flag-drawer ; toggle block visibility
6573 (not (get-char-property (match-end 0) 'invisible))))
6575 ;; Show-subtree, ARG levels up from here.
6576 ((integerp arg)
6577 (save-excursion
6578 (org-back-to-heading)
6579 (outline-up-heading (if (< arg 0) (- arg)
6580 (- (funcall outline-level) arg)))
6581 (org-show-subtree)))
6583 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6584 ((and (featurep 'org-inlinetask)
6585 (org-inlinetask-at-task-p)
6586 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6587 (org-inlinetask-toggle-visibility))
6589 ((org-try-cdlatex-tab))
6591 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6592 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6593 (save-excursion (beginning-of-line 1)
6594 (looking-at org-outline-regexp)))
6595 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6596 (org-cycle-internal-local))
6598 ;; From there: TAB emulation and template completion.
6599 (buffer-read-only (org-back-to-heading))
6601 ((run-hook-with-args-until-success
6602 'org-tab-after-check-for-cycling-hook))
6604 ((org-try-structure-completion))
6606 ((run-hook-with-args-until-success
6607 'org-tab-before-tab-emulation-hook))
6609 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6610 (or (not (bolp))
6611 (not (looking-at org-outline-regexp))))
6612 (call-interactively (global-key-binding "\t")))
6614 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6615 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6616 (or (and (eq org-cycle-emulate-tab 'white)
6617 (= (match-end 0) (point-at-eol)))
6618 (and (eq org-cycle-emulate-tab 'whitestart)
6619 (>= (match-end 0) pos))))
6621 (eq org-cycle-emulate-tab t))
6622 (call-interactively (global-key-binding "\t")))
6624 (t (save-excursion
6625 (org-back-to-heading)
6626 (org-cycle)))))))
6628 (defun org-cycle-internal-global ()
6629 "Do the global cycling action."
6630 ;; Hack to avoid display of messages for .org attachments in Gnus
6631 (let (message-log-max ; Don't populate the *Messages* buffer
6632 (ga (string-match "\\*fontification" (buffer-name))))
6633 (cond
6634 ((and (eq last-command this-command)
6635 (eq org-cycle-global-status 'overview))
6636 ;; We just created the overview - now do table of contents
6637 ;; This can be slow in very large buffers, so indicate action
6638 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6639 (unless ga (message "CONTENTS..."))
6640 (org-content)
6641 (unless ga (message "CONTENTS...done"))
6642 (setq org-cycle-global-status 'contents)
6643 (run-hook-with-args 'org-cycle-hook 'contents))
6645 ((and (eq last-command this-command)
6646 (eq org-cycle-global-status 'contents))
6647 ;; We just showed the table of contents - now show everything
6648 (run-hook-with-args 'org-pre-cycle-hook 'all)
6649 (show-all)
6650 (unless ga (message "SHOW ALL"))
6651 (setq org-cycle-global-status 'all)
6652 (run-hook-with-args 'org-cycle-hook 'all))
6655 ;; Default action: go to overview
6656 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6657 (org-overview)
6658 (unless ga (message "OVERVIEW"))
6659 (setq org-cycle-global-status 'overview)
6660 (run-hook-with-args 'org-cycle-hook 'overview)))))
6662 (defun org-cycle-internal-local ()
6663 "Do the local cycling action."
6664 (let (message-log-max ; Don't populate the *Messages* buffer
6665 (goal-column 0) eoh eol eos has-children children-skipped struct)
6666 ;; First, determine end of headline (EOH), end of subtree or item
6667 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6668 (save-excursion
6669 (if (org-at-item-p)
6670 (progn
6671 (beginning-of-line)
6672 (setq struct (org-list-struct))
6673 (setq eoh (point-at-eol))
6674 (setq eos (org-list-get-item-end-before-blank (point) struct))
6675 (setq has-children (org-list-has-child-p (point) struct)))
6676 (org-back-to-heading)
6677 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6678 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6679 (setq has-children
6680 (or (save-excursion
6681 (let ((level (funcall outline-level)))
6682 (outline-next-heading)
6683 (and (org-at-heading-p t)
6684 (> (funcall outline-level) level))))
6685 (save-excursion
6686 (org-list-search-forward (org-item-beginning-re) eos t)))))
6687 ;; Determine end invisible part of buffer (EOL)
6688 (beginning-of-line 2)
6689 ;; XEmacs doesn't have `next-single-char-property-change'
6690 (if (featurep 'xemacs)
6691 (while (and (not (eobp)) ;; this is like `next-line'
6692 (get-char-property (1- (point)) 'invisible))
6693 (beginning-of-line 2))
6694 (while (and (not (eobp)) ;; this is like `next-line'
6695 (get-char-property (1- (point)) 'invisible))
6696 (goto-char (next-single-char-property-change (point) 'invisible))
6697 (and (eolp) (beginning-of-line 2))))
6698 (setq eol (point)))
6699 ;; Find out what to do next and set `this-command'
6700 (cond
6701 ((= eos eoh)
6702 ;; Nothing is hidden behind this heading
6703 (unless (org-before-first-heading-p)
6704 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6705 (message "EMPTY ENTRY")
6706 (setq org-cycle-subtree-status nil)
6707 (save-excursion
6708 (goto-char eos)
6709 (outline-next-heading)
6710 (if (outline-invisible-p) (org-flag-heading nil))))
6711 ((and (or (>= eol eos)
6712 (not (string-match "\\S-" (buffer-substring eol eos))))
6713 (or has-children
6714 (not (setq children-skipped
6715 org-cycle-skip-children-state-if-no-children))))
6716 ;; Entire subtree is hidden in one line: children view
6717 (unless (org-before-first-heading-p)
6718 (run-hook-with-args 'org-pre-cycle-hook 'children))
6719 (if (org-at-item-p)
6720 (org-list-set-item-visibility (point-at-bol) struct 'children)
6721 (org-show-entry)
6722 (org-with-limited-levels (show-children))
6723 ;; FIXME: This slows down the func way too much.
6724 ;; How keep drawers hidden in subtree anyway?
6725 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6726 ;; (org-cycle-hide-drawers 'subtree))
6728 ;; Fold every list in subtree to top-level items.
6729 (when (eq org-cycle-include-plain-lists 'integrate)
6730 (save-excursion
6731 (org-back-to-heading)
6732 (while (org-list-search-forward (org-item-beginning-re) eos t)
6733 (beginning-of-line 1)
6734 (let* ((struct (org-list-struct))
6735 (prevs (org-list-prevs-alist struct))
6736 (end (org-list-get-bottom-point struct)))
6737 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6738 (org-list-get-all-items (point) struct prevs))
6739 (goto-char (if (< end eos) end eos)))))))
6740 (message "CHILDREN")
6741 (save-excursion
6742 (goto-char eos)
6743 (outline-next-heading)
6744 (if (outline-invisible-p) (org-flag-heading nil)))
6745 (setq org-cycle-subtree-status 'children)
6746 (unless (org-before-first-heading-p)
6747 (run-hook-with-args 'org-cycle-hook 'children)))
6748 ((or children-skipped
6749 (and (eq last-command this-command)
6750 (eq org-cycle-subtree-status 'children)))
6751 ;; We just showed the children, or no children are there,
6752 ;; now show everything.
6753 (unless (org-before-first-heading-p)
6754 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6755 (outline-flag-region eoh eos nil)
6756 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6757 (setq org-cycle-subtree-status 'subtree)
6758 (unless (org-before-first-heading-p)
6759 (run-hook-with-args 'org-cycle-hook 'subtree)))
6761 ;; Default action: hide the subtree.
6762 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6763 (outline-flag-region eoh eos t)
6764 (message "FOLDED")
6765 (setq org-cycle-subtree-status 'folded)
6766 (unless (org-before-first-heading-p)
6767 (run-hook-with-args 'org-cycle-hook 'folded))))))
6769 ;;;###autoload
6770 (defun org-global-cycle (&optional arg)
6771 "Cycle the global visibility. For details see `org-cycle'.
6772 With \\[universal-argument] prefix arg, switch to startup visibility.
6773 With a numeric prefix, show all headlines up to that level."
6774 (interactive "P")
6775 (let ((org-cycle-include-plain-lists
6776 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6777 (cond
6778 ((integerp arg)
6779 (show-all)
6780 (hide-sublevels arg)
6781 (setq org-cycle-global-status 'contents))
6782 ((equal arg '(4))
6783 (org-set-startup-visibility)
6784 (message "Startup visibility, plus VISIBILITY properties."))
6786 (org-cycle '(4))))))
6788 (defun org-set-startup-visibility ()
6789 "Set the visibility required by startup options and properties."
6790 (cond
6791 ((eq org-startup-folded t)
6792 (org-cycle '(4)))
6793 ((eq org-startup-folded 'content)
6794 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6795 (org-cycle '(4)) (org-cycle '(4)))))
6796 (unless (eq org-startup-folded 'showeverything)
6797 (if org-hide-block-startup (org-hide-block-all))
6798 (org-set-visibility-according-to-property 'no-cleanup)
6799 (org-cycle-hide-archived-subtrees 'all)
6800 (org-cycle-hide-drawers 'all)
6801 (org-cycle-show-empty-lines t)))
6803 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6804 "Switch subtree visibilities according to :VISIBILITY: property."
6805 (interactive)
6806 (let (org-show-entry-below state)
6807 (save-excursion
6808 (goto-char (point-min))
6809 (while (re-search-forward
6810 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6811 nil t)
6812 (setq state (match-string 1))
6813 (save-excursion
6814 (org-back-to-heading t)
6815 (hide-subtree)
6816 (org-reveal)
6817 (cond
6818 ((equal state '("fold" "folded"))
6819 (hide-subtree))
6820 ((equal state "children")
6821 (org-show-hidden-entry)
6822 (show-children))
6823 ((equal state "content")
6824 (save-excursion
6825 (save-restriction
6826 (org-narrow-to-subtree)
6827 (org-content))))
6828 ((member state '("all" "showall"))
6829 (show-subtree)))))
6830 (unless no-cleanup
6831 (org-cycle-hide-archived-subtrees 'all)
6832 (org-cycle-hide-drawers 'all)
6833 (org-cycle-show-empty-lines 'all)))))
6835 ;; This function uses outline-regexp instead of the more fundamental
6836 ;; org-outline-regexp so that org-cycle-global works outside of Org
6837 ;; buffers, where outline-regexp is needed.
6838 (defun org-overview ()
6839 "Switch to overview mode, showing only top-level headlines.
6840 Really, this shows all headlines with level equal or greater than the level
6841 of the first headline in the buffer. This is important, because if the
6842 first headline is not level one, then (hide-sublevels 1) gives confusing
6843 results."
6844 (interactive)
6845 (let ((l (org-current-line))
6846 (level (save-excursion
6847 (goto-char (point-min))
6848 (if (re-search-forward (concat "^" outline-regexp) nil t)
6849 (progn
6850 (goto-char (match-beginning 0))
6851 (funcall outline-level))))))
6852 (and level (hide-sublevels level))
6853 (recenter '(4))
6854 (org-goto-line l)))
6856 (defun org-content (&optional arg)
6857 "Show all headlines in the buffer, like a table of contents.
6858 With numerical argument N, show content up to level N."
6859 (interactive "P")
6860 (save-excursion
6861 ;; Visit all headings and show their offspring
6862 (and (integerp arg) (org-overview))
6863 (goto-char (point-max))
6864 (catch 'exit
6865 (while (and (progn (condition-case nil
6866 (outline-previous-visible-heading 1)
6867 (error (goto-char (point-min))))
6869 (looking-at org-outline-regexp))
6870 (if (integerp arg)
6871 (show-children (1- arg))
6872 (show-branches))
6873 (if (bobp) (throw 'exit nil))))))
6876 (defun org-optimize-window-after-visibility-change (state)
6877 "Adjust the window after a change in outline visibility.
6878 This function is the default value of the hook `org-cycle-hook'."
6879 (when (get-buffer-window (current-buffer))
6880 (cond
6881 ((eq state 'content) nil)
6882 ((eq state 'all) nil)
6883 ((eq state 'folded) nil)
6884 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6885 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6887 (defun org-remove-empty-overlays-at (pos)
6888 "Remove outline overlays that do not contain non-white stuff."
6889 (mapc
6890 (lambda (o)
6891 (and (eq 'outline (overlay-get o 'invisible))
6892 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6893 (overlay-end o))))
6894 (delete-overlay o)))
6895 (overlays-at pos)))
6897 (defun org-clean-visibility-after-subtree-move ()
6898 "Fix visibility issues after moving a subtree."
6899 ;; First, find a reasonable region to look at:
6900 ;; Start two siblings above, end three below
6901 (let* ((beg (save-excursion
6902 (and (org-get-last-sibling)
6903 (org-get-last-sibling))
6904 (point)))
6905 (end (save-excursion
6906 (and (org-get-next-sibling)
6907 (org-get-next-sibling)
6908 (org-get-next-sibling))
6909 (if (org-at-heading-p)
6910 (point-at-eol)
6911 (point))))
6912 (level (looking-at "\\*+"))
6913 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6914 (save-excursion
6915 (save-restriction
6916 (narrow-to-region beg end)
6917 (when re
6918 ;; Properly fold already folded siblings
6919 (goto-char (point-min))
6920 (while (re-search-forward re nil t)
6921 (if (and (not (outline-invisible-p))
6922 (save-excursion
6923 (goto-char (point-at-eol)) (outline-invisible-p)))
6924 (hide-entry))))
6925 (org-cycle-show-empty-lines 'overview)
6926 (org-cycle-hide-drawers 'overview)))))
6928 (defun org-cycle-show-empty-lines (state)
6929 "Show empty lines above all visible headlines.
6930 The region to be covered depends on STATE when called through
6931 `org-cycle-hook'. Lisp program can use t for STATE to get the
6932 entire buffer covered. Note that an empty line is only shown if there
6933 are at least `org-cycle-separator-lines' empty lines before the headline."
6934 (when (not (= org-cycle-separator-lines 0))
6935 (save-excursion
6936 (let* ((n (abs org-cycle-separator-lines))
6937 (re (cond
6938 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6939 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6940 (t (let ((ns (number-to-string (- n 2))))
6941 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6942 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6943 beg end b e)
6944 (cond
6945 ((memq state '(overview contents t))
6946 (setq beg (point-min) end (point-max)))
6947 ((memq state '(children folded))
6948 (setq beg (point) end (progn (org-end-of-subtree t t)
6949 (beginning-of-line 2)
6950 (point)))))
6951 (when beg
6952 (goto-char beg)
6953 (while (re-search-forward re end t)
6954 (unless (get-char-property (match-end 1) 'invisible)
6955 (setq e (match-end 1))
6956 (if (< org-cycle-separator-lines 0)
6957 (setq b (save-excursion
6958 (goto-char (match-beginning 0))
6959 (org-back-over-empty-lines)
6960 (if (save-excursion
6961 (goto-char (max (point-min) (1- (point))))
6962 (org-at-heading-p))
6963 (1- (point))
6964 (point))))
6965 (setq b (match-beginning 1)))
6966 (outline-flag-region b e nil)))))))
6967 ;; Never hide empty lines at the end of the file.
6968 (save-excursion
6969 (goto-char (point-max))
6970 (outline-previous-heading)
6971 (outline-end-of-heading)
6972 (if (and (looking-at "[ \t\n]+")
6973 (= (match-end 0) (point-max)))
6974 (outline-flag-region (point) (match-end 0) nil))))
6976 (defun org-show-empty-lines-in-parent ()
6977 "Move to the parent and re-show empty lines before visible headlines."
6978 (save-excursion
6979 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6980 (org-cycle-show-empty-lines context))))
6982 (defun org-files-list ()
6983 "Return `org-agenda-files' list, plus all open org-mode files.
6984 This is useful for operations that need to scan all of a user's
6985 open and agenda-wise Org files."
6986 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6987 (dolist (buf (buffer-list))
6988 (with-current-buffer buf
6989 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6990 (let ((file (expand-file-name (buffer-file-name))))
6991 (unless (member file files)
6992 (push file files))))))
6993 files))
6995 (defsubst org-entry-beginning-position ()
6996 "Return the beginning position of the current entry."
6997 (save-excursion (outline-back-to-heading t) (point)))
6999 (defsubst org-entry-end-position ()
7000 "Return the end position of the current entry."
7001 (save-excursion (outline-next-heading) (point)))
7003 (defun org-cycle-hide-drawers (state)
7004 "Re-hide all drawers after a visibility state change."
7005 (when (and (derived-mode-p 'org-mode)
7006 (not (memq state '(overview folded contents))))
7007 (save-excursion
7008 (let* ((globalp (memq state '(contents all)))
7009 (beg (if globalp (point-min) (point)))
7010 (end (if globalp (point-max)
7011 (if (eq state 'children)
7012 (save-excursion (outline-next-heading) (point))
7013 (org-end-of-subtree t)))))
7014 (goto-char beg)
7015 (while (re-search-forward org-drawer-regexp end t)
7016 (org-flag-drawer t))))))
7018 (defun org-cycle-hide-inline-tasks (state)
7019 "Re-hide inline task when switching to 'contents visibility state."
7020 (when (and (eq state 'contents)
7021 (boundp 'org-inlinetask-min-level)
7022 org-inlinetask-min-level)
7023 (hide-sublevels (1- org-inlinetask-min-level))))
7025 (defun org-flag-drawer (flag)
7026 "When FLAG is non-nil, hide the drawer we are within.
7027 Otherwise make it visible."
7028 (save-excursion
7029 (beginning-of-line 1)
7030 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7031 (let ((b (match-end 0)))
7032 (if (re-search-forward
7033 "^[ \t]*:END:"
7034 (save-excursion (outline-next-heading) (point)) t)
7035 (outline-flag-region b (point-at-eol) flag)
7036 (error ":END: line missing at position %s" b))))))
7038 (defun org-subtree-end-visible-p ()
7039 "Is the end of the current subtree visible?"
7040 (pos-visible-in-window-p
7041 (save-excursion (org-end-of-subtree t) (point))))
7043 (defun org-first-headline-recenter (&optional N)
7044 "Move cursor to the first headline and recenter the headline.
7045 Optional argument N means put the headline into the Nth line of the window."
7046 (goto-char (point-min))
7047 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7048 (beginning-of-line)
7049 (recenter (prefix-numeric-value N))))
7051 ;;; Saving and restoring visibility
7053 (defun org-outline-overlay-data (&optional use-markers)
7054 "Return a list of the locations of all outline overlays.
7055 These are overlays with the `invisible' property value `outline'.
7056 The return value is a list of cons cells, with start and stop
7057 positions for each overlay.
7058 If USE-MARKERS is set, return the positions as markers."
7059 (let (beg end)
7060 (save-excursion
7061 (save-restriction
7062 (widen)
7063 (delq nil
7064 (mapcar (lambda (o)
7065 (when (eq (overlay-get o 'invisible) 'outline)
7066 (setq beg (overlay-start o)
7067 end (overlay-end o))
7068 (and beg end (> end beg)
7069 (if use-markers
7070 (cons (move-marker (make-marker) beg)
7071 (move-marker (make-marker) end))
7072 (cons beg end)))))
7073 (overlays-in (point-min) (point-max))))))))
7075 (defun org-set-outline-overlay-data (data)
7076 "Create visibility overlays for all positions in DATA.
7077 DATA should have been made by `org-outline-overlay-data'."
7078 (let (o)
7079 (save-excursion
7080 (save-restriction
7081 (widen)
7082 (show-all)
7083 (mapc (lambda (c)
7084 (outline-flag-region (car c) (cdr c) t))
7085 data)))))
7087 ;;; Folding of blocks
7089 (defvar org-hide-block-overlays nil
7090 "Overlays hiding blocks.")
7091 (make-variable-buffer-local 'org-hide-block-overlays)
7093 (defun org-block-map (function &optional start end)
7094 "Call FUNCTION at the head of all source blocks in the current buffer.
7095 Optional arguments START and END can be used to limit the range."
7096 (let ((start (or start (point-min)))
7097 (end (or end (point-max))))
7098 (save-excursion
7099 (goto-char start)
7100 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7101 (save-excursion
7102 (save-match-data
7103 (goto-char (match-beginning 0))
7104 (funcall function)))))))
7106 (defun org-hide-block-toggle-all ()
7107 "Toggle the visibility of all blocks in the current buffer."
7108 (org-block-map #'org-hide-block-toggle))
7110 (defun org-hide-block-all ()
7111 "Fold all blocks in the current buffer."
7112 (interactive)
7113 (org-show-block-all)
7114 (org-block-map #'org-hide-block-toggle-maybe))
7116 (defun org-show-block-all ()
7117 "Unfold all blocks in the current buffer."
7118 (interactive)
7119 (mapc 'delete-overlay org-hide-block-overlays)
7120 (setq org-hide-block-overlays nil))
7122 (defun org-hide-block-toggle-maybe ()
7123 "Toggle visibility of block at point."
7124 (interactive)
7125 (let ((case-fold-search t))
7126 (if (save-excursion
7127 (beginning-of-line 1)
7128 (looking-at org-block-regexp))
7129 (progn (org-hide-block-toggle)
7130 t) ;; to signal that we took action
7131 nil))) ;; to signal that we did not
7133 (defun org-hide-block-toggle (&optional force)
7134 "Toggle the visibility of the current block."
7135 (interactive)
7136 (save-excursion
7137 (beginning-of-line)
7138 (if (re-search-forward org-block-regexp nil t)
7139 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7140 (end (match-end 0)) ;; end of entire body
7142 (if (memq t (mapcar (lambda (overlay)
7143 (eq (overlay-get overlay 'invisible)
7144 'org-hide-block))
7145 (overlays-at start)))
7146 (if (or (not force) (eq force 'off))
7147 (mapc (lambda (ov)
7148 (when (member ov org-hide-block-overlays)
7149 (setq org-hide-block-overlays
7150 (delq ov org-hide-block-overlays)))
7151 (when (eq (overlay-get ov 'invisible)
7152 'org-hide-block)
7153 (delete-overlay ov)))
7154 (overlays-at start)))
7155 (setq ov (make-overlay start end))
7156 (overlay-put ov 'invisible 'org-hide-block)
7157 ;; make the block accessible to isearch
7158 (overlay-put
7159 ov 'isearch-open-invisible
7160 (lambda (ov)
7161 (when (member ov org-hide-block-overlays)
7162 (setq org-hide-block-overlays
7163 (delq ov org-hide-block-overlays)))
7164 (when (eq (overlay-get ov 'invisible)
7165 'org-hide-block)
7166 (delete-overlay ov))))
7167 (push ov org-hide-block-overlays)))
7168 (error "Not looking at a source block"))))
7170 ;; org-tab-after-check-for-cycling-hook
7171 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7172 ;; Remove overlays when changing major mode
7173 (add-hook 'org-mode-hook
7174 (lambda () (org-add-hook 'change-major-mode-hook
7175 'org-show-block-all 'append 'local)))
7177 ;;; Org-goto
7179 (defvar org-goto-window-configuration nil)
7180 (defvar org-goto-marker nil)
7181 (defvar org-goto-map)
7182 (defun org-goto-map ()
7183 "Set the keymap `org-goto'."
7184 (setq org-goto-map
7185 (let ((map (make-sparse-keymap)))
7186 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7187 mouse-drag-region universal-argument org-occur))
7188 cmd)
7189 (while (setq cmd (pop cmds))
7190 (substitute-key-definition cmd cmd map global-map)))
7191 (suppress-keymap map)
7192 (org-defkey map "\C-m" 'org-goto-ret)
7193 (org-defkey map [(return)] 'org-goto-ret)
7194 (org-defkey map [(left)] 'org-goto-left)
7195 (org-defkey map [(right)] 'org-goto-right)
7196 (org-defkey map [(control ?g)] 'org-goto-quit)
7197 (org-defkey map "\C-i" 'org-cycle)
7198 (org-defkey map [(tab)] 'org-cycle)
7199 (org-defkey map [(down)] 'outline-next-visible-heading)
7200 (org-defkey map [(up)] 'outline-previous-visible-heading)
7201 (if org-goto-auto-isearch
7202 (if (fboundp 'define-key-after)
7203 (define-key-after map [t] 'org-goto-local-auto-isearch)
7204 nil)
7205 (org-defkey map "q" 'org-goto-quit)
7206 (org-defkey map "n" 'outline-next-visible-heading)
7207 (org-defkey map "p" 'outline-previous-visible-heading)
7208 (org-defkey map "f" 'outline-forward-same-level)
7209 (org-defkey map "b" 'outline-backward-same-level)
7210 (org-defkey map "u" 'outline-up-heading))
7211 (org-defkey map "/" 'org-occur)
7212 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7213 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7214 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7215 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7216 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7217 map)))
7219 (defconst org-goto-help
7220 "Browse buffer copy, to find location or copy text.%s
7221 RET=jump to location C-g=quit and return to previous location
7222 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7224 (defvar org-goto-start-pos) ; dynamically scoped parameter
7226 (defun org-goto (&optional alternative-interface)
7227 "Look up a different location in the current file, keeping current visibility.
7229 When you want look-up or go to a different location in a
7230 document, the fastest way is often to fold the entire buffer and
7231 then dive into the tree. This method has the disadvantage, that
7232 the previous location will be folded, which may not be what you
7233 want.
7235 This command works around this by showing a copy of the current
7236 buffer in an indirect buffer, in overview mode. You can dive
7237 into the tree in that copy, use org-occur and incremental search
7238 to find a location. When pressing RET or `Q', the command
7239 returns to the original buffer in which the visibility is still
7240 unchanged. After RET it will also jump to the location selected
7241 in the indirect buffer and expose the headline hierarchy above.
7243 With a prefix argument, use the alternative interface: e.g. if
7244 `org-goto-interface' is 'outline use 'outline-path-completion."
7245 (interactive "P")
7246 (org-goto-map)
7247 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7248 (org-refile-use-outline-path t)
7249 (org-refile-target-verify-function nil)
7250 (interface
7251 (if (not alternative-interface)
7252 org-goto-interface
7253 (if (eq org-goto-interface 'outline)
7254 'outline-path-completion
7255 'outline)))
7256 (org-goto-start-pos (point))
7257 (selected-point
7258 (if (eq interface 'outline)
7259 (car (org-get-location (current-buffer) org-goto-help))
7260 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7261 (org-refile-check-position pa)
7262 (nth 3 pa)))))
7263 (if selected-point
7264 (progn
7265 (org-mark-ring-push org-goto-start-pos)
7266 (goto-char selected-point)
7267 (if (or (outline-invisible-p) (org-invisible-p2))
7268 (org-show-context 'org-goto)))
7269 (message "Quit"))))
7271 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7272 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7273 (defvar org-goto-local-auto-isearch-map) ; defined below
7275 (defun org-get-location (buf help)
7276 "Let the user select a location in the Org-mode buffer BUF.
7277 This function uses a recursive edit. It returns the selected position
7278 or nil."
7279 (org-no-popups
7280 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7281 (isearch-hide-immediately nil)
7282 (isearch-search-fun-function
7283 (lambda () 'org-goto-local-search-headings))
7284 (org-goto-selected-point org-goto-exit-command))
7285 (save-excursion
7286 (save-window-excursion
7287 (delete-other-windows)
7288 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7289 (org-pop-to-buffer-same-window
7290 (condition-case nil
7291 (make-indirect-buffer (current-buffer) "*org-goto*")
7292 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7293 (with-output-to-temp-buffer "*Org Help*"
7294 (princ (format help (if org-goto-auto-isearch
7295 " Just type for auto-isearch."
7296 " n/p/f/b/u to navigate, q to quit."))))
7297 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7298 (setq buffer-read-only nil)
7299 (let ((org-startup-truncated t)
7300 (org-startup-folded nil)
7301 (org-startup-align-all-tables nil))
7302 (org-mode)
7303 (org-overview))
7304 (setq buffer-read-only t)
7305 (if (and (boundp 'org-goto-start-pos)
7306 (integer-or-marker-p org-goto-start-pos))
7307 (let ((org-show-hierarchy-above t)
7308 (org-show-siblings t)
7309 (org-show-following-heading t))
7310 (goto-char org-goto-start-pos)
7311 (and (outline-invisible-p) (org-show-context)))
7312 (goto-char (point-min)))
7313 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7314 (message "Select location and press RET")
7315 (use-local-map org-goto-map)
7316 (recursive-edit)))
7317 (kill-buffer "*org-goto*")
7318 (cons org-goto-selected-point org-goto-exit-command))))
7320 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7321 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7322 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7323 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7325 (defun org-goto-local-search-headings (string bound noerror)
7326 "Search and make sure that any matches are in headlines."
7327 (catch 'return
7328 (while (if isearch-forward
7329 (search-forward string bound noerror)
7330 (search-backward string bound noerror))
7331 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7332 (and (member :headline context)
7333 (not (member :tags context))))
7334 (throw 'return (point))))))
7336 (defun org-goto-local-auto-isearch ()
7337 "Start isearch."
7338 (interactive)
7339 (goto-char (point-min))
7340 (let ((keys (this-command-keys)))
7341 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7342 (isearch-mode t)
7343 (isearch-process-search-char (string-to-char keys)))))
7345 (defun org-goto-ret (&optional arg)
7346 "Finish `org-goto' by going to the new location."
7347 (interactive "P")
7348 (setq org-goto-selected-point (point)
7349 org-goto-exit-command 'return)
7350 (throw 'exit nil))
7352 (defun org-goto-left ()
7353 "Finish `org-goto' by going to the new location."
7354 (interactive)
7355 (if (org-at-heading-p)
7356 (progn
7357 (beginning-of-line 1)
7358 (setq org-goto-selected-point (point)
7359 org-goto-exit-command 'left)
7360 (throw 'exit nil))
7361 (error "Not on a heading")))
7363 (defun org-goto-right ()
7364 "Finish `org-goto' by going to the new location."
7365 (interactive)
7366 (if (org-at-heading-p)
7367 (progn
7368 (setq org-goto-selected-point (point)
7369 org-goto-exit-command 'right)
7370 (throw 'exit nil))
7371 (error "Not on a heading")))
7373 (defun org-goto-quit ()
7374 "Finish `org-goto' without cursor motion."
7375 (interactive)
7376 (setq org-goto-selected-point nil)
7377 (setq org-goto-exit-command 'quit)
7378 (throw 'exit nil))
7380 ;;; Indirect buffer display of subtrees
7382 (defvar org-indirect-dedicated-frame nil
7383 "This is the frame being used for indirect tree display.")
7384 (defvar org-last-indirect-buffer nil)
7386 (defun org-tree-to-indirect-buffer (&optional arg)
7387 "Create indirect buffer and narrow it to current subtree.
7388 With a numerical prefix ARG, go up to this level and then take that tree.
7389 If ARG is negative, go up that many levels.
7391 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7392 indirect buffer previously made with this command, to avoid proliferation of
7393 indirect buffers. However, when you call the command with a \
7394 \\[universal-argument] prefix, or
7395 when `org-indirect-buffer-display' is `new-frame', the last buffer
7396 is kept so that you can work with several indirect buffers at the same time.
7397 If `org-indirect-buffer-display' is `dedicated-frame', the \
7398 \\[universal-argument] prefix also
7399 requests that a new frame be made for the new buffer, so that the dedicated
7400 frame is not changed."
7401 (interactive "P")
7402 (let ((cbuf (current-buffer))
7403 (cwin (selected-window))
7404 (pos (point))
7405 beg end level heading ibuf)
7406 (save-excursion
7407 (org-back-to-heading t)
7408 (when (numberp arg)
7409 (setq level (org-outline-level))
7410 (if (< arg 0) (setq arg (+ level arg)))
7411 (while (> (setq level (org-outline-level)) arg)
7412 (org-up-heading-safe)))
7413 (setq beg (point)
7414 heading (org-get-heading))
7415 (org-end-of-subtree t t)
7416 (if (org-at-heading-p) (backward-char 1))
7417 (setq end (point)))
7418 (if (and (buffer-live-p org-last-indirect-buffer)
7419 (not (eq org-indirect-buffer-display 'new-frame))
7420 (not arg))
7421 (kill-buffer org-last-indirect-buffer))
7422 (setq ibuf (org-get-indirect-buffer cbuf)
7423 org-last-indirect-buffer ibuf)
7424 (cond
7425 ((or (eq org-indirect-buffer-display 'new-frame)
7426 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7427 (select-frame (make-frame))
7428 (delete-other-windows)
7429 (org-pop-to-buffer-same-window ibuf)
7430 (org-set-frame-title heading))
7431 ((eq org-indirect-buffer-display 'dedicated-frame)
7432 (raise-frame
7433 (select-frame (or (and org-indirect-dedicated-frame
7434 (frame-live-p org-indirect-dedicated-frame)
7435 org-indirect-dedicated-frame)
7436 (setq org-indirect-dedicated-frame (make-frame)))))
7437 (delete-other-windows)
7438 (org-pop-to-buffer-same-window ibuf)
7439 (org-set-frame-title (concat "Indirect: " heading)))
7440 ((eq org-indirect-buffer-display 'current-window)
7441 (org-pop-to-buffer-same-window ibuf))
7442 ((eq org-indirect-buffer-display 'other-window)
7443 (pop-to-buffer ibuf))
7444 (t (error "Invalid value")))
7445 (if (featurep 'xemacs)
7446 (save-excursion (org-mode) (turn-on-font-lock)))
7447 (narrow-to-region beg end)
7448 (show-all)
7449 (goto-char pos)
7450 (run-hook-with-args 'org-cycle-hook 'all)
7451 (and (window-live-p cwin) (select-window cwin))))
7453 (defun org-get-indirect-buffer (&optional buffer)
7454 (setq buffer (or buffer (current-buffer)))
7455 (let ((n 1) (base (buffer-name buffer)) bname)
7456 (while (buffer-live-p
7457 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7458 (setq n (1+ n)))
7459 (condition-case nil
7460 (make-indirect-buffer buffer bname 'clone)
7461 (error (make-indirect-buffer buffer bname)))))
7463 (defun org-set-frame-title (title)
7464 "Set the title of the current frame to the string TITLE."
7465 ;; FIXME: how to name a single frame in XEmacs???
7466 (unless (featurep 'xemacs)
7467 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7469 ;;;; Structure editing
7471 ;;; Inserting headlines
7473 (defun org-previous-line-empty-p (&optional next)
7474 "Is the previous line a blank line?
7475 When NEXT is non-nil, check the next line instead."
7476 (save-excursion
7477 (and (not (bobp))
7478 (or (beginning-of-line (if next 2 0)) t)
7479 (save-match-data
7480 (looking-at "[ \t]*$")))))
7482 (defun org-insert-heading (&optional arg invisible-ok)
7483 "Insert a new heading or item with same depth at point.
7484 If point is in a plain list and ARG is nil, create a new list item.
7485 With one universal prefix argument, insert a heading even in lists.
7486 With two universal prefix arguments, insert the heading at the end
7487 of the parent subtree.
7489 If point is at the beginning of a headline, insert a sibling before
7490 the current headline. If point is not at the beginning, split the line
7491 and create a new headline with the text in the current line after point
7492 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7494 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7495 This is important for non-interactive uses of the command."
7496 (interactive "P")
7497 (cond
7498 ((or (= (buffer-size) 0)
7499 (and (not (save-excursion
7500 (and (ignore-errors (org-back-to-heading invisible-ok))
7501 (org-at-heading-p))))
7502 (or arg (not (org-in-item-p)))))
7503 (insert
7504 (if (org-previous-line-empty-p) "" "\n")
7505 (if (org-in-src-block-p) ",* " "* "))
7506 (run-hooks 'org-insert-heading-hook))
7507 ((or arg
7508 org-insert-heading-respect-content
7509 (not (org-insert-item
7510 (save-excursion
7511 (beginning-of-line)
7512 (looking-at org-list-full-item-re)
7513 (match-string 3)))))
7514 (let (begn endn)
7515 (when (org-buffer-narrowed-p)
7516 (setq begn (point-min) endn (point-max))
7517 (widen))
7518 (let* ((empty-line-p nil)
7519 (eops (equal arg '(16))) ; insert at end of parent subtree
7520 (org-insert-heading-respect-content
7521 (or (not (null arg)) org-insert-heading-respect-content))
7522 (level nil)
7523 (on-heading (org-at-heading-p))
7524 (on-empty-line
7525 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7526 (head (save-excursion
7527 (condition-case nil
7528 (progn
7529 (org-back-to-heading invisible-ok)
7530 (when (and (not on-heading)
7531 (featurep 'org-inlinetask)
7532 (integerp org-inlinetask-min-level)
7533 (>= (length (match-string 0))
7534 org-inlinetask-min-level))
7535 ;; Find a heading level before the inline task
7536 (while (and (setq level (org-up-heading-safe))
7537 (>= level org-inlinetask-min-level)))
7538 (if (org-at-heading-p)
7539 (org-back-to-heading invisible-ok)
7540 (error "This should not happen")))
7541 (unless (and (save-excursion
7542 (save-match-data
7543 (org-backward-heading-same-level 1 invisible-ok))
7544 (= (point) (match-beginning 0)))
7545 (not (org-previous-line-empty-p t)))
7546 (setq empty-line-p (org-previous-line-empty-p)))
7547 (match-string 0))
7548 (error "* "))))
7549 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7550 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7551 pos hide-previous previous-pos)
7552 (if ;; At the beginning of a heading, open a new line for insertiong
7553 (and (bolp) (org-at-heading-p)
7554 (not eops)
7555 (or (bobp)
7556 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7557 (open-line (if blank 2 1))
7558 (save-excursion
7559 (setq previous-pos (point-at-bol))
7560 (end-of-line)
7561 (setq hide-previous (outline-invisible-p)))
7562 (and org-insert-heading-respect-content
7563 (save-excursion
7564 (while (outline-invisible-p)
7565 (org-show-subtree)
7566 (org-up-heading-safe))))
7567 (let ((split
7568 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7569 (save-excursion
7570 (let ((p (point)))
7571 (goto-char (point-at-bol))
7572 (and (looking-at org-complex-heading-regexp)
7573 (match-beginning 4)
7574 (> p (match-beginning 4)))))))
7575 tags pos)
7576 (cond
7577 ;; Insert a new line, possibly at end of parent subtree
7578 ((and (not arg) (not on-heading) (not on-empty-line)
7579 (not (save-excursion
7580 (beginning-of-line 1)
7581 (looking-at org-list-full-item-re))))
7582 (beginning-of-line 1))
7583 (org-insert-heading-respect-content
7584 (if (not eops)
7585 (progn
7586 (org-end-of-subtree nil t)
7587 (and (looking-at "^\\*") (backward-char 1))
7588 (while (and (not (bobp))
7589 ;; Don't delete spaces in empty headlines
7590 (not (looking-back org-outline-regexp))
7591 (member (char-before) '(?\ ?\t ?\n)))
7592 (backward-delete-char 1)))
7593 (let ((p (point)))
7594 (org-up-heading-safe)
7595 (if (= p (point))
7596 (goto-char (point-max))
7597 (org-end-of-subtree nil t))))
7598 (when (featurep 'org-inlinetask)
7599 (while (and (not (eobp))
7600 (looking-at "\\(\\*+\\)[ \t]+")
7601 (>= (length (match-string 1))
7602 org-inlinetask-min-level))
7603 (org-end-of-subtree nil t)))
7604 (or (bolp) (newline))
7605 (or (org-previous-line-empty-p)
7606 (and blank (newline)))
7607 (if (or empty-line-p eops) (open-line 1)))
7608 ;; Insert a headling containing text after point
7609 ((org-at-heading-p)
7610 (when hide-previous
7611 (show-children)
7612 (org-show-entry))
7613 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7614 (setq tags (and (match-end 2) (match-string 2)))
7615 (and (match-end 1)
7616 (delete-region (match-beginning 1) (match-end 1)))
7617 (setq pos (point-at-bol))
7618 (or split (end-of-line 1))
7619 (delete-horizontal-space)
7620 (if (string-match "\\`\\*+\\'"
7621 (buffer-substring (point-at-bol) (point)))
7622 (insert " "))
7623 (newline (if blank 2 1))
7624 (when tags
7625 (save-excursion
7626 (goto-char pos)
7627 (end-of-line 1)
7628 (insert " " tags)
7629 (org-set-tags nil 'align))))
7631 (or split (end-of-line 1))
7632 (newline (cond ((and blank (not on-empty-line)) 2)
7633 (blank 1)
7634 (on-empty-line 0) (t 1)))))))
7635 (insert head) (just-one-space)
7636 (setq pos (point))
7637 (end-of-line 1)
7638 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7639 (when (and org-insert-heading-respect-content hide-previous)
7640 (save-excursion
7641 (goto-char previous-pos)
7642 (hide-subtree)))
7643 (when (and begn endn)
7644 (narrow-to-region (min (point) begn) (max (point) endn)))
7645 (run-hooks 'org-insert-heading-hook))))))
7647 (defun org-get-heading (&optional no-tags no-todo)
7648 "Return the heading of the current entry, without the stars.
7649 When NO-TAGS is non-nil, don't include tags.
7650 When NO-TODO is non-nil, don't include TODO keywords."
7651 (save-excursion
7652 (org-back-to-heading t)
7653 (cond
7654 ((and no-tags no-todo)
7655 (looking-at org-complex-heading-regexp)
7656 (match-string 4))
7657 (no-tags
7658 (looking-at (concat org-outline-regexp
7659 "\\(.*?\\)"
7660 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7661 (match-string 1))
7662 (no-todo
7663 (looking-at org-todo-line-regexp)
7664 (match-string 3))
7665 (t (looking-at org-heading-regexp)
7666 (match-string 2)))))
7668 (defvar orgstruct-mode) ; defined below
7670 (defun org-heading-components ()
7671 "Return the components of the current heading.
7672 This is a list with the following elements:
7673 - the level as an integer
7674 - the reduced level, different if `org-odd-levels-only' is set.
7675 - the TODO keyword, or nil
7676 - the priority character, like ?A, or nil if no priority is given
7677 - the headline text itself, or the tags string if no headline text
7678 - the tags string, or nil."
7679 (save-excursion
7680 (org-back-to-heading t)
7681 (if (let (case-fold-search)
7682 (looking-at
7683 (if orgstruct-mode
7684 org-heading-regexp
7685 org-complex-heading-regexp)))
7686 (if orgstruct-mode
7687 (list (length (match-string 1))
7688 (org-reduced-level (length (match-string 1)))
7691 (match-string 2)
7692 nil)
7693 (list (length (match-string 1))
7694 (org-reduced-level (length (match-string 1)))
7695 (org-match-string-no-properties 2)
7696 (and (match-end 3) (aref (match-string 3) 2))
7697 (org-match-string-no-properties 4)
7698 (org-match-string-no-properties 5))))))
7700 (defun org-get-entry ()
7701 "Get the entry text, after heading, entire subtree."
7702 (save-excursion
7703 (org-back-to-heading t)
7704 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7706 (defun org-insert-heading-after-current ()
7707 "Insert a new heading with same level as current, after current subtree."
7708 (interactive)
7709 (org-back-to-heading)
7710 (org-insert-heading)
7711 (org-move-subtree-down)
7712 (end-of-line 1))
7714 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7715 "Insert heading with `org-insert-heading-respect-content' set to t."
7716 (interactive "P")
7717 (let ((org-insert-heading-respect-content t))
7718 (org-insert-heading arg invisible-ok)))
7720 (defun org-insert-todo-heading-respect-content (&optional force-state)
7721 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7722 (interactive "P")
7723 (let ((org-insert-heading-respect-content t))
7724 (org-insert-todo-heading force-state t)))
7726 (defun org-insert-todo-heading (arg &optional force-heading)
7727 "Insert a new heading with the same level and TODO state as current heading.
7728 If the heading has no TODO state, or if the state is DONE, use the first
7729 state (TODO by default). Also one prefix arg, force first state. With two
7730 prefix args, force inserting at the end of the parent subtree."
7731 (interactive "P")
7732 (when (or force-heading (not (org-insert-item 'checkbox)))
7733 (org-insert-heading (or (and (equal arg '(16)) '(16))
7734 force-heading))
7735 (save-excursion
7736 (org-back-to-heading)
7737 (outline-previous-heading)
7738 (looking-at org-todo-line-regexp))
7739 (let*
7740 ((new-mark-x
7741 (if (or arg
7742 (not (match-beginning 2))
7743 (member (match-string 2) org-done-keywords))
7744 (car org-todo-keywords-1)
7745 (match-string 2)))
7746 (new-mark
7748 (run-hook-with-args-until-success
7749 'org-todo-get-default-hook new-mark-x nil)
7750 new-mark-x)))
7751 (beginning-of-line 1)
7752 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7753 (if org-treat-insert-todo-heading-as-state-change
7754 (org-todo new-mark)
7755 (insert new-mark " "))))
7756 (when org-provide-todo-statistics
7757 (org-update-parent-todo-statistics))))
7759 (defun org-insert-subheading (arg)
7760 "Insert a new subheading and demote it.
7761 Works for outline headings and for plain lists alike."
7762 (interactive "P")
7763 (org-insert-heading arg)
7764 (cond
7765 ((org-at-heading-p) (org-do-demote))
7766 ((org-at-item-p) (org-indent-item))))
7768 (defun org-insert-todo-subheading (arg)
7769 "Insert a new subheading with TODO keyword or checkbox and demote it.
7770 Works for outline headings and for plain lists alike."
7771 (interactive "P")
7772 (org-insert-todo-heading arg)
7773 (cond
7774 ((org-at-heading-p) (org-do-demote))
7775 ((org-at-item-p) (org-indent-item))))
7777 ;;; Promotion and Demotion
7779 (defvar org-after-demote-entry-hook nil
7780 "Hook run after an entry has been demoted.
7781 The cursor will be at the beginning of the entry.
7782 When a subtree is being demoted, the hook will be called for each node.")
7784 (defvar org-after-promote-entry-hook nil
7785 "Hook run after an entry has been promoted.
7786 The cursor will be at the beginning of the entry.
7787 When a subtree is being promoted, the hook will be called for each node.")
7789 (defun org-promote-subtree ()
7790 "Promote the entire subtree.
7791 See also `org-promote'."
7792 (interactive)
7793 (save-excursion
7794 (org-with-limited-levels (org-map-tree 'org-promote)))
7795 (org-fix-position-after-promote))
7797 (defun org-demote-subtree ()
7798 "Demote the entire subtree. See `org-demote'.
7799 See also `org-promote'."
7800 (interactive)
7801 (save-excursion
7802 (org-with-limited-levels (org-map-tree 'org-demote)))
7803 (org-fix-position-after-promote))
7806 (defun org-do-promote ()
7807 "Promote the current heading higher up the tree.
7808 If the region is active in `transient-mark-mode', promote all headings
7809 in the region."
7810 (interactive)
7811 (save-excursion
7812 (if (org-region-active-p)
7813 (org-map-region 'org-promote (region-beginning) (region-end))
7814 (org-promote)))
7815 (org-fix-position-after-promote))
7817 (defun org-do-demote ()
7818 "Demote the current heading lower down the tree.
7819 If the region is active in `transient-mark-mode', demote all headings
7820 in the region."
7821 (interactive)
7822 (save-excursion
7823 (if (org-region-active-p)
7824 (org-map-region 'org-demote (region-beginning) (region-end))
7825 (org-demote)))
7826 (org-fix-position-after-promote))
7828 (defun org-fix-position-after-promote ()
7829 "Make sure that after pro/demotion cursor position is right."
7830 (let ((pos (point)))
7831 (when (save-excursion
7832 (beginning-of-line 1)
7833 (looking-at org-todo-line-regexp)
7834 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7835 (cond ((eobp) (insert " "))
7836 ((eolp) (insert " "))
7837 ((equal (char-after) ?\ ) (forward-char 1))))))
7839 (defun org-current-level ()
7840 "Return the level of the current entry, or nil if before the first headline.
7841 The level is the number of stars at the beginning of the headline."
7842 (save-excursion
7843 (org-with-limited-levels
7844 (if (ignore-errors (org-back-to-heading t))
7845 (funcall outline-level)))))
7847 (defun org-get-previous-line-level ()
7848 "Return the outline depth of the last headline before the current line.
7849 Returns 0 for the first headline in the buffer, and nil if before the
7850 first headline."
7851 (let ((current-level (org-current-level))
7852 (prev-level (when (> (line-number-at-pos) 1)
7853 (save-excursion
7854 (beginning-of-line 0)
7855 (org-current-level)))))
7856 (cond ((null current-level) nil) ; Before first headline
7857 ((null prev-level) 0) ; At first headline
7858 (prev-level))))
7860 (defun org-reduced-level (l)
7861 "Compute the effective level of a heading.
7862 This takes into account the setting of `org-odd-levels-only'."
7863 (cond
7864 ((zerop l) 0)
7865 (org-odd-levels-only (1+ (floor (/ l 2))))
7866 (t l)))
7868 (defun org-level-increment ()
7869 "Return the number of stars that will be added or removed at a
7870 time to headlines when structure editing, based on the value of
7871 `org-odd-levels-only'."
7872 (if org-odd-levels-only 2 1))
7874 (defun org-get-valid-level (level &optional change)
7875 "Rectify a level change under the influence of `org-odd-levels-only'
7876 LEVEL is a current level, CHANGE is by how much the level should be
7877 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7878 even level numbers will become the next higher odd number."
7879 (if org-odd-levels-only
7880 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7881 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7882 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7883 (max 1 (+ level (or change 0)))))
7885 (if (boundp 'define-obsolete-function-alias)
7886 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7887 (define-obsolete-function-alias 'org-get-legal-level
7888 'org-get-valid-level)
7889 (define-obsolete-function-alias 'org-get-legal-level
7890 'org-get-valid-level "23.1")))
7892 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7893 ;; ̀org-with-limited-levels'
7894 (defun org-promote ()
7895 "Promote the current heading higher up the tree.
7896 If the region is active in `transient-mark-mode', promote all headings
7897 in the region."
7898 (org-back-to-heading t)
7899 (let* ((level (save-match-data (funcall outline-level)))
7900 (after-change-functions (remove 'flyspell-after-change-function
7901 after-change-functions))
7902 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7903 (diff (abs (- level (length up-head) -1))))
7904 (cond ((and (= level 1) org-called-with-limited-levels
7905 org-allow-promoting-top-level-subtree)
7906 (replace-match "# " nil t))
7907 ((= level 1)
7908 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7909 (t (replace-match up-head nil t)))
7910 ;; Fixup tag positioning
7911 (unless (= level 1)
7912 (and org-auto-align-tags (org-set-tags nil t))
7913 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7914 (run-hooks 'org-after-promote-entry-hook)))
7916 (defun org-demote ()
7917 "Demote the current heading lower down the tree.
7918 If the region is active in `transient-mark-mode', demote all headings
7919 in the region."
7920 (org-back-to-heading t)
7921 (let* ((level (save-match-data (funcall outline-level)))
7922 (after-change-functions (remove 'flyspell-after-change-function
7923 after-change-functions))
7924 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7925 (diff (abs (- level (length down-head) -1))))
7926 (replace-match down-head nil t)
7927 ;; Fixup tag positioning
7928 (and org-auto-align-tags (org-set-tags nil t))
7929 (if org-adapt-indentation (org-fixup-indentation diff))
7930 (run-hooks 'org-after-demote-entry-hook)))
7932 (defun org-cycle-level ()
7933 "Cycle the level of an empty headline through possible states.
7934 This goes first to child, then to parent, level, then up the hierarchy.
7935 After top level, it switches back to sibling level."
7936 (interactive)
7937 (let ((org-adapt-indentation nil))
7938 (when (org-point-at-end-of-empty-headline)
7939 (setq this-command 'org-cycle-level) ; Only needed for caching
7940 (let ((cur-level (org-current-level))
7941 (prev-level (org-get-previous-line-level)))
7942 (cond
7943 ;; If first headline in file, promote to top-level.
7944 ((= prev-level 0)
7945 (loop repeat (/ (- cur-level 1) (org-level-increment))
7946 do (org-do-promote)))
7947 ;; If same level as prev, demote one.
7948 ((= prev-level cur-level)
7949 (org-do-demote))
7950 ;; If parent is top-level, promote to top level if not already.
7951 ((= prev-level 1)
7952 (loop repeat (/ (- cur-level 1) (org-level-increment))
7953 do (org-do-promote)))
7954 ;; If top-level, return to prev-level.
7955 ((= cur-level 1)
7956 (loop repeat (/ (- prev-level 1) (org-level-increment))
7957 do (org-do-demote)))
7958 ;; If less than prev-level, promote one.
7959 ((< cur-level prev-level)
7960 (org-do-promote))
7961 ;; If deeper than prev-level, promote until higher than
7962 ;; prev-level.
7963 ((> cur-level prev-level)
7964 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7965 do (org-do-promote))))
7966 t))))
7968 (defun org-map-tree (fun)
7969 "Call FUN for every heading underneath the current one."
7970 (org-back-to-heading)
7971 (let ((level (funcall outline-level)))
7972 (save-excursion
7973 (funcall fun)
7974 (while (and (progn
7975 (outline-next-heading)
7976 (> (funcall outline-level) level))
7977 (not (eobp)))
7978 (funcall fun)))))
7980 (defun org-map-region (fun beg end)
7981 "Call FUN for every heading between BEG and END."
7982 (let ((org-ignore-region t))
7983 (save-excursion
7984 (setq end (copy-marker end))
7985 (goto-char beg)
7986 (if (and (re-search-forward org-outline-regexp-bol nil t)
7987 (< (point) end))
7988 (funcall fun))
7989 (while (and (progn
7990 (outline-next-heading)
7991 (< (point) end))
7992 (not (eobp)))
7993 (funcall fun)))))
7995 (defvar org-property-end-re) ; silence byte-compiler
7996 (defun org-fixup-indentation (diff)
7997 "Change the indentation in the current entry by DIFF.
7998 However, if any line in the current entry has no indentation, or if it
7999 would end up with no indentation after the change, nothing at all is done."
8000 (save-excursion
8001 (let ((end (save-excursion (outline-next-heading)
8002 (point-marker)))
8003 (prohibit (if (> diff 0)
8004 "^\\S-"
8005 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8006 col)
8007 (unless (save-excursion (end-of-line 1)
8008 (re-search-forward prohibit end t))
8009 (while (and (< (point) end)
8010 (re-search-forward "^[ \t]+" end t))
8011 (goto-char (match-end 0))
8012 (setq col (current-column))
8013 (if (< diff 0) (replace-match ""))
8014 (org-indent-to-column (+ diff col))))
8015 (move-marker end nil))))
8017 (defun org-convert-to-odd-levels ()
8018 "Convert an org-mode file with all levels allowed to one with odd levels.
8019 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8020 level 5 etc."
8021 (interactive)
8022 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8023 (let ((outline-level 'org-outline-level)
8024 (org-odd-levels-only nil) n)
8025 (save-excursion
8026 (goto-char (point-min))
8027 (while (re-search-forward "^\\*\\*+ " nil t)
8028 (setq n (- (length (match-string 0)) 2))
8029 (while (>= (setq n (1- n)) 0)
8030 (org-demote))
8031 (end-of-line 1))))))
8033 (defun org-convert-to-oddeven-levels ()
8034 "Convert an org-mode file with only odd levels to one with odd/even levels.
8035 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8036 file contains a section with an even level, conversion would
8037 destroy the structure of the file. An error is signaled in this
8038 case."
8039 (interactive)
8040 (goto-char (point-min))
8041 ;; First check if there are no even levels
8042 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8043 (org-show-context t)
8044 (error "Not all levels are odd in this file. Conversion not possible"))
8045 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8046 (let ((outline-regexp org-outline-regexp)
8047 (outline-level 'org-outline-level)
8048 (org-odd-levels-only nil) n)
8049 (save-excursion
8050 (goto-char (point-min))
8051 (while (re-search-forward "^\\*\\*+ " nil t)
8052 (setq n (/ (1- (length (match-string 0))) 2))
8053 (while (>= (setq n (1- n)) 0)
8054 (org-promote))
8055 (end-of-line 1))))))
8057 (defun org-tr-level (n)
8058 "Make N odd if required."
8059 (if org-odd-levels-only (1+ (/ n 2)) n))
8061 ;;; Vertical tree motion, cutting and pasting of subtrees
8063 (defun org-move-subtree-up (&optional arg)
8064 "Move the current subtree up past ARG headlines of the same level."
8065 (interactive "p")
8066 (org-move-subtree-down (- (prefix-numeric-value arg))))
8068 (defun org-move-subtree-down (&optional arg)
8069 "Move the current subtree down past ARG headlines of the same level."
8070 (interactive "p")
8071 (setq arg (prefix-numeric-value arg))
8072 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8073 'org-get-last-sibling))
8074 (ins-point (make-marker))
8075 (cnt (abs arg))
8076 (col (current-column))
8077 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8078 ;; Select the tree
8079 (org-back-to-heading)
8080 (setq beg0 (point))
8081 (save-excursion
8082 (setq ne-beg (org-back-over-empty-lines))
8083 (setq beg (point)))
8084 (save-match-data
8085 (save-excursion (outline-end-of-heading)
8086 (setq folded (outline-invisible-p)))
8087 (outline-end-of-subtree))
8088 (outline-next-heading)
8089 (setq ne-end (org-back-over-empty-lines))
8090 (setq end (point))
8091 (goto-char beg0)
8092 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8093 ;; include less whitespace
8094 (save-excursion
8095 (goto-char beg)
8096 (forward-line (- ne-beg ne-end))
8097 (setq beg (point))))
8098 ;; Find insertion point, with error handling
8099 (while (> cnt 0)
8100 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8101 (progn (goto-char beg0)
8102 (user-error "Cannot move past superior level or buffer limit")))
8103 (setq cnt (1- cnt)))
8104 (if (> arg 0)
8105 ;; Moving forward - still need to move over subtree
8106 (progn (org-end-of-subtree t t)
8107 (save-excursion
8108 (org-back-over-empty-lines)
8109 (or (bolp) (newline)))))
8110 (setq ne-ins (org-back-over-empty-lines))
8111 (move-marker ins-point (point))
8112 (setq txt (buffer-substring beg end))
8113 (org-save-markers-in-region beg end)
8114 (delete-region beg end)
8115 (org-remove-empty-overlays-at beg)
8116 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8117 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8118 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8119 (let ((bbb (point)))
8120 (insert-before-markers txt)
8121 (org-reinstall-markers-in-region bbb)
8122 (move-marker ins-point bbb))
8123 (or (bolp) (insert "\n"))
8124 (setq ins-end (point))
8125 (goto-char ins-point)
8126 (org-skip-whitespace)
8127 (when (and (< arg 0)
8128 (org-first-sibling-p)
8129 (> ne-ins ne-beg))
8130 ;; Move whitespace back to beginning
8131 (save-excursion
8132 (goto-char ins-end)
8133 (let ((kill-whole-line t))
8134 (kill-line (- ne-ins ne-beg)) (point)))
8135 (insert (make-string (- ne-ins ne-beg) ?\n)))
8136 (move-marker ins-point nil)
8137 (if folded
8138 (hide-subtree)
8139 (org-show-entry)
8140 (show-children)
8141 (org-cycle-hide-drawers 'children))
8142 (org-clean-visibility-after-subtree-move)
8143 ;; move back to the initial column we were at
8144 (move-to-column col)))
8146 (defvar org-subtree-clip ""
8147 "Clipboard for cut and paste of subtrees.
8148 This is actually only a copy of the kill, because we use the normal kill
8149 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8151 (defvar org-subtree-clip-folded nil
8152 "Was the last copied subtree folded?
8153 This is used to fold the tree back after pasting.")
8155 (defun org-cut-subtree (&optional n)
8156 "Cut the current subtree into the clipboard.
8157 With prefix arg N, cut this many sequential subtrees.
8158 This is a short-hand for marking the subtree and then cutting it."
8159 (interactive "p")
8160 (org-copy-subtree n 'cut))
8162 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8163 "Cut the current subtree into the clipboard.
8164 With prefix arg N, cut this many sequential subtrees.
8165 This is a short-hand for marking the subtree and then copying it.
8166 If CUT is non-nil, actually cut the subtree.
8167 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8168 of some markers in the region, even if CUT is non-nil. This is
8169 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8170 (interactive "p")
8171 (let (beg end folded (beg0 (point)))
8172 (if (org-called-interactively-p 'any)
8173 (org-back-to-heading nil) ; take what looks like a subtree
8174 (org-back-to-heading t)) ; take what is really there
8175 (setq beg (point))
8176 (skip-chars-forward " \t\r\n")
8177 (save-match-data
8178 (if nosubtrees
8179 (outline-next-heading)
8180 (save-excursion (outline-end-of-heading)
8181 (setq folded (outline-invisible-p)))
8182 (condition-case nil
8183 (org-forward-heading-same-level (1- n) t)
8184 (error nil))
8185 (org-end-of-subtree t t)))
8186 (setq end (point))
8187 (goto-char beg0)
8188 (when (> end beg)
8189 (setq org-subtree-clip-folded folded)
8190 (when (or cut force-store-markers)
8191 (org-save-markers-in-region beg end))
8192 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8193 (setq org-subtree-clip (current-kill 0))
8194 (message "%s: Subtree(s) with %d characters"
8195 (if cut "Cut" "Copied")
8196 (length org-subtree-clip)))))
8198 (defun org-paste-subtree (&optional level tree for-yank)
8199 "Paste the clipboard as a subtree, with modification of headline level.
8200 The entire subtree is promoted or demoted in order to match a new headline
8201 level.
8203 If the cursor is at the beginning of a headline, the same level as
8204 that headline is used to paste the tree.
8206 If not, the new level is derived from the *visible* headings
8207 before and after the insertion point, and taken to be the inferior headline
8208 level of the two. So if the previous visible heading is level 3 and the
8209 next is level 4 (or vice versa), level 4 will be used for insertion.
8210 This makes sure that the subtree remains an independent subtree and does
8211 not swallow low level entries.
8213 You can also force a different level, either by using a numeric prefix
8214 argument, or by inserting the heading marker by hand. For example, if the
8215 cursor is after \"*****\", then the tree will be shifted to level 5.
8217 If optional TREE is given, use this text instead of the kill ring.
8219 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8220 move back over whitespace before inserting, and move point to the end of
8221 the inserted text when done."
8222 (interactive "P")
8223 (setq tree (or tree (and kill-ring (current-kill 0))))
8224 (unless (org-kill-is-subtree-p tree)
8225 (error "%s"
8226 (substitute-command-keys
8227 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8228 (org-with-limited-levels
8229 (let* ((visp (not (outline-invisible-p)))
8230 (txt tree)
8231 (^re_ "\\(\\*+\\)[ \t]*")
8232 (old-level (if (string-match org-outline-regexp-bol txt)
8233 (- (match-end 0) (match-beginning 0) 1)
8234 -1))
8235 (force-level (cond (level (prefix-numeric-value level))
8236 ((and (looking-at "[ \t]*$")
8237 (string-match
8238 "^\\*+$" (buffer-substring
8239 (point-at-bol) (point))))
8240 (- (match-end 1) (match-beginning 1)))
8241 ((and (bolp)
8242 (looking-at org-outline-regexp))
8243 (- (match-end 0) (point) 1))))
8244 (previous-level (save-excursion
8245 (condition-case nil
8246 (progn
8247 (outline-previous-visible-heading 1)
8248 (if (looking-at ^re_)
8249 (- (match-end 0) (match-beginning 0) 1)
8251 (error 1))))
8252 (next-level (save-excursion
8253 (condition-case nil
8254 (progn
8255 (or (looking-at org-outline-regexp)
8256 (outline-next-visible-heading 1))
8257 (if (looking-at ^re_)
8258 (- (match-end 0) (match-beginning 0) 1)
8260 (error 1))))
8261 (new-level (or force-level (max previous-level next-level)))
8262 (shift (if (or (= old-level -1)
8263 (= new-level -1)
8264 (= old-level new-level))
8266 (- new-level old-level)))
8267 (delta (if (> shift 0) -1 1))
8268 (func (if (> shift 0) 'org-demote 'org-promote))
8269 (org-odd-levels-only nil)
8270 beg end newend)
8271 ;; Remove the forced level indicator
8272 (if force-level
8273 (delete-region (point-at-bol) (point)))
8274 ;; Paste
8275 (beginning-of-line (if (bolp) 1 2))
8276 (setq beg (point))
8277 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8278 (insert-before-markers txt)
8279 (unless (string-match "\n\\'" txt) (insert "\n"))
8280 (setq newend (point))
8281 (org-reinstall-markers-in-region beg)
8282 (setq end (point))
8283 (goto-char beg)
8284 (skip-chars-forward " \t\n\r")
8285 (setq beg (point))
8286 (if (and (outline-invisible-p) visp)
8287 (save-excursion (outline-show-heading)))
8288 ;; Shift if necessary
8289 (unless (= shift 0)
8290 (save-restriction
8291 (narrow-to-region beg end)
8292 (while (not (= shift 0))
8293 (org-map-region func (point-min) (point-max))
8294 (setq shift (+ delta shift)))
8295 (goto-char (point-min))
8296 (setq newend (point-max))))
8297 (when (or (org-called-interactively-p 'interactive) for-yank)
8298 (message "Clipboard pasted as level %d subtree" new-level))
8299 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8300 kill-ring
8301 (eq org-subtree-clip (current-kill 0))
8302 org-subtree-clip-folded)
8303 ;; The tree was folded before it was killed/copied
8304 (hide-subtree))
8305 (and for-yank (goto-char newend)))))
8307 (defun org-kill-is-subtree-p (&optional txt)
8308 "Check if the current kill is an outline subtree, or a set of trees.
8309 Returns nil if kill does not start with a headline, or if the first
8310 headline level is not the largest headline level in the tree.
8311 So this will actually accept several entries of equal levels as well,
8312 which is OK for `org-paste-subtree'.
8313 If optional TXT is given, check this string instead of the current kill."
8314 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8315 (re (org-get-limited-outline-regexp))
8316 (^re (concat "^" re))
8317 (start-level (and kill
8318 (string-match
8319 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8320 kill)
8321 (- (match-end 2) (match-beginning 2) 1)))
8322 (start (1+ (or (match-beginning 2) -1))))
8323 (if (not start-level)
8324 (progn
8325 nil) ;; does not even start with a heading
8326 (catch 'exit
8327 (while (setq start (string-match ^re kill (1+ start)))
8328 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8329 (throw 'exit nil)))
8330 t))))
8332 (defvar org-markers-to-move nil
8333 "Markers that should be moved with a cut-and-paste operation.
8334 Those markers are stored together with their positions relative to
8335 the start of the region.")
8337 (defun org-save-markers-in-region (beg end)
8338 "Check markers in region.
8339 If these markers are between BEG and END, record their position relative
8340 to BEG, so that after moving the block of text, we can put the markers back
8341 into place.
8342 This function gets called just before an entry or tree gets cut from the
8343 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8344 called immediately, to move the markers with the entries."
8345 (setq org-markers-to-move nil)
8346 (when (featurep 'org-clock)
8347 (org-clock-save-markers-for-cut-and-paste beg end))
8348 (when (featurep 'org-agenda)
8349 (org-agenda-save-markers-for-cut-and-paste beg end)))
8351 (defun org-check-and-save-marker (marker beg end)
8352 "Check if MARKER is between BEG and END.
8353 If yes, remember the marker and the distance to BEG."
8354 (when (and (marker-buffer marker)
8355 (equal (marker-buffer marker) (current-buffer)))
8356 (if (and (>= marker beg) (< marker end))
8357 (push (cons marker (- marker beg)) org-markers-to-move))))
8359 (defun org-reinstall-markers-in-region (beg)
8360 "Move all remembered markers to their position relative to BEG."
8361 (mapc (lambda (x)
8362 (move-marker (car x) (+ beg (cdr x))))
8363 org-markers-to-move)
8364 (setq org-markers-to-move nil))
8366 (defun org-narrow-to-subtree ()
8367 "Narrow buffer to the current subtree."
8368 (interactive)
8369 (save-excursion
8370 (save-match-data
8371 (org-with-limited-levels
8372 (narrow-to-region
8373 (progn (org-back-to-heading t) (point))
8374 (progn (org-end-of-subtree t t)
8375 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8376 (point)))))))
8378 (defun org-narrow-to-block ()
8379 "Narrow buffer to the current block."
8380 (interactive)
8381 (let* ((case-fold-search t)
8382 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8383 "^[ \t]*#\\+end_.*")))
8384 (if blockp
8385 (narrow-to-region (car blockp) (cdr blockp))
8386 (error "Not in a block"))))
8388 (eval-when-compile
8389 (defvar org-property-drawer-re))
8391 (defvar org-property-start-re) ;; defined below
8392 (defun org-clone-subtree-with-time-shift (n &optional shift)
8393 "Clone the task (subtree) at point N times.
8394 The clones will be inserted as siblings.
8396 In interactive use, the user will be prompted for the number of
8397 clones to be produced. When called with a universal prefix argument
8398 and if the entry has a timestamp, the user will also be prompted for
8399 a time shift, which may be a repeater as used in time stamps, for
8400 example `+3d'.
8402 When a valid repeater is given and the entry contains any time
8403 stamps, the clones will become a sequence in time, with time
8404 stamps in the subtree shifted for each clone produced. If SHIFT
8405 is nil or the empty string, time stamps will be left alone. The
8406 ID property of the original subtree is removed.
8408 If the original subtree did contain time stamps with a repeater,
8409 the following will happen:
8410 - the repeater will be removed in each clone
8411 - an additional clone will be produced, with the current, unshifted
8412 date(s) in the entry.
8413 - the original entry will be placed *after* all the clones, with
8414 repeater intact.
8415 - the start days in the repeater in the original entry will be shifted
8416 to past the last clone.
8417 In this way you can spell out a number of instances of a repeating task,
8418 and still retain the repeater to cover future instances of the task."
8419 (interactive "nNumber of clones to produce: ")
8420 (let ((shift
8421 (or shift
8422 (if (and (equal current-prefix-arg '(4))
8423 (save-excursion
8424 (re-search-forward org-ts-regexp-both
8425 (save-excursion
8426 (org-end-of-subtree t)
8427 (point)) t)))
8428 (read-from-minibuffer
8429 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8430 ""))) ;; No time shift
8431 (n-no-remove -1)
8432 (drawer-re org-drawer-regexp)
8433 beg end template task idprop
8434 shift-n shift-what doshift nmin nmax)
8435 (if (not (and (integerp n) (> n 0)))
8436 (error "Invalid number of replications %s" n))
8437 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8438 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8439 shift)))
8440 (error "Invalid shift specification %s" shift))
8441 (when doshift
8442 (setq shift-n (string-to-number (match-string 1 shift))
8443 shift-what (cdr (assoc (match-string 2 shift)
8444 '(("d" . day) ("w" . week)
8445 ("m" . month) ("y" . year))))))
8446 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8447 (setq nmin 1 nmax n)
8448 (org-back-to-heading t)
8449 (setq beg (point))
8450 (setq idprop (org-entry-get nil "ID"))
8451 (org-end-of-subtree t t)
8452 (or (bolp) (insert "\n"))
8453 (setq end (point))
8454 (setq template (buffer-substring beg end))
8455 (when (and doshift
8456 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8457 (delete-region beg end)
8458 (setq end beg)
8459 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8460 (goto-char end)
8461 (loop for n from nmin to nmax do
8462 ;; prepare clone
8463 (with-temp-buffer
8464 (insert template)
8465 (org-mode)
8466 (goto-char (point-min))
8467 (org-show-subtree)
8468 (and idprop (if org-clone-delete-id
8469 (org-entry-delete nil "ID")
8470 (org-id-get-create t)))
8471 (unless (= n 0)
8472 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8473 (kill-whole-line))
8474 (goto-char (point-min))
8475 (while (re-search-forward drawer-re nil t)
8476 (mapc (lambda (d)
8477 (org-remove-empty-drawer-at d (point))) org-drawers)))
8478 (goto-char (point-min))
8479 (when doshift
8480 (while (re-search-forward org-ts-regexp-both nil t)
8481 (org-timestamp-change (* n shift-n) shift-what))
8482 (unless (= n n-no-remove)
8483 (goto-char (point-min))
8484 (while (re-search-forward org-ts-regexp nil t)
8485 (save-excursion
8486 (goto-char (match-beginning 0))
8487 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8488 (delete-region (match-beginning 1) (match-end 1)))))))
8489 (setq task (buffer-string)))
8490 (insert task))
8491 (goto-char beg)))
8493 ;;; Outline Sorting
8495 (defun org-sort (with-case)
8496 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8497 Optional argument WITH-CASE means sort case-sensitively."
8498 (interactive "P")
8499 (cond
8500 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8501 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8503 (org-call-with-arg 'org-sort-entries with-case))))
8505 (defun org-sort-remove-invisible (s)
8506 "Remove invisible links from string S."
8507 (remove-text-properties 0 (length s) org-rm-props s)
8508 (while (string-match org-bracket-link-regexp s)
8509 (setq s (replace-match (if (match-end 2)
8510 (match-string 3 s)
8511 (match-string 1 s)) t t s)))
8512 (let ((st (format " %s " s)))
8513 (while (string-match org-emph-re st)
8514 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8515 (setq s (substring st 1 -1)))
8518 (defvar org-priority-regexp) ; defined later in the file
8520 (defvar org-after-sorting-entries-or-items-hook nil
8521 "Hook that is run after a bunch of entries or items have been sorted.
8522 When children are sorted, the cursor is in the parent line when this
8523 hook gets called. When a region or a plain list is sorted, the cursor
8524 will be in the first entry of the sorted region/list.")
8526 (defun org-sort-entries
8527 (&optional with-case sorting-type getkey-func compare-func property)
8528 "Sort entries on a certain level of an outline tree.
8529 If there is an active region, the entries in the region are sorted.
8530 Else, if the cursor is before the first entry, sort the top-level items.
8531 Else, the children of the entry at point are sorted.
8533 Sorting can be alphabetically, numerically, by date/time as given by
8534 a time stamp, by a property, by priority order, or by a custom function.
8536 The command prompts for the sorting type unless it has been given to the
8537 function through the SORTING-TYPE argument, which needs to be a character,
8538 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8539 precise meaning of each character:
8541 n Numerically, by converting the beginning of the entry/item to a number.
8542 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8543 o By order of TODO keywords.
8544 t By date/time, either the first active time stamp in the entry, or, if
8545 none exist, by the first inactive one.
8546 s By the scheduled date/time.
8547 d By deadline date/time.
8548 c By creation time, which is assumed to be the first inactive time stamp
8549 at the beginning of a line.
8550 p By priority according to the cookie.
8551 r By the value of a property.
8553 Capital letters will reverse the sort order.
8555 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8556 called with point at the beginning of the record. It must return either
8557 a string or a number that should serve as the sorting key for that record.
8559 Comparing entries ignores case by default. However, with an optional argument
8560 WITH-CASE, the sorting considers case as well.
8562 Sorting is done against the visible part of the headlines, it ignores hidden
8563 links."
8564 (interactive "P")
8565 (let ((case-func (if with-case 'identity 'downcase))
8566 (cmstr
8567 ;; The clock marker is lost when using `sort-subr', let's
8568 ;; store the clocking string.
8569 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8570 (save-excursion
8571 (goto-char org-clock-marker)
8572 (looking-back "^.*") (match-string-no-properties 0))))
8573 start beg end stars re re2
8574 txt what tmp)
8575 ;; Find beginning and end of region to sort
8576 (cond
8577 ((org-region-active-p)
8578 ;; we will sort the region
8579 (setq end (region-end)
8580 what "region")
8581 (goto-char (region-beginning))
8582 (if (not (org-at-heading-p)) (outline-next-heading))
8583 (setq start (point)))
8584 ((or (org-at-heading-p)
8585 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8586 ;; we will sort the children of the current headline
8587 (org-back-to-heading)
8588 (setq start (point)
8589 end (progn (org-end-of-subtree t t)
8590 (or (bolp) (insert "\n"))
8591 (org-back-over-empty-lines)
8592 (point))
8593 what "children")
8594 (goto-char start)
8595 (show-subtree)
8596 (outline-next-heading))
8598 ;; we will sort the top-level entries in this file
8599 (goto-char (point-min))
8600 (or (org-at-heading-p) (outline-next-heading))
8601 (setq start (point))
8602 (goto-char (point-max))
8603 (beginning-of-line 1)
8604 (when (looking-at ".*?\\S-")
8605 ;; File ends in a non-white line
8606 (end-of-line 1)
8607 (insert "\n"))
8608 (setq end (point-max))
8609 (setq what "top-level")
8610 (goto-char start)
8611 (show-all)))
8613 (setq beg (point))
8614 (if (>= beg end) (error "Nothing to sort"))
8616 (looking-at "\\(\\*+\\)")
8617 (setq stars (match-string 1)
8618 re (concat "^" (regexp-quote stars) " +")
8619 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8620 txt (buffer-substring beg end))
8621 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8622 (if (and (not (equal stars "*")) (string-match re2 txt))
8623 (error "Region to sort contains a level above the first entry"))
8625 (unless sorting-type
8626 (message
8627 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8628 [t]ime [s]cheduled [d]eadline [c]reated
8629 A/N/P/R/O/F/T/S/D/C means reversed:"
8630 what)
8631 (setq sorting-type (read-char-exclusive))
8633 (unless getkey-func
8634 (and (= (downcase sorting-type) ?f)
8635 (setq getkey-func
8636 (org-icompleting-read "Sort using function: "
8637 obarray 'fboundp t nil nil))
8638 (setq getkey-func (intern getkey-func))))
8640 (and (= (downcase sorting-type) ?r)
8641 (not property)
8642 (setq property
8643 (org-icompleting-read "Property: "
8644 (mapcar 'list (org-buffer-property-keys t))
8645 nil t))))
8647 (message "Sorting entries...")
8649 (save-restriction
8650 (narrow-to-region start end)
8651 (let ((dcst (downcase sorting-type))
8652 (case-fold-search nil)
8653 (now (current-time)))
8654 (sort-subr
8655 (/= dcst sorting-type)
8656 ;; This function moves to the beginning character of the "record" to
8657 ;; be sorted.
8658 (lambda nil
8659 (if (re-search-forward re nil t)
8660 (goto-char (match-beginning 0))
8661 (goto-char (point-max))))
8662 ;; This function moves to the last character of the "record" being
8663 ;; sorted.
8664 (lambda nil
8665 (save-match-data
8666 (condition-case nil
8667 (outline-forward-same-level 1)
8668 (error
8669 (goto-char (point-max))))))
8670 ;; This function returns the value that gets sorted against.
8671 (lambda nil
8672 (cond
8673 ((= dcst ?n)
8674 (if (looking-at org-complex-heading-regexp)
8675 (string-to-number (org-sort-remove-invisible (match-string 4)))
8676 nil))
8677 ((= dcst ?a)
8678 (if (looking-at org-complex-heading-regexp)
8679 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8680 nil))
8681 ((= dcst ?t)
8682 (let ((end (save-excursion (outline-next-heading) (point))))
8683 (if (or (re-search-forward org-ts-regexp end t)
8684 (re-search-forward org-ts-regexp-both end t))
8685 (org-time-string-to-seconds (match-string 0))
8686 (org-float-time now))))
8687 ((= dcst ?c)
8688 (let ((end (save-excursion (outline-next-heading) (point))))
8689 (if (re-search-forward
8690 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8691 end t)
8692 (org-time-string-to-seconds (match-string 0))
8693 (org-float-time now))))
8694 ((= dcst ?s)
8695 (let ((end (save-excursion (outline-next-heading) (point))))
8696 (if (re-search-forward org-scheduled-time-regexp end t)
8697 (org-time-string-to-seconds (match-string 1))
8698 (org-float-time now))))
8699 ((= dcst ?d)
8700 (let ((end (save-excursion (outline-next-heading) (point))))
8701 (if (re-search-forward org-deadline-time-regexp end t)
8702 (org-time-string-to-seconds (match-string 1))
8703 (org-float-time now))))
8704 ((= dcst ?p)
8705 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8706 (string-to-char (match-string 2))
8707 org-default-priority))
8708 ((= dcst ?r)
8709 (or (org-entry-get nil property) ""))
8710 ((= dcst ?o)
8711 (if (looking-at org-complex-heading-regexp)
8712 (- 9999 (length (member (match-string 2)
8713 org-todo-keywords-1)))))
8714 ((= dcst ?f)
8715 (if getkey-func
8716 (progn
8717 (setq tmp (funcall getkey-func))
8718 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8719 tmp)
8720 (error "Invalid key function `%s'" getkey-func)))
8721 (t (error "Invalid sorting type `%c'" sorting-type))))
8723 (cond
8724 ((= dcst ?a) 'string<)
8725 ((= dcst ?f) compare-func)
8726 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8727 (run-hooks 'org-after-sorting-entries-or-items-hook)
8728 ;; Reset the clock marker if needed
8729 (when cmstr
8730 (save-excursion
8731 (goto-char start)
8732 (search-forward cmstr nil t)
8733 (move-marker org-clock-marker (point))))
8734 (message "Sorting entries...done")))
8736 (defun org-do-sort (table what &optional with-case sorting-type)
8737 "Sort TABLE of WHAT according to SORTING-TYPE.
8738 The user will be prompted for the SORTING-TYPE if the call to this
8739 function does not specify it. WHAT is only for the prompt, to indicate
8740 what is being sorted. The sorting key will be extracted from
8741 the car of the elements of the table.
8742 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8743 (unless sorting-type
8744 (message
8745 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8746 what)
8747 (setq sorting-type (read-char-exclusive)))
8748 (let ((dcst (downcase sorting-type))
8749 extractfun comparefun)
8750 ;; Define the appropriate functions
8751 (cond
8752 ((= dcst ?n)
8753 (setq extractfun 'string-to-number
8754 comparefun (if (= dcst sorting-type) '< '>)))
8755 ((= dcst ?a)
8756 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8757 (lambda(x) (downcase (org-sort-remove-invisible x))))
8758 comparefun (if (= dcst sorting-type)
8759 'string<
8760 (lambda (a b) (and (not (string< a b))
8761 (not (string= a b)))))))
8762 ((= dcst ?t)
8763 (setq extractfun
8764 (lambda (x)
8765 (if (or (string-match org-ts-regexp x)
8766 (string-match org-ts-regexp-both x))
8767 (org-float-time
8768 (org-time-string-to-time (match-string 0 x)))
8770 comparefun (if (= dcst sorting-type) '< '>)))
8771 (t (error "Invalid sorting type `%c'" sorting-type)))
8773 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8774 table)
8775 (lambda (a b) (funcall comparefun (car a) (car b))))))
8778 ;;; The orgstruct minor mode
8780 ;; Define a minor mode which can be used in other modes in order to
8781 ;; integrate the org-mode structure editing commands.
8783 ;; This is really a hack, because the org-mode structure commands use
8784 ;; keys which normally belong to the major mode. Here is how it
8785 ;; works: The minor mode defines all the keys necessary to operate the
8786 ;; structure commands, but wraps the commands into a function which
8787 ;; tests if the cursor is currently at a headline or a plain list
8788 ;; item. If that is the case, the structure command is used,
8789 ;; temporarily setting many Org-mode variables like regular
8790 ;; expressions for filling etc. However, when any of those keys is
8791 ;; used at a different location, function uses `key-binding' to look
8792 ;; up if the key has an associated command in another currently active
8793 ;; keymap (minor modes, major mode, global), and executes that
8794 ;; command. There might be problems if any of the keys is otherwise
8795 ;; used as a prefix key.
8797 (defcustom orgstruct-heading-prefix-regexp nil
8798 "Regexp that matches the custom prefix of Org headlines in
8799 orgstruct(++)-mode."
8800 :group 'org
8801 :version "24.4"
8802 :package-version '(Org . "8.0")
8803 :type 'string)
8804 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8806 (defcustom orgstruct-setup-hook nil
8807 "Hook run after orgstruct-mode-map is filled."
8808 :group 'org
8809 :version "24.4"
8810 :package-version '(Org . "8.0")
8811 :type 'hook)
8813 (defvar orgstruct-initialized nil)
8815 (defvar org-local-vars nil
8816 "List of local variables, for use by `orgstruct-mode'.")
8818 ;;;###autoload
8819 (define-minor-mode orgstruct-mode
8820 "Toggle the minor mode `orgstruct-mode'.
8821 This mode is for using Org-mode structure commands in other
8822 modes. The following keys behave as if Org-mode were active, if
8823 the cursor is on a headline, or on a plain list item (both as
8824 defined by Org-mode)."
8825 nil " OrgStruct" (make-sparse-keymap)
8826 (funcall (if orgstruct-mode
8827 'add-to-invisibility-spec
8828 'remove-from-invisibility-spec)
8829 '(outline . t))
8830 (when orgstruct-mode
8831 (org-load-modules-maybe)
8832 (unless orgstruct-initialized
8833 (orgstruct-setup)
8834 (setq orgstruct-initialized t))))
8836 ;;;###autoload
8837 (defun turn-on-orgstruct ()
8838 "Unconditionally turn on `orgstruct-mode'."
8839 (orgstruct-mode 1))
8841 (defvar org-fb-vars nil)
8842 (make-variable-buffer-local 'org-fb-vars)
8843 (defun orgstruct++-mode (&optional arg)
8844 "Toggle `orgstruct-mode', the enhanced version of it.
8845 In addition to setting orgstruct-mode, this also exports all
8846 indentation and autofilling variables from org-mode into the
8847 buffer. It will also recognize item context in multiline items."
8848 (interactive "P")
8849 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8850 (if (< arg 1)
8851 (progn (orgstruct-mode -1)
8852 (mapc (lambda(v)
8853 (org-set-local (car v)
8854 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8855 org-fb-vars))
8856 (orgstruct-mode 1)
8857 (setq org-fb-vars nil)
8858 (let (var val)
8859 (mapc
8860 (lambda (x)
8861 (when (string-match
8862 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8863 (symbol-name (car x)))
8864 (setq var (car x) val (nth 1 x))
8865 (push (list var `(quote ,(eval var))) org-fb-vars)
8866 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8867 org-local-vars)
8868 (org-set-local 'orgstruct-is-++ t))))
8870 (defvar orgstruct-is-++ nil
8871 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8872 (make-variable-buffer-local 'orgstruct-is-++)
8874 ;;;###autoload
8875 (defun turn-on-orgstruct++ ()
8876 "Unconditionally turn on `orgstruct++-mode'."
8877 (orgstruct++-mode 1))
8879 (defun orgstruct-error ()
8880 "Error when there is no default binding for a structure key."
8881 (interactive)
8882 (funcall (if (fboundp 'user-error)
8883 'user-error
8884 'error)
8885 "This key has no function outside structure elements"))
8887 (defun orgstruct-setup ()
8888 "Setup orgstruct keymap."
8889 (dolist (cell '((org-demote . t)
8890 (org-metaleft . t)
8891 (org-metaright . t)
8892 (org-promote . t)
8893 (org-shiftmetaleft . t)
8894 (org-shiftmetaright . t)
8895 org-backward-element
8896 org-backward-heading-same-level
8897 org-ctrl-c-ret
8898 org-ctrl-c-minus
8899 org-ctrl-c-star
8900 org-cycle
8901 org-forward-heading-same-level
8902 org-insert-heading
8903 org-insert-heading-respect-content
8904 org-kill-note-or-show-branches
8905 org-mark-subtree
8906 org-meta-return
8907 org-metadown
8908 org-metaup
8909 org-narrow-to-subtree
8910 org-promote-subtree
8911 org-reveal
8912 org-shiftdown
8913 org-shiftleft
8914 org-shiftmetadown
8915 org-shiftmetaup
8916 org-shiftright
8917 org-shifttab
8918 org-shifttab
8919 org-shiftup
8920 org-show-subtree
8921 org-sort
8922 org-up-element
8923 outline-demote
8924 outline-next-visible-heading
8925 outline-previous-visible-heading
8926 outline-promote
8927 outline-up-heading
8928 show-children))
8929 (let ((f (or (car-safe cell) cell))
8930 (disable-when-heading-prefix (cdr-safe cell)))
8931 (when (fboundp f)
8932 (dolist (binding (nconc (where-is-internal f org-mode-map)
8933 (where-is-internal f outline-mode-map)))
8934 ;; TODO use local-function-key-map
8935 (dolist (rep '(("<tab>" . "TAB")
8936 ("<return>" . "RET")
8937 ("<escape>" . "ESC")
8938 ("<delete>" . "DEL")))
8939 (setq binding (read-kbd-macro
8940 (let ((case-fold-search))
8941 (replace-regexp-in-string
8942 (regexp-quote (cdr rep))
8943 (car rep)
8944 (key-description binding))))))
8945 (let ((key (lookup-key orgstruct-mode-map binding)))
8946 (when (or (not key) (numberp key))
8947 (condition-case nil
8948 (org-defkey orgstruct-mode-map
8949 binding
8950 (orgstruct-make-binding f binding disable-when-heading-prefix))
8951 (error nil))))))))
8952 (run-hooks 'orgstruct-setup-hook))
8954 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8955 "Create a function for binding in the structure minor mode.
8956 FUN is the command to call inside a table. KEY is the key that
8957 should be checked in for a command to execute outside of tables.
8958 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8959 if `orgstruct-heading-prefix-regexp' is non-nil."
8960 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8961 (let ((nname name)
8962 (i 0))
8963 (while (fboundp (intern nname))
8964 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8965 (setq name (intern nname)))
8966 (eval
8967 (let ((bindings '((org-heading-regexp
8968 (concat "^"
8969 orgstruct-heading-prefix-regexp
8970 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8971 (org-outline-regexp
8972 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8973 (org-outline-regexp-bol
8974 (concat "^" org-outline-regexp))
8975 (outline-regexp org-outline-regexp)
8976 (outline-heading-end-regexp "\n")
8977 (outline-level 'org-outline-level)
8978 (outline-heading-alist))))
8979 `(defun ,name (arg)
8980 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8981 "Outside of structure, run the binding of `"
8982 (key-description key) "'."
8983 (when disable-when-heading-prefix
8984 (concat
8985 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8986 "back to the default binding due to limitations of Org's implementation of\n"
8987 "`" (symbol-name fun) "'.")))
8988 (interactive "p")
8989 (let* ((disable
8990 ,(when disable-when-heading-prefix
8991 '(and orgstruct-heading-prefix-regexp
8992 (not (string= orgstruct-heading-prefix-regexp "")))))
8993 (fallback
8994 (or disable
8995 (not
8996 (let* ,bindings
8997 (org-context-p 'headline 'item
8998 ,(when (memq fun '(org-insert-heading))
8999 '(when orgstruct-is-++
9000 'item-body))))))))
9001 (if fallback
9002 (let* ((orgstruct-mode)
9003 (binding
9004 (loop with key = ,key
9005 for rep in
9006 '(nil
9007 ("<\\([^>]*\\)tab>" . "\\1TAB")
9008 ("<\\([^>]*\\)return>" . "\\1RET")
9009 ("<\\([^>]*\\)escape>" . "\\1ESC")
9010 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9012 (when rep
9013 (setq key (read-kbd-macro
9014 (let ((case-fold-search))
9015 (replace-regexp-in-string
9016 (car rep)
9017 (cdr rep)
9018 (key-description key))))))
9019 thereis (key-binding key))))
9020 (if (keymapp binding)
9021 (set-temporary-overlay-map binding)
9022 (let ((func (or binding
9023 (unless disable
9024 'orgstruct-error))))
9025 (when func
9026 (call-interactively func)))))
9027 (org-run-like-in-org-mode
9028 (lambda ()
9029 (interactive)
9030 (let* ,bindings
9031 (call-interactively ',fun)))))))))
9032 name))
9034 (defun org-contextualize-keys (alist contexts)
9035 "Return valid elements in ALIST depending on CONTEXTS.
9037 `org-agenda-custom-commands' or `org-capture-templates' are the
9038 values used for ALIST, and `org-agenda-custom-commands-contexts'
9039 or `org-capture-templates-contexts' are the associated contexts
9040 definitions."
9041 (let ((contexts
9042 ;; normalize contexts
9043 (mapcar
9044 (lambda(c) (cond ((listp (cadr c))
9045 (list (car c) (car c) (cadr c)))
9046 ((string= "" (cadr c))
9047 (list (car c) (car c) (caddr c)))
9048 (t c))) contexts))
9049 (a alist) c r s)
9050 ;; loop over all commands or templates
9051 (while (setq c (pop a))
9052 (let (vrules repl)
9053 (cond
9054 ((not (assoc (car c) contexts))
9055 (push c r))
9056 ((and (assoc (car c) contexts)
9057 (setq vrules (org-contextualize-validate-key
9058 (car c) contexts)))
9059 (mapc (lambda (vr)
9060 (when (not (equal (car vr) (cadr vr)))
9061 (setq repl vr))) vrules)
9062 (if (not repl) (push c r)
9063 (push (cadr repl) s)
9064 (push
9065 (cons (car c)
9066 (cdr (or (assoc (cadr repl) alist)
9067 (error "Undefined key `%s' as contextual replacement for `%s'"
9068 (cadr repl) (car c)))))
9069 r))))))
9070 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9071 (delq
9073 (delete-dups
9074 (mapcar (lambda (x)
9075 (let ((tpl (car x)))
9076 (when (not (delq
9078 (mapcar (lambda(y)
9079 (equal y tpl)) s))) x)))
9080 (reverse r))))))
9082 (defun org-contextualize-validate-key (key contexts)
9083 "Check CONTEXTS for agenda or capture KEY."
9084 (let (r rr res)
9085 (while (setq r (pop contexts))
9086 (mapc
9087 (lambda (rr)
9088 (when
9089 (and (equal key (car r))
9090 (if (functionp rr) (funcall rr)
9091 (or (and (eq (car rr) 'in-file)
9092 (buffer-file-name)
9093 (string-match (cdr rr) (buffer-file-name)))
9094 (and (eq (car rr) 'in-mode)
9095 (string-match (cdr rr) (symbol-name major-mode)))
9096 (and (eq (car rr) 'in-buffer)
9097 (string-match (cdr rr) (buffer-name)))
9098 (when (and (eq (car rr) 'not-in-file)
9099 (buffer-file-name))
9100 (not (string-match (cdr rr) (buffer-file-name))))
9101 (when (eq (car rr) 'not-in-mode)
9102 (not (string-match (cdr rr) (symbol-name major-mode))))
9103 (when (eq (car rr) 'not-in-buffer)
9104 (not (string-match (cdr rr) (buffer-name)))))))
9105 (push r res)))
9106 (car (last r))))
9107 (delete-dups (delq nil res))))
9109 (defun org-context-p (&rest contexts)
9110 "Check if local context is any of CONTEXTS.
9111 Possible values in the list of contexts are `table', `headline', and `item'."
9112 (let ((pos (point)))
9113 (goto-char (point-at-bol))
9114 (prog1 (or (and (memq 'table contexts)
9115 (looking-at "[ \t]*|"))
9116 (and (memq 'headline contexts)
9117 (looking-at org-outline-regexp))
9118 (and (memq 'item contexts)
9119 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9120 (and (memq 'item-body contexts)
9121 (org-in-item-p)))
9122 (goto-char pos))))
9124 (defun org-get-local-variables ()
9125 "Return a list of all local variables in an Org mode buffer."
9126 (let (varlist)
9127 (with-current-buffer (get-buffer-create "*Org tmp*")
9128 (erase-buffer)
9129 (org-mode)
9130 (setq varlist (buffer-local-variables)))
9131 (kill-buffer "*Org tmp*")
9132 (delq nil
9133 (mapcar
9134 (lambda (x)
9135 (setq x
9136 (if (symbolp x)
9137 (list x)
9138 (list (car x) (cdr x))))
9139 (if (and (not (get (car x) 'org-state))
9140 (string-match
9141 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9142 (symbol-name (car x))))
9143 x nil))
9144 varlist))))
9146 (defun org-clone-local-variables (from-buffer &optional regexp)
9147 "Clone local variables from FROM-BUFFER.
9148 Optional argument REGEXP selects variables to clone."
9149 (mapc
9150 (lambda (pair)
9151 (and (symbolp (car pair))
9152 (or (null regexp)
9153 (string-match regexp (symbol-name (car pair))))
9154 (set (make-local-variable (car pair))
9155 (cdr pair))))
9156 (buffer-local-variables from-buffer)))
9158 ;;;###autoload
9159 (defun org-run-like-in-org-mode (cmd)
9160 "Run a command, pretending that the current buffer is in Org-mode.
9161 This will temporarily bind local variables that are typically bound in
9162 Org-mode to the values they have in Org-mode, and then interactively
9163 call CMD."
9164 (org-load-modules-maybe)
9165 (unless org-local-vars
9166 (setq org-local-vars (org-get-local-variables)))
9167 (let (binds)
9168 (dolist (var org-local-vars)
9169 (when (or (not (boundp (car var)))
9170 (eq (symbol-value (car var))
9171 (default-value (car var))))
9172 (push (list (car var) `(quote ,(cadr var))) binds)))
9173 (eval `(let ,binds
9174 (call-interactively (quote ,cmd))))))
9176 ;;;; Archiving
9178 (defun org-get-category (&optional pos force-refresh)
9179 "Get the category applying to position POS."
9180 (save-match-data
9181 (if force-refresh (org-refresh-category-properties))
9182 (let ((pos (or pos (point))))
9183 (or (get-text-property pos 'org-category)
9184 (progn (org-refresh-category-properties)
9185 (get-text-property pos 'org-category))))))
9187 (defun org-refresh-category-properties ()
9188 "Refresh category text properties in the buffer."
9189 (let ((case-fold-search t)
9190 (inhibit-read-only t)
9191 (def-cat (cond
9192 ((null org-category)
9193 (if buffer-file-name
9194 (file-name-sans-extension
9195 (file-name-nondirectory buffer-file-name))
9196 "???"))
9197 ((symbolp org-category) (symbol-name org-category))
9198 (t org-category)))
9199 beg end cat pos optionp)
9200 (org-with-silent-modifications
9201 (save-excursion
9202 (save-restriction
9203 (widen)
9204 (goto-char (point-min))
9205 (put-text-property (point) (point-max) 'org-category def-cat)
9206 (while (re-search-forward
9207 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9208 (setq pos (match-end 0)
9209 optionp (equal (char-after (match-beginning 0)) ?#)
9210 cat (org-trim (match-string 2)))
9211 (if optionp
9212 (setq beg (point-at-bol) end (point-max))
9213 (org-back-to-heading t)
9214 (setq beg (point) end (org-end-of-subtree t t)))
9215 (put-text-property beg end 'org-category cat)
9216 (put-text-property beg end 'org-category-position beg)
9217 (goto-char pos)))))))
9219 (defun org-refresh-properties (dprop tprop)
9220 "Refresh buffer text properties.
9221 DPROP is the drawer property and TPROP is the corresponding text
9222 property to set."
9223 (let ((case-fold-search t)
9224 (inhibit-read-only t) p)
9225 (org-with-silent-modifications
9226 (save-excursion
9227 (save-restriction
9228 (widen)
9229 (goto-char (point-min))
9230 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9231 (setq p (org-match-string-no-properties 1))
9232 (save-excursion
9233 (org-back-to-heading t)
9234 (put-text-property
9235 (point-at-bol) (point-at-eol) tprop p))))))))
9238 ;;;; Link Stuff
9240 ;;; Link abbreviations
9242 (defun org-link-expand-abbrev (link)
9243 "Apply replacements as defined in `org-link-abbrev-alist'."
9244 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9245 (let* ((key (match-string 1 link))
9246 (as (or (assoc key org-link-abbrev-alist-local)
9247 (assoc key org-link-abbrev-alist)))
9248 (tag (and (match-end 2) (match-string 3 link)))
9249 rpl)
9250 (if (not as)
9251 link
9252 (setq rpl (cdr as))
9253 (cond
9254 ((symbolp rpl) (funcall rpl tag))
9255 ((string-match "%(\\([^)]+\\))" rpl)
9256 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9257 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9258 ((string-match "%h" rpl)
9259 (replace-match (url-hexify-string (or tag "")) t t rpl))
9260 (t (concat rpl tag)))))
9261 link))
9263 ;;; Storing and inserting links
9265 (defvar org-insert-link-history nil
9266 "Minibuffer history for links inserted with `org-insert-link'.")
9268 (defvar org-stored-links nil
9269 "Contains the links stored with `org-store-link'.")
9271 (defvar org-store-link-plist nil
9272 "Plist with info about the most recently link created with `org-store-link'.")
9274 (defvar org-link-protocols nil
9275 "Link protocols added to Org-mode using `org-add-link-type'.")
9277 (defvar org-store-link-functions nil
9278 "List of functions that are called to create and store a link.
9279 Each function will be called in turn until one returns a non-nil
9280 value. Each function should check if it is responsible for creating
9281 this link (for example by looking at the major mode).
9282 If not, it must exit and return nil.
9283 If yes, it should return a non-nil value after a calling
9284 `org-store-link-props' with a list of properties and values.
9285 Special properties are:
9287 :type The link prefix, like \"http\". This must be given.
9288 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9289 This is obligatory as well.
9290 :description Optional default description for the second pair
9291 of brackets in an Org-mode link. The user can still change
9292 this when inserting this link into an Org-mode buffer.
9294 In addition to these, any additional properties can be specified
9295 and then used in capture templates.")
9297 (defun org-add-link-type (type &optional follow export)
9298 "Add TYPE to the list of `org-link-types'.
9299 Re-compute all regular expressions depending on `org-link-types'
9301 FOLLOW and EXPORT are two functions.
9303 FOLLOW should take the link path as the single argument and do whatever
9304 is necessary to follow the link, for example find a file or display
9305 a mail message.
9307 EXPORT should format the link path for export to one of the export formats.
9308 It should be a function accepting three arguments:
9310 path the path of the link, the text after the prefix (like \"http:\")
9311 desc the description of the link, if any, or a description added by
9312 org-export-normalize-links if there is none
9313 format the export format, a symbol like `html' or `latex' or `ascii'..
9315 The function may use the FORMAT information to return different values
9316 depending on the format. The return value will be put literally into
9317 the exported file. If the return value is nil, this means Org should
9318 do what it normally does with links which do not have EXPORT defined.
9320 Org-mode has a built-in default for exporting links. If you are happy with
9321 this default, there is no need to define an export function for the link
9322 type. For a simple example of an export function, see `org-bbdb.el'."
9323 (add-to-list 'org-link-types type t)
9324 (org-make-link-regexps)
9325 (if (assoc type org-link-protocols)
9326 (setcdr (assoc type org-link-protocols) (list follow export))
9327 (push (list type follow export) org-link-protocols)))
9329 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9330 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9332 ;;;###autoload
9333 (defun org-store-link (arg)
9334 "\\<org-mode-map>Store an org-link to the current location.
9335 This link is added to `org-stored-links' and can later be inserted
9336 into an org-buffer with \\[org-insert-link].
9338 For some link types, a prefix arg is interpreted.
9339 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9340 For file links, arg negates `org-context-in-file-links'.
9342 A double prefix arg force skipping storing functions that are not
9343 part of Org's core.
9345 A triple prefix arg force storing a link for each line in the
9346 active region."
9347 (interactive "P")
9348 (org-load-modules-maybe)
9349 (if (and (equal arg '(64)) (org-region-active-p))
9350 (save-excursion
9351 (let ((end (region-end)))
9352 (goto-char (region-beginning))
9353 (set-mark (point))
9354 (while (< (point-at-eol) end)
9355 (move-end-of-line 1) (activate-mark)
9356 (let (current-prefix-arg)
9357 (call-interactively 'org-store-link))
9358 (move-beginning-of-line 2)
9359 (set-mark (point)))))
9360 (org-with-limited-levels
9361 (setq org-store-link-plist nil)
9362 (let (link cpltxt desc description search
9363 txt custom-id agenda-link sfuns sfunsn)
9364 (cond
9366 ;; Store a link using an external link type
9367 ((and (not (equal arg '(16)))
9368 (setq sfuns
9369 (delq
9370 nil (mapcar (lambda (f)
9371 (let (fs) (if (funcall f) (push f fs))))
9372 org-store-link-functions))
9373 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9374 (or (and (cdr sfuns)
9375 (funcall (intern
9376 (completing-read
9377 "Which function for creating the link? "
9378 sfunsn t (car sfunsn)))))
9379 (funcall (caar sfuns)))
9380 (setq link (plist-get org-store-link-plist :link)
9381 desc (or (plist-get org-store-link-plist
9382 :description) link))))
9384 ;; Store a link from a source code buffer
9385 ((org-src-edit-buffer-p)
9386 (let (label gc)
9387 (while (or (not label)
9388 (save-excursion
9389 (save-restriction
9390 (widen)
9391 (goto-char (point-min))
9392 (re-search-forward
9393 (regexp-quote (format org-coderef-label-format label))
9394 nil t))))
9395 (when label (message "Label exists already") (sit-for 2))
9396 (setq label (read-string "Code line label: " label)))
9397 (end-of-line 1)
9398 (setq link (format org-coderef-label-format label))
9399 (setq gc (- 79 (length link)))
9400 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9401 (insert link)
9402 (setq link (concat "(" label ")") desc nil)))
9404 ;; We are in the agenda, link to referenced location
9405 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9406 (let ((m (or (get-text-property (point) 'org-hd-marker)
9407 (get-text-property (point) 'org-marker))))
9408 (when m
9409 (org-with-point-at m
9410 (setq agenda-link
9411 (if (org-called-interactively-p 'any)
9412 (call-interactively 'org-store-link)
9413 (org-store-link nil)))))))
9415 ((eq major-mode 'calendar-mode)
9416 (let ((cd (calendar-cursor-to-date)))
9417 (setq link
9418 (format-time-string
9419 (car org-time-stamp-formats)
9420 (apply 'encode-time
9421 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9422 nil nil nil))))
9423 (org-store-link-props :type "calendar" :date cd)))
9425 ((eq major-mode 'help-mode)
9426 (setq link (concat "help:" (save-excursion
9427 (goto-char (point-min))
9428 (looking-at "^[^ ]+")
9429 (match-string 0))))
9430 (org-store-link-props :type "help"))
9432 ((eq major-mode 'w3-mode)
9433 (setq cpltxt (if (and (buffer-name)
9434 (not (string-match "Untitled" (buffer-name))))
9435 (buffer-name)
9436 (url-view-url t))
9437 link (url-view-url t))
9438 (org-store-link-props :type "w3" :url (url-view-url t)))
9440 ((eq major-mode 'image-mode)
9441 (setq cpltxt (concat "file:"
9442 (abbreviate-file-name buffer-file-name))
9443 link cpltxt)
9444 (org-store-link-props :type "image" :file buffer-file-name))
9446 ;; In dired, store a link to the file of the current line
9447 ((eq major-mode 'dired-mode)
9448 (let ((file (dired-get-filename nil t)))
9449 (setq file (if file
9450 (abbreviate-file-name
9451 (expand-file-name (dired-get-filename nil t)))
9452 ;; otherwise, no file so use current directory.
9453 default-directory))
9454 (setq cpltxt (concat "file:" file)
9455 link cpltxt)))
9457 ((setq search (run-hook-with-args-until-success
9458 'org-create-file-search-functions))
9459 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9460 "::" search))
9461 (setq cpltxt (or description link)))
9463 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9464 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9465 (cond
9466 ;; Store a link using the radio target at point
9467 ((org-in-regexp "<<\\(.*?\\)>>")
9468 (setq cpltxt
9469 (concat "file:"
9470 (abbreviate-file-name
9471 (buffer-file-name (buffer-base-buffer)))
9472 "::" (match-string 1))
9473 link cpltxt))
9474 ((and (featurep 'org-id)
9475 (or (eq org-id-link-to-org-use-id t)
9476 (and (org-called-interactively-p 'any)
9477 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9478 (and (eq org-id-link-to-org-use-id
9479 'create-if-interactive-and-no-custom-id)
9480 (not custom-id))))
9481 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9482 ;; Store a link using the ID at point
9483 (setq link (condition-case nil
9484 (prog1 (org-id-store-link)
9485 (setq desc (plist-get org-store-link-plist
9486 :description)))
9487 (error
9488 ;; Probably before first headline, link only to file
9489 (concat "file:"
9490 (abbreviate-file-name
9491 (buffer-file-name (buffer-base-buffer))))))))
9493 ;; Just link to current headline
9494 (setq cpltxt (concat "file:"
9495 (abbreviate-file-name
9496 (buffer-file-name (buffer-base-buffer)))))
9497 ;; Add a context search string
9498 (when (org-xor org-context-in-file-links arg)
9499 (let* ((ee (org-element-at-point))
9500 (et (org-element-type ee))
9501 (ev (plist-get (cadr ee) :value))
9502 (ek (plist-get (cadr ee) :key))
9503 (eok (and (stringp ek) (string-match "name" ek))))
9504 (setq txt (cond
9505 ((org-at-heading-p) nil)
9506 ((and (eq et 'keyword) eok) ev)
9507 ((org-region-active-p)
9508 (buffer-substring (region-beginning) (region-end)))))
9509 (when (or (null txt) (string-match "\\S-" txt))
9510 (setq cpltxt
9511 (concat cpltxt "::"
9512 (condition-case nil
9513 (org-make-org-heading-search-string txt)
9514 (error "")))
9515 desc (or (and (eq et 'keyword) eok ev)
9516 (nth 4 (ignore-errors (org-heading-components)))
9517 "NONE")))))
9518 (if (string-match "::\\'" cpltxt)
9519 (setq cpltxt (substring cpltxt 0 -2)))
9520 (setq link cpltxt))))
9522 ((buffer-file-name (buffer-base-buffer))
9523 ;; Just link to this file here.
9524 (setq cpltxt (concat "file:"
9525 (abbreviate-file-name
9526 (buffer-file-name (buffer-base-buffer)))))
9527 ;; Add a context string.
9528 (when (org-xor org-context-in-file-links arg)
9529 (setq txt (if (org-region-active-p)
9530 (buffer-substring (region-beginning) (region-end))
9531 (buffer-substring (point-at-bol) (point-at-eol))))
9532 ;; Only use search option if there is some text.
9533 (when (string-match "\\S-" txt)
9534 (setq cpltxt
9535 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9536 desc "NONE")))
9537 (setq link cpltxt))
9539 ((org-called-interactively-p 'interactive)
9540 (user-error "No method for storing a link from this buffer"))
9542 (t (setq link nil)))
9544 ;; We're done setting link and desc, clean up
9545 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9546 (setq link (or link cpltxt)
9547 desc (or desc cpltxt))
9548 (cond ((equal desc "NONE") (setq desc nil))
9549 ((string-match org-bracket-link-regexp desc)
9550 (setq desc
9551 (replace-regexp-in-string
9552 org-bracket-link-regexp
9553 (concat "\\3" (if (equal (length (match-string 0 desc))
9554 (length desc)) "*" "")) desc))))
9556 ;; Return the link
9557 (if (not (and (or (org-called-interactively-p 'any)
9558 executing-kbd-macro) link))
9559 (or agenda-link (and link (org-make-link-string link desc)))
9560 (push (list link desc) org-stored-links)
9561 (message "Stored: %s" (or desc link))
9562 (when custom-id
9563 (setq link (concat "file:" (abbreviate-file-name
9564 (buffer-file-name)) "::#" custom-id))
9565 (push (list link desc) org-stored-links)))))))
9567 (defun org-store-link-props (&rest plist)
9568 "Store link properties, extract names and addresses."
9569 (let (x adr)
9570 (when (setq x (plist-get plist :from))
9571 (setq adr (mail-extract-address-components x))
9572 (setq plist (plist-put plist :fromname (car adr)))
9573 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9574 (when (setq x (plist-get plist :to))
9575 (setq adr (mail-extract-address-components x))
9576 (setq plist (plist-put plist :toname (car adr)))
9577 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9578 (let ((from (plist-get plist :from))
9579 (to (plist-get plist :to)))
9580 (when (and from to org-from-is-user-regexp)
9581 (setq plist
9582 (plist-put plist :fromto
9583 (if (string-match org-from-is-user-regexp from)
9584 (concat "to %t")
9585 (concat "from %f"))))))
9586 (setq org-store-link-plist plist))
9588 (defun org-add-link-props (&rest plist)
9589 "Add these properties to the link property list."
9590 (let (key value)
9591 (while plist
9592 (setq key (pop plist) value (pop plist))
9593 (setq org-store-link-plist
9594 (plist-put org-store-link-plist key value)))))
9596 (defun org-email-link-description (&optional fmt)
9597 "Return the description part of an email link.
9598 This takes information from `org-store-link-plist' and formats it
9599 according to FMT (default from `org-email-link-description-format')."
9600 (setq fmt (or fmt org-email-link-description-format))
9601 (let* ((p org-store-link-plist)
9602 (to (plist-get p :toaddress))
9603 (from (plist-get p :fromaddress))
9604 (table
9605 (list
9606 (cons "%c" (plist-get p :fromto))
9607 (cons "%F" (plist-get p :from))
9608 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9609 (cons "%T" (plist-get p :to))
9610 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9611 (cons "%s" (plist-get p :subject))
9612 (cons "%d" (plist-get p :date))
9613 (cons "%m" (plist-get p :message-id)))))
9614 (when (string-match "%c" fmt)
9615 ;; Check if the user wrote this message
9616 (if (and org-from-is-user-regexp from to
9617 (save-match-data (string-match org-from-is-user-regexp from)))
9618 (setq fmt (replace-match "to %t" t t fmt))
9619 (setq fmt (replace-match "from %f" t t fmt))))
9620 (org-replace-escapes fmt table)))
9622 (defun org-make-org-heading-search-string (&optional string)
9623 "Make search string for the current headline or STRING."
9624 (let ((s (or string
9625 (and (derived-mode-p 'org-mode)
9626 (save-excursion
9627 (org-back-to-heading t)
9628 (org-element-property :raw-value (org-element-at-point))))))
9629 (lines org-context-in-file-links))
9630 (or string (setq s (concat "*" s))) ; Add * for headlines
9631 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9632 (when (and string (integerp lines) (> lines 0))
9633 (let ((slines (org-split-string s "\n")))
9634 (when (< lines (length slines))
9635 (setq s (mapconcat
9636 'identity
9637 (reverse (nthcdr (- (length slines) lines)
9638 (reverse slines))) "\n")))))
9639 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9641 (defun org-make-link-string (link &optional description)
9642 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9643 (unless (string-match "\\S-" link)
9644 (error "Empty link"))
9645 (when (and description
9646 (stringp description)
9647 (not (string-match "\\S-" description)))
9648 (setq description nil))
9649 (when (stringp description)
9650 ;; Remove brackets from the description, they are fatal.
9651 (while (string-match "\\[" description)
9652 (setq description (replace-match "{" t t description)))
9653 (while (string-match "\\]" description)
9654 (setq description (replace-match "}" t t description))))
9655 (when (equal link description)
9656 ;; No description needed, it is identical
9657 (setq description nil))
9658 (when (and (not description)
9659 (not (string-match (org-image-file-name-regexp) link))
9660 (not (equal link (org-link-escape link))))
9661 (setq description (org-extract-attributes link)))
9662 (setq link
9663 (cond ((string-match (org-image-file-name-regexp) link) link)
9664 ((string-match org-link-types-re link)
9665 (concat (match-string 1 link)
9666 (org-link-escape (substring link (match-end 1)))))
9667 (t (org-link-escape link))))
9668 (concat "[[" link "]"
9669 (if description (concat "[" description "]") "")
9670 "]"))
9672 (defconst org-link-escape-chars
9673 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9674 "List of characters that should be escaped in link.
9675 This is the list that is used for internal purposes.")
9677 (defconst org-link-escape-chars-browser
9678 '(?\ )
9679 "List of escapes for characters that are problematic in links.
9680 This is the list that is used before handing over to the browser.")
9682 (defun org-link-escape (text &optional table merge)
9683 "Return percent escaped representation of TEXT.
9684 TEXT is a string with the text to escape.
9685 Optional argument TABLE is a list with characters that should be
9686 escaped. When nil, `org-link-escape-chars' is used.
9687 If optional argument MERGE is set, merge TABLE into
9688 `org-link-escape-chars'."
9689 (cond
9690 ((and table merge)
9691 (mapc (lambda (defchr)
9692 (unless (member defchr table)
9693 (setq table (cons defchr table)))) org-link-escape-chars))
9694 ((null table)
9695 (setq table org-link-escape-chars)))
9696 (mapconcat
9697 (lambda (char)
9698 (if (or (member char table)
9699 (and (or (< char 32) (= char 37) (> char 126))
9700 org-url-hexify-p))
9701 (mapconcat (lambda (sequence-element)
9702 (format "%%%.2X" sequence-element))
9703 (or (encode-coding-char char 'utf-8)
9704 (error "Unable to percent escape character: %s"
9705 (char-to-string char))) "")
9706 (char-to-string char))) text ""))
9708 (defun org-link-unescape (str)
9709 "Unhex hexified Unicode strings as returned from the JavaScript function
9710 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9711 (unless (and (null str) (string= "" str))
9712 (let ((pos 0) (case-fold-search t) unhexed)
9713 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9714 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9715 (setq str (replace-match unhexed t t str))
9716 (setq pos (+ pos (length unhexed))))))
9717 str)
9719 (defun org-link-unescape-compound (hex)
9720 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9721 Note: this function also decodes single byte encodings like
9722 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9723 (save-match-data
9724 (let* ((bytes (cdr (split-string hex "%")))
9725 (ret "")
9726 (eat 0)
9727 (sum 0))
9728 (while bytes
9729 (let* ((val (string-to-number (pop bytes) 16))
9730 (shift-xor
9731 (if (= 0 eat)
9732 (cond
9733 ((>= val 252) (cons 6 252))
9734 ((>= val 248) (cons 5 248))
9735 ((>= val 240) (cons 4 240))
9736 ((>= val 224) (cons 3 224))
9737 ((>= val 192) (cons 2 192))
9738 (t (cons 0 0)))
9739 (cons 6 128))))
9740 (if (>= val 192) (setq eat (car shift-xor)))
9741 (setq val (logxor val (cdr shift-xor)))
9742 (setq sum (+ (lsh sum (car shift-xor)) val))
9743 (if (> eat 0) (setq eat (- eat 1)))
9744 (cond
9745 ((= 0 eat) ;multi byte
9746 (setq ret (concat ret (org-char-to-string sum)))
9747 (setq sum 0))
9748 ((not bytes) ; single byte(s)
9749 (setq ret (org-link-unescape-single-byte-sequence hex))))
9750 )) ;; end (while bytes
9751 ret )))
9753 (defun org-link-unescape-single-byte-sequence (hex)
9754 "Unhexify hex-encoded single byte character sequences."
9755 (mapconcat (lambda (byte)
9756 (char-to-string (string-to-number byte 16)))
9757 (cdr (split-string hex "%")) ""))
9759 (defun org-xor (a b)
9760 "Exclusive or."
9761 (if a (not b) b))
9763 (defun org-fixup-message-id-for-http (s)
9764 "Replace special characters in a message id, so it can be used in an http query."
9765 (when (string-match "%" s)
9766 (setq s (mapconcat (lambda (c)
9767 (if (eq c ?%)
9768 "%25"
9769 (char-to-string c)))
9770 s "")))
9771 (while (string-match "<" s)
9772 (setq s (replace-match "%3C" t t s)))
9773 (while (string-match ">" s)
9774 (setq s (replace-match "%3E" t t s)))
9775 (while (string-match "@" s)
9776 (setq s (replace-match "%40" t t s)))
9779 (defun org-link-prettify (link)
9780 "Return a human-readable representation of LINK.
9781 The car of LINK must be a raw link the cdr of LINK must be either
9782 a link description or nil."
9783 (let ((desc (or (cadr link) "<no description>")))
9784 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9785 "<" (car link) ">")))
9787 ;;;###autoload
9788 (defun org-insert-link-global ()
9789 "Insert a link like Org-mode does.
9790 This command can be called in any mode to insert a link in Org-mode syntax."
9791 (interactive)
9792 (org-load-modules-maybe)
9793 (org-run-like-in-org-mode 'org-insert-link))
9795 (defun org-insert-all-links (&optional keep)
9796 "Insert all links in `org-stored-links'."
9797 (interactive "P")
9798 (let ((links (copy-sequence org-stored-links)) l)
9799 (while (setq l (if keep (pop links) (pop org-stored-links)))
9800 (insert "- ")
9801 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9802 (insert "\n"))))
9804 (defun org-link-fontify-links-to-this-file ()
9805 "Fontify links to the current file in `org-stored-links'."
9806 (let ((f (buffer-file-name)) a b)
9807 (setq a (mapcar (lambda(l)
9808 (let ((ll (car l)))
9809 (when (and (string-match "^file:\\(.+\\)::" ll)
9810 (equal f (expand-file-name (match-string 1 ll))))
9811 ll)))
9812 org-stored-links))
9813 (when (featurep 'org-id)
9814 (setq b (mapcar (lambda(l)
9815 (let ((ll (car l)))
9816 (when (and (string-match "^id:\\(.+\\)$" ll)
9817 (equal f (expand-file-name
9818 (or (org-id-find-id-file
9819 (match-string 1 ll)) ""))))
9820 ll)))
9821 org-stored-links)))
9822 (mapcar (lambda(l)
9823 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9824 (delq nil (append a b)))))
9826 (defvar org-link-links-in-this-file nil)
9827 (defun org-insert-link (&optional complete-file link-location default-description)
9828 "Insert a link. At the prompt, enter the link.
9830 Completion can be used to insert any of the link protocol prefixes like
9831 http or ftp in use.
9833 The history can be used to select a link previously stored with
9834 `org-store-link'. When the empty string is entered (i.e. if you just
9835 press RET at the prompt), the link defaults to the most recently
9836 stored link. As SPC triggers completion in the minibuffer, you need to
9837 use M-SPC or C-q SPC to force the insertion of a space character.
9839 You will also be prompted for a description, and if one is given, it will
9840 be displayed in the buffer instead of the link.
9842 If there is already a link at point, this command will allow you to edit link
9843 and description parts.
9845 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9846 be selected using completion. The path to the file will be relative to the
9847 current directory if the file is in the current directory or a subdirectory.
9848 Otherwise, the link will be the absolute path as completed in the minibuffer
9849 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9850 option `org-link-file-path-type'.
9852 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9853 the current directory or below.
9855 With three \\[universal-argument] prefixes, negate the meaning of
9856 `org-keep-stored-link-after-insertion'.
9858 If `org-make-link-description-function' is non-nil, this function will be
9859 called with the link target, and the result will be the default
9860 link description.
9862 If the LINK-LOCATION parameter is non-nil, this value will be
9863 used as the link location instead of reading one interactively.
9865 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9866 be used as the default description."
9867 (interactive "P")
9868 (let* ((wcf (current-window-configuration))
9869 (origbuf (current-buffer))
9870 (region (if (org-region-active-p)
9871 (buffer-substring (region-beginning) (region-end))))
9872 (remove (and region (list (region-beginning) (region-end))))
9873 (desc region)
9874 tmphist ; byte-compile incorrectly complains about this
9875 (link link-location)
9876 (abbrevs org-link-abbrev-alist-local)
9877 entry file all-prefixes auto-desc)
9878 (cond
9879 (link-location) ; specified by arg, just use it.
9880 ((org-in-regexp org-bracket-link-regexp 1)
9881 ;; We do have a link at point, and we are going to edit it.
9882 (setq remove (list (match-beginning 0) (match-end 0)))
9883 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9884 (setq link (read-string "Link: "
9885 (org-link-unescape
9886 (org-match-string-no-properties 1)))))
9887 ((or (org-in-regexp org-angle-link-re)
9888 (org-in-regexp org-plain-link-re))
9889 ;; Convert to bracket link
9890 (setq remove (list (match-beginning 0) (match-end 0))
9891 link (read-string "Link: "
9892 (org-remove-angle-brackets (match-string 0)))))
9893 ((member complete-file '((4) (16)))
9894 ;; Completing read for file names.
9895 (setq link (org-file-complete-link complete-file)))
9897 ;; Read link, with completion for stored links.
9898 (org-link-fontify-links-to-this-file)
9899 (org-switch-to-buffer-other-window "*Org Links*")
9900 (with-current-buffer "*Org Links*"
9901 (erase-buffer)
9902 (insert "Insert a link.
9903 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9904 (when org-stored-links
9905 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9906 (insert (mapconcat 'org-link-prettify
9907 (reverse org-stored-links) "\n")))
9908 (goto-char (point-min)))
9909 (let ((cw (selected-window)))
9910 (select-window (get-buffer-window "*Org Links*" 'visible))
9911 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9912 (unless (pos-visible-in-window-p (point-max))
9913 (org-fit-window-to-buffer))
9914 (and (window-live-p cw) (select-window cw)))
9915 ;; Fake a link history, containing the stored links.
9916 (setq tmphist (append (mapcar 'car org-stored-links)
9917 org-insert-link-history))
9918 (setq all-prefixes (append (mapcar 'car abbrevs)
9919 (mapcar 'car org-link-abbrev-alist)
9920 org-link-types))
9921 (unwind-protect
9922 (progn
9923 (setq link
9924 (org-completing-read
9925 "Link: "
9926 (append
9927 (mapcar (lambda (x) (concat x ":"))
9928 all-prefixes)
9929 (mapcar 'car org-stored-links))
9930 nil nil nil
9931 'tmphist
9932 (caar org-stored-links)))
9933 (if (not (string-match "\\S-" link))
9934 (error "No link selected"))
9935 (mapc (lambda(l)
9936 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9937 org-stored-links)
9938 (if (or (member link all-prefixes)
9939 (and (equal ":" (substring link -1))
9940 (member (substring link 0 -1) all-prefixes)
9941 (setq link (substring link 0 -1))))
9942 (setq link (with-current-buffer origbuf
9943 (org-link-try-special-completion link)))))
9944 (set-window-configuration wcf)
9945 (kill-buffer "*Org Links*"))
9946 (setq entry (assoc link org-stored-links))
9947 (or entry (push link org-insert-link-history))
9948 (setq desc (or desc (nth 1 entry)))))
9950 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9951 (not org-keep-stored-link-after-insertion))
9952 (setq org-stored-links (delq (assoc link org-stored-links)
9953 org-stored-links)))
9955 (if (string-match org-plain-link-re link)
9956 ;; URL-like link, normalize the use of angular brackets.
9957 (setq link (org-remove-angle-brackets link)))
9959 ;; Check if we are linking to the current file with a search
9960 ;; option If yes, simplify the link by using only the search
9961 ;; option.
9962 (when (and buffer-file-name
9963 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9964 (let* ((path (match-string 1 link))
9965 (case-fold-search nil)
9966 (search (match-string 2 link)))
9967 (save-match-data
9968 (if (equal (file-truename buffer-file-name) (file-truename path))
9969 ;; We are linking to this same file, with a search option
9970 (setq link search)))))
9972 ;; Check if we can/should use a relative path. If yes, simplify the link
9973 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9974 (let* ((type (match-string 1 link))
9975 (path (match-string 2 link))
9976 (origpath path)
9977 (case-fold-search nil))
9978 (cond
9979 ((or (eq org-link-file-path-type 'absolute)
9980 (equal complete-file '(16)))
9981 (setq path (abbreviate-file-name (expand-file-name path))))
9982 ((eq org-link-file-path-type 'noabbrev)
9983 (setq path (expand-file-name path)))
9984 ((eq org-link-file-path-type 'relative)
9985 (setq path (file-relative-name path)))
9987 (save-match-data
9988 (if (string-match (concat "^" (regexp-quote
9989 (expand-file-name
9990 (file-name-as-directory
9991 default-directory))))
9992 (expand-file-name path))
9993 ;; We are linking a file with relative path name.
9994 (setq path (substring (expand-file-name path)
9995 (match-end 0)))
9996 (setq path (abbreviate-file-name (expand-file-name path)))))))
9997 (setq link (concat type path))
9998 (if (equal desc origpath)
9999 (setq desc path))))
10001 (if org-make-link-description-function
10002 (setq desc
10003 (or (condition-case nil
10004 (funcall org-make-link-description-function link desc)
10005 (error (progn (message "Can't get link description from `%s'"
10006 (symbol-name org-make-link-description-function))
10007 (sit-for 2) nil)))
10008 (read-string "Description: " default-description)))
10009 (if default-description (setq desc default-description)
10010 (setq desc (or (and auto-desc desc)
10011 (read-string "Description: " desc)))))
10013 (unless (string-match "\\S-" desc) (setq desc nil))
10014 (if remove (apply 'delete-region remove))
10015 (insert (org-make-link-string link desc))))
10017 (defun org-link-try-special-completion (type)
10018 "If there is completion support for link type TYPE, offer it."
10019 (let ((fun (intern (concat "org-" type "-complete-link"))))
10020 (if (functionp fun)
10021 (funcall fun)
10022 (read-string "Link (no completion support): " (concat type ":")))))
10024 (defun org-file-complete-link (&optional arg)
10025 "Create a file link using completion."
10026 (let (file link)
10027 (setq file (org-iread-file-name "File: "))
10028 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10029 (pwd1 (file-name-as-directory (abbreviate-file-name
10030 (expand-file-name ".")))))
10031 (cond
10032 ((equal arg '(16))
10033 (setq link (concat
10034 "file:"
10035 (abbreviate-file-name (expand-file-name file)))))
10036 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10037 (setq link (concat "file:" (match-string 1 file))))
10038 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10039 (expand-file-name file))
10040 (setq link (concat
10041 "file:" (match-string 1 (expand-file-name file)))))
10042 (t (setq link (concat "file:" file)))))
10043 link))
10045 (defun org-iread-file-name (&rest args)
10046 "Read-file-name using `ido-mode' speedup if available.
10047 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10048 See `read-file-name' for a description of parameters."
10049 (org-without-partial-completion
10050 (if (and org-completion-use-ido
10051 (fboundp 'ido-read-file-name)
10052 (boundp 'ido-mode) ido-mode
10053 (listp (second args)))
10054 (let ((ido-enter-matching-directory nil))
10055 (apply 'ido-read-file-name args))
10056 (apply 'read-file-name args))))
10058 (defun org-completing-read (&rest args)
10059 "Completing-read with SPACE being a normal character."
10060 (let ((enable-recursive-minibuffers t)
10061 (minibuffer-local-completion-map
10062 (copy-keymap minibuffer-local-completion-map)))
10063 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10064 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10065 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10066 (apply 'org-icompleting-read args)))
10068 (defun org-completing-read-no-i (&rest args)
10069 (let (org-completion-use-ido org-completion-use-iswitchb)
10070 (apply 'org-completing-read args)))
10072 (defun org-iswitchb-completing-read (prompt choices &rest args)
10073 "Use iswitch as a completing-read replacement to choose from choices.
10074 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10075 from."
10076 (let* ((iswitchb-use-virtual-buffers nil)
10077 (iswitchb-make-buflist-hook
10078 (lambda ()
10079 (setq iswitchb-temp-buflist choices))))
10080 (iswitchb-read-buffer prompt)))
10082 (defun org-icompleting-read (&rest args)
10083 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10084 (org-without-partial-completion
10085 (if (and org-completion-use-ido
10086 (fboundp 'ido-completing-read)
10087 (boundp 'ido-mode) ido-mode
10088 (listp (second args)))
10089 (let ((ido-enter-matching-directory nil))
10090 (apply 'ido-completing-read (concat (car args))
10091 (if (consp (car (nth 1 args)))
10092 (mapcar 'car (nth 1 args))
10093 (nth 1 args))
10094 (cddr args)))
10095 (if (and org-completion-use-iswitchb
10096 (boundp 'iswitchb-mode) iswitchb-mode
10097 (listp (second args)))
10098 (apply 'org-iswitchb-completing-read (concat (car args))
10099 (if (consp (car (nth 1 args)))
10100 (mapcar 'car (nth 1 args))
10101 (nth 1 args))
10102 (cddr args))
10103 (apply 'completing-read args)))))
10105 (defun org-extract-attributes (s)
10106 "Extract the attributes cookie from a string and set as text property."
10107 (let (a attr (start 0) key value)
10108 (save-match-data
10109 (when (string-match "{{\\([^}]+\\)}}$" s)
10110 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10111 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10112 (setq key (match-string 1 a) value (match-string 2 a)
10113 start (match-end 0)
10114 attr (plist-put attr (intern key) value))))
10115 (org-add-props s nil 'org-attr attr))
10118 ;;; Opening/following a link
10120 (defvar org-link-search-failed nil)
10122 (defvar org-open-link-functions nil
10123 "Hook for functions finding a plain text link.
10124 These functions must take a single argument, the link content.
10125 They will be called for links that look like [[link text][description]]
10126 when LINK TEXT does not have a protocol like \"http:\" and does not look
10127 like a filename (e.g. \"./blue.png\").
10129 These functions will be called *before* Org attempts to resolve the
10130 link by doing text searches in the current buffer - so if you want a
10131 link \"[[target]]\" to still find \"<<target>>\", your function should
10132 handle this as a special case.
10134 When the function does handle the link, it must return a non-nil value.
10135 If it decides that it is not responsible for this link, it must return
10136 nil to indicate that that Org-mode can continue with other options
10137 like exact and fuzzy text search.")
10139 (defun org-next-link (&optional search-backward)
10140 "Move forward to the next link.
10141 If the link is in hidden text, expose it."
10142 (interactive "P")
10143 (when (and org-link-search-failed (eq this-command last-command))
10144 (goto-char (point-min))
10145 (message "Link search wrapped back to beginning of buffer"))
10146 (setq org-link-search-failed nil)
10147 (let* ((pos (point))
10148 (ct (org-context))
10149 (a (assoc :link ct))
10150 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10151 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10152 ((looking-at org-any-link-re)
10153 ;; Don't stay stuck at link without an org-link face
10154 (forward-char (if search-backward -1 1))))
10155 (if (funcall srch-fun org-any-link-re nil t)
10156 (progn
10157 (goto-char (match-beginning 0))
10158 (if (outline-invisible-p) (org-show-context)))
10159 (goto-char pos)
10160 (setq org-link-search-failed t)
10161 (message "No further link found"))))
10163 (defun org-previous-link ()
10164 "Move backward to the previous link.
10165 If the link is in hidden text, expose it."
10166 (interactive)
10167 (funcall 'org-next-link t))
10169 (defun org-translate-link (s)
10170 "Translate a link string if a translation function has been defined."
10171 (if (and org-link-translation-function
10172 (fboundp org-link-translation-function)
10173 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10174 (progn
10175 (setq s (funcall org-link-translation-function
10176 (match-string 1 s) (match-string 2 s)))
10177 (concat (car s) ":" (cdr s)))
10180 (defun org-translate-link-from-planner (type path)
10181 "Translate a link from Emacs Planner syntax so that Org can follow it.
10182 This is still an experimental function, your mileage may vary."
10183 (cond
10184 ((member type '("http" "https" "news" "ftp"))
10185 ;; standard Internet links are the same.
10186 nil)
10187 ((and (equal type "irc") (string-match "^//" path))
10188 ;; Planner has two / at the beginning of an irc link, we have 1.
10189 ;; We should have zero, actually....
10190 (setq path (substring path 1)))
10191 ((and (equal type "lisp") (string-match "^/" path))
10192 ;; Planner has a slash, we do not.
10193 (setq type "elisp" path (substring path 1)))
10194 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10195 ;; A typical message link. Planner has the id after the final slash,
10196 ;; we separate it with a hash mark
10197 (setq path (concat (match-string 1 path) "#"
10198 (org-remove-angle-brackets (match-string 2 path))))))
10199 (cons type path))
10201 (defun org-find-file-at-mouse (ev)
10202 "Open file link or URL at mouse."
10203 (interactive "e")
10204 (mouse-set-point ev)
10205 (org-open-at-point 'in-emacs))
10207 (defun org-open-at-mouse (ev)
10208 "Open file link or URL at mouse.
10209 See the docstring of `org-open-file' for details."
10210 (interactive "e")
10211 (mouse-set-point ev)
10212 (if (eq major-mode 'org-agenda-mode)
10213 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10214 (org-open-at-point))
10216 (defvar org-window-config-before-follow-link nil
10217 "The window configuration before following a link.
10218 This is saved in case the need arises to restore it.")
10220 (defvar org-open-link-marker (make-marker)
10221 "Marker pointing to the location where `org-open-at-point; was called.")
10223 ;;;###autoload
10224 (defun org-open-at-point-global ()
10225 "Follow a link like Org-mode does.
10226 This command can be called in any mode to follow a link that has
10227 Org-mode syntax."
10228 (interactive)
10229 (org-run-like-in-org-mode 'org-open-at-point))
10231 ;;;###autoload
10232 (defun org-open-link-from-string (s &optional arg reference-buffer)
10233 "Open a link in the string S, as if it was in Org-mode."
10234 (interactive "sLink: \nP")
10235 (let ((reference-buffer (or reference-buffer (current-buffer))))
10236 (with-temp-buffer
10237 (let ((org-inhibit-startup (not reference-buffer)))
10238 (org-mode)
10239 (insert s)
10240 (goto-char (point-min))
10241 (when reference-buffer
10242 (setq org-link-abbrev-alist-local
10243 (with-current-buffer reference-buffer
10244 org-link-abbrev-alist-local)))
10245 (org-open-at-point arg reference-buffer)))))
10247 (defvar org-open-at-point-functions nil
10248 "Hook that is run when following a link at point.
10250 Functions in this hook must return t if they identify and follow
10251 a link at point. If they don't find anything interesting at point,
10252 they must return nil.")
10254 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10255 (defun org-open-at-point (&optional arg reference-buffer)
10256 "Open link at or after point.
10257 If there is no link at point, this function will search forward up to
10258 the end of the current line.
10259 Normally, files will be opened by an appropriate application. If the
10260 optional prefix argument ARG is non-nil, Emacs will visit the file.
10261 With a double prefix argument, try to open outside of Emacs, in the
10262 application the system uses for this file type."
10263 (interactive "P")
10264 ;; if in a code block, then open the block's results
10265 (unless (call-interactively #'org-babel-open-src-block-result)
10266 (org-load-modules-maybe)
10267 (move-marker org-open-link-marker (point))
10268 (setq org-window-config-before-follow-link (current-window-configuration))
10269 (org-remove-occur-highlights nil nil t)
10270 (cond
10271 ((and (org-at-heading-p)
10272 (not (org-at-timestamp-p t))
10273 (not (org-in-regexp
10274 (concat org-plain-link-re "\\|"
10275 org-bracket-link-regexp "\\|"
10276 org-angle-link-re "\\|"
10277 "[ \t]:[^ \t\n]+:[ \t]*$")))
10278 (not (get-text-property (point) 'org-linked-text)))
10279 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10280 (lk0 (car lkall))
10281 (lk (if (stringp lk0) (list lk0) lk0))
10282 (lkend (cdr lkall)))
10283 (mapcar (lambda(l)
10284 (search-forward l nil lkend)
10285 (goto-char (match-beginning 0))
10286 (org-open-at-point))
10287 lk))
10288 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10289 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10290 ((and (org-at-timestamp-p t)
10291 (not (org-in-regexp org-bracket-link-regexp)))
10292 (org-follow-timestamp-link))
10293 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10294 (not (org-in-regexp org-any-link-re)))
10295 (org-footnote-action))
10297 (let (type path link line search (pos (point)))
10298 (catch 'match
10299 (save-excursion
10300 (skip-chars-forward "^]\n\r")
10301 (when (org-in-regexp org-bracket-link-regexp 1)
10302 (setq link (org-extract-attributes
10303 (org-link-unescape (org-match-string-no-properties 1))))
10304 (while (string-match " *\n *" link)
10305 (setq link (replace-match " " t t link)))
10306 (setq link (org-link-expand-abbrev link))
10307 (cond
10308 ((or (file-name-absolute-p link)
10309 (string-match "^\\.\\.?/" link))
10310 (setq type "file" path link))
10311 ((string-match org-link-re-with-space3 link)
10312 (setq type (match-string 1 link) path (match-string 2 link)))
10313 ((string-match "^help:+\\(.+\\)" link)
10314 (setq type "help" path (match-string 1 link)))
10315 (t (setq type "thisfile" path link)))
10316 (throw 'match t)))
10318 (when (get-text-property (point) 'org-linked-text)
10319 (setq type "thisfile"
10320 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10321 (1+ (point)) (point))
10322 path (buffer-substring
10323 (or (previous-single-property-change pos 'org-linked-text)
10324 (point-min))
10325 (or (next-single-property-change pos 'org-linked-text)
10326 (point-max))))
10327 (throw 'match t))
10329 (save-excursion
10330 (when (or (org-in-regexp org-angle-link-re)
10331 (let ((match (org-in-regexp org-plain-link-re)))
10332 ;; Check a plain link is not within a bracket link
10333 (and match
10334 (save-excursion
10335 (progn
10336 (goto-char (car match))
10337 (not (org-in-regexp org-bracket-link-regexp))))))
10338 (let ((line_ending (save-excursion (end-of-line) (point))))
10339 ;; We are in a line before a plain or bracket link
10340 (or (re-search-forward org-plain-link-re line_ending t)
10341 (re-search-forward org-bracket-link-regexp line_ending t))))
10342 (setq type (match-string 1)
10343 path (org-link-unescape (match-string 2)))
10344 (throw 'match t)))
10345 (save-excursion
10346 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10347 (setq type "tags"
10348 path (match-string 1))
10349 (while (string-match ":" path)
10350 (setq path (replace-match "+" t t path)))
10351 (throw 'match t)))
10352 (when (org-in-regexp "<\\([^><\n]+\\)>")
10353 (setq type "tree-match"
10354 path (match-string 1))
10355 (throw 'match t)))
10356 (unless path
10357 (user-error "No link found"))
10359 ;; switch back to reference buffer
10360 ;; needed when if called in a temporary buffer through
10361 ;; org-open-link-from-string
10362 (with-current-buffer (or reference-buffer (current-buffer))
10364 ;; Remove any trailing spaces in path
10365 (if (string-match " +\\'" path)
10366 (setq path (replace-match "" t t path)))
10367 (if (and org-link-translation-function
10368 (fboundp org-link-translation-function))
10369 ;; Check if we need to translate the link
10370 (let ((tmp (funcall org-link-translation-function type path)))
10371 (setq type (car tmp) path (cdr tmp))))
10373 (cond
10375 ((assoc type org-link-protocols)
10376 (funcall (nth 1 (assoc type org-link-protocols)) path))
10378 ((equal type "help")
10379 (let ((f-or-v (intern path)))
10380 (cond ((fboundp f-or-v)
10381 (describe-function f-or-v))
10382 ((boundp f-or-v)
10383 (describe-variable f-or-v))
10384 (t (error "Not a known function or variable")))))
10386 ((equal type "mailto")
10387 (let ((cmd (car org-link-mailto-program))
10388 (args (cdr org-link-mailto-program)) args1
10389 (address path) (subject "") a)
10390 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10391 (setq address (match-string 1 path)
10392 subject (org-link-escape (match-string 2 path))))
10393 (while args
10394 (cond
10395 ((not (stringp (car args))) (push (pop args) args1))
10396 (t (setq a (pop args))
10397 (if (string-match "%a" a)
10398 (setq a (replace-match address t t a)))
10399 (if (string-match "%s" a)
10400 (setq a (replace-match subject t t a)))
10401 (push a args1))))
10402 (apply cmd (nreverse args1))))
10404 ((member type '("http" "https" "ftp" "news"))
10405 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10406 (org-link-escape
10407 path org-link-escape-chars-browser)
10408 path))))
10410 ((string= type "doi")
10411 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10412 (org-link-escape
10413 path org-link-escape-chars-browser)
10414 path))))
10416 ((member type '("message"))
10417 (browse-url (concat type ":" path)))
10419 ((string= type "tags")
10420 (org-tags-view arg path))
10422 ((string= type "tree-match")
10423 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10425 ((string= type "file")
10426 (if (string-match "::\\([0-9]+\\)\\'" path)
10427 (setq line (string-to-number (match-string 1 path))
10428 path (substring path 0 (match-beginning 0)))
10429 (if (string-match "::\\(.+\\)\\'" path)
10430 (setq search (match-string 1 path)
10431 path (substring path 0 (match-beginning 0)))))
10432 (if (string-match "[*?{]" (file-name-nondirectory path))
10433 (dired path)
10434 (org-open-file path arg line search)))
10436 ((string= type "shell")
10437 (let ((buf (generate-new-buffer "*Org Shell Output"))
10438 (cmd path))
10439 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10440 (string-match org-confirm-shell-link-not-regexp cmd))
10441 (not org-confirm-shell-link-function)
10442 (funcall org-confirm-shell-link-function
10443 (format "Execute \"%s\" in shell? "
10444 (org-add-props cmd nil
10445 'face 'org-warning))))
10446 (progn
10447 (message "Executing %s" cmd)
10448 (shell-command cmd buf)
10449 (if (featurep 'midnight)
10450 (setq clean-buffer-list-kill-buffer-names
10451 (cons buf clean-buffer-list-kill-buffer-names))))
10452 (error "Abort"))))
10454 ((string= type "elisp")
10455 (let ((cmd path))
10456 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10457 (string-match org-confirm-elisp-link-not-regexp cmd))
10458 (not org-confirm-elisp-link-function)
10459 (funcall org-confirm-elisp-link-function
10460 (format "Execute \"%s\" as elisp? "
10461 (org-add-props cmd nil
10462 'face 'org-warning))))
10463 (message "%s => %s" cmd
10464 (if (equal (string-to-char cmd) ?\()
10465 (eval (read cmd))
10466 (call-interactively (read cmd))))
10467 (error "Abort"))))
10469 ((and (string= type "thisfile")
10470 (run-hook-with-args-until-success
10471 'org-open-link-functions path)))
10473 ((string= type "thisfile")
10474 (if arg
10475 (switch-to-buffer-other-window
10476 (org-get-buffer-for-internal-link (current-buffer)))
10477 (org-mark-ring-push))
10478 (let ((cmd `(org-link-search
10479 ,path
10480 ,(cond ((equal arg '(4)) ''occur)
10481 ((equal arg '(16)) ''org-occur))
10482 ,pos)))
10483 (condition-case nil (let ((org-link-search-inhibit-query t))
10484 (eval cmd))
10485 (error (progn (widen) (eval cmd))))))
10487 (t (browse-url-at-point)))))))
10488 (move-marker org-open-link-marker nil)
10489 (run-hook-with-args 'org-follow-link-hook)))
10491 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10492 "Offer links in the current entry and return the selected link.
10493 If there is only one link, return it.
10494 If NTH is an integer, return the NTH link found.
10495 If ZERO is a string, check also this string for a link, and if
10496 there is one, return it."
10497 (with-current-buffer buffer
10498 (save-excursion
10499 (save-restriction
10500 (widen)
10501 (goto-char marker)
10502 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10503 "\\(" org-angle-link-re "\\)\\|"
10504 "\\(" org-plain-link-re "\\)"))
10505 (cnt ?0)
10506 (in-emacs (if (integerp nth) nil nth))
10507 have-zero end links link c)
10508 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10509 (push (match-string 0 zero) links)
10510 (setq cnt (1- cnt) have-zero t))
10511 (save-excursion
10512 (org-back-to-heading t)
10513 (setq end (save-excursion (outline-next-heading) (point)))
10514 (while (re-search-forward re end t)
10515 (push (match-string 0) links))
10516 (setq links (org-uniquify (reverse links))))
10517 (cond
10518 ((null links)
10519 (message "No links"))
10520 ((equal (length links) 1)
10521 (setq link (car links)))
10522 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10523 (setq link (nth (if have-zero nth (1- nth)) links)))
10524 (t ; we have to select a link
10525 (save-excursion
10526 (save-window-excursion
10527 (delete-other-windows)
10528 (with-output-to-temp-buffer "*Select Link*"
10529 (mapc (lambda (l)
10530 (if (not (string-match org-bracket-link-regexp l))
10531 (princ (format "[%c] %s\n" (incf cnt)
10532 (org-remove-angle-brackets l)))
10533 (if (match-end 3)
10534 (princ (format "[%c] %s (%s)\n" (incf cnt)
10535 (match-string 3 l) (match-string 1 l)))
10536 (princ (format "[%c] %s\n" (incf cnt)
10537 (match-string 1 l))))))
10538 links))
10539 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10540 (message "Select link to open, RET to open all:")
10541 (setq c (read-char-exclusive))
10542 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10543 (when (equal c ?q) (error "Abort"))
10544 (if (equal c ?\C-m)
10545 (setq link links)
10546 (setq nth (- c ?0))
10547 (if have-zero (setq nth (1+ nth)))
10548 (unless (and (integerp nth) (>= (length links) nth))
10549 (error "Invalid link selection"))
10550 (setq link (nth (1- nth) links)))))
10551 (cons link end))))))
10553 ;; Add special file links that specify the way of opening
10555 (org-add-link-type "file+sys" 'org-open-file-with-system)
10556 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10557 (defun org-open-file-with-system (path)
10558 "Open file at PATH using the system way of opening it."
10559 (org-open-file path 'system))
10560 (defun org-open-file-with-emacs (path)
10561 "Open file at PATH in Emacs."
10562 (org-open-file path 'emacs))
10565 ;;; File search
10567 (defvar org-create-file-search-functions nil
10568 "List of functions to construct the right search string for a file link.
10569 These functions are called in turn with point at the location to
10570 which the link should point.
10572 A function in the hook should first test if it would like to
10573 handle this file type, for example by checking the `major-mode'
10574 or the file extension. If it decides not to handle this file, it
10575 should just return nil to give other functions a chance. If it
10576 does handle the file, it must return the search string to be used
10577 when following the link. The search string will be part of the
10578 file link, given after a double colon, and `org-open-at-point'
10579 will automatically search for it. If special measures must be
10580 taken to make the search successful, another function should be
10581 added to the companion hook `org-execute-file-search-functions',
10582 which see.
10584 A function in this hook may also use `setq' to set the variable
10585 `description' to provide a suggestion for the descriptive text to
10586 be used for this link when it gets inserted into an Org-mode
10587 buffer with \\[org-insert-link].")
10589 (defvar org-execute-file-search-functions nil
10590 "List of functions to execute a file search triggered by a link.
10592 Functions added to this hook must accept a single argument, the
10593 search string that was part of the file link, the part after the
10594 double colon. The function must first check if it would like to
10595 handle this search, for example by checking the `major-mode' or
10596 the file extension. If it decides not to handle this search, it
10597 should just return nil to give other functions a chance. If it
10598 does handle the search, it must return a non-nil value to keep
10599 other functions from trying.
10601 Each function can access the current prefix argument through the
10602 variable `current-prefix-arg'. Note that a single prefix is used
10603 to force opening a link in Emacs, so it may be good to only use a
10604 numeric or double prefix to guide the search function.
10606 In case this is needed, a function in this hook can also restore
10607 the window configuration before `org-open-at-point' was called using:
10609 (set-window-configuration org-window-config-before-follow-link)")
10611 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10612 (defun org-link-search (s &optional type avoid-pos stealth)
10613 "Search for a link search option.
10614 If S is surrounded by forward slashes, it is interpreted as a
10615 regular expression. In org-mode files, this will create an `org-occur'
10616 sparse tree. In ordinary files, `occur' will be used to list matches.
10617 If the current buffer is in `dired-mode', grep will be used to search
10618 in all files. If AVOID-POS is given, ignore matches near that position.
10620 When optional argument STEALTH is non-nil, do not modify
10621 visibility around point, thus ignoring
10622 `org-show-hierarchy-above', `org-show-following-heading' and
10623 `org-show-siblings' variables."
10624 (let ((case-fold-search t)
10625 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10626 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10627 (append '(("") (" ") ("\t") ("\n"))
10628 org-emphasis-alist)
10629 "\\|") "\\)"))
10630 (pos (point))
10631 (pre nil) (post nil)
10632 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10633 (cond
10634 ;; First check if there are any special search functions
10635 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10636 ;; Now try the builtin stuff
10637 ((and (equal (string-to-char s0) ?#)
10638 (> (length s0) 1)
10639 (save-excursion
10640 (goto-char (point-min))
10641 (and
10642 (re-search-forward
10643 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10644 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10645 (setq type 'dedicated
10646 pos (match-beginning 0))))
10647 ;; There is an exact target for this
10648 (goto-char pos)
10649 (org-back-to-heading t)))
10650 ((save-excursion
10651 (goto-char (point-min))
10652 (and
10653 (re-search-forward
10654 (concat "<<" (regexp-quote s0) ">>") nil t)
10655 (setq type 'dedicated
10656 pos (match-beginning 0))))
10657 ;; There is an exact target for this
10658 (goto-char pos))
10659 ((save-excursion
10660 (goto-char (point-min))
10661 (and
10662 (re-search-forward
10663 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10664 (setq type 'dedicated pos (match-beginning 0))))
10665 ;; Found an element with a matching #+name affiliated keyword.
10666 (goto-char pos))
10667 ((and (string-match "^(\\(.*\\))$" s0)
10668 (save-excursion
10669 (goto-char (point-min))
10670 (and
10671 (re-search-forward
10672 (concat "[^[]" (regexp-quote
10673 (format org-coderef-label-format
10674 (match-string 1 s0))))
10675 nil t)
10676 (setq type 'dedicated
10677 pos (1+ (match-beginning 0))))))
10678 ;; There is a coderef target for this
10679 (goto-char pos))
10680 ((string-match "^/\\(.*\\)/$" s)
10681 ;; A regular expression
10682 (cond
10683 ((derived-mode-p 'org-mode)
10684 (org-occur (match-string 1 s)))
10685 (t (org-do-occur (match-string 1 s)))))
10686 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10687 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10688 (goto-char (point-min))
10689 (cond
10690 ((let (case-fold-search)
10691 (re-search-forward (format org-complex-heading-regexp-format
10692 (regexp-quote s))
10693 nil t))
10694 ;; OK, found a match
10695 (setq type 'dedicated)
10696 (goto-char (match-beginning 0)))
10697 ((and (not org-link-search-inhibit-query)
10698 (eq org-link-search-must-match-exact-headline 'query-to-create)
10699 (y-or-n-p "No match - create this as a new heading? "))
10700 (goto-char (point-max))
10701 (or (bolp) (newline))
10702 (insert "* " s "\n")
10703 (beginning-of-line 0))
10705 (goto-char pos)
10706 (error "No match"))))
10708 ;; A normal search string
10709 (when (equal (string-to-char s) ?*)
10710 ;; Anchor on headlines, post may include tags.
10711 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10712 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10713 s (substring s 1)))
10714 (remove-text-properties
10715 0 (length s)
10716 '(face nil mouse-face nil keymap nil fontified nil) s)
10717 ;; Make a series of regular expressions to find a match
10718 (setq words (org-split-string s "[ \n\r\t]+")
10720 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10721 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10722 "\\)" markers)
10723 re2a_ (concat "\\(" (mapconcat 'downcase words
10724 "[ \t\r\n]+") "\\)[ \t\r\n]")
10725 re2a (concat "[ \t\r\n]" re2a_)
10726 re4_ (concat "\\(" (mapconcat 'downcase words
10727 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10728 re4 (concat "[^a-zA-Z_]" re4_)
10730 re1 (concat pre re2 post)
10731 re3 (concat pre (if pre re4_ re4) post)
10732 re5 (concat pre ".*" re4)
10733 re2 (concat pre re2)
10734 re2a (concat pre (if pre re2a_ re2a))
10735 re4 (concat pre (if pre re4_ re4))
10736 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10737 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10738 re5 "\\)"))
10739 (cond
10740 ((eq type 'org-occur) (org-occur reall))
10741 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10742 (t (goto-char (point-min))
10743 (setq type 'fuzzy)
10744 (if (or (and (org-search-not-self 1 re0 nil t)
10745 (setq type 'dedicated))
10746 (org-search-not-self 1 re1 nil t)
10747 (org-search-not-self 1 re2 nil t)
10748 (org-search-not-self 1 re2a nil t)
10749 (org-search-not-self 1 re3 nil t)
10750 (org-search-not-self 1 re4 nil t)
10751 (org-search-not-self 1 re5 nil t))
10752 (goto-char (match-beginning 1))
10753 (goto-char pos)
10754 (error "No match"))))))
10755 (and (derived-mode-p 'org-mode)
10756 (not stealth)
10757 (org-show-context 'link-search))
10758 type))
10760 (defun org-search-not-self (group &rest args)
10761 "Execute `re-search-forward', but only accept matches that do not
10762 enclose the position of `org-open-link-marker'."
10763 (let ((m org-open-link-marker))
10764 (catch 'exit
10765 (while (apply 're-search-forward args)
10766 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10767 (goto-char (match-end group))
10768 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10769 (> (match-beginning 0) (marker-position m))
10770 (< (match-end 0) (marker-position m)))
10771 (save-match-data
10772 (or (not (org-in-regexp
10773 org-bracket-link-analytic-regexp 1))
10774 (not (match-end 4)) ; no description
10775 (and (<= (match-beginning 4) (point))
10776 (>= (match-end 4) (point))))))
10777 (throw 'exit (point))))))))
10779 (defun org-get-buffer-for-internal-link (buffer)
10780 "Return a buffer to be used for displaying the link target of internal links."
10781 (cond
10782 ((not org-display-internal-link-with-indirect-buffer)
10783 buffer)
10784 ((string-match "(Clone)$" (buffer-name buffer))
10785 (message "Buffer is already a clone, not making another one")
10786 ;; we also do not modify visibility in this case
10787 buffer)
10788 (t ; make a new indirect buffer for displaying the link
10789 (let* ((bn (buffer-name buffer))
10790 (ibn (concat bn "(Clone)"))
10791 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10792 (with-current-buffer ib (org-overview))
10793 ib))))
10795 (defun org-do-occur (regexp &optional cleanup)
10796 "Call the Emacs command `occur'.
10797 If CLEANUP is non-nil, remove the printout of the regular expression
10798 in the *Occur* buffer. This is useful if the regex is long and not useful
10799 to read."
10800 (occur regexp)
10801 (when cleanup
10802 (let ((cwin (selected-window)) win beg end)
10803 (when (setq win (get-buffer-window "*Occur*"))
10804 (select-window win))
10805 (goto-char (point-min))
10806 (when (re-search-forward "match[a-z]+" nil t)
10807 (setq beg (match-end 0))
10808 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10809 (setq end (1- (match-beginning 0)))))
10810 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10811 (goto-char (point-min))
10812 (select-window cwin))))
10814 ;;; The mark ring for links jumps
10816 (defvar org-mark-ring nil
10817 "Mark ring for positions before jumps in Org-mode.")
10818 (defvar org-mark-ring-last-goto nil
10819 "Last position in the mark ring used to go back.")
10820 ;; Fill and close the ring
10821 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10822 (loop for i from 1 to org-mark-ring-length do
10823 (push (make-marker) org-mark-ring))
10824 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10825 org-mark-ring)
10827 (defun org-mark-ring-push (&optional pos buffer)
10828 "Put the current position or POS into the mark ring and rotate it."
10829 (interactive)
10830 (setq pos (or pos (point)))
10831 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10832 (move-marker (car org-mark-ring)
10833 (or pos (point))
10834 (or buffer (current-buffer)))
10835 (message "%s"
10836 (substitute-command-keys
10837 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10839 (defun org-mark-ring-goto (&optional n)
10840 "Jump to the previous position in the mark ring.
10841 With prefix arg N, jump back that many stored positions. When
10842 called several times in succession, walk through the entire ring.
10843 Org-mode commands jumping to a different position in the current file,
10844 or to another Org-mode file, automatically push the old position
10845 onto the ring."
10846 (interactive "p")
10847 (let (p m)
10848 (if (eq last-command this-command)
10849 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10850 (setq p org-mark-ring))
10851 (setq org-mark-ring-last-goto p)
10852 (setq m (car p))
10853 (org-pop-to-buffer-same-window (marker-buffer m))
10854 (goto-char m)
10855 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10857 (defun org-remove-angle-brackets (s)
10858 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10859 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10861 (defun org-add-angle-brackets (s)
10862 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10863 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10865 (defun org-remove-double-quotes (s)
10866 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10867 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10870 ;;; Following specific links
10872 (defun org-follow-timestamp-link ()
10873 "Open an agenda view for the time-stamp date/range at point."
10874 (cond
10875 ((org-at-date-range-p t)
10876 (let ((org-agenda-start-on-weekday)
10877 (t1 (match-string 1))
10878 (t2 (match-string 2)) tt1 tt2)
10879 (setq tt1 (time-to-days (org-time-string-to-time t1))
10880 tt2 (time-to-days (org-time-string-to-time t2)))
10881 (let ((org-agenda-buffer-tmp-name
10882 (format "*Org Agenda(a:%s)"
10883 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10884 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10885 ((org-at-timestamp-p t)
10886 (let ((org-agenda-buffer-tmp-name
10887 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10888 (org-agenda-list nil (time-to-days (org-time-string-to-time
10889 (substring (match-string 1) 0 10)))
10890 1)))
10891 (t (error "This should not happen"))))
10894 ;;; Following file links
10895 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10896 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10897 (declare-function mailcap-mime-info
10898 "mailcap" (string &optional request no-decode))
10899 (defvar org-wait nil)
10900 (defun org-open-file (path &optional in-emacs line search)
10901 "Open the file at PATH.
10902 First, this expands any special file name abbreviations. Then the
10903 configuration variable `org-file-apps' is checked if it contains an
10904 entry for this file type, and if yes, the corresponding command is launched.
10906 If no application is found, Emacs simply visits the file.
10908 With optional prefix argument IN-EMACS, Emacs will visit the file.
10909 With a double \\[universal-argument] \\[universal-argument] \
10910 prefix arg, Org tries to avoid opening in Emacs
10911 and to use an external application to visit the file.
10913 Optional LINE specifies a line to go to, optional SEARCH a string
10914 to search for. If LINE or SEARCH is given, the file will be
10915 opened in Emacs, unless an entry from org-file-apps that makes
10916 use of groups in a regexp matches.
10918 If you want to change the way frames are used when following a
10919 link, please customize `org-link-frame-setup'.
10921 If the file does not exist, an error is thrown."
10922 (let* ((file (if (equal path "")
10923 buffer-file-name
10924 (substitute-in-file-name (expand-file-name path))))
10925 (file-apps (append org-file-apps (org-default-apps)))
10926 (apps (org-remove-if
10927 'org-file-apps-entry-match-against-dlink-p file-apps))
10928 (apps-dlink (org-remove-if-not
10929 'org-file-apps-entry-match-against-dlink-p file-apps))
10930 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10931 (dirp (if remp nil (file-directory-p file)))
10932 (file (if (and dirp org-open-directory-means-index-dot-org)
10933 (concat (file-name-as-directory file) "index.org")
10934 file))
10935 (a-m-a-p (assq 'auto-mode apps))
10936 (dfile (downcase file))
10937 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10938 (link (cond ((and (eq line nil)
10939 (eq search nil))
10940 file)
10941 (line
10942 (concat file "::" (number-to-string line)))
10943 (search
10944 (concat file "::" search))))
10945 (dlink (downcase link))
10946 (old-buffer (current-buffer))
10947 (old-pos (point))
10948 (old-mode major-mode)
10949 ext cmd link-match-data)
10950 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10951 (setq ext (match-string 1 dfile))
10952 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10953 (setq ext (match-string 1 dfile))))
10954 (cond
10955 ((member in-emacs '((16) system))
10956 (setq cmd (cdr (assoc 'system apps))))
10957 (in-emacs (setq cmd 'emacs))
10959 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10960 (and dirp (cdr (assoc 'directory apps)))
10961 ; first, try matching against apps-dlink
10962 ; if we get a match here, store the match data for later
10963 (let ((match (assoc-default dlink apps-dlink
10964 'string-match)))
10965 (if match
10966 (progn (setq link-match-data (match-data))
10967 match)
10968 (progn (setq in-emacs (or in-emacs line search))
10969 nil))) ; if we have no match in apps-dlink,
10970 ; always open the file in emacs if line or search
10971 ; is given (for backwards compatibility)
10972 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10973 'string-match)
10974 (cdr (assoc ext apps))
10975 (cdr (assoc t apps))))))
10976 (when (eq cmd 'system)
10977 (setq cmd (cdr (assoc 'system apps))))
10978 (when (eq cmd 'default)
10979 (setq cmd (cdr (assoc t apps))))
10980 (when (eq cmd 'mailcap)
10981 (require 'mailcap)
10982 (mailcap-parse-mailcaps)
10983 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10984 (command (mailcap-mime-info mime-type)))
10985 (if (stringp command)
10986 (setq cmd command)
10987 (setq cmd 'emacs))))
10988 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10989 (not (file-exists-p file))
10990 (not org-open-non-existing-files))
10991 (error "No such file: %s" file))
10992 (cond
10993 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10994 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10995 (while (string-match "['\"]%s['\"]" cmd)
10996 (setq cmd (replace-match "%s" t t cmd)))
10997 (while (string-match "%s" cmd)
10998 (setq cmd (replace-match
10999 (save-match-data
11000 (shell-quote-argument
11001 (convert-standard-filename file)))
11002 t t cmd)))
11004 ;; Replace "%1", "%2" etc. in command with group matches from regex
11005 (save-match-data
11006 (let ((match-index 1)
11007 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11008 (set-match-data link-match-data)
11009 (while (<= match-index number-of-groups)
11010 (let ((regex (concat "%" (number-to-string match-index)))
11011 (replace-with (match-string match-index dlink)))
11012 (while (string-match regex cmd)
11013 (setq cmd (replace-match replace-with t t cmd))))
11014 (setq match-index (+ match-index 1)))))
11016 (save-window-excursion
11017 (message "Running %s...done" cmd)
11018 (start-process-shell-command cmd nil cmd)
11019 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11020 ((or (stringp cmd)
11021 (eq cmd 'emacs))
11022 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11023 (widen)
11024 (if line (org-goto-line line)
11025 (if search (org-link-search search))))
11026 ((consp cmd)
11027 (let ((file (convert-standard-filename file)))
11028 (save-match-data
11029 (set-match-data link-match-data)
11030 (eval cmd))))
11031 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11032 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11033 (or (not (equal old-buffer (current-buffer)))
11034 (not (equal old-pos (point))))
11035 (org-mark-ring-push old-pos old-buffer))))
11037 (defun org-file-apps-entry-match-against-dlink-p (entry)
11038 "This function returns non-nil if `entry' uses a regular
11039 expression which should be matched against the whole link by
11040 org-open-file.
11042 It assumes that is the case when the entry uses a regular
11043 expression which has at least one grouping construct and the
11044 action is either a lisp form or a command string containing
11045 '%1', i.e. using at least one subexpression match as a
11046 parameter."
11047 (let ((selector (car entry))
11048 (action (cdr entry)))
11049 (if (stringp selector)
11050 (and (> (regexp-opt-depth selector) 0)
11051 (or (and (stringp action)
11052 (string-match "%[0-9]" action))
11053 (consp action)))
11054 nil)))
11056 (defun org-default-apps ()
11057 "Return the default applications for this operating system."
11058 (cond
11059 ((eq system-type 'darwin)
11060 org-file-apps-defaults-macosx)
11061 ((eq system-type 'windows-nt)
11062 org-file-apps-defaults-windowsnt)
11063 (t org-file-apps-defaults-gnu)))
11065 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11066 "Convert extensions to regular expressions in the cars of LIST.
11067 Also, weed out any non-string entries, because the return value is used
11068 only for regexp matching.
11069 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11070 point to the symbol `emacs', indicating that the file should
11071 be opened in Emacs."
11072 (append
11073 (delq nil
11074 (mapcar (lambda (x)
11075 (if (not (stringp (car x)))
11077 (if (string-match "\\W" (car x))
11079 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11080 list))
11081 (if add-auto-mode
11082 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11084 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11085 (defun org-file-remote-p (file)
11086 "Test whether FILE specifies a location on a remote system.
11087 Return non-nil if the location is indeed remote.
11089 For example, the filename \"/user@host:/foo\" specifies a location
11090 on the system \"/user@host:\"."
11091 (cond ((fboundp 'file-remote-p)
11092 (file-remote-p file))
11093 ((fboundp 'tramp-handle-file-remote-p)
11094 (tramp-handle-file-remote-p file))
11095 ((and (boundp 'ange-ftp-name-format)
11096 (string-match (car ange-ftp-name-format) file))
11097 t)))
11100 ;;;; Refiling
11102 (defun org-get-org-file ()
11103 "Read a filename, with default directory `org-directory'."
11104 (let ((default (or org-default-notes-file remember-data-file)))
11105 (read-file-name (format "File name [%s]: " default)
11106 (file-name-as-directory org-directory)
11107 default)))
11109 (defun org-notes-order-reversed-p ()
11110 "Check if the current file should receive notes in reversed order."
11111 (cond
11112 ((not org-reverse-note-order) nil)
11113 ((eq t org-reverse-note-order) t)
11114 ((not (listp org-reverse-note-order)) nil)
11115 (t (catch 'exit
11116 (let ((all org-reverse-note-order)
11117 entry)
11118 (while (setq entry (pop all))
11119 (if (string-match (car entry) buffer-file-name)
11120 (throw 'exit (cdr entry))))
11121 nil)))))
11123 (defvar org-refile-target-table nil
11124 "The list of refile targets, created by `org-refile'.")
11126 (defvar org-agenda-new-buffers nil
11127 "Buffers created to visit agenda files.")
11129 (defvar org-refile-cache nil
11130 "Cache for refile targets.")
11132 (defvar org-refile-markers nil
11133 "All the markers used for caching refile locations.")
11135 (defun org-refile-marker (pos)
11136 "Get a new refile marker, but only if caching is in use."
11137 (if (not org-refile-use-cache)
11139 (let ((m (make-marker)))
11140 (move-marker m pos)
11141 (push m org-refile-markers)
11142 m)))
11144 (defun org-refile-cache-clear ()
11145 "Clear the refile cache and disable all the markers."
11146 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11147 (setq org-refile-markers nil)
11148 (setq org-refile-cache nil)
11149 (message "Refile cache has been cleared"))
11151 (defun org-refile-cache-check-set (set)
11152 "Check if all the markers in the cache still have live buffers."
11153 (let (marker)
11154 (catch 'exit
11155 (while (and set (setq marker (nth 3 (pop set))))
11156 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11157 (when (and marker (null (marker-buffer marker)))
11158 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11159 (sit-for 3)
11160 (throw 'exit nil)))
11161 t)))
11163 (defun org-refile-cache-put (set &rest identifiers)
11164 "Push the refile targets SET into the cache, under IDENTIFIERS."
11165 (let* ((key (sha1 (prin1-to-string identifiers)))
11166 (entry (assoc key org-refile-cache)))
11167 (if entry
11168 (setcdr entry set)
11169 (push (cons key set) org-refile-cache))))
11171 (defun org-refile-cache-get (&rest identifiers)
11172 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11173 (cond
11174 ((not org-refile-cache) nil)
11175 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11177 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11178 org-refile-cache))))
11179 (and set (org-refile-cache-check-set set) set)))))
11181 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11182 "Produce a table with refile targets."
11183 (let ((case-fold-search nil)
11184 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11185 (entries (or org-refile-targets '((nil . (:level . 1)))))
11186 targets tgs txt re files f desc descre fast-path-p level pos0)
11187 (message "Getting targets...")
11188 (with-current-buffer (or default-buffer (current-buffer))
11189 (while (setq entry (pop entries))
11190 (setq files (car entry) desc (cdr entry))
11191 (setq fast-path-p nil)
11192 (cond
11193 ((null files) (setq files (list (current-buffer))))
11194 ((eq files 'org-agenda-files)
11195 (setq files (org-agenda-files 'unrestricted)))
11196 ((and (symbolp files) (fboundp files))
11197 (setq files (funcall files)))
11198 ((and (symbolp files) (boundp files))
11199 (setq files (symbol-value files))))
11200 (if (stringp files) (setq files (list files)))
11201 (cond
11202 ((eq (car desc) :tag)
11203 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11204 ((eq (car desc) :todo)
11205 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11206 ((eq (car desc) :regexp)
11207 (setq descre (cdr desc)))
11208 ((eq (car desc) :level)
11209 (setq descre (concat "^\\*\\{" (number-to-string
11210 (if org-odd-levels-only
11211 (1- (* 2 (cdr desc)))
11212 (cdr desc)))
11213 "\\}[ \t]")))
11214 ((eq (car desc) :maxlevel)
11215 (setq fast-path-p t)
11216 (setq descre (concat "^\\*\\{1," (number-to-string
11217 (if org-odd-levels-only
11218 (1- (* 2 (cdr desc)))
11219 (cdr desc)))
11220 "\\}[ \t]")))
11221 (t (error "Bad refiling target description %s" desc)))
11222 (while (setq f (pop files))
11223 (with-current-buffer
11224 (if (bufferp f) f (org-get-agenda-file-buffer f))
11226 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11227 (progn
11228 (if (bufferp f) (setq f (buffer-file-name
11229 (buffer-base-buffer f))))
11230 (setq f (and f (expand-file-name f)))
11231 (if (eq org-refile-use-outline-path 'file)
11232 (push (list (file-name-nondirectory f) f nil nil) tgs))
11233 (save-excursion
11234 (save-restriction
11235 (widen)
11236 (goto-char (point-min))
11237 (while (re-search-forward descre nil t)
11238 (goto-char (setq pos0 (point-at-bol)))
11239 (catch 'next
11240 (when org-refile-target-verify-function
11241 (save-match-data
11242 (or (funcall org-refile-target-verify-function)
11243 (throw 'next t))))
11244 (when (and (looking-at org-complex-heading-regexp)
11245 (not (member (match-string 4) excluded-entries))
11246 (match-string 4))
11247 (setq level (org-reduced-level
11248 (- (match-end 1) (match-beginning 1)))
11249 txt (org-link-display-format (match-string 4))
11250 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11251 re (format org-complex-heading-regexp-format
11252 (regexp-quote (match-string 4))))
11253 (when org-refile-use-outline-path
11254 (setq txt (mapconcat
11255 'org-protect-slash
11256 (append
11257 (if (eq org-refile-use-outline-path
11258 'file)
11259 (list (file-name-nondirectory
11260 (buffer-file-name
11261 (buffer-base-buffer))))
11262 (if (eq org-refile-use-outline-path
11263 'full-file-path)
11264 (list (buffer-file-name
11265 (buffer-base-buffer)))))
11266 (org-get-outline-path fast-path-p
11267 level txt)
11268 (list txt))
11269 "/")))
11270 (push (list txt f re (org-refile-marker (point)))
11271 tgs)))
11272 (when (= (point) pos0)
11273 ;; verification function has not moved point
11274 (goto-char (point-at-eol))))))))
11275 (when org-refile-use-cache
11276 (org-refile-cache-put tgs (buffer-file-name) descre))
11277 (setq targets (append tgs targets))))))
11278 (message "Getting targets...done")
11279 (nreverse targets)))
11281 (defun org-protect-slash (s)
11282 (while (string-match "/" s)
11283 (setq s (replace-match "\\" t t s)))
11286 (defvar org-olpa (make-vector 20 nil))
11288 (defun org-get-outline-path (&optional fastp level heading)
11289 "Return the outline path to the current entry, as a list.
11291 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11292 routine which makes outline path derivations for an entire file,
11293 avoiding backtracing. Refile target collection makes use of that."
11294 (if fastp
11295 (progn
11296 (if (> level 19)
11297 (error "Outline path failure, more than 19 levels"))
11298 (loop for i from level upto 19 do
11299 (aset org-olpa i nil))
11300 (prog1
11301 (delq nil (append org-olpa nil))
11302 (aset org-olpa level heading)))
11303 (let (rtn case-fold-search)
11304 (save-excursion
11305 (save-restriction
11306 (widen)
11307 (while (org-up-heading-safe)
11308 (when (looking-at org-complex-heading-regexp)
11309 (push (org-match-string-no-properties 4) rtn)))
11310 rtn)))))
11312 (defun org-format-outline-path (path &optional width prefix separator)
11313 "Format the outline path PATH for display.
11314 WIDTH is the maximum number of characters that is available.
11315 PREFIX is a prefix to be included in the returned string,
11316 such as the file name.
11317 SEPARATOR is inserted between the different parts of the path,
11318 the default is \"/\"."
11319 (setq width (or width 79))
11320 (if prefix (setq width (- width (length prefix))))
11321 (if (not path)
11322 (or prefix "")
11323 (let* ((nsteps (length path))
11324 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11325 (maxwidth (if (<= total-width width)
11326 10000 ;; everything fits
11327 ;; we need to shorten the level headings
11328 (/ (- width nsteps) nsteps)))
11329 (org-odd-levels-only nil)
11330 (n 0)
11331 (total (1+ (length prefix))))
11332 (setq maxwidth (max maxwidth 10))
11333 (concat prefix
11334 (if prefix (or separator "/"))
11335 (mapconcat
11336 (lambda (h)
11337 (setq n (1+ n))
11338 (if (and (= n nsteps) (< maxwidth 10000))
11339 (setq maxwidth (- total-width total)))
11340 (if (< (length h) maxwidth)
11341 (progn (setq total (+ total (length h) 1)) h)
11342 (setq h (substring h 0 (- maxwidth 2))
11343 total (+ total maxwidth 1))
11344 (if (string-match "[ \t]+\\'" h)
11345 (setq h (substring h 0 (match-beginning 0))))
11346 (setq h (concat h "..")))
11347 (org-add-props h nil 'face
11348 (nth (% (1- n) org-n-level-faces)
11349 org-level-faces))
11351 path (or separator "/"))))))
11353 (defun org-display-outline-path (&optional file current separator just-return-string)
11354 "Display the current outline path in the echo area.
11356 If FILE is non-nil, prepend the output with the file name.
11357 If CURRENT is non-nil, append the current heading to the output.
11358 SEPARATOR is passed through to `org-format-outline-path'. It separates
11359 the different parts of the path and defaults to \"/\".
11360 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11361 (interactive "P")
11362 (let* (case-fold-search
11363 message-log-max ; Don't populate the *Messages* buffer
11364 (bfn (buffer-file-name (buffer-base-buffer)))
11365 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11366 res)
11367 (if current (setq path (append path
11368 (save-excursion
11369 (org-back-to-heading t)
11370 (if (looking-at org-complex-heading-regexp)
11371 (list (match-string 4)))))))
11372 (setq res
11373 (org-format-outline-path
11374 path
11375 (1- (frame-width))
11376 (and file bfn (concat (file-name-nondirectory bfn) separator))
11377 separator))
11378 (if just-return-string
11379 (org-no-properties res)
11380 (message "%s" res))))
11382 (defvar org-refile-history nil
11383 "History for refiling operations.")
11385 (defvar org-after-refile-insert-hook nil
11386 "Hook run after `org-refile' has inserted its stuff at the new location.
11387 Note that this is still *before* the stuff will be removed from
11388 the *old* location.")
11390 (defvar org-capture-last-stored-marker)
11391 (defvar org-refile-keep nil
11392 "Non-nil means `org-refile' will copy instead of refile.")
11394 (defun org-copy ()
11395 "Like `org-refile', but copy."
11396 (interactive)
11397 (let ((org-refile-keep t))
11398 (funcall 'org-refile nil nil nil "Copy")))
11400 (defun org-refile (&optional goto default-buffer rfloc msg)
11401 "Move the entry or entries at point to another heading.
11402 The list of target headings is compiled using the information in
11403 `org-refile-targets', which see.
11405 At the target location, the entry is filed as a subitem of the target
11406 heading. Depending on `org-reverse-note-order', the new subitem will
11407 either be the first or the last subitem.
11409 If there is an active region, all entries in that region will be moved.
11410 However, the region must fulfill the requirement that the first heading
11411 is the first one sets the top-level of the moved text - at most siblings
11412 below it are allowed.
11414 With prefix arg GOTO, the command will only visit the target location
11415 and not actually move anything.
11417 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11418 go to the location where the last refiling operation has put the subtree.
11419 With a prefix argument of `2', refile to the running clock.
11421 RFLOC can be a refile location obtained in a different way.
11423 MSG is a string to replace \"Refile\" in the default prompt with
11424 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11426 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11428 If you are using target caching (see `org-refile-use-cache'),
11429 you have to clear the target cache in order to find new targets.
11430 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11431 prefix argument (`C-u C-u C-u C-c C-w')."
11433 (interactive "P")
11434 (if (member goto '(0 (64)))
11435 (org-refile-cache-clear)
11436 (let* ((actionmsg (or msg "Refile"))
11437 (cbuf (current-buffer))
11438 (regionp (org-region-active-p))
11439 (region-start (and regionp (region-beginning)))
11440 (region-end (and regionp (region-end)))
11441 (region-length (and regionp (- region-end region-start)))
11442 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11443 pos it nbuf file re level reversed)
11444 (setq last-command nil)
11445 (when regionp
11446 (goto-char region-start)
11447 (or (bolp) (goto-char (point-at-bol)))
11448 (setq region-start (point))
11449 (unless (or (org-kill-is-subtree-p
11450 (buffer-substring region-start region-end))
11451 (prog1 org-refile-active-region-within-subtree
11452 (org-toggle-heading)))
11453 (error "The region is not a (sequence of) subtree(s)")))
11454 (if (equal goto '(16))
11455 (org-refile-goto-last-stored)
11456 (when (or
11457 (and (equal goto 2)
11458 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11459 (prog1
11460 (setq it (list (or org-clock-heading "running clock")
11461 (buffer-file-name
11462 (marker-buffer org-clock-hd-marker))
11464 (marker-position org-clock-hd-marker)))
11465 (setq goto nil)))
11466 (setq it (or rfloc
11467 (let (heading-text)
11468 (save-excursion
11469 (unless goto
11470 (org-back-to-heading t)
11471 (setq heading-text
11472 (nth 4 (org-heading-components))))
11474 (org-refile-get-location
11475 (cond (goto "Goto")
11476 (regionp (concat actionmsg " region to"))
11477 (t (concat actionmsg " subtree \""
11478 heading-text "\" to")))
11479 default-buffer
11480 (and (not (equal '(4) goto))
11481 org-refile-allow-creating-parent-nodes)
11482 goto))))))
11483 (setq file (nth 1 it)
11484 re (nth 2 it)
11485 pos (nth 3 it))
11486 (if (and (not goto)
11488 (equal (buffer-file-name) file)
11489 (if regionp
11490 (and (>= pos region-start)
11491 (<= pos region-end))
11492 (and (>= pos (point))
11493 (< pos (save-excursion
11494 (org-end-of-subtree t t))))))
11495 (error "Cannot refile to position inside the tree or region"))
11497 (setq nbuf (or (find-buffer-visiting file)
11498 (find-file-noselect file)))
11499 (if goto
11500 (progn
11501 (org-pop-to-buffer-same-window nbuf)
11502 (goto-char pos)
11503 (org-show-context 'org-goto))
11504 (if regionp
11505 (progn
11506 (org-kill-new (buffer-substring region-start region-end))
11507 (org-save-markers-in-region region-start region-end))
11508 (org-copy-subtree 1 nil t))
11509 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11510 (find-file-noselect file)))
11511 (setq reversed (org-notes-order-reversed-p))
11512 (save-excursion
11513 (save-restriction
11514 (widen)
11515 (if pos
11516 (progn
11517 (goto-char pos)
11518 (looking-at org-outline-regexp)
11519 (setq level (org-get-valid-level (funcall outline-level) 1))
11520 (goto-char
11521 (if reversed
11522 (or (outline-next-heading) (point-max))
11523 (or (save-excursion (org-get-next-sibling))
11524 (org-end-of-subtree t t)
11525 (point-max)))))
11526 (setq level 1)
11527 (if (not reversed)
11528 (goto-char (point-max))
11529 (goto-char (point-min))
11530 (or (outline-next-heading) (goto-char (point-max)))))
11531 (if (not (bolp)) (newline))
11532 (org-paste-subtree level)
11533 (when org-log-refile
11534 (org-add-log-setup 'refile nil nil 'findpos
11535 org-log-refile)
11536 (unless (eq org-log-refile 'note)
11537 (save-excursion (org-add-log-note))))
11538 (and org-auto-align-tags
11539 (let ((org-loop-over-headlines-in-active-region nil))
11540 (org-set-tags nil t)))
11541 (with-demoted-errors
11542 (bookmark-set "org-refile-last-stored"))
11543 ;; If we are refiling for capture, make sure that the
11544 ;; last-capture pointers point here
11545 (when (org-bound-and-true-p org-refile-for-capture)
11546 (with-demoted-errors
11547 (bookmark-set "org-capture-last-stored-marker"))
11548 (move-marker org-capture-last-stored-marker (point)))
11549 (if (fboundp 'deactivate-mark) (deactivate-mark))
11550 (run-hooks 'org-after-refile-insert-hook))))
11551 (unless org-refile-keep
11552 (if regionp
11553 (delete-region (point) (+ (point) region-length))
11554 (org-cut-subtree)))
11555 (when (featurep 'org-inlinetask)
11556 (org-inlinetask-remove-END-maybe))
11557 (setq org-markers-to-move nil)
11558 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11560 (defun org-refile-goto-last-stored ()
11561 "Go to the location where the last refile was stored."
11562 (interactive)
11563 (bookmark-jump "org-refile-last-stored")
11564 (message "This is the location of the last refile"))
11566 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11567 no-exclude)
11568 "Prompt the user for a refile location, using PROMPT.
11569 PROMPT should not be suffixed with a colon and a space, because
11570 this function appends the default value from
11571 `org-refile-history' automatically, if that is not empty.
11572 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11573 this is used for the GOTO interface."
11574 (let ((org-refile-targets org-refile-targets)
11575 (org-refile-use-outline-path org-refile-use-outline-path)
11576 excluded-entries)
11577 (when (and (derived-mode-p 'org-mode)
11578 (not org-refile-use-cache)
11579 (not no-exclude))
11580 (org-map-tree
11581 (lambda()
11582 (setq excluded-entries
11583 (append excluded-entries (list (org-get-heading t t)))))))
11584 (setq org-refile-target-table
11585 (org-refile-get-targets default-buffer excluded-entries)))
11586 (unless org-refile-target-table
11587 (error "No refile targets"))
11588 (let* ((cbuf (current-buffer))
11589 (partial-completion-mode nil)
11590 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11591 (cfunc (if (and org-refile-use-outline-path
11592 org-outline-path-complete-in-steps)
11593 'org-olpath-completing-read
11594 'org-icompleting-read))
11595 (extra (if org-refile-use-outline-path "/" ""))
11596 (cbnex (concat (buffer-name) extra))
11597 (filename (and cfn (expand-file-name cfn)))
11598 (tbl (mapcar
11599 (lambda (x)
11600 (if (and (not (member org-refile-use-outline-path
11601 '(file full-file-path)))
11602 (not (equal filename (nth 1 x))))
11603 (cons (concat (car x) extra " ("
11604 (file-name-nondirectory (nth 1 x)) ")")
11605 (cdr x))
11606 (cons (concat (car x) extra) (cdr x))))
11607 org-refile-target-table))
11608 (completion-ignore-case t)
11609 cdef
11610 (prompt (concat prompt
11611 (or (and (car org-refile-history)
11612 (concat " (default " (car org-refile-history) ")"))
11613 (and (assoc cbnex tbl) (setq cdef cbnex)
11614 (concat " (default " cbnex ")"))) ": "))
11615 pa answ parent-target child parent old-hist)
11616 (setq old-hist org-refile-history)
11617 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11618 nil 'org-refile-history (or cdef (car org-refile-history))))
11619 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11620 (org-refile-check-position pa)
11621 (if pa
11622 (progn
11623 (when (or (not org-refile-history)
11624 (not (eq old-hist org-refile-history))
11625 (not (equal (car pa) (car org-refile-history))))
11626 (setq org-refile-history
11627 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11628 org-refile-history
11629 (cdr org-refile-history))))
11630 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11631 (pop org-refile-history)))
11633 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11634 (progn
11635 (setq parent (match-string 1 answ)
11636 child (match-string 2 answ))
11637 (setq parent-target (or (assoc parent tbl)
11638 (assoc (concat parent "/") tbl)))
11639 (when (and parent-target
11640 (or (eq new-nodes t)
11641 (and (eq new-nodes 'confirm)
11642 (y-or-n-p (format "Create new node \"%s\"? "
11643 child)))))
11644 (org-refile-new-child parent-target child)))
11645 (error "Invalid target location")))))
11647 (declare-function org-string-nw-p "org-macs" (s))
11648 (defun org-refile-check-position (refile-pointer)
11649 "Check if the refile pointer matches the headline to which it points."
11650 (let* ((file (nth 1 refile-pointer))
11651 (re (nth 2 refile-pointer))
11652 (pos (nth 3 refile-pointer))
11653 buffer)
11654 (if (and (not (markerp pos)) (not file))
11655 (error "Please save the buffer to a file before refiling")
11656 (when (org-string-nw-p re)
11657 (setq buffer (if (markerp pos)
11658 (marker-buffer pos)
11659 (or (find-buffer-visiting file)
11660 (find-file-noselect file))))
11661 (with-current-buffer buffer
11662 (save-excursion
11663 (save-restriction
11664 (widen)
11665 (goto-char pos)
11666 (beginning-of-line 1)
11667 (unless (org-looking-at-p re)
11668 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11670 (defun org-refile-new-child (parent-target child)
11671 "Use refile target PARENT-TARGET to add new CHILD below it."
11672 (unless parent-target
11673 (error "Cannot find parent for new node"))
11674 (let ((file (nth 1 parent-target))
11675 (pos (nth 3 parent-target))
11676 level)
11677 (with-current-buffer (or (find-buffer-visiting file)
11678 (find-file-noselect file))
11679 (save-excursion
11680 (save-restriction
11681 (widen)
11682 (if pos
11683 (goto-char pos)
11684 (goto-char (point-max))
11685 (if (not (bolp)) (newline)))
11686 (when (looking-at org-outline-regexp)
11687 (setq level (funcall outline-level))
11688 (org-end-of-subtree t t))
11689 (org-back-over-empty-lines)
11690 (insert "\n" (make-string
11691 (if pos (org-get-valid-level level 1) 1) ?*)
11692 " " child "\n")
11693 (beginning-of-line 0)
11694 (list (concat (car parent-target) "/" child) file "" (point)))))))
11696 (defun org-olpath-completing-read (prompt collection &rest args)
11697 "Read an outline path like a file name."
11698 (let ((thetable collection)
11699 (org-completion-use-ido nil) ; does not work with ido.
11700 (org-completion-use-iswitchb nil)) ; or iswitchb
11701 (apply
11702 'org-icompleting-read prompt
11703 (lambda (string predicate &optional flag)
11704 (let (rtn r f (l (length string)))
11705 (cond
11706 ((eq flag nil)
11707 ;; try completion
11708 (try-completion string thetable))
11709 ((eq flag t)
11710 ;; all-completions
11711 (setq rtn (all-completions string thetable predicate))
11712 (mapcar
11713 (lambda (x)
11714 (setq r (substring x l))
11715 (if (string-match " ([^)]*)$" x)
11716 (setq f (match-string 0 x))
11717 (setq f ""))
11718 (if (string-match "/" r)
11719 (concat string (substring r 0 (match-end 0)) f)
11721 rtn))
11722 ((eq flag 'lambda)
11723 ;; exact match?
11724 (assoc string thetable)))))
11725 args)))
11727 ;;;; Dynamic blocks
11729 (defun org-find-dblock (name)
11730 "Find the first dynamic block with name NAME in the buffer.
11731 If not found, stay at current position and return nil."
11732 (let ((case-fold-search t) pos)
11733 (save-excursion
11734 (goto-char (point-min))
11735 (setq pos (and (re-search-forward
11736 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11737 (match-beginning 0))))
11738 (if pos (goto-char pos))
11739 pos))
11741 (defconst org-dblock-start-re
11742 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11743 "Matches the start line of a dynamic block, with parameters.")
11745 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11746 "Matches the end of a dynamic block.")
11748 (defun org-create-dblock (plist)
11749 "Create a dynamic block section, with parameters taken from PLIST.
11750 PLIST must contain a :name entry which is used as name of the block."
11751 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11752 (end-of-line 1)
11753 (newline))
11754 (let ((col (current-column))
11755 (name (plist-get plist :name)))
11756 (insert "#+BEGIN: " name)
11757 (while plist
11758 (if (eq (car plist) :name)
11759 (setq plist (cddr plist))
11760 (insert " " (prin1-to-string (pop plist)))))
11761 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11762 (beginning-of-line -2)))
11764 (defun org-prepare-dblock ()
11765 "Prepare dynamic block for refresh.
11766 This empties the block, puts the cursor at the insert position and returns
11767 the property list including an extra property :name with the block name."
11768 (unless (looking-at org-dblock-start-re)
11769 (error "Not at a dynamic block"))
11770 (let* ((begdel (1+ (match-end 0)))
11771 (name (org-no-properties (match-string 1)))
11772 (params (append (list :name name)
11773 (read (concat "(" (match-string 3) ")")))))
11774 (save-excursion
11775 (beginning-of-line 1)
11776 (skip-chars-forward " \t")
11777 (setq params (plist-put params :indentation-column (current-column))))
11778 (unless (re-search-forward org-dblock-end-re nil t)
11779 (error "Dynamic block not terminated"))
11780 (setq params
11781 (append params
11782 (list :content (buffer-substring
11783 begdel (match-beginning 0)))))
11784 (delete-region begdel (match-beginning 0))
11785 (goto-char begdel)
11786 (open-line 1)
11787 params))
11789 (defun org-map-dblocks (&optional command)
11790 "Apply COMMAND to all dynamic blocks in the current buffer.
11791 If COMMAND is not given, use `org-update-dblock'."
11792 (let ((cmd (or command 'org-update-dblock)))
11793 (save-excursion
11794 (goto-char (point-min))
11795 (while (re-search-forward org-dblock-start-re nil t)
11796 (goto-char (match-beginning 0))
11797 (save-excursion
11798 (condition-case nil
11799 (funcall cmd)
11800 (error (message "Error during update of dynamic block"))))
11801 (unless (re-search-forward org-dblock-end-re nil t)
11802 (error "Dynamic block not terminated"))))))
11804 (defun org-dblock-update (&optional arg)
11805 "User command for updating dynamic blocks.
11806 Update the dynamic block at point. With prefix ARG, update all dynamic
11807 blocks in the buffer."
11808 (interactive "P")
11809 (if arg
11810 (org-update-all-dblocks)
11811 (or (looking-at org-dblock-start-re)
11812 (org-beginning-of-dblock))
11813 (org-update-dblock)))
11815 (defun org-update-dblock ()
11816 "Update the dynamic block at point.
11817 This means to empty the block, parse for parameters and then call
11818 the correct writing function."
11819 (interactive)
11820 (save-window-excursion
11821 (let* ((pos (point))
11822 (line (org-current-line))
11823 (params (org-prepare-dblock))
11824 (name (plist-get params :name))
11825 (indent (plist-get params :indentation-column))
11826 (cmd (intern (concat "org-dblock-write:" name))))
11827 (message "Updating dynamic block `%s' at line %d..." name line)
11828 (funcall cmd params)
11829 (message "Updating dynamic block `%s' at line %d...done" name line)
11830 (goto-char pos)
11831 (when (and indent (> indent 0))
11832 (setq indent (make-string indent ?\ ))
11833 (save-excursion
11834 (org-beginning-of-dblock)
11835 (forward-line 1)
11836 (while (not (looking-at org-dblock-end-re))
11837 (insert indent)
11838 (beginning-of-line 2))
11839 (when (looking-at org-dblock-end-re)
11840 (and (looking-at "[ \t]+")
11841 (replace-match ""))
11842 (insert indent)))))))
11844 (defun org-beginning-of-dblock ()
11845 "Find the beginning of the dynamic block at point.
11846 Error if there is no such block at point."
11847 (let ((pos (point))
11848 beg)
11849 (end-of-line 1)
11850 (if (and (re-search-backward org-dblock-start-re nil t)
11851 (setq beg (match-beginning 0))
11852 (re-search-forward org-dblock-end-re nil t)
11853 (> (match-end 0) pos))
11854 (goto-char beg)
11855 (goto-char pos)
11856 (error "Not in a dynamic block"))))
11858 (defun org-update-all-dblocks ()
11859 "Update all dynamic blocks in the buffer.
11860 This function can be used in a hook."
11861 (interactive)
11862 (when (derived-mode-p 'org-mode)
11863 (org-map-dblocks 'org-update-dblock)))
11866 ;;;; Completion
11868 (defun org-get-export-keywords ()
11869 "Return a list of all currently understood export keywords.
11870 Export keywords include options, block names, attributes and
11871 keywords relative to each registered export back-end."
11872 (delq nil
11873 (let (keywords)
11874 (mapc
11875 (lambda (back-end)
11876 (let ((props (cdr back-end)))
11877 ;; Back-end name (for keywords, like #+LATEX:)
11878 (push (upcase (symbol-name (car back-end))) keywords)
11879 ;; Back-end options.
11880 (mapc (lambda (option) (push (cadr option) keywords))
11881 (plist-get (cdr back-end) :options-alist))))
11882 (org-bound-and-true-p org-export-registered-backends))
11883 keywords)))
11885 (defconst org-options-keywords
11886 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11887 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11888 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11889 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11890 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11892 (defcustom org-structure-template-alist
11893 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11894 "<src lang=\"?\">\n\n</src>")
11895 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11896 "<example>\n?\n</example>")
11897 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11898 "<quote>\n?\n</quote>")
11899 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11900 "<verse>\n?\n</verse>")
11901 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11902 "<verbatim>\n?\n</verbatim>")
11903 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11904 "<center>\n?\n</center>")
11905 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11906 "<literal style=\"latex\">\n?\n</literal>")
11907 ("L" "#+LaTeX: "
11908 "<literal style=\"latex\">?</literal>")
11909 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11910 "<literal style=\"html\">\n?\n</literal>")
11911 ("H" "#+HTML: "
11912 "<literal style=\"html\">?</literal>")
11913 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11914 ("A" "#+ASCII: ")
11915 ("i" "#+INDEX: ?"
11916 "#+INDEX: ?")
11917 ("I" "#+INCLUDE: %file ?"
11918 "<include file=%file markup=\"?\">"))
11919 "Structure completion elements.
11920 This is a list of abbreviation keys and values. The value gets inserted
11921 if you type `<' followed by the key and then press the completion key,
11922 usually `M-TAB'. %file will be replaced by a file name after prompting
11923 for the file using completion. The cursor will be placed at the position
11924 of the `?` in the template.
11925 There are two templates for each key, the first uses the original Org syntax,
11926 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11927 the default when the /org-mtags.el/ module has been loaded. See also the
11928 variable `org-mtags-prefer-muse-templates'."
11929 :group 'org-completion
11930 :type '(repeat
11931 (string :tag "Key")
11932 (string :tag "Template")
11933 (string :tag "Muse Template")))
11935 (defun org-try-structure-completion ()
11936 "Try to complete a structure template before point.
11937 This looks for strings like \"<e\" on an otherwise empty line and
11938 expands them."
11939 (let ((l (buffer-substring (point-at-bol) (point)))
11941 (when (and (looking-at "[ \t]*$")
11942 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11943 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11944 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11945 (match-beginning 1)) a)
11946 t)))
11948 (defun org-complete-expand-structure-template (start cell)
11949 "Expand a structure template."
11950 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11951 (rpl (nth (if musep 2 1) cell))
11952 (ind ""))
11953 (delete-region start (point))
11954 (when (string-match "\\`#\\+" rpl)
11955 (cond
11956 ((bolp))
11957 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11958 (setq ind (buffer-substring (point-at-bol) (point))))
11959 (t (newline))))
11960 (setq start (point))
11961 (if (string-match "%file" rpl)
11962 (setq rpl (replace-match
11963 (concat
11964 "\""
11965 (save-match-data
11966 (abbreviate-file-name (read-file-name "Include file: ")))
11967 "\"")
11968 t t rpl)))
11969 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11970 (concat "\n" ind)))
11971 (insert rpl)
11972 (if (re-search-backward "\\?" start t) (delete-char 1))))
11974 ;;;; TODO, DEADLINE, Comments
11976 (defun org-toggle-comment ()
11977 "Change the COMMENT state of an entry."
11978 (interactive)
11979 (save-excursion
11980 (org-back-to-heading)
11981 (let (case-fold-search)
11982 (cond
11983 ((looking-at (format org-heading-keyword-regexp-format
11984 org-comment-string))
11985 (goto-char (match-end 1))
11986 (looking-at (concat " +" org-comment-string))
11987 (replace-match "" t t)
11988 (when (eolp) (insert " ")))
11989 ((looking-at org-outline-regexp)
11990 (goto-char (match-end 0))
11991 (insert org-comment-string " "))))))
11993 (defvar org-last-todo-state-is-todo nil
11994 "This is non-nil when the last TODO state change led to a TODO state.
11995 If the last change removed the TODO tag or switched to DONE, then
11996 this is nil.")
11998 (defvar org-setting-tags nil) ; dynamically skipped
12000 (defvar org-todo-setup-filter-hook nil
12001 "Hook for functions that pre-filter todo specs.
12002 Each function takes a todo spec and returns either nil or the spec
12003 transformed into canonical form." )
12005 (defvar org-todo-get-default-hook nil
12006 "Hook for functions that get a default item for todo.
12007 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12008 nil or a string to be used for the todo mark." )
12010 (defvar org-agenda-headline-snapshot-before-repeat)
12012 (defun org-current-effective-time ()
12013 "Return current time adjusted for `org-extend-today-until' variable."
12014 (let* ((ct (org-current-time))
12015 (dct (decode-time ct))
12016 (ct1
12017 (cond
12018 (org-use-last-clock-out-time-as-effective-time
12019 (or (org-clock-get-last-clock-out-time) ct))
12020 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12021 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12022 (t ct))))
12023 ct1))
12025 (defun org-todo-yesterday (&optional arg)
12026 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12027 (interactive "P")
12028 (if (eq major-mode 'org-agenda-mode)
12029 (apply 'org-agenda-todo-yesterday arg)
12030 (let* ((hour (third (decode-time
12031 (org-current-time))))
12032 (org-extend-today-until (1+ hour)))
12033 (org-todo arg))))
12035 (defvar org-block-entry-blocking ""
12036 "First entry preventing the TODO state change.")
12038 (defun org-todo (&optional arg)
12039 "Change the TODO state of an item.
12040 The state of an item is given by a keyword at the start of the heading,
12041 like
12042 *** TODO Write paper
12043 *** DONE Call mom
12045 The different keywords are specified in the variable `org-todo-keywords'.
12046 By default the available states are \"TODO\" and \"DONE\".
12047 So for this example: when the item starts with TODO, it is changed to DONE.
12048 When it starts with DONE, the DONE is removed. And when neither TODO nor
12049 DONE are present, add TODO at the beginning of the heading.
12051 With \\[universal-argument] prefix arg, use completion to determine the new \
12052 state.
12053 With numeric prefix arg, switch to that state.
12054 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12055 keywords (nextset).
12056 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12057 With a numeric prefix arg of 0, inhibit note taking for the change.
12059 For calling through lisp, arg is also interpreted in the following way:
12060 'none -> empty state
12061 \"\"(empty string) -> switch to empty state
12062 'done -> switch to DONE
12063 'nextset -> switch to the next set of keywords
12064 'previousset -> switch to the previous set of keywords
12065 \"WAITING\" -> switch to the specified keyword, but only if it
12066 really is a member of `org-todo-keywords'."
12067 (interactive "P")
12068 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12069 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12070 'region-start-level 'region))
12071 org-loop-over-headlines-in-active-region)
12072 (org-map-entries
12073 `(org-todo ,arg)
12074 org-loop-over-headlines-in-active-region
12075 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12076 (if (equal arg '(16)) (setq arg 'nextset))
12077 (let ((org-blocker-hook org-blocker-hook)
12078 commentp
12079 case-fold-search)
12080 (when (equal arg '(64))
12081 (setq arg nil org-blocker-hook nil))
12082 (when (and org-blocker-hook
12083 (or org-inhibit-blocking
12084 (org-entry-get nil "NOBLOCKING")))
12085 (setq org-blocker-hook nil))
12086 (save-excursion
12087 (catch 'exit
12088 (org-back-to-heading t)
12089 (when (looking-at (concat "^\\*+ " org-comment-string))
12090 (org-toggle-comment)
12091 (setq commentp t))
12092 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12093 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12094 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12095 (let* ((match-data (match-data))
12096 (startpos (point-at-bol))
12097 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12098 (org-log-done org-log-done)
12099 (org-log-repeat org-log-repeat)
12100 (org-todo-log-states org-todo-log-states)
12101 (org-inhibit-logging
12102 (if (equal arg 0)
12103 (progn (setq arg nil) 'note) org-inhibit-logging))
12104 (this (match-string 1))
12105 (hl-pos (match-beginning 0))
12106 (head (org-get-todo-sequence-head this))
12107 (ass (assoc head org-todo-kwd-alist))
12108 (interpret (nth 1 ass))
12109 (done-word (nth 3 ass))
12110 (final-done-word (nth 4 ass))
12111 (org-last-state (or this ""))
12112 (completion-ignore-case t)
12113 (member (member this org-todo-keywords-1))
12114 (tail (cdr member))
12115 (org-state (cond
12116 ((and org-todo-key-trigger
12117 (or (and (equal arg '(4))
12118 (eq org-use-fast-todo-selection 'prefix))
12119 (and (not arg) org-use-fast-todo-selection
12120 (not (eq org-use-fast-todo-selection
12121 'prefix)))))
12122 ;; Use fast selection
12123 (org-fast-todo-selection))
12124 ((and (equal arg '(4))
12125 (or (not org-use-fast-todo-selection)
12126 (not org-todo-key-trigger)))
12127 ;; Read a state with completion
12128 (org-icompleting-read
12129 "State: " (mapcar 'list org-todo-keywords-1)
12130 nil t))
12131 ((eq arg 'right)
12132 (if this
12133 (if tail (car tail) nil)
12134 (car org-todo-keywords-1)))
12135 ((eq arg 'left)
12136 (if (equal member org-todo-keywords-1)
12138 (if this
12139 (nth (- (length org-todo-keywords-1)
12140 (length tail) 2)
12141 org-todo-keywords-1)
12142 (org-last org-todo-keywords-1))))
12143 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12144 (setq arg nil))) ; hack to fall back to cycling
12145 (arg
12146 ;; user or caller requests a specific state
12147 (cond
12148 ((equal arg "") nil)
12149 ((eq arg 'none) nil)
12150 ((eq arg 'done) (or done-word (car org-done-keywords)))
12151 ((eq arg 'nextset)
12152 (or (car (cdr (member head org-todo-heads)))
12153 (car org-todo-heads)))
12154 ((eq arg 'previousset)
12155 (let ((org-todo-heads (reverse org-todo-heads)))
12156 (or (car (cdr (member head org-todo-heads)))
12157 (car org-todo-heads))))
12158 ((car (member arg org-todo-keywords-1)))
12159 ((stringp arg)
12160 (error "State `%s' not valid in this file" arg))
12161 ((nth (1- (prefix-numeric-value arg))
12162 org-todo-keywords-1))))
12163 ((null member) (or head (car org-todo-keywords-1)))
12164 ((equal this final-done-word) nil) ;; -> make empty
12165 ((null tail) nil) ;; -> first entry
12166 ((memq interpret '(type priority))
12167 (if (eq this-command last-command)
12168 (car tail)
12169 (if (> (length tail) 0)
12170 (or done-word (car org-done-keywords))
12171 nil)))
12173 (car tail))))
12174 (org-state (or
12175 (run-hook-with-args-until-success
12176 'org-todo-get-default-hook org-state org-last-state)
12177 org-state))
12178 (next (if org-state (concat " " org-state " ") " "))
12179 (change-plist (list :type 'todo-state-change :from this :to org-state
12180 :position startpos))
12181 dolog now-done-p)
12182 (when org-blocker-hook
12183 (setq org-last-todo-state-is-todo
12184 (not (member this org-done-keywords)))
12185 (unless (save-excursion
12186 (save-match-data
12187 (org-with-wide-buffer
12188 (run-hook-with-args-until-failure
12189 'org-blocker-hook change-plist))))
12190 (if (org-called-interactively-p 'interactive)
12191 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12192 this org-state org-block-entry-blocking)
12193 ;; fail silently
12194 (message "TODO state change from %s to %s blocked (by \"%s\")"
12195 this org-state org-block-entry-blocking)
12196 (throw 'exit nil))))
12197 (store-match-data match-data)
12198 (replace-match next t t)
12199 (unless (pos-visible-in-window-p hl-pos)
12200 (message "TODO state changed to %s" (org-trim next)))
12201 (unless head
12202 (setq head (org-get-todo-sequence-head org-state)
12203 ass (assoc head org-todo-kwd-alist)
12204 interpret (nth 1 ass)
12205 done-word (nth 3 ass)
12206 final-done-word (nth 4 ass)))
12207 (when (memq arg '(nextset previousset))
12208 (message "Keyword-Set %d/%d: %s"
12209 (- (length org-todo-sets) -1
12210 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12211 (length org-todo-sets)
12212 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12213 (setq org-last-todo-state-is-todo
12214 (not (member org-state org-done-keywords)))
12215 (setq now-done-p (and (member org-state org-done-keywords)
12216 (not (member this org-done-keywords))))
12217 (and logging (org-local-logging logging))
12218 (when (and (or org-todo-log-states org-log-done)
12219 (not (eq org-inhibit-logging t))
12220 (not (memq arg '(nextset previousset))))
12221 ;; we need to look at recording a time and note
12222 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12223 (nth 2 (assoc this org-todo-log-states))))
12224 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12225 (setq dolog 'time))
12226 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12227 (and org-state
12228 (member org-state org-not-done-keywords)
12229 (not (member this org-not-done-keywords))))
12230 ;; This is now a todo state and was not one before
12231 ;; If there was a CLOSED time stamp, get rid of it.
12232 (org-add-planning-info nil nil 'closed))
12233 (when (and now-done-p org-log-done)
12234 ;; It is now done, and it was not done before
12235 (org-add-planning-info 'closed (org-current-effective-time))
12236 (if (and (not dolog) (eq 'note org-log-done))
12237 (org-add-log-setup 'done org-state this 'findpos 'note)))
12238 (when (and org-state dolog)
12239 ;; This is a non-nil state, and we need to log it
12240 (org-add-log-setup 'state org-state this 'findpos dolog)))
12241 ;; Fixup tag positioning
12242 (org-todo-trigger-tag-changes org-state)
12243 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12244 (when org-provide-todo-statistics
12245 (org-update-parent-todo-statistics))
12246 (run-hooks 'org-after-todo-state-change-hook)
12247 (if (and arg (not (member org-state org-done-keywords)))
12248 (setq head (org-get-todo-sequence-head org-state)))
12249 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12250 ;; Do we need to trigger a repeat?
12251 (when now-done-p
12252 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12253 ;; This is for the agenda, take a snapshot of the headline.
12254 (save-match-data
12255 (setq org-agenda-headline-snapshot-before-repeat
12256 (org-get-heading))))
12257 (org-auto-repeat-maybe org-state))
12258 ;; Fixup cursor location if close to the keyword
12259 (if (and (outline-on-heading-p)
12260 (not (bolp))
12261 (save-excursion (beginning-of-line 1)
12262 (looking-at org-todo-line-regexp))
12263 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12264 (progn
12265 (goto-char (or (match-end 2) (match-end 1)))
12266 (and (looking-at " ") (just-one-space))))
12267 (when org-trigger-hook
12268 (save-excursion
12269 (run-hook-with-args 'org-trigger-hook change-plist)))
12270 (when commentp (org-toggle-comment))))))))
12272 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12273 "Block turning an entry into a TODO, using the hierarchy.
12274 This checks whether the current task should be blocked from state
12275 changes. Such blocking occurs when:
12277 1. The task has children which are not all in a completed state.
12279 2. A task has a parent with the property :ORDERED:, and there
12280 are siblings prior to the current task with incomplete
12281 status.
12283 3. The parent of the task is blocked because it has siblings that should
12284 be done first, or is child of a block grandparent TODO entry."
12286 (if (not org-enforce-todo-dependencies)
12287 t ; if locally turned off don't block
12288 (catch 'dont-block
12289 ;; If this is not a todo state change, or if this entry is already DONE,
12290 ;; do not block
12291 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12292 (member (plist-get change-plist :from)
12293 (cons 'done org-done-keywords))
12294 (member (plist-get change-plist :to)
12295 (cons 'todo org-not-done-keywords))
12296 (not (plist-get change-plist :to)))
12297 (throw 'dont-block t))
12298 ;; If this task has children, and any are undone, it's blocked
12299 (save-excursion
12300 (org-back-to-heading t)
12301 (let ((this-level (funcall outline-level)))
12302 (outline-next-heading)
12303 (let ((child-level (funcall outline-level)))
12304 (while (and (not (eobp))
12305 (> child-level this-level))
12306 ;; this todo has children, check whether they are all
12307 ;; completed
12308 (if (and (not (org-entry-is-done-p))
12309 (org-entry-is-todo-p))
12310 (progn (setq org-block-entry-blocking (org-get-heading))
12311 (throw 'dont-block nil)))
12312 (outline-next-heading)
12313 (setq child-level (funcall outline-level))))))
12314 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12315 ;; any previous siblings are undone, it's blocked
12316 (save-excursion
12317 (org-back-to-heading t)
12318 (let* ((pos (point))
12319 (parent-pos (and (org-up-heading-safe) (point))))
12320 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12321 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12322 (forward-line 1)
12323 (re-search-forward org-not-done-heading-regexp pos t))
12324 (setq org-block-entry-blocking (match-string 0))
12325 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12326 ;; Search further up the hierarchy, to see if an ancestor is blocked
12327 (while t
12328 (goto-char parent-pos)
12329 (if (not (looking-at org-not-done-heading-regexp))
12330 (throw 'dont-block t)) ; do not block, parent is not a TODO
12331 (setq pos (point))
12332 (setq parent-pos (and (org-up-heading-safe) (point)))
12333 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12334 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12335 (forward-line 1)
12336 (re-search-forward org-not-done-heading-regexp pos t)
12337 (setq org-block-entry-blocking (org-get-heading)))
12338 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12340 (defcustom org-track-ordered-property-with-tag nil
12341 "Should the ORDERED property also be shown as a tag?
12342 The ORDERED property decides if an entry should require subtasks to be
12343 completed in sequence. Since a property is not very visible, setting
12344 this option means that toggling the ORDERED property with the command
12345 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12346 not relevant for the behavior, but it makes things more visible.
12348 Note that toggling the tag with tags commands will not change the property
12349 and therefore not influence behavior!
12351 This can be t, meaning the tag ORDERED should be used, It can also be a
12352 string to select a different tag for this task."
12353 :group 'org-todo
12354 :type '(choice
12355 (const :tag "No tracking" nil)
12356 (const :tag "Track with ORDERED tag" t)
12357 (string :tag "Use other tag")))
12359 (defun org-toggle-ordered-property ()
12360 "Toggle the ORDERED property of the current entry.
12361 For better visibility, you can track the value of this property with a tag.
12362 See variable `org-track-ordered-property-with-tag'."
12363 (interactive)
12364 (let* ((t1 org-track-ordered-property-with-tag)
12365 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12366 (save-excursion
12367 (org-back-to-heading)
12368 (if (org-entry-get nil "ORDERED")
12369 (progn
12370 (org-delete-property "ORDERED" "PROPERTIES")
12371 (and tag (org-toggle-tag tag 'off))
12372 (message "Subtasks can be completed in arbitrary order"))
12373 (org-entry-put nil "ORDERED" "t")
12374 (and tag (org-toggle-tag tag 'on))
12375 (message "Subtasks must be completed in sequence")))))
12377 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12378 (defun org-block-todo-from-checkboxes (change-plist)
12379 "Block turning an entry into a TODO, using checkboxes.
12380 This checks whether the current task should be blocked from state
12381 changes because there are unchecked boxes in this entry."
12382 (if (not org-enforce-todo-checkbox-dependencies)
12383 t ; if locally turned off don't block
12384 (catch 'dont-block
12385 ;; If this is not a todo state change, or if this entry is already DONE,
12386 ;; do not block
12387 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12388 (member (plist-get change-plist :from)
12389 (cons 'done org-done-keywords))
12390 (member (plist-get change-plist :to)
12391 (cons 'todo org-not-done-keywords))
12392 (not (plist-get change-plist :to)))
12393 (throw 'dont-block t))
12394 ;; If this task has checkboxes that are not checked, it's blocked
12395 (save-excursion
12396 (org-back-to-heading t)
12397 (let ((beg (point)) end)
12398 (outline-next-heading)
12399 (setq end (point))
12400 (goto-char beg)
12401 (if (org-list-search-forward
12402 (concat (org-item-beginning-re)
12403 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12404 "\\[[- ]\\]")
12405 end t)
12406 (progn
12407 (if (boundp 'org-blocked-by-checkboxes)
12408 (setq org-blocked-by-checkboxes t))
12409 (throw 'dont-block nil)))))
12410 t))) ; do not block
12412 (defun org-entry-blocked-p ()
12413 "Is the current entry blocked?"
12414 (org-with-silent-modifications
12415 (if (org-entry-get nil "NOBLOCKING")
12416 nil ;; Never block this entry
12417 (not (run-hook-with-args-until-failure
12418 'org-blocker-hook
12419 (list :type 'todo-state-change
12420 :position (point)
12421 :from 'todo
12422 :to 'done))))))
12424 (defun org-update-statistics-cookies (all)
12425 "Update the statistics cookie, either from TODO or from checkboxes.
12426 This should be called with the cursor in a line with a statistics cookie."
12427 (interactive "P")
12428 (if all
12429 (progn
12430 (org-update-checkbox-count 'all)
12431 (org-map-entries 'org-update-parent-todo-statistics))
12432 (if (not (org-at-heading-p))
12433 (org-update-checkbox-count)
12434 (let ((pos (point-marker))
12435 end l1 l2)
12436 (ignore-errors (org-back-to-heading t))
12437 (if (not (org-at-heading-p))
12438 (org-update-checkbox-count)
12439 (setq l1 (org-outline-level))
12440 (setq end (save-excursion
12441 (outline-next-heading)
12442 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12443 (point)))
12444 (if (and (save-excursion
12445 (re-search-forward
12446 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12447 (not (save-excursion (re-search-forward
12448 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12449 (org-update-checkbox-count)
12450 (if (and l2 (> l2 l1))
12451 (progn
12452 (goto-char end)
12453 (org-update-parent-todo-statistics))
12454 (goto-char pos)
12455 (beginning-of-line 1)
12456 (while (re-search-forward
12457 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12458 (point-at-eol) t)
12459 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12460 (goto-char pos)
12461 (move-marker pos nil)))))
12463 (defvar org-entry-property-inherited-from) ;; defined below
12464 (defun org-update-parent-todo-statistics ()
12465 "Update any statistics cookie in the parent of the current headline.
12466 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12467 the entire subtree and this will travel up the hierarchy and update
12468 statistics everywhere."
12469 (let* ((prop (save-excursion (org-up-heading-safe)
12470 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12471 (recursive (or (not org-hierarchical-todo-statistics)
12472 (and prop (string-match "\\<recursive\\>" prop))))
12473 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12475 (first t)
12476 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12477 level ltoggle l1 new ndel
12478 (cnt-all 0) (cnt-done 0) is-percent kwd
12479 checkbox-beg ov ovs ove cookie-present)
12480 (catch 'exit
12481 (save-excursion
12482 (beginning-of-line 1)
12483 (setq ltoggle (funcall outline-level))
12484 ;; Three situations are to consider:
12486 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12487 ;; to the top-level ancestor on the headline;
12489 ;; 2. If parent has "recursive" property, repeat up to the
12490 ;; headline setting that property, taking inheritance into
12491 ;; account;
12493 ;; 3. Else, move up to direct parent and proceed only once.
12494 (while (and (setq level (org-up-heading-safe))
12495 (or recursive first)
12496 (>= (point) lim))
12497 (setq first nil cookie-present nil)
12498 (unless (and level
12499 (not (string-match
12500 "\\<checkbox\\>"
12501 (downcase (or (org-entry-get nil "COOKIE_DATA")
12502 "")))))
12503 (throw 'exit nil))
12504 (while (re-search-forward box-re (point-at-eol) t)
12505 (setq cnt-all 0 cnt-done 0 cookie-present t)
12506 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12507 (save-match-data
12508 (unless (outline-next-heading) (throw 'exit nil))
12509 (while (and (looking-at org-complex-heading-regexp)
12510 (> (setq l1 (length (match-string 1))) level))
12511 (setq kwd (and (or recursive (= l1 ltoggle))
12512 (match-string 2)))
12513 (if (or (eq org-provide-todo-statistics 'all-headlines)
12514 (and (listp org-provide-todo-statistics)
12515 (or (member kwd org-provide-todo-statistics)
12516 (member kwd org-done-keywords))))
12517 (setq cnt-all (1+ cnt-all))
12518 (if (eq org-provide-todo-statistics t)
12519 (and kwd (setq cnt-all (1+ cnt-all)))))
12520 (and (member kwd org-done-keywords)
12521 (setq cnt-done (1+ cnt-done)))
12522 (outline-next-heading)))
12523 (setq new
12524 (if is-percent
12525 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12526 (format "[%d/%d]" cnt-done cnt-all))
12527 ndel (- (match-end 0) checkbox-beg))
12528 ;; handle overlays when updating cookie from column view
12529 (when (setq ov (car (overlays-at checkbox-beg)))
12530 (setq ovs (overlay-start ov) ove (overlay-end ov))
12531 (delete-overlay ov))
12532 (goto-char checkbox-beg)
12533 (insert new)
12534 (delete-region (point) (+ (point) ndel))
12535 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12536 (when ov (move-overlay ov ovs ove)))
12537 (when cookie-present
12538 (run-hook-with-args 'org-after-todo-statistics-hook
12539 cnt-done (- cnt-all cnt-done))))))
12540 (run-hooks 'org-todo-statistics-hook)))
12542 (defvar org-after-todo-statistics-hook nil
12543 "Hook that is called after a TODO statistics cookie has been updated.
12544 Each function is called with two arguments: the number of not-done entries
12545 and the number of done entries.
12547 For example, the following function, when added to this hook, will switch
12548 an entry to DONE when all children are done, and back to TODO when new
12549 entries are set to a TODO status. Note that this hook is only called
12550 when there is a statistics cookie in the headline!
12552 (defun org-summary-todo (n-done n-not-done)
12553 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12554 (let (org-log-done org-log-states) ; turn off logging
12555 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12558 (defvar org-todo-statistics-hook nil
12559 "Hook that is run whenever Org thinks TODO statistics should be updated.
12560 This hook runs even if there is no statistics cookie present, in which case
12561 `org-after-todo-statistics-hook' would not run.")
12563 (defun org-todo-trigger-tag-changes (state)
12564 "Apply the changes defined in `org-todo-state-tags-triggers'."
12565 (let ((l org-todo-state-tags-triggers)
12566 changes)
12567 (when (or (not state) (equal state ""))
12568 (setq changes (append changes (cdr (assoc "" l)))))
12569 (when (and (stringp state) (> (length state) 0))
12570 (setq changes (append changes (cdr (assoc state l)))))
12571 (when (member state org-not-done-keywords)
12572 (setq changes (append changes (cdr (assoc 'todo l)))))
12573 (when (member state org-done-keywords)
12574 (setq changes (append changes (cdr (assoc 'done l)))))
12575 (dolist (c changes)
12576 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12578 (defun org-local-logging (value)
12579 "Get logging settings from a property VALUE."
12580 (let* (words w a)
12581 ;; directly set the variables, they are already local.
12582 (setq org-log-done nil
12583 org-log-repeat nil
12584 org-todo-log-states nil)
12585 (setq words (org-split-string value))
12586 (while (setq w (pop words))
12587 (cond
12588 ((setq a (assoc w org-startup-options))
12589 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12590 (set (nth 1 a) (nth 2 a))))
12591 ((setq a (org-extract-log-state-settings w))
12592 (and (member (car a) org-todo-keywords-1)
12593 (push a org-todo-log-states)))))))
12595 (defun org-get-todo-sequence-head (kwd)
12596 "Return the head of the TODO sequence to which KWD belongs.
12597 If KWD is not set, check if there is a text property remembering the
12598 right sequence."
12599 (let (p)
12600 (cond
12601 ((not kwd)
12602 (or (get-text-property (point-at-bol) 'org-todo-head)
12603 (progn
12604 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12605 nil (point-at-eol)))
12606 (get-text-property p 'org-todo-head))))
12607 ((not (member kwd org-todo-keywords-1))
12608 (car org-todo-keywords-1))
12609 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12611 (defun org-fast-todo-selection ()
12612 "Fast TODO keyword selection with single keys.
12613 Returns the new TODO keyword, or nil if no state change should occur."
12614 (let* ((fulltable org-todo-key-alist)
12615 (done-keywords org-done-keywords) ;; needed for the faces.
12616 (maxlen (apply 'max (mapcar
12617 (lambda (x)
12618 (if (stringp (car x)) (string-width (car x)) 0))
12619 fulltable)))
12620 (expert nil)
12621 (fwidth (+ maxlen 3 1 3))
12622 (ncol (/ (- (window-width) 4) fwidth))
12623 tg cnt e c tbl
12624 groups ingroup)
12625 (save-excursion
12626 (save-window-excursion
12627 (if expert
12628 (set-buffer (get-buffer-create " *Org todo*"))
12629 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12630 (erase-buffer)
12631 (org-set-local 'org-done-keywords done-keywords)
12632 (setq tbl fulltable cnt 0)
12633 (while (setq e (pop tbl))
12634 (cond
12635 ((equal e '(:startgroup))
12636 (push '() groups) (setq ingroup t)
12637 (when (not (= cnt 0))
12638 (setq cnt 0)
12639 (insert "\n"))
12640 (insert "{ "))
12641 ((equal e '(:endgroup))
12642 (setq ingroup nil cnt 0)
12643 (insert "}\n"))
12644 ((equal e '(:newline))
12645 (when (not (= cnt 0))
12646 (setq cnt 0)
12647 (insert "\n")
12648 (setq e (car tbl))
12649 (while (equal (car tbl) '(:newline))
12650 (insert "\n")
12651 (setq tbl (cdr tbl)))))
12653 (setq tg (car e) c (cdr e))
12654 (if ingroup (push tg (car groups)))
12655 (setq tg (org-add-props tg nil 'face
12656 (org-get-todo-face tg)))
12657 (if (and (= cnt 0) (not ingroup)) (insert " "))
12658 (insert "[" c "] " tg (make-string
12659 (- fwidth 4 (length tg)) ?\ ))
12660 (when (= (setq cnt (1+ cnt)) ncol)
12661 (insert "\n")
12662 (if ingroup (insert " "))
12663 (setq cnt 0)))))
12664 (insert "\n")
12665 (goto-char (point-min))
12666 (if (not expert) (org-fit-window-to-buffer))
12667 (message "[a-z..]:Set [SPC]:clear")
12668 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12669 (cond
12670 ((or (= c ?\C-g)
12671 (and (= c ?q) (not (rassoc c fulltable))))
12672 (setq quit-flag t))
12673 ((= c ?\ ) nil)
12674 ((setq e (rassoc c fulltable) tg (car e))
12676 (t (setq quit-flag t)))))))
12678 (defun org-entry-is-todo-p ()
12679 (member (org-get-todo-state) org-not-done-keywords))
12681 (defun org-entry-is-done-p ()
12682 (member (org-get-todo-state) org-done-keywords))
12684 (defun org-get-todo-state ()
12685 "Return the TODO keyword of the current subtree."
12686 (save-excursion
12687 (org-back-to-heading t)
12688 (and (looking-at org-todo-line-regexp)
12689 (match-end 2)
12690 (match-string 2))))
12692 (defun org-at-date-range-p (&optional inactive-ok)
12693 "Is the cursor inside a date range?"
12694 (interactive)
12695 (save-excursion
12696 (catch 'exit
12697 (let ((pos (point)))
12698 (skip-chars-backward "^[<\r\n")
12699 (skip-chars-backward "<[")
12700 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12701 (>= (match-end 0) pos)
12702 (throw 'exit t))
12703 (skip-chars-backward "^<[\r\n")
12704 (skip-chars-backward "<[")
12705 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12706 (>= (match-end 0) pos)
12707 (throw 'exit t)))
12708 nil)))
12710 (defun org-get-repeat (&optional tagline)
12711 "Check if there is a deadline/schedule with repeater in this entry."
12712 (save-match-data
12713 (save-excursion
12714 (org-back-to-heading t)
12715 (and (re-search-forward (if tagline
12716 (concat tagline "\\s-*" org-repeat-re)
12717 org-repeat-re)
12718 (org-entry-end-position) t)
12719 (match-string-no-properties 1)))))
12721 (defvar org-last-changed-timestamp)
12722 (defvar org-last-inserted-timestamp)
12723 (defvar org-log-post-message)
12724 (defvar org-log-note-purpose)
12725 (defvar org-log-note-how)
12726 (defvar org-log-note-extra)
12727 (defun org-auto-repeat-maybe (done-word)
12728 "Check if the current headline contains a repeated deadline/schedule.
12729 If yes, set TODO state back to what it was and change the base date
12730 of repeating deadline/scheduled time stamps to new date.
12731 This function is run automatically after each state change to a DONE state."
12732 ;; last-state is dynamically scoped into this function
12733 (let* ((repeat (org-get-repeat))
12734 (aa (assoc org-last-state org-todo-kwd-alist))
12735 (interpret (nth 1 aa))
12736 (head (nth 2 aa))
12737 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12738 (msg "Entry repeats: ")
12739 (org-log-done nil)
12740 (org-todo-log-states nil)
12741 re type n what ts time to-state)
12742 (when repeat
12743 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12744 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12745 org-todo-repeat-to-state))
12746 (unless (and to-state (member to-state org-todo-keywords-1))
12747 (setq to-state (if (eq interpret 'type) org-last-state head)))
12748 (org-todo to-state)
12749 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12750 (org-entry-put nil "LAST_REPEAT" (format-time-string
12751 (org-time-stamp-format t t))))
12752 (when org-log-repeat
12753 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12754 (memq 'org-add-log-note post-command-hook))
12755 ;; OK, we are already setup for some record
12756 (if (eq org-log-repeat 'note)
12757 ;; make sure we take a note, not only a time stamp
12758 (setq org-log-note-how 'note))
12759 ;; Set up for taking a record
12760 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12761 org-last-state
12762 'findpos org-log-repeat)))
12763 (org-back-to-heading t)
12764 (org-add-planning-info nil nil 'closed)
12765 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12766 org-deadline-time-regexp "\\)\\|\\("
12767 org-ts-regexp "\\)"))
12768 (while (re-search-forward
12769 re (save-excursion (outline-next-heading) (point)) t)
12770 (setq type (if (match-end 1) org-scheduled-string
12771 (if (match-end 3) org-deadline-string "Plain:"))
12772 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12773 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12774 (setq n (string-to-number (match-string 2 ts))
12775 what (match-string 3 ts))
12776 (if (equal what "w") (setq n (* n 7) what "d"))
12777 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12778 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12779 ;; Preparation, see if we need to modify the start date for the change
12780 (when (match-end 1)
12781 (setq time (save-match-data (org-time-string-to-time ts)))
12782 (cond
12783 ((equal (match-string 1 ts) ".")
12784 ;; Shift starting date to today
12785 (org-timestamp-change
12786 (- (org-today) (time-to-days time))
12787 'day))
12788 ((equal (match-string 1 ts) "+")
12789 (let ((nshiftmax 10) (nshift 0))
12790 (while (or (= nshift 0)
12791 (<= (time-to-days time)
12792 (time-to-days (current-time))))
12793 (when (= (incf nshift) nshiftmax)
12794 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12795 (error "Abort")))
12796 (org-timestamp-change n (cdr (assoc what whata)))
12797 (org-at-timestamp-p t)
12798 (setq ts (match-string 1))
12799 (setq time (save-match-data (org-time-string-to-time ts)))))
12800 (org-timestamp-change (- n) (cdr (assoc what whata)))
12801 ;; rematch, so that we have everything in place for the real shift
12802 (org-at-timestamp-p t)
12803 (setq ts (match-string 1))
12804 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12805 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12806 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12807 (setq org-log-post-message msg)
12808 (message "%s" msg))))
12810 (defun org-show-todo-tree (arg)
12811 "Make a compact tree which shows all headlines marked with TODO.
12812 The tree will show the lines where the regexp matches, and all higher
12813 headlines above the match.
12814 With a \\[universal-argument] prefix, prompt for a regexp to match.
12815 With a numeric prefix N, construct a sparse tree for the Nth element
12816 of `org-todo-keywords-1'."
12817 (interactive "P")
12818 (let ((case-fold-search nil)
12819 (kwd-re
12820 (cond ((null arg) org-not-done-regexp)
12821 ((equal arg '(4))
12822 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12823 (mapcar 'list org-todo-keywords-1))))
12824 (concat "\\("
12825 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12826 "\\)\\>")))
12827 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12828 (regexp-quote (nth (1- (prefix-numeric-value arg))
12829 org-todo-keywords-1)))
12830 (t (error "Invalid prefix argument: %s" arg)))))
12831 (message "%d TODO entries found"
12832 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12834 (defun org-deadline (arg &optional time)
12835 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12836 With one universal prefix argument, remove any deadline from the item.
12837 With two universal prefix arguments, prompt for a warning delay.
12838 With argument TIME, set the deadline at the corresponding date. TIME
12839 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12840 (interactive "P")
12841 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12842 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12843 'region-start-level 'region))
12844 org-loop-over-headlines-in-active-region)
12845 (org-map-entries
12846 `(org-deadline ',arg ,time)
12847 org-loop-over-headlines-in-active-region
12848 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12849 (let* ((old-date (org-entry-get nil "DEADLINE"))
12850 (old-date-time (if old-date (org-time-string-to-time old-date)))
12851 (repeater (and old-date
12852 (string-match
12853 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12854 old-date)
12855 (match-string 1 old-date))))
12856 (cond
12857 ((equal arg '(4))
12858 (when (and old-date org-log-redeadline)
12859 (org-add-log-setup 'deldeadline nil old-date 'findpos
12860 org-log-redeadline))
12861 (org-remove-timestamp-with-keyword org-deadline-string)
12862 (message "Item no longer has a deadline."))
12863 ((equal arg '(16))
12864 (save-excursion
12865 (if (re-search-forward
12866 org-deadline-time-regexp
12867 (save-excursion (outline-next-heading) (point)) t)
12868 (let* ((rpl0 (match-string 1))
12869 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12870 (replace-match
12871 (concat org-deadline-string
12872 " <" rpl
12873 (format " -%dd"
12874 (abs
12875 (- (time-to-days
12876 (save-match-data
12877 (org-read-date nil t nil "Warn starting from" old-date-time)))
12878 (time-to-days old-date-time))))
12879 ">") t t))
12880 (user-error "No deadline information to update"))))
12882 (org-add-planning-info 'deadline time 'closed)
12883 (when (and old-date org-log-redeadline
12884 (not (equal old-date
12885 (substring org-last-inserted-timestamp 1 -1))))
12886 (org-add-log-setup 'redeadline nil old-date 'findpos
12887 org-log-redeadline))
12888 (when repeater
12889 (save-excursion
12890 (org-back-to-heading t)
12891 (when (re-search-forward (concat org-deadline-string " "
12892 org-last-inserted-timestamp)
12893 (save-excursion
12894 (outline-next-heading) (point)) t)
12895 (goto-char (1- (match-end 0)))
12896 (insert " " repeater)
12897 (setq org-last-inserted-timestamp
12898 (concat (substring org-last-inserted-timestamp 0 -1)
12899 " " repeater
12900 (substring org-last-inserted-timestamp -1))))))
12901 (message "Deadline on %s" org-last-inserted-timestamp))))))
12903 (defun org-schedule (arg &optional time)
12904 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12905 With one universal prefix argument, remove any scheduling date from the item.
12906 With two universal prefix arguments, prompt for a delay cookie.
12907 With argument TIME, scheduled at the corresponding date. TIME can
12908 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12909 (interactive "P")
12910 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12911 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12912 'region-start-level 'region))
12913 org-loop-over-headlines-in-active-region)
12914 (org-map-entries
12915 `(org-schedule ',arg ,time)
12916 org-loop-over-headlines-in-active-region
12917 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12918 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12919 (old-date-time (if old-date (org-time-string-to-time old-date)))
12920 (repeater (and old-date
12921 (string-match
12922 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12923 old-date)
12924 (match-string 1 old-date))))
12925 (cond
12926 ((equal arg '(4))
12927 (progn
12928 (when (and old-date org-log-reschedule)
12929 (org-add-log-setup 'delschedule nil old-date 'findpos
12930 org-log-reschedule))
12931 (org-remove-timestamp-with-keyword org-scheduled-string)
12932 (message "Item is no longer scheduled.")))
12933 ((equal arg '(16))
12934 (save-excursion
12935 (if (re-search-forward
12936 org-scheduled-time-regexp
12937 (save-excursion (outline-next-heading) (point)) t)
12938 (let* ((rpl0 (match-string 1))
12939 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12940 (replace-match
12941 (concat org-scheduled-string
12942 " <" rpl
12943 (format " -%dd"
12944 (abs
12945 (- (time-to-days
12946 (save-match-data
12947 (org-read-date nil t nil "Delay until" old-date-time)))
12948 (time-to-days old-date-time))))
12949 ">") t t))
12950 (user-error "No scheduled information to update"))))
12952 (org-add-planning-info 'scheduled time 'closed)
12953 (when (and old-date org-log-reschedule
12954 (not (equal old-date
12955 (substring org-last-inserted-timestamp 1 -1))))
12956 (org-add-log-setup 'reschedule nil old-date 'findpos
12957 org-log-reschedule))
12958 (when repeater
12959 (save-excursion
12960 (org-back-to-heading t)
12961 (when (re-search-forward (concat org-scheduled-string " "
12962 org-last-inserted-timestamp)
12963 (save-excursion
12964 (outline-next-heading) (point)) t)
12965 (goto-char (1- (match-end 0)))
12966 (insert " " repeater)
12967 (setq org-last-inserted-timestamp
12968 (concat (substring org-last-inserted-timestamp 0 -1)
12969 " " repeater
12970 (substring org-last-inserted-timestamp -1))))))
12971 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12973 (defun org-get-scheduled-time (pom &optional inherit)
12974 "Get the scheduled time as a time tuple, of a format suitable
12975 for calling org-schedule with, or if there is no scheduling,
12976 returns nil."
12977 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12978 (when time
12979 (apply 'encode-time (org-parse-time-string time)))))
12981 (defun org-get-deadline-time (pom &optional inherit)
12982 "Get the deadline as a time tuple, of a format suitable for
12983 calling org-deadline with, or if there is no scheduling, returns
12984 nil."
12985 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12986 (when time
12987 (apply 'encode-time (org-parse-time-string time)))))
12989 (defun org-remove-timestamp-with-keyword (keyword)
12990 "Remove all time stamps with KEYWORD in the current entry."
12991 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12992 beg)
12993 (save-excursion
12994 (org-back-to-heading t)
12995 (setq beg (point))
12996 (outline-next-heading)
12997 (while (re-search-backward re beg t)
12998 (replace-match "")
12999 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13000 (equal (char-before) ?\ ))
13001 (backward-delete-char 1)
13002 (if (string-match "^[ \t]*$" (buffer-substring
13003 (point-at-bol) (point-at-eol)))
13004 (delete-region (point-at-bol)
13005 (min (point-max) (1+ (point-at-eol))))))))))
13007 (defun org-add-planning-info (what &optional time &rest remove)
13008 "Insert new timestamp with keyword in the line directly after the headline.
13009 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13010 If non is given, the user is prompted for a date.
13011 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13012 be removed."
13013 (interactive)
13014 (let (org-time-was-given org-end-time-was-given ts
13015 end default-time default-input)
13017 (catch 'exit
13018 (when (and (memq what '(scheduled deadline))
13019 (or (not time)
13020 (and (stringp time)
13021 (string-match "^[-+]+[0-9]" time))))
13022 ;; Try to get a default date/time from existing timestamp
13023 (save-excursion
13024 (org-back-to-heading t)
13025 (setq end (save-excursion (outline-next-heading) (point)))
13026 (when (re-search-forward (if (eq what 'scheduled)
13027 org-scheduled-time-regexp
13028 org-deadline-time-regexp)
13029 end t)
13030 (setq ts (match-string 1)
13031 default-time
13032 (apply 'encode-time (org-parse-time-string ts))
13033 default-input (and ts (org-get-compact-tod ts))))))
13034 (when what
13035 (setq time
13036 (if (stringp time)
13037 ;; This is a string (relative or absolute), set proper date
13038 (apply 'encode-time
13039 (org-read-date-analyze
13040 time default-time (decode-time default-time)))
13041 ;; If necessary, get the time from the user
13042 (or time (org-read-date nil 'to-time nil nil
13043 default-time default-input)))))
13045 (when (and org-insert-labeled-timestamps-at-point
13046 (member what '(scheduled deadline)))
13047 (insert
13048 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13049 (org-insert-time-stamp time org-time-was-given
13050 nil nil nil (list org-end-time-was-given))
13051 (setq what nil))
13052 (save-excursion
13053 (save-restriction
13054 (let (col list elt ts buffer-invisibility-spec)
13055 (org-back-to-heading t)
13056 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13057 (goto-char (match-end 1))
13058 (setq col (current-column))
13059 (goto-char (match-end 0))
13060 (if (eobp) (insert "\n") (forward-char 1))
13061 (when (and (not what)
13062 (not (looking-at
13063 (concat "[ \t]*"
13064 org-keyword-time-not-clock-regexp))))
13065 ;; Nothing to add, nothing to remove...... :-)
13066 (throw 'exit nil))
13067 (if (and (not (looking-at org-outline-regexp))
13068 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13069 "[^\r\n]*"))
13070 (not (equal (match-string 1) org-clock-string)))
13071 (narrow-to-region (match-beginning 0) (match-end 0))
13072 (insert-before-markers "\n")
13073 (backward-char 1)
13074 (narrow-to-region (point) (point))
13075 (and org-adapt-indentation (org-indent-to-column col)))
13076 ;; Check if we have to remove something.
13077 (setq list (cons what remove))
13078 (while list
13079 (setq elt (pop list))
13080 (when (or (and (eq elt 'scheduled)
13081 (re-search-forward org-scheduled-time-regexp nil t))
13082 (and (eq elt 'deadline)
13083 (re-search-forward org-deadline-time-regexp nil t))
13084 (and (eq elt 'closed)
13085 (re-search-forward org-closed-time-regexp nil t)))
13086 (replace-match "")
13087 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13088 (and (looking-at "[ \t]+") (replace-match ""))
13089 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13090 (when what
13091 (insert
13092 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13093 (cond ((eq what 'scheduled) org-scheduled-string)
13094 ((eq what 'deadline) org-deadline-string)
13095 ((eq what 'closed) org-closed-string))
13096 " ")
13097 (setq ts (org-insert-time-stamp
13098 time
13099 (or org-time-was-given
13100 (and (eq what 'closed) org-log-done-with-time))
13101 (eq what 'closed)
13102 nil nil (list org-end-time-was-given)))
13103 (insert
13104 (if (not (or (bolp) (eq (char-before) ?\ )
13105 (memq (char-after) '(32 10))
13106 (eobp))) " " ""))
13107 (end-of-line 1))
13108 (goto-char (point-min))
13109 (widen)
13110 (if (and (looking-at "[ \t]*\n")
13111 (equal (char-before) ?\n))
13112 (delete-region (1- (point)) (point-at-eol)))
13113 ts))))))
13115 (defvar org-log-note-marker (make-marker))
13116 (defvar org-log-note-purpose nil)
13117 (defvar org-log-note-state nil)
13118 (defvar org-log-note-previous-state nil)
13119 (defvar org-log-note-how nil)
13120 (defvar org-log-note-extra nil)
13121 (defvar org-log-note-window-configuration nil)
13122 (defvar org-log-note-return-to (make-marker))
13123 (defvar org-log-note-effective-time nil
13124 "Remembered current time so that dynamically scoped
13125 `org-extend-today-until' affects tha timestamps in state change
13126 log")
13128 (defvar org-log-post-message nil
13129 "Message to be displayed after a log note has been stored.
13130 The auto-repeater uses this.")
13132 (defun org-add-note ()
13133 "Add a note to the current entry.
13134 This is done in the same way as adding a state change note."
13135 (interactive)
13136 (org-add-log-setup 'note nil nil 'findpos nil))
13138 (defvar org-property-end-re)
13139 (defun org-add-log-setup (&optional purpose state prev-state
13140 findpos how extra)
13141 "Set up the post command hook to take a note.
13142 If this is about to TODO state change, the new state is expected in STATE.
13143 When FINDPOS is non-nil, find the correct position for the note in
13144 the current entry. If not, assume that it can be inserted at point.
13145 HOW is an indicator what kind of note should be created.
13146 EXTRA is additional text that will be inserted into the notes buffer."
13147 (let* ((org-log-into-drawer (org-log-into-drawer))
13148 (drawer (cond ((stringp org-log-into-drawer)
13149 org-log-into-drawer)
13150 (org-log-into-drawer "LOGBOOK"))))
13151 (save-restriction
13152 (save-excursion
13153 (when findpos
13154 (org-back-to-heading t)
13155 (narrow-to-region (point) (save-excursion
13156 (outline-next-heading) (point)))
13157 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13158 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13159 "[^\r\n]*\\)?"))
13160 (goto-char (match-end 0))
13161 (cond
13162 (drawer
13163 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13164 nil t)
13165 (progn
13166 (goto-char (match-end 0))
13167 (or org-log-states-order-reversed
13168 (and (re-search-forward org-property-end-re nil t)
13169 (goto-char (1- (match-beginning 0))))))
13170 (insert "\n:" drawer ":\n:END:")
13171 (beginning-of-line 0)
13172 (org-indent-line)
13173 (beginning-of-line 2)
13174 (org-indent-line)
13175 (end-of-line 0)))
13176 ((and org-log-state-notes-insert-after-drawers
13177 (save-excursion
13178 (forward-line) (looking-at org-drawer-regexp)))
13179 (forward-line)
13180 (while (looking-at org-drawer-regexp)
13181 (goto-char (match-end 0))
13182 (re-search-forward org-property-end-re (point-max) t)
13183 (forward-line))
13184 (forward-line -1)))
13185 (unless org-log-states-order-reversed
13186 (and (= (char-after) ?\n) (forward-char 1))
13187 (org-skip-over-state-notes)
13188 (skip-chars-backward " \t\n\r")))
13189 (move-marker org-log-note-marker (point))
13190 (setq org-log-note-purpose purpose
13191 org-log-note-state state
13192 org-log-note-previous-state prev-state
13193 org-log-note-how how
13194 org-log-note-extra extra
13195 org-log-note-effective-time (org-current-effective-time))
13196 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13198 (defun org-skip-over-state-notes ()
13199 "Skip past the list of State notes in an entry."
13200 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13201 (when (ignore-errors (goto-char (org-in-item-p)))
13202 (let* ((struct (org-list-struct))
13203 (prevs (org-list-prevs-alist struct)))
13204 (while (looking-at "[ \t]*- State")
13205 (goto-char (or (org-list-get-next-item (point) struct prevs)
13206 (org-list-get-item-end (point) struct)))))))
13208 (defun org-add-log-note (&optional purpose)
13209 "Pop up a window for taking a note, and add this note later at point."
13210 (remove-hook 'post-command-hook 'org-add-log-note)
13211 (setq org-log-note-window-configuration (current-window-configuration))
13212 (delete-other-windows)
13213 (move-marker org-log-note-return-to (point))
13214 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13215 (goto-char org-log-note-marker)
13216 (org-switch-to-buffer-other-window "*Org Note*")
13217 (erase-buffer)
13218 (if (memq org-log-note-how '(time state))
13219 (let (current-prefix-arg) (org-store-log-note))
13220 (let ((org-inhibit-startup t)) (org-mode))
13221 (insert (format "# Insert note for %s.
13222 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13223 (cond
13224 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13225 ((eq org-log-note-purpose 'done) "closed todo item")
13226 ((eq org-log-note-purpose 'state)
13227 (format "state change from \"%s\" to \"%s\""
13228 (or org-log-note-previous-state "")
13229 (or org-log-note-state "")))
13230 ((eq org-log-note-purpose 'reschedule)
13231 "rescheduling")
13232 ((eq org-log-note-purpose 'delschedule)
13233 "no longer scheduled")
13234 ((eq org-log-note-purpose 'redeadline)
13235 "changing deadline")
13236 ((eq org-log-note-purpose 'deldeadline)
13237 "removing deadline")
13238 ((eq org-log-note-purpose 'refile)
13239 "refiling")
13240 ((eq org-log-note-purpose 'note)
13241 "this entry")
13242 (t (error "This should not happen")))))
13243 (if org-log-note-extra (insert org-log-note-extra))
13244 (org-set-local 'org-finish-function 'org-store-log-note)
13245 (run-hooks 'org-log-buffer-setup-hook)))
13247 (defvar org-note-abort nil) ; dynamically scoped
13248 (defun org-store-log-note ()
13249 "Finish taking a log note, and insert it to where it belongs."
13250 (let ((txt (buffer-string)))
13251 (kill-buffer (current-buffer))
13252 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13253 lines ind bul)
13254 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13255 (setq txt (replace-match "" t t txt)))
13256 (if (string-match "\\s-+\\'" txt)
13257 (setq txt (replace-match "" t t txt)))
13258 (setq lines (org-split-string txt "\n"))
13259 (when (and note (string-match "\\S-" note))
13260 (setq note
13261 (org-replace-escapes
13262 note
13263 (list (cons "%u" (user-login-name))
13264 (cons "%U" user-full-name)
13265 (cons "%t" (format-time-string
13266 (org-time-stamp-format 'long 'inactive)
13267 org-log-note-effective-time))
13268 (cons "%T" (format-time-string
13269 (org-time-stamp-format 'long nil)
13270 org-log-note-effective-time))
13271 (cons "%d" (format-time-string
13272 (org-time-stamp-format nil 'inactive)
13273 org-log-note-effective-time))
13274 (cons "%D" (format-time-string
13275 (org-time-stamp-format nil nil)
13276 org-log-note-effective-time))
13277 (cons "%s" (if org-log-note-state
13278 (concat "\"" org-log-note-state "\"")
13279 ""))
13280 (cons "%S" (if org-log-note-previous-state
13281 (concat "\"" org-log-note-previous-state "\"")
13282 "\"\"")))))
13283 (if lines (setq note (concat note " \\\\")))
13284 (push note lines))
13285 (when (or current-prefix-arg org-note-abort)
13286 (when org-log-into-drawer
13287 (org-remove-empty-drawer-at
13288 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13289 org-log-note-marker))
13290 (setq lines nil))
13291 (when lines
13292 (with-current-buffer (marker-buffer org-log-note-marker)
13293 (save-excursion
13294 (goto-char org-log-note-marker)
13295 (move-marker org-log-note-marker nil)
13296 (end-of-line 1)
13297 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13298 (setq ind (save-excursion
13299 (if (ignore-errors (goto-char (org-in-item-p)))
13300 (let ((struct (org-list-struct)))
13301 (org-list-get-ind
13302 (org-list-get-top-point struct) struct))
13303 (skip-chars-backward " \r\t\n")
13304 (cond
13305 ((and (org-at-heading-p)
13306 org-adapt-indentation)
13307 (1+ (org-current-level)))
13308 ((org-at-heading-p) 0)
13309 (t (org-get-indentation))))))
13310 (setq bul (org-list-bullet-string "-"))
13311 (org-indent-line-to ind)
13312 (insert bul (pop lines))
13313 (let ((ind-body (+ (length bul) ind)))
13314 (while lines
13315 (insert "\n")
13316 (org-indent-line-to ind-body)
13317 (insert (pop lines))))
13318 (message "Note stored")
13319 (org-back-to-heading t)
13320 (org-cycle-hide-drawers 'children))
13321 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13322 ;; from within `org-add-log-note' because `buffer-undo-list'
13323 ;; is then modified outside of `org-with-remote-undo'.
13324 (when (eq this-command 'org-agenda-todo)
13325 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13326 ;; Don't add undo information when called from `org-agenda-todo'
13327 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13328 (set-window-configuration org-log-note-window-configuration)
13329 (with-current-buffer (marker-buffer org-log-note-return-to)
13330 (goto-char org-log-note-return-to))
13331 (move-marker org-log-note-return-to nil)
13332 (and org-log-post-message (message "%s" org-log-post-message))))
13334 (defun org-remove-empty-drawer-at (drawer pos)
13335 "Remove an empty drawer DRAWER at position POS.
13336 POS may also be a marker."
13337 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13338 (save-excursion
13339 (save-restriction
13340 (widen)
13341 (goto-char pos)
13342 (if (org-in-regexp
13343 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13344 (replace-match ""))))))
13346 (defvar org-ts-type nil)
13347 (defun org-sparse-tree (&optional arg type)
13348 "Create a sparse tree, prompt for the details.
13349 This command can create sparse trees. You first need to select the type
13350 of match used to create the tree:
13352 t Show all TODO entries.
13353 T Show entries with a specific TODO keyword.
13354 m Show entries selected by a tags/property match.
13355 p Enter a property name and its value (both with completion on existing
13356 names/values) and show entries with that property.
13357 r Show entries matching a regular expression (`/' can be used as well).
13358 b Show deadlines and scheduled items before a date.
13359 a Show deadlines and scheduled items after a date.
13360 d Show deadlines due within `org-deadline-warning-days'.
13361 D Show deadlines and scheduled items between a date range."
13362 (interactive "P")
13363 (let (ans kwd value ts-type)
13364 (setq type (or type org-sparse-tree-default-date-type))
13365 (setq org-ts-type type)
13366 (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"
13367 (cond ((eq type 'all) "all timestamps")
13368 ((eq type 'scheduled) "only scheduled")
13369 ((eq type 'deadline) "only deadline")
13370 ((eq type 'active) "only active timestamps")
13371 ((eq type 'inactive) "only inactive timestamps")
13372 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13373 ((eq type 'closed) "with a closed time-stamp")
13374 (t "scheduled/deadline")))
13375 (setq ans (read-char-exclusive))
13376 (cond
13377 ((equal ans ?c)
13378 (org-sparse-tree
13379 arg (cadr (member type '(scheduled-or-deadline
13380 all scheduled deadline active inactive closed)))))
13381 ((equal ans ?d)
13382 (call-interactively 'org-check-deadlines))
13383 ((equal ans ?b)
13384 (call-interactively 'org-check-before-date))
13385 ((equal ans ?a)
13386 (call-interactively 'org-check-after-date))
13387 ((equal ans ?D)
13388 (call-interactively 'org-check-dates-range))
13389 ((equal ans ?t)
13390 (call-interactively 'org-show-todo-tree))
13391 ((equal ans ?T)
13392 (org-show-todo-tree '(4)))
13393 ((member ans '(?T ?m))
13394 (call-interactively 'org-match-sparse-tree))
13395 ((member ans '(?p ?P))
13396 (setq kwd (org-icompleting-read "Property: "
13397 (mapcar 'list (org-buffer-property-keys))))
13398 (setq value (org-icompleting-read "Value: "
13399 (mapcar 'list (org-property-values kwd))))
13400 (unless (string-match "\\`{.*}\\'" value)
13401 (setq value (concat "\"" value "\"")))
13402 (org-match-sparse-tree arg (concat kwd "=" value)))
13403 ((member ans '(?r ?R ?/))
13404 (call-interactively 'org-occur))
13405 (t (error "No such sparse tree command \"%c\"" ans)))))
13407 (defvar org-occur-highlights nil
13408 "List of overlays used for occur matches.")
13409 (make-variable-buffer-local 'org-occur-highlights)
13410 (defvar org-occur-parameters nil
13411 "Parameters of the active org-occur calls.
13412 This is a list, each call to org-occur pushes as cons cell,
13413 containing the regular expression and the callback, onto the list.
13414 The list can contain several entries if `org-occur' has been called
13415 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13416 will only contain one set of parameters. When the highlights are
13417 removed (for example with `C-c C-c', or with the next edit (depending
13418 on `org-remove-highlights-with-change'), this variable is emptied
13419 as well.")
13420 (make-variable-buffer-local 'org-occur-parameters)
13422 (defun org-occur (regexp &optional keep-previous callback)
13423 "Make a compact tree which shows all matches of REGEXP.
13424 The tree will show the lines where the regexp matches, and all higher
13425 headlines above the match. It will also show the heading after the match,
13426 to make sure editing the matching entry is easy.
13427 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13428 call to `org-occur' will be kept, to allow stacking of calls to this
13429 command.
13430 If CALLBACK is non-nil, it is a function which is called to confirm
13431 that the match should indeed be shown."
13432 (interactive "sRegexp: \nP")
13433 (when (equal regexp "")
13434 (error "Regexp cannot be empty"))
13435 (unless keep-previous
13436 (org-remove-occur-highlights nil nil t))
13437 (push (cons regexp callback) org-occur-parameters)
13438 (let ((cnt 0))
13439 (save-excursion
13440 (goto-char (point-min))
13441 (if (or (not keep-previous) ; do not want to keep
13442 (not org-occur-highlights)) ; no previous matches
13443 ;; hide everything
13444 (org-overview))
13445 (while (re-search-forward regexp nil t)
13446 (when (or (not callback)
13447 (save-match-data (funcall callback)))
13448 (setq cnt (1+ cnt))
13449 (when org-highlight-sparse-tree-matches
13450 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13451 (org-show-context 'occur-tree))))
13452 (when org-remove-highlights-with-change
13453 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13454 nil 'local))
13455 (unless org-sparse-tree-open-archived-trees
13456 (org-hide-archived-subtrees (point-min) (point-max)))
13457 (run-hooks 'org-occur-hook)
13458 (if (org-called-interactively-p 'interactive)
13459 (message "%d match(es) for regexp %s" cnt regexp))
13460 cnt))
13462 (defun org-occur-next-match (&optional n reset)
13463 "Function for `next-error-function' to find sparse tree matches.
13464 N is the number of matches to move, when negative move backwards.
13465 RESET is entirely ignored - this function always goes back to the
13466 starting point when no match is found."
13467 (let* ((limit (if (< n 0) (point-min) (point-max)))
13468 (search-func (if (< n 0)
13469 'previous-single-char-property-change
13470 'next-single-char-property-change))
13471 (n (abs n))
13472 (pos (point))
13474 (catch 'exit
13475 (while (setq p1 (funcall search-func (point) 'org-type))
13476 (when (equal p1 limit)
13477 (goto-char pos)
13478 (error "No more matches"))
13479 (when (equal (get-char-property p1 'org-type) 'org-occur)
13480 (setq n (1- n))
13481 (when (= n 0)
13482 (goto-char p1)
13483 (throw 'exit (point))))
13484 (goto-char p1))
13485 (goto-char p1)
13486 (error "No more matches"))))
13488 (defun org-show-context (&optional key)
13489 "Make sure point and context are visible.
13490 How much context is shown depends upon the variables
13491 `org-show-hierarchy-above', `org-show-following-heading',
13492 `org-show-entry-below' and `org-show-siblings'."
13493 (let ((heading-p (org-at-heading-p t))
13494 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13495 (following-p (org-get-alist-option org-show-following-heading key))
13496 (entry-p (org-get-alist-option org-show-entry-below key))
13497 (siblings-p (org-get-alist-option org-show-siblings key)))
13498 ;; Show heading or entry text
13499 (if (and heading-p (not entry-p))
13500 (org-flag-heading nil) ; only show the heading
13501 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13502 (org-show-hidden-entry))) ; show entire entry
13503 (when following-p
13504 ;; Show next sibling, or heading below text
13505 (save-excursion
13506 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13507 (org-flag-heading nil))))
13508 (when siblings-p (org-show-siblings))
13509 (when hierarchy-p
13510 ;; show all higher headings, possibly with siblings
13511 (save-excursion
13512 (while (and (condition-case nil
13513 (progn (org-up-heading-all 1) t)
13514 (error nil))
13515 (not (bobp)))
13516 (org-flag-heading nil)
13517 (when siblings-p (org-show-siblings)))))
13518 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13520 (defvar org-reveal-start-hook nil
13521 "Hook run before revealing a location.")
13523 (defun org-reveal (&optional siblings)
13524 "Show current entry, hierarchy above it, and the following headline.
13525 This can be used to show a consistent set of context around locations
13526 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13527 not t for the search context.
13529 With optional argument SIBLINGS, on each level of the hierarchy all
13530 siblings are shown. This repairs the tree structure to what it would
13531 look like when opened with hierarchical calls to `org-cycle'.
13532 With double optional argument \\[universal-argument] \\[universal-argument], \
13533 go to the parent and show the
13534 entire tree."
13535 (interactive "P")
13536 (run-hooks 'org-reveal-start-hook)
13537 (let ((org-show-hierarchy-above t)
13538 (org-show-following-heading t)
13539 (org-show-siblings (if siblings t org-show-siblings)))
13540 (org-show-context nil))
13541 (when (equal siblings '(16))
13542 (save-excursion
13543 (when (org-up-heading-safe)
13544 (org-show-subtree)
13545 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13547 (defun org-highlight-new-match (beg end)
13548 "Highlight from BEG to END and mark the highlight is an occur headline."
13549 (let ((ov (make-overlay beg end)))
13550 (overlay-put ov 'face 'secondary-selection)
13551 (overlay-put ov 'org-type 'org-occur)
13552 (push ov org-occur-highlights)))
13554 (defun org-remove-occur-highlights (&optional beg end noremove)
13555 "Remove the occur highlights from the buffer.
13556 BEG and END are ignored. If NOREMOVE is nil, remove this function
13557 from the `before-change-functions' in the current buffer."
13558 (interactive)
13559 (unless org-inhibit-highlight-removal
13560 (mapc 'delete-overlay org-occur-highlights)
13561 (setq org-occur-highlights nil)
13562 (setq org-occur-parameters nil)
13563 (unless noremove
13564 (remove-hook 'before-change-functions
13565 'org-remove-occur-highlights 'local))))
13567 ;;;; Priorities
13569 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13570 "Regular expression matching the priority indicator.")
13572 (defvar org-remove-priority-next-time nil)
13574 (defun org-priority-up ()
13575 "Increase the priority of the current item."
13576 (interactive)
13577 (org-priority 'up))
13579 (defun org-priority-down ()
13580 "Decrease the priority of the current item."
13581 (interactive)
13582 (org-priority 'down))
13584 (defun org-priority (&optional action show)
13585 "Change the priority of an item.
13586 ACTION can be `set', `up', `down', or a character."
13587 (interactive "P")
13588 (if (equal action '(4))
13589 (org-show-priority)
13590 (unless org-enable-priority-commands
13591 (error "Priority commands are disabled"))
13592 (setq action (or action 'set))
13593 (let (current new news have remove)
13594 (save-excursion
13595 (org-back-to-heading t)
13596 (if (looking-at org-priority-regexp)
13597 (setq current (string-to-char (match-string 2))
13598 have t))
13599 (cond
13600 ((eq action 'remove)
13601 (setq remove t new ?\ ))
13602 ((or (eq action 'set)
13603 (if (featurep 'xemacs) (characterp action) (integerp action)))
13604 (if (not (eq action 'set))
13605 (setq new action)
13606 (message "Priority %c-%c, SPC to remove: "
13607 org-highest-priority org-lowest-priority)
13608 (save-match-data
13609 (setq new (read-char-exclusive))))
13610 (if (and (= (upcase org-highest-priority) org-highest-priority)
13611 (= (upcase org-lowest-priority) org-lowest-priority))
13612 (setq new (upcase new)))
13613 (cond ((equal new ?\ ) (setq remove t))
13614 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13615 (error "Priority must be between `%c' and `%c'"
13616 org-highest-priority org-lowest-priority))))
13617 ((eq action 'up)
13618 (setq new (if have
13619 (1- current) ; normal cycling
13620 ;; last priority was empty
13621 (if (eq last-command this-command)
13622 org-lowest-priority ; wrap around empty to lowest
13623 ;; default
13624 (if org-priority-start-cycle-with-default
13625 org-default-priority
13626 (1- org-default-priority))))))
13627 ((eq action 'down)
13628 (setq new (if have
13629 (1+ current) ; normal cycling
13630 ;; last priority was empty
13631 (if (eq last-command this-command)
13632 org-highest-priority ; wrap around empty to highest
13633 ;; default
13634 (if org-priority-start-cycle-with-default
13635 org-default-priority
13636 (1+ org-default-priority))))))
13637 (t (error "Invalid action")))
13638 (if (or (< (upcase new) org-highest-priority)
13639 (> (upcase new) org-lowest-priority))
13640 (if (and (memq action '(up down))
13641 (not have) (not (eq last-command this-command)))
13642 ;; `new' is from default priority
13643 (error
13644 "The default can not be set, see `org-default-priority' why")
13645 ;; normal cycling: `new' is beyond highest/lowest priority
13646 ;; and is wrapped around to the empty priority
13647 (setq remove t)))
13648 (setq news (format "%c" new))
13649 (if have
13650 (if remove
13651 (replace-match "" t t nil 1)
13652 (replace-match news t t nil 2))
13653 (if remove
13654 (error "No priority cookie found in line")
13655 (let ((case-fold-search nil))
13656 (looking-at org-todo-line-regexp))
13657 (if (match-end 2)
13658 (progn
13659 (goto-char (match-end 2))
13660 (insert " [#" news "]"))
13661 (goto-char (match-beginning 3))
13662 (insert "[#" news "] "))))
13663 (org-preserve-lc (org-set-tags nil 'align)))
13664 (if remove
13665 (message "Priority removed")
13666 (message "Priority of current item set to %s" news)))))
13668 (defun org-show-priority ()
13669 "Show the priority of the current item.
13670 This priority is composed of the main priority given with the [#A] cookies,
13671 and by additional input from the age of a schedules or deadline entry."
13672 (interactive)
13673 (let ((pri (if (eq major-mode 'org-agenda-mode)
13674 (org-get-at-bol 'priority)
13675 (save-excursion
13676 (save-match-data
13677 (beginning-of-line)
13678 (and (looking-at org-heading-regexp)
13679 (org-get-priority (match-string 0))))))))
13680 (message "Priority is %d" (if pri pri -1000))))
13682 (defun org-get-priority (s)
13683 "Find priority cookie and return priority."
13684 (save-match-data
13685 (if (functionp org-get-priority-function)
13686 (funcall org-get-priority-function)
13687 (if (not (string-match org-priority-regexp s))
13688 (* 1000 (- org-lowest-priority org-default-priority))
13689 (* 1000 (- org-lowest-priority
13690 (string-to-char (match-string 2 s))))))))
13692 ;;;; Tags
13694 (defvar org-agenda-archives-mode)
13695 (defvar org-map-continue-from nil
13696 "Position from where mapping should continue.
13697 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13699 (defvar org-scanner-tags nil
13700 "The current tag list while the tags scanner is running.")
13701 (defvar org-trust-scanner-tags nil
13702 "Should `org-get-tags-at' use the tags for the scanner.
13703 This is for internal dynamical scoping only.
13704 When this is non-nil, the function `org-get-tags-at' will return the value
13705 of `org-scanner-tags' instead of building the list by itself. This
13706 can lead to large speed-ups when the tags scanner is used in a file with
13707 many entries, and when the list of tags is retrieved, for example to
13708 obtain a list of properties. Building the tags list for each entry in such
13709 a file becomes an N^2 operation - but with this variable set, it scales
13710 as N.")
13712 (defun org-scan-tags (action matcher todo-only &optional start-level)
13713 "Sca headline tags with inheritance and produce output ACTION.
13715 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13716 or `agenda' to produce an entry list for an agenda view. It can also be
13717 a Lisp form or a function that should be called at each matched headline, in
13718 this case the return value is a list of all return values from these calls.
13720 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13721 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13722 only lines with a not-done TODO keyword are included in the output.
13723 This should be the same variable that was scoped into
13724 and set by `org-make-tags-matcher' when it constructed MATCHER.
13726 START-LEVEL can be a string with asterisks, reducing the scope to
13727 headlines matching this string."
13728 (require 'org-agenda)
13729 (let* ((re (concat "^"
13730 (if start-level
13731 ;; Get the correct level to match
13732 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13733 org-outline-regexp)
13734 " *\\(\\<\\("
13735 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13736 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13737 (props (list 'face 'default
13738 'done-face 'org-agenda-done
13739 'undone-face 'default
13740 'mouse-face 'highlight
13741 'org-not-done-regexp org-not-done-regexp
13742 'org-todo-regexp org-todo-regexp
13743 'org-complex-heading-regexp org-complex-heading-regexp
13744 'help-echo
13745 (format "mouse-2 or RET jump to org file %s"
13746 (abbreviate-file-name
13747 (or (buffer-file-name (buffer-base-buffer))
13748 (buffer-name (buffer-base-buffer)))))))
13749 (case-fold-search nil)
13750 (org-map-continue-from nil)
13751 lspos tags tags-list
13752 (tags-alist (list (cons 0 org-file-tags)))
13753 (llast 0) rtn rtn1 level category i txt
13754 todo marker entry priority)
13755 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13756 (setq action (list 'lambda nil action)))
13757 (save-excursion
13758 (goto-char (point-min))
13759 (when (eq action 'sparse-tree)
13760 (org-overview)
13761 (org-remove-occur-highlights))
13762 (while (re-search-forward re nil t)
13763 (setq org-map-continue-from nil)
13764 (catch :skip
13765 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13766 tags (if (match-end 4) (org-match-string-no-properties 4)))
13767 (goto-char (setq lspos (match-beginning 0)))
13768 (setq level (org-reduced-level (org-outline-level))
13769 category (org-get-category))
13770 (setq i llast llast level)
13771 ;; remove tag lists from same and sublevels
13772 (while (>= i level)
13773 (when (setq entry (assoc i tags-alist))
13774 (setq tags-alist (delete entry tags-alist)))
13775 (setq i (1- i)))
13776 ;; add the next tags
13777 (when tags
13778 (setq tags (org-split-string tags ":")
13779 tags-alist
13780 (cons (cons level tags) tags-alist)))
13781 ;; compile tags for current headline
13782 (setq tags-list
13783 (if org-use-tag-inheritance
13784 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13785 tags)
13786 org-scanner-tags tags-list)
13787 (when org-use-tag-inheritance
13788 (setcdr (car tags-alist)
13789 (mapcar (lambda (x)
13790 (setq x (copy-sequence x))
13791 (org-add-prop-inherited x))
13792 (cdar tags-alist))))
13793 (when (and tags org-use-tag-inheritance
13794 (or (not (eq t org-use-tag-inheritance))
13795 org-tags-exclude-from-inheritance))
13796 ;; selective inheritance, remove uninherited ones
13797 (setcdr (car tags-alist)
13798 (org-remove-uninherited-tags (cdar tags-alist))))
13799 (when (and
13801 ;; eval matcher only when the todo condition is OK
13802 (and (or (not todo-only) (member todo org-not-done-keywords))
13803 (let ((case-fold-search t) (org-trust-scanner-tags t))
13804 (eval matcher)))
13806 ;; Call the skipper, but return t if it does not skip,
13807 ;; so that the `and' form continues evaluating
13808 (progn
13809 (unless (eq action 'sparse-tree) (org-agenda-skip))
13812 ;; Check if timestamps are deselecting this entry
13813 (or (not todo-only)
13814 (and (member todo org-not-done-keywords)
13815 (or (not org-agenda-tags-todo-honor-ignore-options)
13816 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13818 ;; select this headline
13819 (cond
13820 ((eq action 'sparse-tree)
13821 (and org-highlight-sparse-tree-matches
13822 (org-get-heading) (match-end 0)
13823 (org-highlight-new-match
13824 (match-beginning 1) (match-end 1)))
13825 (org-show-context 'tags-tree))
13826 ((eq action 'agenda)
13827 (setq txt (org-agenda-format-item
13829 (concat
13830 (if (eq org-tags-match-list-sublevels 'indented)
13831 (make-string (1- level) ?.) "")
13832 (org-get-heading))
13833 level category
13834 tags-list)
13835 priority (org-get-priority txt))
13836 (goto-char lspos)
13837 (setq marker (org-agenda-new-marker))
13838 (org-add-props txt props
13839 'org-marker marker 'org-hd-marker marker 'org-category category
13840 'todo-state todo
13841 'priority priority 'type "tagsmatch")
13842 (push txt rtn))
13843 ((functionp action)
13844 (setq org-map-continue-from nil)
13845 (save-excursion
13846 (setq rtn1 (funcall action))
13847 (push rtn1 rtn)))
13848 (t (error "Invalid action")))
13850 ;; if we are to skip sublevels, jump to end of subtree
13851 (unless org-tags-match-list-sublevels
13852 (org-end-of-subtree t)
13853 (backward-char 1))))
13854 ;; Get the correct position from where to continue
13855 (if org-map-continue-from
13856 (goto-char org-map-continue-from)
13857 (and (= (point) lspos) (end-of-line 1)))))
13858 (when (and (eq action 'sparse-tree)
13859 (not org-sparse-tree-open-archived-trees))
13860 (org-hide-archived-subtrees (point-min) (point-max)))
13861 (nreverse rtn)))
13863 (defun org-remove-uninherited-tags (tags)
13864 "Remove all tags that are not inherited from the list TAGS."
13865 (cond
13866 ((eq org-use-tag-inheritance t)
13867 (if org-tags-exclude-from-inheritance
13868 (org-delete-all org-tags-exclude-from-inheritance tags)
13869 tags))
13870 ((not org-use-tag-inheritance) nil)
13871 ((stringp org-use-tag-inheritance)
13872 (delq nil (mapcar
13873 (lambda (x)
13874 (if (and (string-match org-use-tag-inheritance x)
13875 (not (member x org-tags-exclude-from-inheritance)))
13876 x nil))
13877 tags)))
13878 ((listp org-use-tag-inheritance)
13879 (delq nil (mapcar
13880 (lambda (x)
13881 (if (member x org-use-tag-inheritance) x nil))
13882 tags)))))
13884 (defun org-match-sparse-tree (&optional todo-only match)
13885 "Create a sparse tree according to tags string MATCH.
13886 MATCH can contain positive and negative selection of tags, like
13887 \"+WORK+URGENT-WITHBOSS\".
13888 If optional argument TODO-ONLY is non-nil, only select lines that are
13889 also TODO lines."
13890 (interactive "P")
13891 (org-agenda-prepare-buffers (list (current-buffer)))
13892 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13894 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13896 (defvar org-cached-props nil)
13897 (defun org-cached-entry-get (pom property)
13898 (if (or (eq t org-use-property-inheritance)
13899 (and (stringp org-use-property-inheritance)
13900 (string-match org-use-property-inheritance property))
13901 (and (listp org-use-property-inheritance)
13902 (member property org-use-property-inheritance)))
13903 ;; Caching is not possible, check it directly
13904 (org-entry-get pom property 'inherit)
13905 ;; Get all properties, so that we can do complicated checks easily
13906 (cdr (assoc property (or org-cached-props
13907 (setq org-cached-props
13908 (org-entry-properties pom)))))))
13910 (defun org-global-tags-completion-table (&optional files)
13911 "Return the list of all tags in all agenda buffer/files.
13912 Optional FILES argument is a list of files which can be used
13913 instead of the agenda files."
13914 (save-excursion
13915 (org-uniquify
13916 (delq nil
13917 (apply 'append
13918 (mapcar
13919 (lambda (file)
13920 (set-buffer (find-file-noselect file))
13921 (append (org-get-buffer-tags)
13922 (mapcar (lambda (x) (if (stringp (car-safe x))
13923 (list (car-safe x)) nil))
13924 org-tag-alist)))
13925 (if (and files (car files))
13926 files
13927 (org-agenda-files))))))))
13929 (defun org-make-tags-matcher (match)
13930 "Create the TAGS/TODO matcher form for the selection string MATCH.
13932 The variable `todo-only' is scoped dynamically into this function.
13933 It will be set to t if the matcher restricts matching to TODO entries,
13934 otherwise will not be touched.
13936 Returns a cons of the selection string MATCH and the constructed
13937 lisp form implementing the matcher. The matcher is to be evaluated
13938 at an Org entry, with point on the headline, and returns t if the
13939 entry matches the selection string MATCH. The returned lisp form
13940 references two variables with information about the entry, which
13941 must be bound around the form's evaluation: todo, the TODO keyword
13942 at the entry (or nil of none); and tags-list, the list of all tags
13943 at the entry including inherited ones. Additionally, the category
13944 of the entry (if any) must be specified as the text property
13945 'org-category on the headline.
13947 See also `org-scan-tags'.
13949 (declare (special todo-only))
13950 (unless (boundp 'todo-only)
13951 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13952 (unless match
13953 ;; Get a new match request, with completion against the global
13954 ;; tags table and the local tags in current buffer
13955 (let ((org-last-tags-completion-table
13956 (org-uniquify
13957 (delq nil (append (org-get-buffer-tags)
13958 (org-global-tags-completion-table))))))
13959 (setq match (org-completing-read-no-i
13960 "Match: " 'org-tags-completion-function nil nil nil
13961 'org-tags-history))))
13963 ;; Parse the string and create a lisp form
13964 (let ((match0 match)
13965 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13966 minus tag mm
13967 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13968 orterms term orlist re-p str-p level-p level-op time-p
13969 prop-p pn pv po gv rest)
13970 ;; Expand group tags
13971 (setq match (org-tags-expand match))
13972 (if (string-match "/+" match)
13973 ;; match contains also a todo-matching request
13974 (progn
13975 (setq tagsmatch (substring match 0 (match-beginning 0))
13976 todomatch (substring match (match-end 0)))
13977 (if (string-match "^!" todomatch)
13978 (setq todo-only t todomatch (substring todomatch 1)))
13979 (if (string-match "^\\s-*$" todomatch)
13980 (setq todomatch nil)))
13981 ;; only matching tags
13982 (setq tagsmatch match todomatch nil))
13984 ;; Make the tags matcher
13985 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13986 (setq tagsmatcher t)
13987 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13988 (while (setq term (pop orterms))
13989 (while (and (equal (substring term -1) "\\") orterms)
13990 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13991 (while (string-match re term)
13992 (setq rest (substring term (match-end 0))
13993 minus (and (match-end 1)
13994 (equal (match-string 1 term) "-"))
13995 tag (save-match-data (replace-regexp-in-string
13996 "\\\\-" "-"
13997 (match-string 2 term)))
13998 re-p (equal (string-to-char tag) ?{)
13999 level-p (match-end 4)
14000 prop-p (match-end 5)
14001 mm (cond
14002 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14003 (level-p
14004 (setq level-op (org-op-to-function (match-string 3 term)))
14005 `(,level-op level ,(string-to-number
14006 (match-string 4 term))))
14007 (prop-p
14008 (setq pn (match-string 5 term)
14009 po (match-string 6 term)
14010 pv (match-string 7 term)
14011 re-p (equal (string-to-char pv) ?{)
14012 str-p (equal (string-to-char pv) ?\")
14013 time-p (save-match-data
14014 (string-match "^\"[[<].*[]>]\"$" pv))
14015 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14016 (if time-p (setq pv (org-matcher-time pv)))
14017 (setq po (org-op-to-function po (if time-p 'time str-p)))
14018 (cond
14019 ((equal pn "CATEGORY")
14020 (setq gv '(get-text-property (point) 'org-category)))
14021 ((equal pn "TODO")
14022 (setq gv 'todo))
14024 (setq gv `(org-cached-entry-get nil ,pn))))
14025 (if re-p
14026 (if (eq po 'org<>)
14027 `(not (string-match ,pv (or ,gv "")))
14028 `(string-match ,pv (or ,gv "")))
14029 (if str-p
14030 `(,po (or ,gv "") ,pv)
14031 `(,po (string-to-number (or ,gv ""))
14032 ,(string-to-number pv) ))))
14033 (t `(member ,tag tags-list)))
14034 mm (if minus (list 'not mm) mm)
14035 term rest)
14036 (push mm tagsmatcher))
14037 (push (if (> (length tagsmatcher) 1)
14038 (cons 'and tagsmatcher)
14039 (car tagsmatcher))
14040 orlist)
14041 (setq tagsmatcher nil))
14042 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14043 (setq tagsmatcher
14044 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14045 ;; Make the todo matcher
14046 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14047 (setq todomatcher t)
14048 (setq orterms (org-split-string todomatch "|") orlist nil)
14049 (while (setq term (pop orterms))
14050 (while (string-match re term)
14051 (setq minus (and (match-end 1)
14052 (equal (match-string 1 term) "-"))
14053 kwd (match-string 2 term)
14054 re-p (equal (string-to-char kwd) ?{)
14055 term (substring term (match-end 0))
14056 mm (if re-p
14057 `(string-match ,(substring kwd 1 -1) todo)
14058 (list 'equal 'todo kwd))
14059 mm (if minus (list 'not mm) mm))
14060 (push mm todomatcher))
14061 (push (if (> (length todomatcher) 1)
14062 (cons 'and todomatcher)
14063 (car todomatcher))
14064 orlist)
14065 (setq todomatcher nil))
14066 (setq todomatcher (if (> (length orlist) 1)
14067 (cons 'or orlist) (car orlist))))
14069 ;; Return the string and lisp forms of the matcher
14070 (setq matcher (if todomatcher
14071 (list 'and tagsmatcher todomatcher)
14072 tagsmatcher))
14073 (when todo-only
14074 (setq matcher (list 'and '(member todo org-not-done-keywords)
14075 matcher)))
14076 (cons match0 matcher)))
14078 (defun org-tags-expand (match &optional single-as-list downcased)
14079 "Expand group tags in MATCH.
14081 This replaces every group tag in MATCH with a regexp tag search.
14082 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14083 will be replaced like this:
14085 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14086 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14087 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14089 Replacing by a regexp preserves the structure of the match.
14090 E.g., this expansion
14092 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14094 will match anything tagged with \"Lab\" and \"Home\", or tagged
14095 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14097 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14098 assumed to be a single group tag, and the function will return
14099 the list of tags in this group.
14101 When DOWNCASE is non-nil, expand downcased TAGS."
14102 (if org-group-tags
14103 (let* ((case-fold-search t)
14104 (stable org-mode-syntax-table)
14105 (tal (or org-tag-groups-alist-for-agenda
14106 org-tag-groups-alist))
14107 (tal (if downcased
14108 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14109 (tml (mapcar 'car tal))
14110 (rtnmatch match) rpl)
14111 ;; @ and _ are allowed as word-components in tags
14112 (modify-syntax-entry ?@ "w" stable)
14113 (modify-syntax-entry ?_ "w" stable)
14114 (while (and tml
14115 (string-match
14116 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14117 (regexp-opt tml) "\\>\\)") rtnmatch))
14118 (let* ((dir (match-string 1 rtnmatch))
14119 (tag (match-string 2 rtnmatch))
14120 (tag (if downcased (downcase tag) tag)))
14121 (setq tml (delete tag tml))
14122 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14123 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14124 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14125 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14126 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14127 (if single-as-list
14128 (or (reverse rpl) (list rtnmatch))
14129 rtnmatch))
14130 (if single-as-list (list (if downcased (downcase match) match))
14131 match)))
14133 (defun org-op-to-function (op &optional stringp)
14134 "Turn an operator into the appropriate function."
14135 (setq op
14136 (cond
14137 ((equal op "<" ) '(< string< org-time<))
14138 ((equal op ">" ) '(> org-string> org-time>))
14139 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14140 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14141 ((member op '("=" "==")) '(= string= org-time=))
14142 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14143 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14145 (defun org<> (a b) (not (= a b)))
14146 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14147 (defun org-string>= (a b) (not (string< a b)))
14148 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14149 (defun org-string<> (a b) (not (string= a b)))
14150 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14151 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14152 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14153 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14154 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14155 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14156 (defun org-2ft (s)
14157 "Convert S to a floating point time.
14158 If S is already a number, just return it. If it is a string, parse
14159 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14160 (cond
14161 ((numberp s) s)
14162 ((stringp s)
14163 (condition-case nil
14164 (float-time (apply 'encode-time (org-parse-time-string s)))
14165 (error 0.)))
14166 (t 0.)))
14168 (defun org-time-today ()
14169 "Time in seconds today at 0:00.
14170 Returns the float number of seconds since the beginning of the
14171 epoch to the beginning of today (00:00)."
14172 (float-time (apply 'encode-time
14173 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14175 (defun org-matcher-time (s)
14176 "Interpret a time comparison value."
14177 (save-match-data
14178 (cond
14179 ((string= s "<now>") (float-time))
14180 ((string= s "<today>") (org-time-today))
14181 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14182 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14183 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14184 (+ (org-time-today)
14185 (* (string-to-number (match-string 1 s))
14186 (cdr (assoc (match-string 2 s)
14187 '(("d" . 86400.0) ("w" . 604800.0)
14188 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14189 (t (org-2ft s)))))
14191 (defun org-match-any-p (re list)
14192 "Does re match any element of list?"
14193 (setq list (mapcar (lambda (x) (string-match re x)) list))
14194 (delq nil list))
14196 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14197 (defvar org-tags-overlay (make-overlay 1 1))
14198 (org-detach-overlay org-tags-overlay)
14200 (defun org-get-local-tags-at (&optional pos)
14201 "Get a list of tags defined in the current headline."
14202 (org-get-tags-at pos 'local))
14204 (defun org-get-local-tags ()
14205 "Get a list of tags defined in the current headline."
14206 (org-get-tags-at nil 'local))
14208 (defun org-get-tags-at (&optional pos local)
14209 "Get a list of all headline tags applicable at POS.
14210 POS defaults to point. If tags are inherited, the list contains
14211 the targets in the same sequence as the headlines appear, i.e.
14212 the tags of the current headline come last.
14213 When LOCAL is non-nil, only return tags from the current headline,
14214 ignore inherited ones."
14215 (interactive)
14216 (if (and org-trust-scanner-tags
14217 (or (not pos) (equal pos (point)))
14218 (not local))
14219 org-scanner-tags
14220 (let (tags ltags lastpos parent)
14221 (save-excursion
14222 (save-restriction
14223 (widen)
14224 (goto-char (or pos (point)))
14225 (save-match-data
14226 (catch 'done
14227 (condition-case nil
14228 (progn
14229 (org-back-to-heading t)
14230 (while (not (equal lastpos (point)))
14231 (setq lastpos (point))
14232 (when (looking-at
14233 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14234 (setq ltags (org-split-string
14235 (org-match-string-no-properties 1) ":"))
14236 (when parent
14237 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14238 (setq tags (append
14239 (if parent
14240 (org-remove-uninherited-tags ltags)
14241 ltags)
14242 tags)))
14243 (or org-use-tag-inheritance (throw 'done t))
14244 (if local (throw 'done t))
14245 (or (org-up-heading-safe) (error nil))
14246 (setq parent t)))
14247 (error nil)))))
14248 (if local
14249 tags
14250 (reverse (delete-dups
14251 (reverse (append
14252 (org-remove-uninherited-tags
14253 org-file-tags) tags)))))))))
14255 (defun org-add-prop-inherited (s)
14256 (add-text-properties 0 (length s) '(inherited t) s)
14259 (defun org-toggle-tag (tag &optional onoff)
14260 "Toggle the tag TAG for the current line.
14261 If ONOFF is `on' or `off', don't toggle but set to this state."
14262 (let (res current)
14263 (save-excursion
14264 (org-back-to-heading t)
14265 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14266 (point-at-eol) t)
14267 (progn
14268 (setq current (match-string 1))
14269 (replace-match ""))
14270 (setq current ""))
14271 (setq current (nreverse (org-split-string current ":")))
14272 (cond
14273 ((eq onoff 'on)
14274 (setq res t)
14275 (or (member tag current) (push tag current)))
14276 ((eq onoff 'off)
14277 (or (not (member tag current)) (setq current (delete tag current))))
14278 (t (if (member tag current)
14279 (setq current (delete tag current))
14280 (setq res t)
14281 (push tag current))))
14282 (end-of-line 1)
14283 (if current
14284 (progn
14285 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14286 (org-set-tags nil t))
14287 (delete-horizontal-space))
14288 (run-hooks 'org-after-tags-change-hook))
14289 res))
14291 (defun org-align-tags-here (to-col)
14292 ;; Assumes that this is a headline
14293 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14294 (beginning-of-line 1)
14295 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14296 (< pos (match-beginning 2)))
14297 (progn
14298 (setq tags-l (- (match-end 2) (match-beginning 2)))
14299 (goto-char (match-beginning 1))
14300 (insert " ")
14301 (delete-region (point) (1+ (match-beginning 2)))
14302 (setq ncol (max (current-column)
14303 (1+ col)
14304 (if (> to-col 0)
14305 to-col
14306 (- (abs to-col) tags-l))))
14307 (setq p (point))
14308 (insert (make-string (- ncol (current-column)) ?\ ))
14309 (setq ncol (current-column))
14310 (when indent-tabs-mode (tabify p (point-at-eol)))
14311 (org-move-to-column (min ncol col) t))
14312 (goto-char pos))))
14314 (defun org-set-tags-command (&optional arg just-align)
14315 "Call the set-tags command for the current entry."
14316 (interactive "P")
14317 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14318 (org-set-tags arg just-align)
14319 (save-excursion
14320 (unless (and (org-region-active-p)
14321 org-loop-over-headlines-in-active-region)
14322 (org-back-to-heading t))
14323 (org-set-tags arg just-align))))
14325 (defun org-set-tags-to (data)
14326 "Set the tags of the current entry to DATA, replacing the current tags.
14327 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14328 If DATA is nil or the empty string, any tags will be removed."
14329 (interactive "sTags: ")
14330 (setq data
14331 (cond
14332 ((eq data nil) "")
14333 ((equal data "") "")
14334 ((stringp data)
14335 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14336 ":"))
14337 ((listp data)
14338 (concat ":" (mapconcat 'identity data ":") ":"))))
14339 (when data
14340 (save-excursion
14341 (org-back-to-heading t)
14342 (when (looking-at org-complex-heading-regexp)
14343 (if (match-end 5)
14344 (progn
14345 (goto-char (match-beginning 5))
14346 (insert data)
14347 (delete-region (point) (point-at-eol))
14348 (org-set-tags nil 'align))
14349 (goto-char (point-at-eol))
14350 (insert " " data)
14351 (org-set-tags nil 'align)))
14352 (beginning-of-line 1)
14353 (if (looking-at ".*?\\([ \t]+\\)$")
14354 (delete-region (match-beginning 1) (match-end 1))))))
14356 (defun org-align-all-tags ()
14357 "Align the tags i all headings."
14358 (interactive)
14359 (save-excursion
14360 (or (ignore-errors (org-back-to-heading t))
14361 (outline-next-heading))
14362 (if (org-at-heading-p)
14363 (org-set-tags t)
14364 (message "No headings"))))
14366 (defvar org-indent-indentation-per-level)
14367 (defun org-set-tags (&optional arg just-align)
14368 "Set the tags for the current headline.
14369 With prefix ARG, realign all tags in headings in the current buffer."
14370 (interactive "P")
14371 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14372 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14373 'region-start-level 'region))
14374 org-loop-over-headlines-in-active-region)
14375 (org-map-entries
14376 ;; We don't use ARG and JUST-ALIGN here these args are not
14377 ;; useful when looping over headlines
14378 `(org-set-tags)
14379 org-loop-over-headlines-in-active-region
14380 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14381 (let* ((re org-outline-regexp-bol)
14382 (current (unless arg (org-get-tags-string)))
14383 (col (current-column))
14384 (org-setting-tags t)
14385 table current-tags inherited-tags ; computed below when needed
14386 tags p0 c0 c1 rpl di tc level)
14387 (if arg
14388 (save-excursion
14389 (goto-char (point-min))
14390 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14391 (while (re-search-forward re nil t)
14392 (org-set-tags nil t)
14393 (end-of-line 1)))
14394 (message "All tags realigned to column %d" org-tags-column))
14395 (if just-align
14396 (setq tags current)
14397 ;; Get a new set of tags from the user
14398 (save-excursion
14399 (setq table (append org-tag-persistent-alist
14400 (or org-tag-alist (org-get-buffer-tags))
14401 (and
14402 org-complete-tags-always-offer-all-agenda-tags
14403 (org-global-tags-completion-table
14404 (org-agenda-files))))
14405 org-last-tags-completion-table table
14406 current-tags (org-split-string current ":")
14407 inherited-tags (nreverse
14408 (nthcdr (length current-tags)
14409 (nreverse (org-get-tags-at))))
14410 tags
14411 (if (or (eq t org-use-fast-tag-selection)
14412 (and org-use-fast-tag-selection
14413 (delq nil (mapcar 'cdr table))))
14414 (org-fast-tag-selection
14415 current-tags inherited-tags table
14416 (if org-fast-tag-selection-include-todo
14417 org-todo-key-alist))
14418 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14419 (org-trim
14420 (org-icompleting-read "Tags: "
14421 'org-tags-completion-function
14422 nil nil current 'org-tags-history))))))
14423 (while (string-match "[-+&]+" tags)
14424 ;; No boolean logic, just a list
14425 (setq tags (replace-match ":" t t tags))))
14427 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14429 (if org-tags-sort-function
14430 (setq tags (mapconcat 'identity
14431 (sort (org-split-string
14432 tags (org-re "[^[:alnum:]_@#%]+"))
14433 org-tags-sort-function) ":")))
14435 (if (string-match "\\`[\t ]*\\'" tags)
14436 (setq tags "")
14437 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14438 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14440 ;; Insert new tags at the correct column
14441 (beginning-of-line 1)
14442 (setq level (or (and (looking-at org-outline-regexp)
14443 (- (match-end 0) (point) 1))
14445 (cond
14446 ((and (equal current "") (equal tags "")))
14447 ((re-search-forward
14448 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14449 (point-at-eol) t)
14450 (if (equal tags "")
14451 (setq rpl "")
14452 (goto-char (match-beginning 0))
14453 (setq c0 (current-column)
14454 ;; compute offset for the case of org-indent-mode active
14455 di (if org-indent-mode
14456 (* (1- org-indent-indentation-per-level) (1- level))
14458 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14459 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14460 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14461 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14462 (replace-match rpl t t)
14463 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14464 tags)
14465 (t (error "Tags alignment failed")))
14466 (org-move-to-column col)
14467 (unless just-align
14468 (run-hooks 'org-after-tags-change-hook))))))
14470 (defun org-change-tag-in-region (beg end tag off)
14471 "Add or remove TAG for each entry in the region.
14472 This works in the agenda, and also in an org-mode buffer."
14473 (interactive
14474 (list (region-beginning) (region-end)
14475 (let ((org-last-tags-completion-table
14476 (if (derived-mode-p 'org-mode)
14477 (org-uniquify
14478 (delq nil (append (org-get-buffer-tags)
14479 (org-global-tags-completion-table))))
14480 (org-global-tags-completion-table))))
14481 (org-icompleting-read
14482 "Tag: " 'org-tags-completion-function nil nil nil
14483 'org-tags-history))
14484 (progn
14485 (message "[s]et or [r]emove? ")
14486 (equal (read-char-exclusive) ?r))))
14487 (if (fboundp 'deactivate-mark) (deactivate-mark))
14488 (let ((agendap (equal major-mode 'org-agenda-mode))
14489 l1 l2 m buf pos newhead (cnt 0))
14490 (goto-char end)
14491 (setq l2 (1- (org-current-line)))
14492 (goto-char beg)
14493 (setq l1 (org-current-line))
14494 (loop for l from l1 to l2 do
14495 (org-goto-line l)
14496 (setq m (get-text-property (point) 'org-hd-marker))
14497 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14498 (and agendap m))
14499 (setq buf (if agendap (marker-buffer m) (current-buffer))
14500 pos (if agendap m (point)))
14501 (with-current-buffer buf
14502 (save-excursion
14503 (save-restriction
14504 (goto-char pos)
14505 (setq cnt (1+ cnt))
14506 (org-toggle-tag tag (if off 'off 'on))
14507 (setq newhead (org-get-heading)))))
14508 (and agendap (org-agenda-change-all-lines newhead m))))
14509 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14511 (defun org-tags-completion-function (string predicate &optional flag)
14512 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14513 (confirm (lambda (x) (stringp (car x)))))
14514 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14515 (setq s1 (match-string 1 string)
14516 s2 (match-string 2 string))
14517 (setq s1 "" s2 string))
14518 (cond
14519 ((eq flag nil)
14520 ;; try completion
14521 (setq rtn (try-completion s2 ctable confirm))
14522 (if (stringp rtn)
14523 (setq rtn
14524 (concat s1 s2 (substring rtn (length s2))
14525 (if (and org-add-colon-after-tag-completion
14526 (assoc rtn ctable))
14527 ":" ""))))
14528 rtn)
14529 ((eq flag t)
14530 ;; all-completions
14531 (all-completions s2 ctable confirm))
14532 ((eq flag 'lambda)
14533 ;; exact match?
14534 (assoc s2 ctable)))))
14536 (defun org-fast-tag-insert (kwd tags face &optional end)
14537 "Insert KDW, and the TAGS, the latter with face FACE.
14538 Also insert END."
14539 (insert (format "%-12s" (concat kwd ":"))
14540 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14541 (or end "")))
14543 (defun org-fast-tag-show-exit (flag)
14544 (save-excursion
14545 (org-goto-line 3)
14546 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14547 (replace-match ""))
14548 (when flag
14549 (end-of-line 1)
14550 (org-move-to-column (- (window-width) 19) t)
14551 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14553 (defun org-set-current-tags-overlay (current prefix)
14554 "Add an overlay to CURRENT tag with PREFIX."
14555 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14556 (if (featurep 'xemacs)
14557 (org-overlay-display org-tags-overlay (concat prefix s)
14558 'secondary-selection)
14559 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14560 (org-overlay-display org-tags-overlay (concat prefix s)))))
14562 (defvar org-last-tag-selection-key nil)
14563 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14564 "Fast tag selection with single keys.
14565 CURRENT is the current list of tags in the headline, INHERITED is the
14566 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14567 possibly with grouping information. TODO-TABLE is a similar table with
14568 TODO keywords, should these have keys assigned to them.
14569 If the keys are nil, a-z are automatically assigned.
14570 Returns the new tags string, or nil to not change the current settings."
14571 (let* ((fulltable (append table todo-table))
14572 (maxlen (apply 'max (mapcar
14573 (lambda (x)
14574 (if (stringp (car x)) (string-width (car x)) 0))
14575 fulltable)))
14576 (buf (current-buffer))
14577 (expert (eq org-fast-tag-selection-single-key 'expert))
14578 (buffer-tags nil)
14579 (fwidth (+ maxlen 3 1 3))
14580 (ncol (/ (- (window-width) 4) fwidth))
14581 (i-face 'org-done)
14582 (c-face 'org-todo)
14583 tg cnt e c char c1 c2 ntable tbl rtn
14584 ov-start ov-end ov-prefix
14585 (exit-after-next org-fast-tag-selection-single-key)
14586 (done-keywords org-done-keywords)
14587 groups ingroup)
14588 (save-excursion
14589 (beginning-of-line 1)
14590 (if (looking-at
14591 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14592 (setq ov-start (match-beginning 1)
14593 ov-end (match-end 1)
14594 ov-prefix "")
14595 (setq ov-start (1- (point-at-eol))
14596 ov-end (1+ ov-start))
14597 (skip-chars-forward "^\n\r")
14598 (setq ov-prefix
14599 (concat
14600 (buffer-substring (1- (point)) (point))
14601 (if (> (current-column) org-tags-column)
14603 (make-string (- org-tags-column (current-column)) ?\ ))))))
14604 (move-overlay org-tags-overlay ov-start ov-end)
14605 (save-window-excursion
14606 (if expert
14607 (set-buffer (get-buffer-create " *Org tags*"))
14608 (delete-other-windows)
14609 (split-window-vertically)
14610 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14611 (erase-buffer)
14612 (org-set-local 'org-done-keywords done-keywords)
14613 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14614 (org-fast-tag-insert "Current" current c-face "\n\n")
14615 (org-fast-tag-show-exit exit-after-next)
14616 (org-set-current-tags-overlay current ov-prefix)
14617 (setq tbl fulltable char ?a cnt 0)
14618 (while (setq e (pop tbl))
14619 (cond
14620 ((equal (car e) :startgroup)
14621 (push '() groups) (setq ingroup t)
14622 (when (not (= cnt 0))
14623 (setq cnt 0)
14624 (insert "\n"))
14625 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14626 ((equal (car e) :endgroup)
14627 (setq ingroup nil cnt 0)
14628 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14629 ((equal e '(:newline))
14630 (when (not (= cnt 0))
14631 (setq cnt 0)
14632 (insert "\n")
14633 (setq e (car tbl))
14634 (while (equal (car tbl) '(:newline))
14635 (insert "\n")
14636 (setq tbl (cdr tbl)))))
14637 ((equal e '(:grouptags)) nil)
14639 (setq tg (copy-sequence (car e)) c2 nil)
14640 (if (cdr e)
14641 (setq c (cdr e))
14642 ;; automatically assign a character.
14643 (setq c1 (string-to-char
14644 (downcase (substring
14645 tg (if (= (string-to-char tg) ?@) 1 0)))))
14646 (if (or (rassoc c1 ntable) (rassoc c1 table))
14647 (while (or (rassoc char ntable) (rassoc char table))
14648 (setq char (1+ char)))
14649 (setq c2 c1))
14650 (setq c (or c2 char)))
14651 (if ingroup (push tg (car groups)))
14652 (setq tg (org-add-props tg nil 'face
14653 (cond
14654 ((not (assoc tg table))
14655 (org-get-todo-face tg))
14656 ((member tg current) c-face)
14657 ((member tg inherited) i-face))))
14658 (if (equal (caar tbl) :grouptags)
14659 (org-add-props tg nil 'face 'org-tag-group))
14660 (if (and (= cnt 0) (not ingroup)) (insert " "))
14661 (insert "[" c "] " tg (make-string
14662 (- fwidth 4 (length tg)) ?\ ))
14663 (push (cons tg c) ntable)
14664 (when (= (setq cnt (1+ cnt)) ncol)
14665 (insert "\n")
14666 (if ingroup (insert " "))
14667 (setq cnt 0)))))
14668 (setq ntable (nreverse ntable))
14669 (insert "\n")
14670 (goto-char (point-min))
14671 (if (not expert) (org-fit-window-to-buffer))
14672 (setq rtn
14673 (catch 'exit
14674 (while t
14675 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14676 (if (not groups) "no " "")
14677 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14678 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14679 (setq org-last-tag-selection-key c)
14680 (cond
14681 ((= c ?\r) (throw 'exit t))
14682 ((= c ?!)
14683 (setq groups (not groups))
14684 (goto-char (point-min))
14685 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14686 ((= c ?\C-c)
14687 (if (not expert)
14688 (org-fast-tag-show-exit
14689 (setq exit-after-next (not exit-after-next)))
14690 (setq expert nil)
14691 (delete-other-windows)
14692 (set-window-buffer (split-window-vertically) " *Org tags*")
14693 (org-switch-to-buffer-other-window " *Org tags*")
14694 (org-fit-window-to-buffer)))
14695 ((or (= c ?\C-g)
14696 (and (= c ?q) (not (rassoc c ntable))))
14697 (org-detach-overlay org-tags-overlay)
14698 (setq quit-flag t))
14699 ((= c ?\ )
14700 (setq current nil)
14701 (if exit-after-next (setq exit-after-next 'now)))
14702 ((= c ?\t)
14703 (condition-case nil
14704 (setq tg (org-icompleting-read
14705 "Tag: "
14706 (or buffer-tags
14707 (with-current-buffer buf
14708 (org-get-buffer-tags)))))
14709 (quit (setq tg "")))
14710 (when (string-match "\\S-" tg)
14711 (add-to-list 'buffer-tags (list tg))
14712 (if (member tg current)
14713 (setq current (delete tg current))
14714 (push tg current)))
14715 (if exit-after-next (setq exit-after-next 'now)))
14716 ((setq e (rassoc c todo-table) tg (car e))
14717 (with-current-buffer buf
14718 (save-excursion (org-todo tg)))
14719 (if exit-after-next (setq exit-after-next 'now)))
14720 ((setq e (rassoc c ntable) tg (car e))
14721 (if (member tg current)
14722 (setq current (delete tg current))
14723 (loop for g in groups do
14724 (if (member tg g)
14725 (mapc (lambda (x)
14726 (setq current (delete x current)))
14727 g)))
14728 (push tg current))
14729 (if exit-after-next (setq exit-after-next 'now))))
14731 ;; Create a sorted list
14732 (setq current
14733 (sort current
14734 (lambda (a b)
14735 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14736 (if (eq exit-after-next 'now) (throw 'exit t))
14737 (goto-char (point-min))
14738 (beginning-of-line 2)
14739 (delete-region (point) (point-at-eol))
14740 (org-fast-tag-insert "Current" current c-face)
14741 (org-set-current-tags-overlay current ov-prefix)
14742 (while (re-search-forward
14743 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14744 (setq tg (match-string 1))
14745 (add-text-properties
14746 (match-beginning 1) (match-end 1)
14747 (list 'face
14748 (cond
14749 ((member tg current) c-face)
14750 ((member tg inherited) i-face)
14751 (t (get-text-property (match-beginning 1) 'face))))))
14752 (goto-char (point-min)))))
14753 (org-detach-overlay org-tags-overlay)
14754 (if rtn
14755 (mapconcat 'identity current ":")
14756 nil))))
14758 (defun org-get-tags-string ()
14759 "Get the TAGS string in the current headline."
14760 (unless (org-at-heading-p t)
14761 (error "Not on a heading"))
14762 (save-excursion
14763 (beginning-of-line 1)
14764 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14765 (org-match-string-no-properties 1)
14766 "")))
14768 (defun org-get-tags ()
14769 "Get the list of tags specified in the current headline."
14770 (org-split-string (org-get-tags-string) ":"))
14772 (defun org-get-buffer-tags ()
14773 "Get a table of all tags used in the buffer, for completion."
14774 (let (tags)
14775 (save-excursion
14776 (goto-char (point-min))
14777 (while (re-search-forward
14778 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14779 (when (equal (char-after (point-at-bol 0)) ?*)
14780 (mapc (lambda (x) (add-to-list 'tags x))
14781 (org-split-string (org-match-string-no-properties 1) ":")))))
14782 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14783 (mapcar 'list tags)))
14785 ;;;; The mapping API
14787 (defun org-map-entries (func &optional match scope &rest skip)
14788 "Call FUNC at each headline selected by MATCH in SCOPE.
14790 FUNC is a function or a lisp form. The function will be called without
14791 arguments, with the cursor positioned at the beginning of the headline.
14792 The return values of all calls to the function will be collected and
14793 returned as a list.
14795 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14796 does not need to preserve point. After evaluation, the cursor will be
14797 moved to the end of the line (presumably of the headline of the
14798 processed entry) and search continues from there. Under some
14799 circumstances, this may not produce the wanted results. For example,
14800 if you have removed (e.g. archived) the current (sub)tree it could
14801 mean that the next entry will be skipped entirely. In such cases, you
14802 can specify the position from where search should continue by making
14803 FUNC set the variable `org-map-continue-from' to the desired buffer
14804 position.
14806 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14807 Only headlines that are matched by this query will be considered during
14808 the iteration. When MATCH is nil or t, all headlines will be
14809 visited by the iteration.
14811 SCOPE determines the scope of this command. It can be any of:
14813 nil The current buffer, respecting the restriction if any
14814 tree The subtree started with the entry at point
14815 region The entries within the active region, if any
14816 region-start-level
14817 The entries within the active region, but only those at
14818 the same level than the first one.
14819 file The current buffer, without restriction
14820 file-with-archives
14821 The current buffer, and any archives associated with it
14822 agenda All agenda files
14823 agenda-with-archives
14824 All agenda files with any archive files associated with them
14825 \(file1 file2 ...)
14826 If this is a list, all files in the list will be scanned
14828 The remaining args are treated as settings for the skipping facilities of
14829 the scanner. The following items can be given here:
14831 archive skip trees with the archive tag
14832 comment skip trees with the COMMENT keyword
14833 function or Emacs Lisp form:
14834 will be used as value for `org-agenda-skip-function', so
14835 whenever the function returns a position, FUNC will not be
14836 called for that entry and search will continue from the
14837 position returned
14839 If your function needs to retrieve the tags including inherited tags
14840 at the *current* entry, you can use the value of the variable
14841 `org-scanner-tags' which will be much faster than getting the value
14842 with `org-get-tags-at'. If your function gets properties with
14843 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14844 to t around the call to `org-entry-properties' to get the same speedup.
14845 Note that if your function moves around to retrieve tags and properties at
14846 a *different* entry, you cannot use these techniques."
14847 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14848 (not (org-region-active-p)))
14849 (let* ((org-agenda-archives-mode nil) ; just to make sure
14850 (org-agenda-skip-archived-trees (memq 'archive skip))
14851 (org-agenda-skip-comment-trees (memq 'comment skip))
14852 (org-agenda-skip-function
14853 (car (org-delete-all '(comment archive) skip)))
14854 (org-tags-match-list-sublevels t)
14855 (start-level (eq scope 'region-start-level))
14856 matcher file res
14857 org-todo-keywords-for-agenda
14858 org-done-keywords-for-agenda
14859 org-todo-keyword-alist-for-agenda
14860 org-drawers-for-agenda
14861 org-tag-alist-for-agenda
14862 todo-only)
14864 (cond
14865 ((eq match t) (setq matcher t))
14866 ((eq match nil) (setq matcher t))
14867 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14869 (save-window-excursion
14870 (save-restriction
14871 (cond ((eq scope 'tree)
14872 (org-back-to-heading t)
14873 (org-narrow-to-subtree)
14874 (setq scope nil))
14875 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14876 (org-region-active-p))
14877 ;; If needed, set start-level to a string like "2"
14878 (when start-level
14879 (save-excursion
14880 (goto-char (region-beginning))
14881 (unless (org-at-heading-p) (outline-next-heading))
14882 (setq start-level (org-current-level))))
14883 (narrow-to-region (region-beginning)
14884 (save-excursion
14885 (goto-char (region-end))
14886 (unless (and (bolp) (org-at-heading-p))
14887 (outline-next-heading))
14888 (point)))
14889 (setq scope nil)))
14891 (if (not scope)
14892 (progn
14893 (org-agenda-prepare-buffers
14894 (list (buffer-file-name (current-buffer))))
14895 (setq res (org-scan-tags func matcher todo-only start-level)))
14896 ;; Get the right scope
14897 (cond
14898 ((and scope (listp scope) (symbolp (car scope)))
14899 (setq scope (eval scope)))
14900 ((eq scope 'agenda)
14901 (setq scope (org-agenda-files t)))
14902 ((eq scope 'agenda-with-archives)
14903 (setq scope (org-agenda-files t))
14904 (setq scope (org-add-archive-files scope)))
14905 ((eq scope 'file)
14906 (setq scope (list (buffer-file-name))))
14907 ((eq scope 'file-with-archives)
14908 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14909 (org-agenda-prepare-buffers scope)
14910 (while (setq file (pop scope))
14911 (with-current-buffer (org-find-base-buffer-visiting file)
14912 (save-excursion
14913 (save-restriction
14914 (widen)
14915 (goto-char (point-min))
14916 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14917 res)))
14919 ;;;; Properties
14921 ;;; Setting and retrieving properties
14923 (defconst org-special-properties
14924 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14925 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14926 "The special properties valid in Org-mode.
14928 These are properties that are not defined in the property drawer,
14929 but in some other way.")
14931 (defconst org-default-properties
14932 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14933 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14934 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14935 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14936 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14937 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14938 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14939 "Some properties that are used by Org-mode for various purposes.
14940 Being in this list makes sure that they are offered for completion.")
14942 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14943 "Regular expression matching the first line of a property drawer.")
14945 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14946 "Regular expression matching the last line of a property drawer.")
14948 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14949 "Regular expression matching the first line of a property drawer.")
14951 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14952 "Regular expression matching the first line of a property drawer.")
14954 (defconst org-property-drawer-re
14955 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14956 org-property-end-re "\\)\n?")
14957 "Matches an entire property drawer.")
14959 (defconst org-clock-drawer-re
14960 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14961 org-property-end-re "\\)\n?")
14962 "Matches an entire clock drawer.")
14964 (defsubst org-re-property (property)
14965 "Return a regexp matching a PROPERTY line.
14966 Match group 1 will be set to the value."
14967 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14969 (defsubst org-re-property-keyword (property)
14970 "Return a regexp matching a PROPERTY line, possibly with no
14971 value for the property."
14972 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14974 (defun org-property-action ()
14975 "Do an action on properties."
14976 (interactive)
14977 (let (c)
14978 (org-at-property-p)
14979 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14980 (setq c (read-char-exclusive))
14981 (cond
14982 ((equal c ?s)
14983 (call-interactively 'org-set-property))
14984 ((equal c ?d)
14985 (call-interactively 'org-delete-property))
14986 ((equal c ?D)
14987 (call-interactively 'org-delete-property-globally))
14988 ((equal c ?c)
14989 (call-interactively 'org-compute-property-at-point))
14990 (t (error "No such property action %c" c)))))
14992 (defun org-inc-effort ()
14993 "Increment the value of the effort property in the current entry."
14994 (interactive)
14995 (org-set-effort nil t))
14997 (defvar org-clock-effort) ;; Defined in org-clock.el
14998 (defvar org-clock-current-task) ;; Defined in org-clock.el
14999 (defun org-set-effort (&optional value increment)
15000 "Set the effort property of the current entry.
15001 With numerical prefix arg, use the nth allowed value, 0 stands for the
15002 10th allowed value.
15004 When INCREMENT is non-nil, set the property to the next allowed value."
15005 (interactive "P")
15006 (if (equal value 0) (setq value 10))
15007 (let* ((completion-ignore-case t)
15008 (prop org-effort-property)
15009 (cur (org-entry-get nil prop))
15010 (allowed (org-property-get-allowed-values nil prop 'table))
15011 (existing (mapcar 'list (org-property-values prop)))
15012 (heading (nth 4 (org-heading-components)))
15014 (val (cond
15015 ((stringp value) value)
15016 ((and allowed (integerp value))
15017 (or (car (nth (1- value) allowed))
15018 (car (org-last allowed))))
15019 ((and allowed increment)
15020 (or (caadr (member (list cur) allowed))
15021 (error "Allowed effort values are not set")))
15022 (allowed
15023 (message "Select 1-9,0, [RET%s]: %s"
15024 (if cur (concat "=" cur) "")
15025 (mapconcat 'car allowed " "))
15026 (setq rpl (read-char-exclusive))
15027 (if (equal rpl ?\r)
15029 (setq rpl (- rpl ?0))
15030 (if (equal rpl 0) (setq rpl 10))
15031 (if (and (> rpl 0) (<= rpl (length allowed)))
15032 (car (nth (1- rpl) allowed))
15033 (org-completing-read "Effort: " allowed nil))))
15035 (let (org-completion-use-ido org-completion-use-iswitchb)
15036 (org-completing-read
15037 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15038 (concat "[" cur "]") "")
15039 ": ")
15040 existing nil nil "" nil cur))))))
15041 (unless (equal (org-entry-get nil prop) val)
15042 (org-entry-put nil prop val))
15043 (save-excursion
15044 (org-back-to-heading t)
15045 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15046 (when (string= heading org-clock-current-task)
15047 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15048 (org-clock-update-mode-line))
15049 (message "%s is now %s" prop val)))
15051 (defun org-at-property-p ()
15052 "Is cursor inside a property drawer?"
15053 (save-excursion
15054 (beginning-of-line 1)
15055 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15056 (save-match-data ;; Used by calling procedures
15057 (let ((p (point))
15058 (range (unless (org-before-first-heading-p)
15059 (org-get-property-block))))
15060 (and range (<= (car range) p) (< p (cdr range))))))))
15062 (defun org-get-property-block (&optional beg end force)
15063 "Return the (beg . end) range of the body of the property drawer.
15064 BEG and END are the beginning and end of the current subtree, or of
15065 the part before the first headline. If they are not given, they will
15066 be found. If the drawer does not exist and FORCE is non-nil, create
15067 the drawer."
15068 (catch 'exit
15069 (save-excursion
15070 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15071 (progn (org-back-to-heading t) (point))))
15072 (end (or end (and (not (outline-next-heading)) (point-max))
15073 (point))))
15074 (goto-char beg)
15075 (if (re-search-forward org-property-start-re end t)
15076 (setq beg (1+ (match-end 0)))
15077 (if force
15078 (save-excursion
15079 (org-insert-property-drawer)
15080 (setq end (progn (outline-next-heading) (point))))
15081 (throw 'exit nil))
15082 (goto-char beg)
15083 (if (re-search-forward org-property-start-re end t)
15084 (setq beg (1+ (match-end 0)))))
15085 (if (re-search-forward org-property-end-re end t)
15086 (setq end (match-beginning 0))
15087 (or force (throw 'exit nil))
15088 (goto-char beg)
15089 (setq end beg)
15090 (org-indent-line)
15091 (insert ":END:\n"))
15092 (cons beg end)))))
15094 (defun org-entry-properties (&optional pom which specific)
15095 "Get all properties of the entry at point-or-marker POM.
15096 This includes the TODO keyword, the tags, time strings for deadline,
15097 scheduled, and clocking, and any additional properties defined in the
15098 entry. The return value is an alist, keys may occur multiple times
15099 if the property key was used several times.
15100 POM may also be nil, in which case the current entry is used.
15101 If WHICH is nil or `all', get all properties. If WHICH is
15102 `special' or `standard', only get that subclass. If WHICH
15103 is a string only get exactly this property. SPECIFIC can be a string, the
15104 specific property we are interested in. Specifying it can speed
15105 things up because then unnecessary parsing is avoided."
15106 (setq which (or which 'all))
15107 (org-with-point-at pom
15108 (let ((clockstr (substring org-clock-string 0 -1))
15109 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15110 (case-fold-search nil)
15111 beg end range props sum-props key key1 value string clocksum clocksumt)
15112 (save-excursion
15113 (when (condition-case nil
15114 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15115 (error nil))
15116 (setq beg (point))
15117 (setq sum-props (get-text-property (point) 'org-summaries))
15118 (setq clocksum (get-text-property (point) :org-clock-minutes)
15119 clocksumt (get-text-property (point) :org-clock-minutes-today))
15120 (outline-next-heading)
15121 (setq end (point))
15122 (when (memq which '(all special))
15123 ;; Get the special properties, like TODO and tags
15124 (goto-char beg)
15125 (when (and (or (not specific) (string= specific "TODO"))
15126 (looking-at org-todo-line-regexp) (match-end 2))
15127 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15128 (when (and (or (not specific) (string= specific "PRIORITY"))
15129 (looking-at org-priority-regexp))
15130 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15131 (when (or (not specific) (string= specific "FILE"))
15132 (push (cons "FILE" buffer-file-name) props))
15133 (when (and (or (not specific) (string= specific "TAGS"))
15134 (setq value (org-get-tags-string))
15135 (string-match "\\S-" value))
15136 (push (cons "TAGS" value) props))
15137 (when (and (or (not specific) (string= specific "ALLTAGS"))
15138 (setq value (org-get-tags-at)))
15139 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15140 ":"))
15141 props))
15142 (when (or (not specific) (string= specific "BLOCKED"))
15143 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15144 (when (or (not specific)
15145 (member specific
15146 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15147 "TIMESTAMP" "TIMESTAMP_IA")))
15148 (catch 'match
15149 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15150 (setq key (if (match-end 1)
15151 (substring (org-match-string-no-properties 1)
15152 0 -1))
15153 string (if (equal key clockstr)
15154 (org-trim
15155 (buffer-substring-no-properties
15156 (match-beginning 3) (goto-char
15157 (point-at-eol))))
15158 (substring (org-match-string-no-properties 3)
15159 1 -1)))
15160 ;; Get the correct property name from the key. This is
15161 ;; necessary if the user has configured time keywords.
15162 (setq key1 (concat key ":"))
15163 (cond
15164 ((not key)
15165 (setq key
15166 (if (= (char-after (match-beginning 3)) ?\[)
15167 "TIMESTAMP_IA" "TIMESTAMP")))
15168 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15169 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15170 ((equal key1 org-closed-string) (setq key "CLOSED"))
15171 ((equal key1 org-clock-string) (setq key "CLOCK")))
15172 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15173 (progn
15174 (push (cons key string) props)
15175 ;; no need to search further if match is found
15176 (throw 'match t))
15177 (when (or (equal key "CLOCK") (not (assoc key props)))
15178 (push (cons key string) props)))))))
15180 (when (memq which '(all standard))
15181 ;; Get the standard properties, like :PROP: ...
15182 (setq range (org-get-property-block beg end))
15183 (when range
15184 (goto-char (car range))
15185 (while (re-search-forward
15186 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15187 (cdr range) t)
15188 (setq key (org-match-string-no-properties 1)
15189 value (org-trim (or (org-match-string-no-properties 2) "")))
15190 (unless (member key excluded)
15191 (push (cons key (or value "")) props)))))
15192 (if clocksum
15193 (push (cons "CLOCKSUM"
15194 (org-columns-number-to-string (/ (float clocksum) 60.)
15195 'add_times))
15196 props))
15197 (if clocksumt
15198 (push (cons "CLOCKSUM_T"
15199 (org-columns-number-to-string (/ (float clocksumt) 60.)
15200 'add_times))
15201 props))
15202 (unless (assoc "CATEGORY" props)
15203 (push (cons "CATEGORY" (org-get-category)) props))
15204 (append sum-props (nreverse props)))))))
15206 (defun org-entry-get (pom property &optional inherit literal-nil)
15207 "Get value of PROPERTY for entry or content at point-or-marker POM.
15208 If INHERIT is non-nil and the entry does not have the property,
15209 then also check higher levels of the hierarchy.
15210 If INHERIT is the symbol `selective', use inheritance only if the setting
15211 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15212 If the property is present but empty, the return value is the empty string.
15213 If the property is not present at all, nil is returned.
15215 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15216 do not interpret it as the list atom nil. This is used for inheritance
15217 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15218 (org-with-point-at pom
15219 (if (and inherit (if (eq inherit 'selective)
15220 (org-property-inherit-p property)
15222 (org-entry-get-with-inheritance property literal-nil)
15223 (if (member property org-special-properties)
15224 ;; We need a special property. Use `org-entry-properties' to
15225 ;; retrieve it, but specify the wanted property
15226 (cdr (assoc property (org-entry-properties nil 'special property)))
15227 (let ((range (org-get-property-block)))
15228 (when (and range (not (eq (car range) (cdr range))))
15229 (let* ((props (list (or (assoc property org-file-properties)
15230 (assoc property org-global-properties)
15231 (assoc property org-global-properties-fixed))))
15232 (ap (lambda (key)
15233 (when (re-search-forward
15234 (org-re-property key) (cdr range) t)
15235 (setq props
15236 (org-update-property-plist
15238 (if (match-end 1)
15239 (org-match-string-no-properties 1) "")
15240 props)))))
15241 val)
15242 (goto-char (car range))
15243 (funcall ap property)
15244 (goto-char (car range))
15245 (while (funcall ap (concat property "+")))
15246 (setq val (cdr (assoc property props)))
15247 (when val (if literal-nil val (org-not-nil val))))))))))
15249 (defun org-property-or-variable-value (var &optional inherit)
15250 "Check if there is a property fixing the value of VAR.
15251 If yes, return this value. If not, return the current value of the variable."
15252 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15253 (if (and prop (stringp prop) (string-match "\\S-" prop))
15254 (read prop)
15255 (symbol-value var))))
15257 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15258 "Delete the property PROPERTY from entry at point-or-marker POM.
15259 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15260 an empty drawer to delete."
15261 (org-with-point-at pom
15262 (if (member property org-special-properties)
15263 nil ; cannot delete these properties.
15264 (let ((range (org-get-property-block)))
15265 (if (and range
15266 (goto-char (car range))
15267 (re-search-forward
15268 (org-re-property property)
15269 (cdr range) t))
15270 (progn
15271 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15272 (and delete-empty-drawer
15273 (org-remove-empty-drawer-at
15274 delete-empty-drawer (car range)))
15276 nil)))))
15278 ;; Multi-values properties are properties that contain multiple values
15279 ;; These values are assumed to be single words, separated by whitespace.
15280 (defun org-entry-add-to-multivalued-property (pom property value)
15281 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15282 (let* ((old (org-entry-get pom property))
15283 (values (and old (org-split-string old "[ \t]"))))
15284 (setq value (org-entry-protect-space value))
15285 (unless (member value values)
15286 (setq values (append values (list value)))
15287 (org-entry-put pom property
15288 (mapconcat 'identity values " ")))))
15290 (defun org-entry-remove-from-multivalued-property (pom property value)
15291 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15292 (let* ((old (org-entry-get pom property))
15293 (values (and old (org-split-string old "[ \t]"))))
15294 (setq value (org-entry-protect-space value))
15295 (when (member value values)
15296 (setq values (delete value values))
15297 (org-entry-put pom property
15298 (mapconcat 'identity values " ")))))
15300 (defun org-entry-member-in-multivalued-property (pom property value)
15301 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15302 (let* ((old (org-entry-get pom property))
15303 (values (and old (org-split-string old "[ \t]"))))
15304 (setq value (org-entry-protect-space value))
15305 (member value values)))
15307 (defun org-entry-get-multivalued-property (pom property)
15308 "Return a list of values in a multivalued property."
15309 (let* ((value (org-entry-get pom property))
15310 (values (and value (org-split-string value "[ \t]"))))
15311 (mapcar 'org-entry-restore-space values)))
15313 (defun org-entry-put-multivalued-property (pom property &rest values)
15314 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15315 VALUES should be a list of strings. Spaces will be protected."
15316 (org-entry-put pom property
15317 (mapconcat 'org-entry-protect-space values " "))
15318 (let* ((value (org-entry-get pom property))
15319 (values (and value (org-split-string value "[ \t]"))))
15320 (mapcar 'org-entry-restore-space values)))
15322 (defun org-entry-protect-space (s)
15323 "Protect spaces and newline in string S."
15324 (while (string-match " " s)
15325 (setq s (replace-match "%20" t t s)))
15326 (while (string-match "\n" s)
15327 (setq s (replace-match "%0A" t t s)))
15330 (defun org-entry-restore-space (s)
15331 "Restore spaces and newline in string S."
15332 (while (string-match "%20" s)
15333 (setq s (replace-match " " t t s)))
15334 (while (string-match "%0A" s)
15335 (setq s (replace-match "\n" t t s)))
15338 (defvar org-entry-property-inherited-from (make-marker)
15339 "Marker pointing to the entry from where a property was inherited.
15340 Each call to `org-entry-get-with-inheritance' will set this marker to the
15341 location of the entry where the inheritance search matched. If there was
15342 no match, the marker will point nowhere.
15343 Note that also `org-entry-get' calls this function, if the INHERIT flag
15344 is set.")
15346 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15347 "Get PROPERTY of entry or content at point, search higher levels if needed.
15348 The search will stop at the first ancestor which has the property defined.
15349 If the value found is \"nil\", return nil to show that the property
15350 should be considered as undefined (this is the meaning of nil here).
15351 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15352 (move-marker org-entry-property-inherited-from nil)
15353 (let (tmp)
15354 (save-excursion
15355 (save-restriction
15356 (widen)
15357 (catch 'ex
15358 (while t
15359 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15360 (or (ignore-errors (org-back-to-heading t))
15361 (goto-char (point-min)))
15362 (move-marker org-entry-property-inherited-from (point))
15363 (throw 'ex tmp))
15364 (or (ignore-errors (org-up-heading-safe))
15365 (throw 'ex nil))))))
15366 (setq tmp (or tmp
15367 (cdr (assoc property org-file-properties))
15368 (cdr (assoc property org-global-properties))
15369 (cdr (assoc property org-global-properties-fixed))))
15370 (if literal-nil tmp (org-not-nil tmp))))
15372 (defvar org-property-changed-functions nil
15373 "Hook called when the value of a property has changed.
15374 Each hook function should accept two arguments, the name of the property
15375 and the new value.")
15377 (defun org-entry-put (pom property value)
15378 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15379 (org-with-point-at pom
15380 (org-back-to-heading t)
15381 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15382 range)
15383 (cond
15384 ((equal property "TODO")
15385 (when (and (stringp value) (string-match "\\S-" value)
15386 (not (member value org-todo-keywords-1)))
15387 (error "\"%s\" is not a valid TODO state" value))
15388 (if (or (not value)
15389 (not (string-match "\\S-" value)))
15390 (setq value 'none))
15391 (org-todo value)
15392 (org-set-tags nil 'align))
15393 ((equal property "PRIORITY")
15394 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15395 (string-to-char value) ?\ ))
15396 (org-set-tags nil 'align))
15397 ((equal property "CLOCKSUM")
15398 (if (not (re-search-forward
15399 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15400 (error "Cannot find a clock log")
15401 (goto-char (- (match-end 1) 2))
15402 (cond
15403 ((eq value 'earlier) (org-timestamp-down))
15404 ((eq value 'later) (org-timestamp-up)))
15405 (org-clock-sum-current-item)))
15406 ((equal property "SCHEDULED")
15407 (if (re-search-forward org-scheduled-time-regexp end t)
15408 (cond
15409 ((eq value 'earlier) (org-timestamp-change -1 'day))
15410 ((eq value 'later) (org-timestamp-change 1 'day))
15411 (t (call-interactively 'org-schedule)))
15412 (call-interactively 'org-schedule)))
15413 ((equal property "DEADLINE")
15414 (if (re-search-forward org-deadline-time-regexp end t)
15415 (cond
15416 ((eq value 'earlier) (org-timestamp-change -1 'day))
15417 ((eq value 'later) (org-timestamp-change 1 'day))
15418 (t (call-interactively 'org-deadline)))
15419 (call-interactively 'org-deadline)))
15420 ((member property org-special-properties)
15421 (error "The %s property can not yet be set with `org-entry-put'"
15422 property))
15423 (t ; a non-special property
15424 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15425 (setq range (org-get-property-block beg end 'force))
15426 (goto-char (car range))
15427 (if (re-search-forward
15428 (org-re-property-keyword property) (cdr range) t)
15429 (progn
15430 (delete-region (match-beginning 0) (match-end 0))
15431 (goto-char (match-beginning 0)))
15432 (goto-char (cdr range))
15433 (insert "\n")
15434 (backward-char 1)
15435 (org-indent-line))
15436 (insert ":" property ":")
15437 (and value (insert " " value))
15438 (org-indent-line)))))
15439 (run-hook-with-args 'org-property-changed-functions property value)))
15441 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15442 "Get all property keys in the current buffer.
15443 With INCLUDE-SPECIALS, also list the special properties that reflect things
15444 like tags and TODO state.
15445 With INCLUDE-DEFAULTS, also include properties that has special meaning
15446 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15447 and others.
15448 With INCLUDE-COLUMNS, also include property names given in COLUMN
15449 formats in the current buffer."
15450 (let (rtn range cfmt s p)
15451 (save-excursion
15452 (save-restriction
15453 (widen)
15454 (goto-char (point-min))
15455 (while (re-search-forward org-property-start-re nil t)
15456 (setq range (org-get-property-block))
15457 (goto-char (car range))
15458 (while (re-search-forward
15459 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15460 (cdr range) t)
15461 (add-to-list 'rtn (org-match-string-no-properties 1)))
15462 (outline-next-heading))))
15464 (when include-specials
15465 (setq rtn (append org-special-properties rtn)))
15467 (when include-defaults
15468 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15469 (add-to-list 'rtn org-effort-property))
15471 (when include-columns
15472 (save-excursion
15473 (save-restriction
15474 (widen)
15475 (goto-char (point-min))
15476 (while (re-search-forward
15477 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15478 nil t)
15479 (setq cfmt (match-string 2) s 0)
15480 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15481 cfmt s)
15482 (setq s (match-end 0)
15483 p (match-string 1 cfmt))
15484 (unless (or (equal p "ITEM")
15485 (member p org-special-properties))
15486 (add-to-list 'rtn (match-string 1 cfmt))))))))
15488 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15490 (defun org-property-values (key)
15491 "Return a list of all values of property KEY in the current buffer."
15492 (save-excursion
15493 (save-restriction
15494 (widen)
15495 (goto-char (point-min))
15496 (let ((re (org-re-property key))
15497 values)
15498 (while (re-search-forward re nil t)
15499 (add-to-list 'values (org-trim (match-string 1))))
15500 (delete "" values)))))
15502 (defun org-insert-property-drawer ()
15503 "Insert a property drawer into the current entry."
15504 (org-back-to-heading t)
15505 (looking-at org-outline-regexp)
15506 (let ((indent (if org-adapt-indentation
15507 (- (match-end 0) (match-beginning 0))
15509 (beg (point))
15510 (re (concat "^[ \t]*" org-keyword-time-regexp))
15511 end hiddenp)
15512 (outline-next-heading)
15513 (setq end (point))
15514 (goto-char beg)
15515 (while (re-search-forward re end t))
15516 (setq hiddenp (outline-invisible-p))
15517 (end-of-line 1)
15518 (and (equal (char-after) ?\n) (forward-char 1))
15519 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15520 (if (member (match-string 1) '("CLOCK:" ":END:"))
15521 ;; just skip this line
15522 (beginning-of-line 2)
15523 ;; Drawer start, find the end
15524 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15525 (beginning-of-line 1)))
15526 (org-skip-over-state-notes)
15527 (skip-chars-backward " \t\n\r")
15528 (if (eq (char-before) ?*) (forward-char 1))
15529 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15530 (beginning-of-line 0)
15531 (org-indent-to-column indent)
15532 (beginning-of-line 2)
15533 (org-indent-to-column indent)
15534 (beginning-of-line 0)
15535 (if hiddenp
15536 (save-excursion
15537 (org-back-to-heading t)
15538 (hide-entry))
15539 (org-flag-drawer t))))
15541 (defun org-insert-drawer (&optional arg drawer)
15542 "Insert a drawer at point.
15544 Optional argument DRAWER, when non-nil, is a string representing
15545 drawer's name. Otherwise, the user is prompted for a name.
15547 If a region is active, insert the drawer around that region
15548 instead.
15550 Point is left between drawer's boundaries."
15551 (interactive "P")
15552 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15553 "LOGBOOK"))
15554 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15555 ;; internally by Org. They are meant to be inserted
15556 ;; automatically.
15557 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15558 ;; Remove system drawers from list. Note: For some reason,
15559 ;; `org-completing-read' ignores the predicate while
15560 ;; `completing-read' handles it fine.
15561 (drawer (if arg "PROPERTIES"
15562 (or drawer
15563 (completing-read
15564 "Drawer: " org-drawers
15565 (lambda (d) (not (member d system-drawers))))))))
15566 (cond
15567 ;; With C-u, fall back on `org-insert-property-drawer'
15568 (arg (org-insert-property-drawer))
15569 ;; With an active region, insert a drawer at point.
15570 ((not (org-region-active-p))
15571 (progn
15572 (unless (bolp) (insert "\n"))
15573 (insert (format ":%s:\n\n:END:\n" drawer))
15574 (forward-line -2)))
15575 ;; Otherwise, insert the drawer at point
15577 (let ((rbeg (region-beginning))
15578 (rend (copy-marker (region-end))))
15579 (unwind-protect
15580 (progn
15581 (goto-char rbeg)
15582 (beginning-of-line)
15583 (when (save-excursion
15584 (re-search-forward org-outline-regexp-bol rend t))
15585 (error "Drawers cannot contain headlines"))
15586 ;; Position point at the beginning of the first
15587 ;; non-blank line in region. Insert drawer's opening
15588 ;; there, then indent it.
15589 (org-skip-whitespace)
15590 (beginning-of-line)
15591 (insert ":" drawer ":\n")
15592 (forward-line -1)
15593 (indent-for-tab-command)
15594 ;; Move point to the beginning of the first blank line
15595 ;; after the last non-blank line in region. Insert
15596 ;; drawer's closing, then indent it.
15597 (goto-char rend)
15598 (skip-chars-backward " \r\t\n")
15599 (insert "\n:END:")
15600 (deactivate-mark t)
15601 (indent-for-tab-command)
15602 (unless (eolp) (insert "\n")))
15603 ;; Clear marker, whatever the outcome of insertion is.
15604 (set-marker rend nil)))))))
15606 (defvar org-property-set-functions-alist nil
15607 "Property set function alist.
15608 Each entry should have the following format:
15610 (PROPERTY . READ-FUNCTION)
15612 The read function will be called with the same argument as
15613 `org-completing-read'.")
15615 (defun org-set-property-function (property)
15616 "Get the function that should be used to set PROPERTY.
15617 This is computed according to `org-property-set-functions-alist'."
15618 (or (cdr (assoc property org-property-set-functions-alist))
15619 'org-completing-read))
15621 (defun org-read-property-value (property)
15622 "Read PROPERTY value from user."
15623 (let* ((completion-ignore-case t)
15624 (allowed (org-property-get-allowed-values nil property 'table))
15625 (cur (org-entry-get nil property))
15626 (prompt (concat property " value"
15627 (if (and cur (string-match "\\S-" cur))
15628 (concat " [" cur "]") "") ": "))
15629 (set-function (org-set-property-function property))
15630 (val (if allowed
15631 (funcall set-function prompt allowed nil
15632 (not (get-text-property 0 'org-unrestricted
15633 (caar allowed))))
15634 (let (org-completion-use-ido org-completion-use-iswitchb)
15635 (funcall set-function prompt
15636 (mapcar 'list (org-property-values property))
15637 nil nil "" nil cur)))))
15638 (if (equal val "")
15640 val)))
15642 (defvar org-last-set-property nil)
15643 (defvar org-last-set-property-value nil)
15644 (defun org-read-property-name ()
15645 "Read a property name."
15646 (let* ((completion-ignore-case t)
15647 (keys (org-buffer-property-keys nil t t))
15648 (default-prop (or (save-excursion
15649 (save-match-data
15650 (beginning-of-line)
15651 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15652 (null (string= (match-string 1) "END"))
15653 (match-string 1))))
15654 org-last-set-property))
15655 (property (org-icompleting-read
15656 (concat "Property"
15657 (if default-prop (concat " [" default-prop "]") "")
15658 ": ")
15659 (mapcar 'list keys)
15660 nil nil nil nil
15661 default-prop)))
15662 (if (member property keys)
15663 property
15664 (or (cdr (assoc (downcase property)
15665 (mapcar (lambda (x) (cons (downcase x) x))
15666 keys)))
15667 property))))
15669 (defun org-set-property-and-value (use-last)
15670 "Allow to set [PROPERTY]: [value] direction from prompt.
15671 When use-default, don't even ask, just use the last
15672 \"[PROPERTY]: [value]\" string from the history."
15673 (interactive "P")
15674 (let* ((completion-ignore-case t)
15675 (pv (or (and use-last org-last-set-property-value)
15676 (org-completing-read
15677 "Enter a \"[Property]: [value]\" pair: "
15678 nil nil nil nil nil
15679 org-last-set-property-value)))
15680 prop val)
15681 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15682 (setq prop (match-string 1 pv)
15683 val (match-string 2 pv))
15684 (org-set-property prop val))))
15686 (defun org-set-property (property value)
15687 "In the current entry, set PROPERTY to VALUE.
15688 When called interactively, this will prompt for a property name, offering
15689 completion on existing and default properties. And then it will prompt
15690 for a value, offering completion either on allowed values (via an inherited
15691 xxx_ALL property) or on existing values in other instances of this property
15692 in the current file."
15693 (interactive (list nil nil))
15694 (let* ((property (or property (org-read-property-name)))
15695 (value (or value (org-read-property-value property)))
15696 (fn (cdr (assoc property org-properties-postprocess-alist))))
15697 (setq org-last-set-property property)
15698 (setq org-last-set-property-value (concat property ": " value))
15699 ;; Possibly postprocess the inserted value:
15700 (when fn (setq value (funcall fn value)))
15701 (unless (equal (org-entry-get nil property) value)
15702 (org-entry-put nil property value))))
15704 (defun org-delete-property (property &optional delete-empty-drawer)
15705 "In the current entry, delete PROPERTY.
15706 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15707 an empty drawer to delete."
15708 (interactive
15709 (let* ((completion-ignore-case t)
15710 (prop (org-icompleting-read "Property: "
15711 (org-entry-properties nil 'standard))))
15712 (list prop)))
15713 (message "Property %s %s" property
15714 (if (org-entry-delete nil property delete-empty-drawer)
15715 "deleted"
15716 "was not present in the entry")))
15718 (defun org-delete-property-globally (property)
15719 "Remove PROPERTY globally, from all entries."
15720 (interactive
15721 (let* ((completion-ignore-case t)
15722 (prop (org-icompleting-read
15723 "Globally remove property: "
15724 (mapcar 'list (org-buffer-property-keys)))))
15725 (list prop)))
15726 (save-excursion
15727 (save-restriction
15728 (widen)
15729 (goto-char (point-min))
15730 (let ((cnt 0))
15731 (while (re-search-forward
15732 (org-re-property property)
15733 nil t)
15734 (setq cnt (1+ cnt))
15735 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15736 (message "Property \"%s\" removed from %d entries" property cnt)))))
15738 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15740 (defun org-compute-property-at-point ()
15741 "Compute the property at point.
15742 This looks for an enclosing column format, extracts the operator and
15743 then applies it to the property in the column format's scope."
15744 (interactive)
15745 (unless (org-at-property-p)
15746 (error "Not at a property"))
15747 (let ((prop (org-match-string-no-properties 2)))
15748 (org-columns-get-format-and-top-level)
15749 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15750 (error "No operator defined for property %s" prop))
15751 (org-columns-compute prop)))
15753 (defvar org-property-allowed-value-functions nil
15754 "Hook for functions supplying allowed values for a specific property.
15755 The functions must take a single argument, the name of the property, and
15756 return a flat list of allowed values. If \":ETC\" is one of
15757 the values, this means that these values are intended as defaults for
15758 completion, but that other values should be allowed too.
15759 The functions must return nil if they are not responsible for this
15760 property.")
15762 (defun org-property-get-allowed-values (pom property &optional table)
15763 "Get allowed values for the property PROPERTY.
15764 When TABLE is non-nil, return an alist that can directly be used for
15765 completion."
15766 (let (vals)
15767 (cond
15768 ((equal property "TODO")
15769 (setq vals (org-with-point-at pom
15770 (append org-todo-keywords-1 '("")))))
15771 ((equal property "PRIORITY")
15772 (let ((n org-lowest-priority))
15773 (while (>= n org-highest-priority)
15774 (push (char-to-string n) vals)
15775 (setq n (1- n)))))
15776 ((member property org-special-properties))
15777 ((setq vals (run-hook-with-args-until-success
15778 'org-property-allowed-value-functions property)))
15780 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15781 (when (and vals (string-match "\\S-" vals))
15782 (setq vals (car (read-from-string (concat "(" vals ")"))))
15783 (setq vals (mapcar (lambda (x)
15784 (cond ((stringp x) x)
15785 ((numberp x) (number-to-string x))
15786 ((symbolp x) (symbol-name x))
15787 (t "???")))
15788 vals)))))
15789 (when (member ":ETC" vals)
15790 (setq vals (remove ":ETC" vals))
15791 (org-add-props (car vals) '(org-unrestricted t)))
15792 (if table (mapcar 'list vals) vals)))
15794 (defun org-property-previous-allowed-value (&optional previous)
15795 "Switch to the next allowed value for this property."
15796 (interactive)
15797 (org-property-next-allowed-value t))
15799 (defun org-property-next-allowed-value (&optional previous)
15800 "Switch to the next allowed value for this property."
15801 (interactive)
15802 (unless (org-at-property-p)
15803 (error "Not at a property"))
15804 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15805 (key (match-string 2))
15806 (value (match-string 3))
15807 (allowed (or (org-property-get-allowed-values (point) key)
15808 (and (member value '("[ ]" "[-]" "[X]"))
15809 '("[ ]" "[X]"))))
15810 (heading (save-match-data (nth 4 (org-heading-components))))
15811 nval)
15812 (unless allowed
15813 (error "Allowed values for this property have not been defined"))
15814 (if previous (setq allowed (reverse allowed)))
15815 (if (member value allowed)
15816 (setq nval (car (cdr (member value allowed)))))
15817 (setq nval (or nval (car allowed)))
15818 (if (equal nval value)
15819 (error "Only one allowed value for this property"))
15820 (org-at-property-p)
15821 (replace-match (concat " :" key ": " nval) t t)
15822 (org-indent-line)
15823 (beginning-of-line 1)
15824 (skip-chars-forward " \t")
15825 (when (equal prop org-effort-property)
15826 (save-excursion
15827 (org-back-to-heading t)
15828 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15829 (when (string= org-clock-current-task heading)
15830 (setq org-clock-effort nval)
15831 (org-clock-update-mode-line)))
15832 (run-hook-with-args 'org-property-changed-functions key nval)))
15834 (defun org-find-olp (path &optional this-buffer)
15835 "Return a marker pointing to the entry at outline path OLP.
15836 If anything goes wrong, throw an error.
15837 You can wrap this call to catch the error like this:
15839 (condition-case msg
15840 (org-mobile-locate-entry (match-string 4))
15841 (error (nth 1 msg)))
15843 The return value will then be either a string with the error message,
15844 or a marker if everything is OK.
15846 If THIS-BUFFER is set, the outline path does not contain a file,
15847 only headings."
15848 (let* ((file (if this-buffer buffer-file-name (pop path)))
15849 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15850 (level 1)
15851 (lmin 1)
15852 (lmax 1)
15853 limit re end found pos heading cnt flevel)
15854 (unless buffer (error "File not found :%s" file))
15855 (with-current-buffer buffer
15856 (save-excursion
15857 (save-restriction
15858 (widen)
15859 (setq limit (point-max))
15860 (goto-char (point-min))
15861 (while (setq heading (pop path))
15862 (setq re (format org-complex-heading-regexp-format
15863 (regexp-quote heading)))
15864 (setq cnt 0 pos (point))
15865 (while (re-search-forward re end t)
15866 (setq level (- (match-end 1) (match-beginning 1)))
15867 (if (and (>= level lmin) (<= level lmax))
15868 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15869 (when (= cnt 0) (error "Heading not found on level %d: %s"
15870 lmax heading))
15871 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15872 lmax heading))
15873 (goto-char found)
15874 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15875 (setq end (save-excursion (org-end-of-subtree t t))))
15876 (when (org-at-heading-p)
15877 (point-marker)))))))
15879 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15880 "Find node HEADING in BUFFER.
15881 Return a marker to the heading if it was found, or nil if not.
15882 If POS-ONLY is set, return just the position instead of a marker.
15884 The heading text must match exact, but it may have a TODO keyword,
15885 a priority cookie and tags in the standard locations."
15886 (with-current-buffer (or buffer (current-buffer))
15887 (save-excursion
15888 (save-restriction
15889 (widen)
15890 (goto-char (point-min))
15891 (let (case-fold-search)
15892 (if (re-search-forward
15893 (format org-complex-heading-regexp-format
15894 (regexp-quote heading)) nil t)
15895 (if pos-only
15896 (match-beginning 0)
15897 (move-marker (make-marker) (match-beginning 0)))))))))
15899 (defun org-find-exact-heading-in-directory (heading &optional dir)
15900 "Find Org node headline HEADING in all .org files in directory DIR.
15901 When the target headline is found, return a marker to this location."
15902 (let ((files (directory-files (or dir default-directory)
15903 nil "\\`[^.#].*\\.org\\'"))
15904 file visiting m buffer)
15905 (catch 'found
15906 (while (setq file (pop files))
15907 (message "trying %s" file)
15908 (setq visiting (org-find-base-buffer-visiting file))
15909 (setq buffer (or visiting (find-file-noselect file)))
15910 (setq m (org-find-exact-headline-in-buffer
15911 heading buffer))
15912 (when (and (not m) (not visiting)) (kill-buffer buffer))
15913 (and m (throw 'found m))))))
15915 (defun org-find-entry-with-id (ident)
15916 "Locate the entry that contains the ID property with exact value IDENT.
15917 IDENT can be a string, a symbol or a number, this function will search for
15918 the string representation of it.
15919 Return the position where this entry starts, or nil if there is no such entry."
15920 (interactive "sID: ")
15921 (let ((id (cond
15922 ((stringp ident) ident)
15923 ((symbol-name ident) (symbol-name ident))
15924 ((numberp ident) (number-to-string ident))
15925 (t (error "IDENT %s must be a string, symbol or number" ident))))
15926 (case-fold-search nil))
15927 (save-excursion
15928 (save-restriction
15929 (widen)
15930 (goto-char (point-min))
15931 (when (re-search-forward
15932 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15933 nil t)
15934 (org-back-to-heading t)
15935 (point))))))
15937 ;;;; Timestamps
15939 (defvar org-last-changed-timestamp nil)
15940 (defvar org-last-inserted-timestamp nil
15941 "The last time stamp inserted with `org-insert-time-stamp'.")
15942 (defvar org-time-was-given) ; dynamically scoped parameter
15943 (defvar org-end-time-was-given) ; dynamically scoped parameter
15944 (defvar org-ts-what) ; dynamically scoped parameter
15946 (defun org-time-stamp (arg &optional inactive)
15947 "Prompt for a date/time and insert a time stamp.
15948 If the user specifies a time like HH:MM or if this command is
15949 called with at least one prefix argument, the time stamp contains
15950 the date and the time. Otherwise, only the date is be included.
15952 All parts of a date not specified by the user is filled in from
15953 the current date/time. So if you just press return without
15954 typing anything, the time stamp will represent the current
15955 date/time.
15957 If there is already a timestamp at the cursor, it will be
15958 modified.
15960 With two universal prefix arguments, insert an active timestamp
15961 with the current time without prompting the user."
15962 (interactive "P")
15963 (let* ((ts nil)
15964 (default-time
15965 ;; Default time is either today, or, when entering a range,
15966 ;; the range start.
15967 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15968 (save-excursion
15969 (re-search-backward
15970 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15971 (- (point) 20) t)))
15972 (apply 'encode-time (org-parse-time-string (match-string 1)))
15973 (current-time)))
15974 (default-input (and ts (org-get-compact-tod ts)))
15975 (repeater (save-excursion
15976 (save-match-data
15977 (beginning-of-line)
15978 (when (re-search-forward
15979 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15980 (save-excursion (progn (end-of-line) (point))) t)
15981 (match-string 0)))))
15982 org-time-was-given org-end-time-was-given time)
15983 (cond
15984 ((and (org-at-timestamp-p t)
15985 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15986 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15987 (insert "--")
15988 (setq time (let ((this-command this-command))
15989 (org-read-date arg 'totime nil nil
15990 default-time default-input inactive)))
15991 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15992 ((org-at-timestamp-p t)
15993 (setq time (let ((this-command this-command))
15994 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15995 (when (org-at-timestamp-p t) ; just to get the match data
15996 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15997 (replace-match "")
15998 (setq org-last-changed-timestamp
15999 (org-insert-time-stamp
16000 time (or org-time-was-given arg)
16001 inactive nil nil (list org-end-time-was-given)))
16002 (when repeater (goto-char (1- (point))) (insert " " repeater)
16003 (setq org-last-changed-timestamp
16004 (concat (substring org-last-inserted-timestamp 0 -1)
16005 " " repeater ">"))))
16006 (message "Timestamp updated"))
16007 ((equal arg '(16))
16008 (org-insert-time-stamp (current-time) t))
16010 (setq time (let ((this-command this-command))
16011 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16012 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16013 nil nil (list org-end-time-was-given))))))
16015 ;; FIXME: can we use this for something else, like computing time differences?
16016 (defun org-get-compact-tod (s)
16017 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16018 (let* ((t1 (match-string 1 s))
16019 (h1 (string-to-number (match-string 2 s)))
16020 (m1 (string-to-number (match-string 3 s)))
16021 (t2 (and (match-end 4) (match-string 5 s)))
16022 (h2 (and t2 (string-to-number (match-string 6 s))))
16023 (m2 (and t2 (string-to-number (match-string 7 s))))
16024 dh dm)
16025 (if (not t2)
16027 (setq dh (- h2 h1) dm (- m2 m1))
16028 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16029 (concat t1 "+" (number-to-string dh)
16030 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16032 (defun org-time-stamp-inactive (&optional arg)
16033 "Insert an inactive time stamp.
16034 An inactive time stamp is enclosed in square brackets instead of angle
16035 brackets. It is inactive in the sense that it does not trigger agenda entries,
16036 does not link to the calendar and cannot be changed with the S-cursor keys.
16037 So these are more for recording a certain time/date."
16038 (interactive "P")
16039 (org-time-stamp arg 'inactive))
16041 (defvar org-date-ovl (make-overlay 1 1))
16042 (overlay-put org-date-ovl 'face 'org-date-selected)
16043 (org-detach-overlay org-date-ovl)
16045 (defvar org-ans1) ; dynamically scoped parameter
16046 (defvar org-ans2) ; dynamically scoped parameter
16048 (defvar org-plain-time-of-day-regexp) ; defined below
16050 (defvar org-overriding-default-time nil) ; dynamically scoped
16051 (defvar org-read-date-overlay nil)
16052 (defvar org-dcst nil) ; dynamically scoped
16053 (defvar org-read-date-history nil)
16054 (defvar org-read-date-final-answer nil)
16055 (defvar org-read-date-analyze-futurep nil)
16056 (defvar org-read-date-analyze-forced-year nil)
16057 (defvar org-read-date-inactive)
16059 (defvar org-read-date-minibuffer-local-map
16060 (let ((map (make-sparse-keymap)))
16061 (set-keymap-parent map minibuffer-local-map)
16062 (org-defkey map (kbd ".")
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(calendar-goto-today))))
16065 (org-defkey map [(meta shift left)]
16066 (lambda () (interactive)
16067 (org-eval-in-calendar '(calendar-backward-month 1))))
16068 (org-defkey map [(meta shift right)]
16069 (lambda () (interactive)
16070 (org-eval-in-calendar '(calendar-forward-month 1))))
16071 (org-defkey map [(meta shift up)]
16072 (lambda () (interactive)
16073 (org-eval-in-calendar '(calendar-backward-year 1))))
16074 (org-defkey map [(meta shift down)]
16075 (lambda () (interactive)
16076 (org-eval-in-calendar '(calendar-forward-year 1))))
16077 (org-defkey map [?\e (shift left)]
16078 (lambda () (interactive)
16079 (org-eval-in-calendar '(calendar-backward-month 1))))
16080 (org-defkey map [?\e (shift right)]
16081 (lambda () (interactive)
16082 (org-eval-in-calendar '(calendar-forward-month 1))))
16083 (org-defkey map [?\e (shift up)]
16084 (lambda () (interactive)
16085 (org-eval-in-calendar '(calendar-backward-year 1))))
16086 (org-defkey map [?\e (shift down)]
16087 (lambda () (interactive)
16088 (org-eval-in-calendar '(calendar-forward-year 1))))
16089 (org-defkey map [(shift up)]
16090 (lambda () (interactive)
16091 (org-eval-in-calendar '(calendar-backward-week 1))))
16092 (org-defkey map [(shift down)]
16093 (lambda () (interactive)
16094 (org-eval-in-calendar '(calendar-forward-week 1))))
16095 (org-defkey map [(shift left)]
16096 (lambda () (interactive)
16097 (org-eval-in-calendar '(calendar-backward-day 1))))
16098 (org-defkey map [(shift right)]
16099 (lambda () (interactive)
16100 (org-eval-in-calendar '(calendar-forward-day 1))))
16101 (org-defkey map "!"
16102 (lambda () (interactive)
16103 (org-eval-in-calendar '(diary-view-entries))
16104 (message "")))
16105 (org-defkey map ">"
16106 (lambda () (interactive)
16107 (org-eval-in-calendar '(scroll-calendar-left 1))))
16108 (org-defkey map "<"
16109 (lambda () (interactive)
16110 (org-eval-in-calendar '(scroll-calendar-right 1))))
16111 (org-defkey map "\C-v"
16112 (lambda () (interactive)
16113 (org-eval-in-calendar
16114 '(calendar-scroll-left-three-months 1))))
16115 (org-defkey map "\M-v"
16116 (lambda () (interactive)
16117 (org-eval-in-calendar
16118 '(calendar-scroll-right-three-months 1))))
16119 map)
16120 "Keymap for minibuffer commands when using `org-read-date'.")
16122 (defun org-read-date (&optional org-with-time to-time from-string prompt
16123 default-time default-input inactive)
16124 "Read a date, possibly a time, and make things smooth for the user.
16125 The prompt will suggest to enter an ISO date, but you can also enter anything
16126 which will at least partially be understood by `parse-time-string'.
16127 Unrecognized parts of the date will default to the current day, month, year,
16128 hour and minute. If this command is called to replace a timestamp at point,
16129 or to enter the second timestamp of a range, the default time is taken
16130 from the existing stamp. Furthermore, the command prefers the future,
16131 so if you are giving a date where the year is not given, and the day-month
16132 combination is already past in the current year, it will assume you
16133 mean next year. For details, see the manual. A few examples:
16135 3-2-5 --> 2003-02-05
16136 feb 15 --> currentyear-02-15
16137 2/15 --> currentyear-02-15
16138 sep 12 9 --> 2009-09-12
16139 12:45 --> today 12:45
16140 22 sept 0:34 --> currentyear-09-22 0:34
16141 12 --> currentyear-currentmonth-12
16142 Fri --> nearest Friday after today
16143 -Tue --> last Tuesday
16144 etc.
16146 Furthermore you can specify a relative date by giving, as the *first* thing
16147 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16148 change in days weeks, months, years.
16149 With a single plus or minus, the date is relative to today. With a double
16150 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16151 +4d --> four days from today
16152 +4 --> same as above
16153 +2w --> two weeks from today
16154 ++5 --> five days from default date
16156 The function understands only English month and weekday abbreviations.
16158 While prompting, a calendar is popped up - you can also select the
16159 date with the mouse (button 1). The calendar shows a period of three
16160 months. To scroll it to other months, use the keys `>' and `<'.
16161 If you don't like the calendar, turn it off with
16162 \(setq org-read-date-popup-calendar nil)
16164 With optional argument TO-TIME, the date will immediately be converted
16165 to an internal time.
16166 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16167 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16168 still enter a time, and this function will inform the calling routine
16169 about this change. The calling routine may then choose to change the
16170 format used to insert the time stamp into the buffer to include the time.
16171 With optional argument FROM-STRING, read from this string instead from
16172 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16173 the time/date that is used for everything that is not specified by the
16174 user."
16175 (require 'parse-time)
16176 (let* ((org-time-stamp-rounding-minutes
16177 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16178 (org-dcst org-display-custom-times)
16179 (ct (org-current-time))
16180 (org-def (or org-overriding-default-time default-time ct))
16181 (org-defdecode (decode-time org-def))
16182 (dummy (progn
16183 (when (< (nth 2 org-defdecode) org-extend-today-until)
16184 (setcar (nthcdr 2 org-defdecode) -1)
16185 (setcar (nthcdr 1 org-defdecode) 59)
16186 (setq org-def (apply 'encode-time org-defdecode)
16187 org-defdecode (decode-time org-def)))))
16188 (mouse-autoselect-window nil) ; Don't let the mouse jump
16189 (calendar-frame-setup nil)
16190 (calendar-setup nil)
16191 (calendar-move-hook nil)
16192 (calendar-view-diary-initially-flag nil)
16193 (calendar-view-holidays-initially-flag nil)
16194 (timestr (format-time-string
16195 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16196 (prompt (concat (if prompt (concat prompt " ") "")
16197 (format "Date+time [%s]: " timestr)))
16198 ans (org-ans0 "") org-ans1 org-ans2 final)
16200 (cond
16201 (from-string (setq ans from-string))
16202 (org-read-date-popup-calendar
16203 (save-excursion
16204 (save-window-excursion
16205 (calendar)
16206 (org-eval-in-calendar '(setq cursor-type nil) t)
16207 (unwind-protect
16208 (progn
16209 (calendar-forward-day (- (time-to-days org-def)
16210 (calendar-absolute-from-gregorian
16211 (calendar-current-date))))
16212 (org-eval-in-calendar nil t)
16213 (let* ((old-map (current-local-map))
16214 (map (copy-keymap calendar-mode-map))
16215 (minibuffer-local-map
16216 (copy-keymap org-read-date-minibuffer-local-map)))
16217 (org-defkey map (kbd "RET") 'org-calendar-select)
16218 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16219 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16220 (unwind-protect
16221 (progn
16222 (use-local-map map)
16223 (setq org-read-date-inactive inactive)
16224 (add-hook 'post-command-hook 'org-read-date-display)
16225 (setq org-ans0 (read-string prompt default-input
16226 'org-read-date-history nil))
16227 ;; org-ans0: from prompt
16228 ;; org-ans1: from mouse click
16229 ;; org-ans2: from calendar motion
16230 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16231 (remove-hook 'post-command-hook 'org-read-date-display)
16232 (use-local-map old-map)
16233 (when org-read-date-overlay
16234 (delete-overlay org-read-date-overlay)
16235 (setq org-read-date-overlay nil)))))
16236 (bury-buffer "*Calendar*")))))
16238 (t ; Naked prompt only
16239 (unwind-protect
16240 (setq ans (read-string prompt default-input
16241 'org-read-date-history timestr))
16242 (when org-read-date-overlay
16243 (delete-overlay org-read-date-overlay)
16244 (setq org-read-date-overlay nil)))))
16246 (setq final (org-read-date-analyze ans org-def org-defdecode))
16248 (when org-read-date-analyze-forced-year
16249 (message "Year was forced into %s"
16250 (if org-read-date-force-compatible-dates
16251 "compatible range (1970-2037)"
16252 "range representable on this machine"))
16253 (ding))
16255 ;; One round trip to get rid of 34th of August and stuff like that....
16256 (setq final (decode-time (apply 'encode-time final)))
16258 (setq org-read-date-final-answer ans)
16260 (if to-time
16261 (apply 'encode-time final)
16262 (if (and (boundp 'org-time-was-given) org-time-was-given)
16263 (format "%04d-%02d-%02d %02d:%02d"
16264 (nth 5 final) (nth 4 final) (nth 3 final)
16265 (nth 2 final) (nth 1 final))
16266 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16268 (defvar org-def)
16269 (defvar org-defdecode)
16270 (defvar org-with-time)
16271 (defun org-read-date-display ()
16272 "Display the current date prompt interpretation in the minibuffer."
16273 (when org-read-date-display-live
16274 (when org-read-date-overlay
16275 (delete-overlay org-read-date-overlay))
16276 (when (minibufferp (current-buffer))
16277 (save-excursion
16278 (end-of-line 1)
16279 (while (not (equal (buffer-substring
16280 (max (point-min) (- (point) 4)) (point))
16281 " "))
16282 (insert " ")))
16283 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16284 " " (or org-ans1 org-ans2)))
16285 (org-end-time-was-given nil)
16286 (f (org-read-date-analyze ans org-def org-defdecode))
16287 (fmts (if org-dcst
16288 org-time-stamp-custom-formats
16289 org-time-stamp-formats))
16290 (fmt (if (or org-with-time
16291 (and (boundp 'org-time-was-given) org-time-was-given))
16292 (cdr fmts)
16293 (car fmts)))
16294 (txt (format-time-string fmt (apply 'encode-time f)))
16295 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16296 (txt (concat "=> " txt)))
16297 (when (and org-end-time-was-given
16298 (string-match org-plain-time-of-day-regexp txt))
16299 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16300 org-end-time-was-given
16301 (substring txt (match-end 0)))))
16302 (when org-read-date-analyze-futurep
16303 (setq txt (concat txt " (=>F)")))
16304 (setq org-read-date-overlay
16305 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16306 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16308 (defun org-read-date-analyze (ans org-def org-defdecode)
16309 "Analyze the combined answer of the date prompt."
16310 ;; FIXME: cleanup and comment
16311 (let ((nowdecode (decode-time (current-time)))
16312 delta deltan deltaw deltadef year month day
16313 hour minute second wday pm h2 m2 tl wday1
16314 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16315 (setq org-read-date-analyze-futurep nil
16316 org-read-date-analyze-forced-year nil)
16317 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16318 (setq ans "+0"))
16320 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16321 (setq ans (replace-match "" t t ans)
16322 deltan (car delta)
16323 deltaw (nth 1 delta)
16324 deltadef (nth 2 delta)))
16326 ;; Check if there is an iso week date in there. If yes, store the
16327 ;; info and postpone interpreting it until the rest of the parsing
16328 ;; is done.
16329 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16330 (setq iso-year (if (match-end 1)
16331 (org-small-year-to-year
16332 (string-to-number (match-string 1 ans))))
16333 iso-weekday (if (match-end 3)
16334 (string-to-number (match-string 3 ans)))
16335 iso-week (string-to-number (match-string 2 ans)))
16336 (setq ans (replace-match "" t t ans)))
16338 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16339 (when (string-match
16340 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16341 (setq year (if (match-end 2)
16342 (string-to-number (match-string 2 ans))
16343 (progn (setq kill-year t)
16344 (string-to-number (format-time-string "%Y"))))
16345 month (string-to-number (match-string 3 ans))
16346 day (string-to-number (match-string 4 ans)))
16347 (if (< year 100) (setq year (+ 2000 year)))
16348 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16349 t nil ans)))
16351 ;; Help matching dotted european dates
16352 (when (string-match
16353 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16354 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16355 (setq kill-year t)
16356 (string-to-number (format-time-string "%Y")))
16357 day (string-to-number (match-string 1 ans))
16358 month (string-to-number (match-string 2 ans))
16359 ans (replace-match (format "%04d-%02d-%02d" year month day)
16360 t nil ans)))
16362 ;; Help matching american dates, like 5/30 or 5/30/7
16363 (when (string-match
16364 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16365 (setq year (if (match-end 4)
16366 (string-to-number (match-string 4 ans))
16367 (progn (setq kill-year t)
16368 (string-to-number (format-time-string "%Y"))))
16369 month (string-to-number (match-string 1 ans))
16370 day (string-to-number (match-string 2 ans)))
16371 (if (< year 100) (setq year (+ 2000 year)))
16372 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16373 t nil ans)))
16374 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16375 ;; If there is a time with am/pm, and *no* time without it, we convert
16376 ;; so that matching will be successful.
16377 (loop for i from 1 to 2 do ; twice, for end time as well
16378 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16379 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16380 (setq hour (string-to-number (match-string 1 ans))
16381 minute (if (match-end 3)
16382 (string-to-number (match-string 3 ans))
16384 pm (equal ?p
16385 (string-to-char (downcase (match-string 4 ans)))))
16386 (if (and (= hour 12) (not pm))
16387 (setq hour 0)
16388 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16389 (setq ans (replace-match (format "%02d:%02d" hour minute)
16390 t t ans))))
16392 ;; Check if a time range is given as a duration
16393 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16394 (setq hour (string-to-number (match-string 1 ans))
16395 h2 (+ hour (string-to-number (match-string 3 ans)))
16396 minute (string-to-number (match-string 2 ans))
16397 m2 (+ minute (if (match-end 5) (string-to-number
16398 (match-string 5 ans))0)))
16399 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16400 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16401 t t ans)))
16403 ;; Check if there is a time range
16404 (when (boundp 'org-end-time-was-given)
16405 (setq org-time-was-given nil)
16406 (when (and (string-match org-plain-time-of-day-regexp ans)
16407 (match-end 8))
16408 (setq org-end-time-was-given (match-string 8 ans))
16409 (setq ans (concat (substring ans 0 (match-beginning 7))
16410 (substring ans (match-end 7))))))
16412 (setq tl (parse-time-string ans)
16413 day (or (nth 3 tl) (nth 3 org-defdecode))
16414 month (or (nth 4 tl)
16415 (if (and org-read-date-prefer-future
16416 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16417 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16418 (nth 4 org-defdecode)))
16419 year (or (and (not kill-year) (nth 5 tl))
16420 (if (and org-read-date-prefer-future
16421 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16422 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16423 (nth 5 org-defdecode)))
16424 hour (or (nth 2 tl) (nth 2 org-defdecode))
16425 minute (or (nth 1 tl) (nth 1 org-defdecode))
16426 second (or (nth 0 tl) 0)
16427 wday (nth 6 tl))
16429 (when (and (eq org-read-date-prefer-future 'time)
16430 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16431 (equal day (nth 3 nowdecode))
16432 (equal month (nth 4 nowdecode))
16433 (equal year (nth 5 nowdecode))
16434 (nth 2 tl)
16435 (or (< (nth 2 tl) (nth 2 nowdecode))
16436 (and (= (nth 2 tl) (nth 2 nowdecode))
16437 (nth 1 tl)
16438 (< (nth 1 tl) (nth 1 nowdecode)))))
16439 (setq day (1+ day)
16440 futurep t))
16442 ;; Special date definitions below
16443 (cond
16444 (iso-week
16445 ;; There was an iso week
16446 (require 'cal-iso)
16447 (setq futurep nil)
16448 (setq year (or iso-year year)
16449 day (or iso-weekday wday 1)
16450 wday nil ; to make sure that the trigger below does not match
16451 iso-date (calendar-gregorian-from-absolute
16452 (calendar-absolute-from-iso
16453 (list iso-week day year))))
16454 ; FIXME: Should we also push ISO weeks into the future?
16455 ; (when (and org-read-date-prefer-future
16456 ; (not iso-year)
16457 ; (< (calendar-absolute-from-gregorian iso-date)
16458 ; (time-to-days (current-time))))
16459 ; (setq year (1+ year)
16460 ; iso-date (calendar-gregorian-from-absolute
16461 ; (calendar-absolute-from-iso
16462 ; (list iso-week day year)))))
16463 (setq month (car iso-date)
16464 year (nth 2 iso-date)
16465 day (nth 1 iso-date)))
16466 (deltan
16467 (setq futurep nil)
16468 (unless deltadef
16469 (let ((now (decode-time (current-time))))
16470 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16471 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16472 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16473 ((equal deltaw "m") (setq month (+ month deltan)))
16474 ((equal deltaw "y") (setq year (+ year deltan)))))
16475 ((and wday (not (nth 3 tl)))
16476 ;; Weekday was given, but no day, so pick that day in the week
16477 ;; on or after the derived date.
16478 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16479 (unless (equal wday wday1)
16480 (setq day (+ day (% (- wday wday1 -7) 7))))))
16481 (if (and (boundp 'org-time-was-given)
16482 (nth 2 tl))
16483 (setq org-time-was-given t))
16484 (if (< year 100) (setq year (+ 2000 year)))
16485 ;; Check of the date is representable
16486 (if org-read-date-force-compatible-dates
16487 (progn
16488 (if (< year 1970)
16489 (setq year 1970 org-read-date-analyze-forced-year t))
16490 (if (> year 2037)
16491 (setq year 2037 org-read-date-analyze-forced-year t)))
16492 (condition-case nil
16493 (ignore (encode-time second minute hour day month year))
16494 (error
16495 (setq year (nth 5 org-defdecode))
16496 (setq org-read-date-analyze-forced-year t))))
16497 (setq org-read-date-analyze-futurep futurep)
16498 (list second minute hour day month year)))
16500 (defvar parse-time-weekdays)
16501 (defun org-read-date-get-relative (s today default)
16502 "Check string S for special relative date string.
16503 TODAY and DEFAULT are internal times, for today and for a default.
16504 Return shift list (N what def-flag)
16505 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16506 N is the number of WHATs to shift.
16507 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16508 the DEFAULT date rather than TODAY."
16509 (require 'parse-time)
16510 (when (and
16511 (string-match
16512 (concat
16513 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16514 "\\([0-9]+\\)?"
16515 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16516 "\\([ \t]\\|$\\)") s)
16517 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16518 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16519 (string-to-char (substring (match-string 1 s) -1))
16520 ?+))
16521 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16522 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16523 (what (if (match-end 3) (match-string 3 s) "d"))
16524 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16525 (date (if rel default today))
16526 (wday (nth 6 (decode-time date)))
16527 delta)
16528 (if wday1
16529 (progn
16530 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16531 (if (= delta 0) (setq delta 7))
16532 (if (= dir ?-)
16533 (progn
16534 (setq delta (- delta 7))
16535 (if (= delta 0) (setq delta -7))))
16536 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16537 (list delta "d" rel))
16538 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16540 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16541 "Turn a user-specified date into the internal representation.
16542 The internal representation needed by the calendar is (month day year).
16543 This is a wrapper to handle the brain-dead convention in calendar that
16544 user function argument order change dependent on argument order."
16545 (if (boundp 'calendar-date-style)
16546 (cond
16547 ((eq calendar-date-style 'american)
16548 (list arg1 arg2 arg3))
16549 ((eq calendar-date-style 'european)
16550 (list arg2 arg1 arg3))
16551 ((eq calendar-date-style 'iso)
16552 (list arg2 arg3 arg1)))
16553 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16554 (if (org-bound-and-true-p european-calendar-style)
16555 (list arg2 arg1 arg3)
16556 (list arg1 arg2 arg3)))))
16558 (defun org-eval-in-calendar (form &optional keepdate)
16559 "Eval FORM in the calendar window and return to current window.
16560 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16561 otherwise stick to the current value of `org-ans2'."
16562 (let ((sf (selected-frame))
16563 (sw (selected-window)))
16564 (select-window (get-buffer-window "*Calendar*" t))
16565 (eval form)
16566 (when (and (not keepdate) (calendar-cursor-to-date))
16567 (let* ((date (calendar-cursor-to-date))
16568 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16569 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16570 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16571 (select-window sw)
16572 (org-select-frame-set-input-focus sf)))
16574 (defun org-calendar-select ()
16575 "Return to `org-read-date' with the date currently selected.
16576 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16577 (interactive)
16578 (when (calendar-cursor-to-date)
16579 (let* ((date (calendar-cursor-to-date))
16580 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16581 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16582 (if (active-minibuffer-window) (exit-minibuffer))))
16584 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16585 "Insert a date stamp for the date given by the internal TIME.
16586 WITH-HM means use the stamp format that includes the time of the day.
16587 INACTIVE means use square brackets instead of angular ones, so that the
16588 stamp will not contribute to the agenda.
16589 PRE and POST are optional strings to be inserted before and after the
16590 stamp.
16591 The command returns the inserted time stamp."
16592 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16593 stamp)
16594 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16595 (insert-before-markers (or pre ""))
16596 (when (listp extra)
16597 (setq extra (car extra))
16598 (if (and (stringp extra)
16599 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16600 (setq extra (format "-%02d:%02d"
16601 (string-to-number (match-string 1 extra))
16602 (string-to-number (match-string 2 extra))))
16603 (setq extra nil)))
16604 (when extra
16605 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16606 (insert-before-markers (setq stamp (format-time-string fmt time)))
16607 (insert-before-markers (or post ""))
16608 (setq org-last-inserted-timestamp stamp)))
16610 (defun org-toggle-time-stamp-overlays ()
16611 "Toggle the use of custom time stamp formats."
16612 (interactive)
16613 (setq org-display-custom-times (not org-display-custom-times))
16614 (unless org-display-custom-times
16615 (let ((p (point-min)) (bmp (buffer-modified-p)))
16616 (while (setq p (next-single-property-change p 'display))
16617 (if (and (get-text-property p 'display)
16618 (eq (get-text-property p 'face) 'org-date))
16619 (remove-text-properties
16620 p (setq p (next-single-property-change p 'display))
16621 '(display t))))
16622 (set-buffer-modified-p bmp)))
16623 (if (featurep 'xemacs)
16624 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16625 (org-restart-font-lock)
16626 (setq org-table-may-need-update t)
16627 (if org-display-custom-times
16628 (message "Time stamps are overlaid with custom format")
16629 (message "Time stamp overlays removed")))
16631 (defun org-display-custom-time (beg end)
16632 "Overlay modified time stamp format over timestamp between BEG and END."
16633 (let* ((ts (buffer-substring beg end))
16634 t1 w1 with-hm tf time str w2 (off 0))
16635 (save-match-data
16636 (setq t1 (org-parse-time-string ts t))
16637 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16638 (setq off (- (match-end 0) (match-beginning 0)))))
16639 (setq end (- end off))
16640 (setq w1 (- end beg)
16641 with-hm (and (nth 1 t1) (nth 2 t1))
16642 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16643 time (org-fix-decoded-time t1)
16644 str (org-add-props
16645 (format-time-string
16646 (substring tf 1 -1) (apply 'encode-time time))
16647 nil 'mouse-face 'highlight)
16648 w2 (length str))
16649 (if (not (= w2 w1))
16650 (add-text-properties (1+ beg) (+ 2 beg)
16651 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16652 (if (featurep 'xemacs)
16653 (progn
16654 (put-text-property beg end 'invisible t)
16655 (put-text-property beg end 'end-glyph (make-glyph str)))
16656 (put-text-property beg end 'display str))))
16658 (defun org-translate-time (string)
16659 "Translate all timestamps in STRING to custom format.
16660 But do this only if the variable `org-display-custom-times' is set."
16661 (when org-display-custom-times
16662 (save-match-data
16663 (let* ((start 0)
16664 (re org-ts-regexp-both)
16665 t1 with-hm inactive tf time str beg end)
16666 (while (setq start (string-match re string start))
16667 (setq beg (match-beginning 0)
16668 end (match-end 0)
16669 t1 (save-match-data
16670 (org-parse-time-string (substring string beg end) t))
16671 with-hm (and (nth 1 t1) (nth 2 t1))
16672 inactive (equal (substring string beg (1+ beg)) "[")
16673 tf (funcall (if with-hm 'cdr 'car)
16674 org-time-stamp-custom-formats)
16675 time (org-fix-decoded-time t1)
16676 str (format-time-string
16677 (concat
16678 (if inactive "[" "<") (substring tf 1 -1)
16679 (if inactive "]" ">"))
16680 (apply 'encode-time time))
16681 string (replace-match str t t string)
16682 start (+ start (length str)))))))
16683 string)
16685 (defun org-fix-decoded-time (time)
16686 "Set 0 instead of nil for the first 6 elements of time.
16687 Don't touch the rest."
16688 (let ((n 0))
16689 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16691 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16693 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16694 "Difference between TIMESTAMP-STRING and now in days.
16695 If SECONDS is non-nil, return the difference in seconds."
16696 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16697 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16698 (funcall fdiff (current-time)))))
16700 (defun org-deadline-close (timestamp-string &optional ndays)
16701 "Is the time in TIMESTAMP-STRING close to the current date?"
16702 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16703 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16704 (not (org-entry-is-done-p))))
16706 (defun org-get-wdays (ts &optional delay zero-delay)
16707 "Get the deadline lead time appropriate for timestring TS.
16708 When DELAY is non-nil, get the delay time for scheduled items
16709 instead of the deadline lead time. When ZERO-DELAY is non-nil
16710 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16711 don't try to find the delay cookie in the scheduled timestamp."
16712 (let ((tv (if delay org-scheduled-delay-days
16713 org-deadline-warning-days)))
16714 (cond
16715 ((or (and delay (< tv 0))
16716 (and delay zero-delay (<= tv 0))
16717 (and (not delay) (<= tv 0)))
16718 ;; Enforce this value no matter what
16719 (- tv))
16720 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16721 ;; lead time is specified.
16722 (floor (* (string-to-number (match-string 1 ts))
16723 (cdr (assoc (match-string 2 ts)
16724 '(("d" . 1) ("w" . 7)
16725 ("m" . 30.4) ("y" . 365.25)
16726 ("h" . 0.041667)))))))
16727 ;; go for the default.
16728 (t tv))))
16730 (defun org-calendar-select-mouse (ev)
16731 "Return to `org-read-date' with the date currently selected.
16732 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16733 (interactive "e")
16734 (mouse-set-point ev)
16735 (when (calendar-cursor-to-date)
16736 (let* ((date (calendar-cursor-to-date))
16737 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16738 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16739 (if (active-minibuffer-window) (exit-minibuffer))))
16741 (defun org-check-deadlines (ndays)
16742 "Check if there are any deadlines due or past due.
16743 A deadline is considered due if it happens within `org-deadline-warning-days'
16744 days from today's date. If the deadline appears in an entry marked DONE,
16745 it is not shown. The prefix arg NDAYS can be used to test that many
16746 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16747 (interactive "P")
16748 (let* ((org-warn-days
16749 (cond
16750 ((equal ndays '(4)) 100000)
16751 (ndays (prefix-numeric-value ndays))
16752 (t (abs org-deadline-warning-days))))
16753 (case-fold-search nil)
16754 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16755 (callback
16756 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16758 (message "%d deadlines past-due or due within %d days"
16759 (org-occur regexp nil callback)
16760 org-warn-days)))
16762 (defsubst org-re-timestamp (type)
16763 "Return a regexp for timestamp TYPE.
16764 Allowed values for TYPE are:
16766 all: all timestamps
16767 active: only active timestamps (<...>)
16768 inactive: only inactive timestamps ([...])
16769 scheduled: only scheduled timestamps
16770 deadline: only deadline timestamps
16771 closed: only closed time-stamps
16773 When TYPE is nil, fall back on returning a regexp that matches
16774 both scheduled and deadline timestamps."
16775 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16776 ((eq type 'active) org-ts-regexp)
16777 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16778 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16779 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16780 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16781 ((eq type 'scheduled-or-deadline)
16782 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16784 (defun org-check-before-date (date)
16785 "Check if there are deadlines or scheduled entries before DATE."
16786 (interactive (list (org-read-date)))
16787 (let ((case-fold-search nil)
16788 (regexp (org-re-timestamp org-ts-type))
16789 (callback
16790 (lambda () (time-less-p
16791 (org-time-string-to-time (match-string 1))
16792 (org-time-string-to-time date)))))
16793 (message "%d entries before %s"
16794 (org-occur regexp nil callback) date)))
16796 (defun org-check-after-date (date)
16797 "Check if there are deadlines or scheduled entries after DATE."
16798 (interactive (list (org-read-date)))
16799 (let ((case-fold-search nil)
16800 (regexp (org-re-timestamp org-ts-type))
16801 (callback
16802 (lambda () (not
16803 (time-less-p
16804 (org-time-string-to-time (match-string 1))
16805 (org-time-string-to-time date))))))
16806 (message "%d entries after %s"
16807 (org-occur regexp nil callback) date)))
16809 (defun org-check-dates-range (start-date end-date)
16810 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16811 (interactive (list (org-read-date nil nil nil "Range starts")
16812 (org-read-date nil nil nil "Range end")))
16813 (let ((case-fold-search nil)
16814 (regexp (org-re-timestamp org-ts-type))
16815 (callback
16816 (lambda ()
16817 (let ((match (match-string 1)))
16818 (and
16819 (not (time-less-p
16820 (org-time-string-to-time match)
16821 (org-time-string-to-time start-date)))
16822 (time-less-p
16823 (org-time-string-to-time match)
16824 (org-time-string-to-time end-date)))))))
16825 (message "%d entries between %s and %s"
16826 (org-occur regexp nil callback) start-date end-date)))
16828 (defun org-evaluate-time-range (&optional to-buffer)
16829 "Evaluate a time range by computing the difference between start and end.
16830 Normally the result is just printed in the echo area, but with prefix arg
16831 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16832 If the time range is actually in a table, the result is inserted into the
16833 next column.
16834 For time difference computation, a year is assumed to be exactly 365
16835 days in order to avoid rounding problems."
16836 (interactive "P")
16838 (org-clock-update-time-maybe)
16839 (save-excursion
16840 (unless (org-at-date-range-p t)
16841 (goto-char (point-at-bol))
16842 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16843 (if (not (org-at-date-range-p t))
16844 (error "Not at a time-stamp range, and none found in current line")))
16845 (let* ((ts1 (match-string 1))
16846 (ts2 (match-string 2))
16847 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16848 (match-end (match-end 0))
16849 (time1 (org-time-string-to-time ts1))
16850 (time2 (org-time-string-to-time ts2))
16851 (t1 (org-float-time time1))
16852 (t2 (org-float-time time2))
16853 (diff (abs (- t2 t1)))
16854 (negative (< (- t2 t1) 0))
16855 ;; (ys (floor (* 365 24 60 60)))
16856 (ds (* 24 60 60))
16857 (hs (* 60 60))
16858 (fy "%dy %dd %02d:%02d")
16859 (fy1 "%dy %dd")
16860 (fd "%dd %02d:%02d")
16861 (fd1 "%dd")
16862 (fh "%02d:%02d")
16863 y d h m align)
16864 (if havetime
16865 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16867 d (floor (/ diff ds)) diff (mod diff ds)
16868 h (floor (/ diff hs)) diff (mod diff hs)
16869 m (floor (/ diff 60)))
16870 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16872 d (floor (+ (/ diff ds) 0.5))
16873 h 0 m 0))
16874 (if (not to-buffer)
16875 (message "%s" (org-make-tdiff-string y d h m))
16876 (if (org-at-table-p)
16877 (progn
16878 (goto-char match-end)
16879 (setq align t)
16880 (and (looking-at " *|") (goto-char (match-end 0))))
16881 (goto-char match-end))
16882 (if (looking-at
16883 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16884 (replace-match ""))
16885 (if negative (insert " -"))
16886 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16887 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16888 (insert " " (format fh h m))))
16889 (if align (org-table-align))
16890 (message "Time difference inserted")))))
16892 (defun org-make-tdiff-string (y d h m)
16893 (let ((fmt "")
16894 (l nil))
16895 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16896 l (push y l)))
16897 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16898 l (push d l)))
16899 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16900 l (push h l)))
16901 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16902 l (push m l)))
16903 (apply 'format fmt (nreverse l))))
16905 (defun org-time-string-to-time (s &optional buffer pos)
16906 "Convert a timestamp string into internal time."
16907 (condition-case errdata
16908 (apply 'encode-time (org-parse-time-string s))
16909 (error (error "Bad timestamp `%s'%s\nError was: %s"
16910 s (if (not (and buffer pos))
16912 (format " at %d in buffer `%s'" pos buffer))
16913 (cdr errdata)))))
16915 (defun org-time-string-to-seconds (s)
16916 "Convert a timestamp string to a number of seconds."
16917 (org-float-time (org-time-string-to-time s)))
16919 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16920 "Convert a time stamp to an absolute day number.
16921 If there is a specifier for a cyclic time stamp, get the closest
16922 date to DAYNR.
16923 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16924 The variable `date' is bound by the calendar when this is called."
16925 (cond
16926 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16927 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16928 daynr
16929 (+ daynr 1000)))
16930 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16931 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16932 (time-to-days (current-time))) (match-string 0 s)
16933 prefer show-all))
16934 (t (time-to-days
16935 (condition-case errdata
16936 (apply 'encode-time (org-parse-time-string s))
16937 (error (error "Bad timestamp `%s'%s\nError was: %s"
16938 s (if (not (and buffer pos))
16940 (format " at %d in buffer `%s'" pos buffer))
16941 (cdr errdata))))))))
16943 (defun org-days-to-iso-week (days)
16944 "Return the iso week number."
16945 (require 'cal-iso)
16946 (car (calendar-iso-from-absolute days)))
16948 (defun org-small-year-to-year (year)
16949 "Convert 2-digit years into 4-digit years.
16950 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16951 The year 2000 cannot be abbreviated. Any year larger than 99
16952 is returned unchanged."
16953 (if (< year 38)
16954 (setq year (+ 2000 year))
16955 (if (< year 100)
16956 (setq year (+ 1900 year))))
16957 year)
16959 (defun org-time-from-absolute (d)
16960 "Return the time corresponding to date D.
16961 D may be an absolute day number, or a calendar-type list (month day year)."
16962 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16963 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16965 (defun org-calendar-holiday ()
16966 "List of holidays, for Diary display in Org-mode."
16967 (require 'holidays)
16968 (let ((hl (funcall
16969 (if (fboundp 'calendar-check-holidays)
16970 'calendar-check-holidays 'check-calendar-holidays) date)))
16971 (if hl (mapconcat 'identity hl "; "))))
16973 (defun org-diary-sexp-entry (sexp entry date)
16974 "Process a SEXP diary ENTRY for DATE."
16975 (require 'diary-lib)
16976 (let ((result (if calendar-debug-sexp
16977 (let ((stack-trace-on-error t))
16978 (eval (car (read-from-string sexp))))
16979 (condition-case nil
16980 (eval (car (read-from-string sexp)))
16981 (error
16982 (beep)
16983 (message "Bad sexp at line %d in %s: %s"
16984 (org-current-line)
16985 (buffer-file-name) sexp)
16986 (sleep-for 2))))))
16987 (cond ((stringp result) (split-string result "; "))
16988 ((and (consp result)
16989 (not (consp (cdr result)))
16990 (stringp (cdr result))) (cdr result))
16991 ((and (consp result)
16992 (stringp (car result))) result)
16993 (result entry))))
16995 (defun org-diary-to-ical-string (frombuf)
16996 "Get iCalendar entries from diary entries in buffer FROMBUF.
16997 This uses the icalendar.el library."
16998 (let* ((tmpdir (if (featurep 'xemacs)
16999 (temp-directory)
17000 temporary-file-directory))
17001 (tmpfile (make-temp-name
17002 (expand-file-name "orgics" tmpdir)))
17003 buf rtn b e)
17004 (with-current-buffer frombuf
17005 (icalendar-export-region (point-min) (point-max) tmpfile)
17006 (setq buf (find-buffer-visiting tmpfile))
17007 (set-buffer buf)
17008 (goto-char (point-min))
17009 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17010 (setq b (match-beginning 0)))
17011 (goto-char (point-max))
17012 (if (re-search-backward "^END:VEVENT" nil t)
17013 (setq e (match-end 0)))
17014 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17015 (kill-buffer buf)
17016 (delete-file tmpfile)
17017 rtn))
17019 (defun org-closest-date (start current change prefer show-all)
17020 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17021 When PREFER is `past', return a date that is either CURRENT or past.
17022 When PREFER is `future', return a date that is either CURRENT or future.
17023 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17024 ;; Make the proper lists from the dates
17025 (catch 'exit
17026 (let ((a1 '(("h" . hour)
17027 ("d" . day)
17028 ("w" . week)
17029 ("m" . month)
17030 ("y" . year)))
17031 (shour (nth 2 (org-parse-time-string start)))
17032 dn dw sday cday n1 n2 n0
17033 d m y y1 y2 date1 date2 nmonths nm ny m2)
17035 (setq start (org-date-to-gregorian start)
17036 current (org-date-to-gregorian
17037 (if show-all
17038 current
17039 (time-to-days (current-time))))
17040 sday (calendar-absolute-from-gregorian start)
17041 cday (calendar-absolute-from-gregorian current))
17043 (if (<= cday sday) (throw 'exit sday))
17045 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17046 (setq dn (string-to-number (match-string 1 change))
17047 dw (cdr (assoc (match-string 2 change) a1)))
17048 (error "Invalid change specifier: %s" change))
17049 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17050 (cond
17051 ((eq dw 'hour)
17052 (let ((missing-hours
17053 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17054 dn)))
17055 (setq n1 (if (zerop missing-hours) cday
17056 (- cday (1+ (floor (/ missing-hours 24)))))
17057 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17058 ((eq dw 'day)
17059 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17060 n2 (+ n1 dn)))
17061 ((eq dw 'year)
17062 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17063 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17064 (setq date1 (list m d y1)
17065 n1 (calendar-absolute-from-gregorian date1)
17066 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17067 n2 (calendar-absolute-from-gregorian date2)))
17068 ((eq dw 'month)
17069 ;; approx number of month between the two dates
17070 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17071 ;; How often does dn fit in there?
17072 (setq d (nth 1 start) m (car start) y (nth 2 start)
17073 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17074 m (+ m nm)
17075 ny (floor (/ m 12))
17076 y (+ y ny)
17077 m (- m (* ny 12)))
17078 (while (> m 12) (setq m (- m 12) y (1+ y)))
17079 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17080 (setq m2 (+ m dn) y2 y)
17081 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17082 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17083 (while (<= n2 cday)
17084 (setq n1 n2 m m2 y y2)
17085 (setq m2 (+ m dn) y2 y)
17086 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17087 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17088 ;; Make sure n1 is the earlier date
17089 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17090 (if show-all
17091 (cond
17092 ((eq prefer 'past) (if (= cday n2) n2 n1))
17093 ((eq prefer 'future) (if (= cday n1) n1 n2))
17094 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17095 (cond
17096 ((eq prefer 'past) (if (= cday n2) n2 n1))
17097 ((eq prefer 'future) (if (= cday n1) n1 n2))
17098 (t (if (= cday n1) n1 n2)))))))
17100 (defun org-date-to-gregorian (date)
17101 "Turn any specification of DATE into a Gregorian date for the calendar."
17102 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17103 ((and (listp date) (= (length date) 3)) date)
17104 ((stringp date)
17105 (setq date (org-parse-time-string date))
17106 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17107 ((listp date)
17108 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17110 (defun org-parse-time-string (s &optional nodefault)
17111 "Parse the standard Org-mode time string.
17112 This should be a lot faster than the normal `parse-time-string'.
17113 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17114 hour and minute fields will be nil if not given."
17115 (cond ((string-match org-ts-regexp0 s)
17116 (list 0
17117 (if (or (match-beginning 8) (not nodefault))
17118 (string-to-number (or (match-string 8 s) "0")))
17119 (if (or (match-beginning 7) (not nodefault))
17120 (string-to-number (or (match-string 7 s) "0")))
17121 (string-to-number (match-string 4 s))
17122 (string-to-number (match-string 3 s))
17123 (string-to-number (match-string 2 s))
17124 nil nil nil))
17125 ((string-match "^<[^>]+>$" s)
17126 (decode-time (seconds-to-time (org-matcher-time s))))
17127 (t (error "Not a standard Org-mode time string: %s" s))))
17129 (defun org-timestamp-up (&optional arg)
17130 "Increase the date item at the cursor by one.
17131 If the cursor is on the year, change the year. If it is on the month,
17132 the day or the time, change that.
17133 With prefix ARG, change by that many units."
17134 (interactive "p")
17135 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17137 (defun org-timestamp-down (&optional arg)
17138 "Decrease the date item at the cursor by one.
17139 If the cursor is on the year, change the year. If it is on the month,
17140 the day or the time, change that.
17141 With prefix ARG, change by that many units."
17142 (interactive "p")
17143 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17145 (defun org-timestamp-up-day (&optional arg)
17146 "Increase the date in the time stamp by one day.
17147 With prefix ARG, change that many days."
17148 (interactive "p")
17149 (if (and (not (org-at-timestamp-p t))
17150 (org-at-heading-p))
17151 (org-todo 'up)
17152 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17154 (defun org-timestamp-down-day (&optional arg)
17155 "Decrease the date in the time stamp by one day.
17156 With prefix ARG, change that many days."
17157 (interactive "p")
17158 (if (and (not (org-at-timestamp-p t))
17159 (org-at-heading-p))
17160 (org-todo 'down)
17161 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17163 (defun org-at-timestamp-p (&optional inactive-ok)
17164 "Determine if the cursor is in or at a timestamp."
17165 (interactive)
17166 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17167 (pos (point))
17168 (ans (or (looking-at tsr)
17169 (save-excursion
17170 (skip-chars-backward "^[<\n\r\t")
17171 (if (> (point) (point-min)) (backward-char 1))
17172 (and (looking-at tsr)
17173 (> (- (match-end 0) pos) -1))))))
17174 (and ans
17175 (boundp 'org-ts-what)
17176 (setq org-ts-what
17177 (cond
17178 ((= pos (match-beginning 0)) 'bracket)
17179 ;; Point is considered to be "on the bracket" whether
17180 ;; it's really on it or right after it.
17181 ((= pos (1- (match-end 0))) 'bracket)
17182 ((= pos (match-end 0)) 'after)
17183 ((org-pos-in-match-range pos 2) 'year)
17184 ((org-pos-in-match-range pos 3) 'month)
17185 ((org-pos-in-match-range pos 7) 'hour)
17186 ((org-pos-in-match-range pos 8) 'minute)
17187 ((or (org-pos-in-match-range pos 4)
17188 (org-pos-in-match-range pos 5)) 'day)
17189 ((and (> pos (or (match-end 8) (match-end 5)))
17190 (< pos (match-end 0)))
17191 (- pos (or (match-end 8) (match-end 5))))
17192 (t 'day))))
17193 ans))
17195 (defun org-toggle-timestamp-type ()
17196 "Toggle the type (<active> or [inactive]) of a time stamp."
17197 (interactive)
17198 (when (org-at-timestamp-p t)
17199 (let ((beg (match-beginning 0)) (end (match-end 0))
17200 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17201 (save-excursion
17202 (goto-char beg)
17203 (while (re-search-forward "[][<>]" end t)
17204 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17205 t t)))
17206 (message "Timestamp is now %sactive"
17207 (if (equal (char-after beg) ?<) "" "in")))))
17209 (defun org-at-clock-log-p nil
17210 "Is the cursor on the clock log line?"
17211 (save-excursion
17212 (move-beginning-of-line 1)
17213 (looking-at "^[ \t]*CLOCK:")))
17215 (defvar org-clock-history) ; defined in org-clock.el
17216 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17217 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17218 "Change the date in the time stamp at point.
17219 The date will be changed by N times WHAT. WHAT can be `day', `month',
17220 `year', `minute', `second'. If WHAT is not given, the cursor position
17221 in the timestamp determines what will be changed.
17222 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17223 (let ((origin (point)) origin-cat
17224 with-hm inactive
17225 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17226 org-ts-what
17227 extra rem
17228 ts time time0 fixnext clrgx)
17229 (if (not (org-at-timestamp-p t))
17230 (error "Not at a timestamp"))
17231 (if (and (not what) (eq org-ts-what 'bracket))
17232 (org-toggle-timestamp-type)
17233 ;; Point isn't on brackets. Remember the part of the time-stamp
17234 ;; the point was in. Indeed, size of time-stamps may change,
17235 ;; but point must be kept in the same category nonetheless.
17236 (setq origin-cat org-ts-what)
17237 (if (and (not what) (not (eq org-ts-what 'day))
17238 org-display-custom-times
17239 (get-text-property (point) 'display)
17240 (not (get-text-property (1- (point)) 'display)))
17241 (setq org-ts-what 'day))
17242 (setq org-ts-what (or what org-ts-what)
17243 inactive (= (char-after (match-beginning 0)) ?\[)
17244 ts (match-string 0))
17245 (replace-match "")
17246 (when (string-match
17247 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17249 (setq extra (match-string 1 ts))
17250 (if suppress-tmp-delay
17251 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17252 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17253 (setq with-hm t))
17254 (setq time0 (org-parse-time-string ts))
17255 (when (and updown
17256 (eq org-ts-what 'minute)
17257 (not current-prefix-arg))
17258 ;; This looks like s-up and s-down. Change by one rounding step.
17259 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17260 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17261 (setcar (cdr time0) (+ (nth 1 time0)
17262 (if (> n 0) (- rem) (- dm rem))))))
17263 (setq time
17264 (encode-time (or (car time0) 0)
17265 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17266 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17267 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17268 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17269 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17270 (nthcdr 6 time0)))
17271 (when (and (member org-ts-what '(hour minute))
17272 extra
17273 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17274 (setq extra (org-modify-ts-extra
17275 extra
17276 (if (eq org-ts-what 'hour) 2 5)
17277 n dm)))
17278 (when (integerp org-ts-what)
17279 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17280 (if (eq what 'calendar)
17281 (let ((cal-date (org-get-date-from-calendar)))
17282 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17283 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17284 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17285 (setcar time0 (or (car time0) 0))
17286 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17287 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17288 (setq time (apply 'encode-time time0))))
17289 ;; Insert the new time-stamp, and ensure point stays in the same
17290 ;; category as before (i.e. not after the last position in that
17291 ;; category).
17292 (let ((pos (point)))
17293 ;; Stay before inserted string. `save-excursion' is of no use.
17294 (setq org-last-changed-timestamp
17295 (org-insert-time-stamp time with-hm inactive nil nil extra))
17296 (goto-char pos))
17297 (save-match-data
17298 (looking-at org-ts-regexp3)
17299 (goto-char (cond
17300 ;; `day' category ends before `hour' if any, or at
17301 ;; the end of the day name.
17302 ((eq origin-cat 'day)
17303 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17304 ((eq origin-cat 'hour) (min (match-end 7) origin))
17305 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17306 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17307 ;; `year' and `month' have both fixed size: point
17308 ;; couldn't have moved into another part.
17309 (t origin))))
17310 ;; Update clock if on a CLOCK line.
17311 (org-clock-update-time-maybe)
17312 ;; Maybe adjust the closest clock in `org-clock-history'
17313 (when org-clock-adjust-closest
17314 (if (not (and (org-at-clock-log-p)
17315 (< 1 (length (delq nil (mapcar 'marker-position
17316 org-clock-history))))))
17317 (message "No clock to adjust")
17318 (cond ((save-excursion ; fix previous clock?
17319 (re-search-backward org-ts-regexp0 nil t)
17320 (org-looking-back (concat org-clock-string " \\[")))
17321 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17322 ((save-excursion ; fix next clock?
17323 (re-search-backward org-ts-regexp0 nil t)
17324 (looking-at (concat org-ts-regexp0 "\\] =>")))
17325 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17326 (save-window-excursion
17327 ;; Find closest clock to point, adjust the previous/next one in history
17328 (let* ((p (save-excursion (org-back-to-heading t)))
17329 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17330 (clfixnth
17331 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17332 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17333 (if (not clfixpos)
17334 (message "No clock to adjust")
17335 (save-excursion
17336 (org-goto-marker-or-bmk clfixpos)
17337 (org-show-subtree)
17338 (when (re-search-forward clrgx nil t)
17339 (goto-char (match-beginning 1))
17340 (let (org-clock-adjust-closest)
17341 (org-timestamp-change n org-ts-what updown))
17342 (message "Clock adjusted in %s for heading: %s"
17343 (file-name-nondirectory (buffer-file-name))
17344 (org-get-heading t t)))))))))
17345 ;; Try to recenter the calendar window, if any.
17346 (if (and org-calendar-follow-timestamp-change
17347 (get-buffer-window "*Calendar*" t)
17348 (memq org-ts-what '(day month year)))
17349 (org-recenter-calendar (time-to-days time))))))
17351 (defun org-modify-ts-extra (s pos n dm)
17352 "Change the different parts of the lead-time and repeat fields in timestamp."
17353 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17354 ng h m new rem)
17355 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17356 (cond
17357 ((or (org-pos-in-match-range pos 2)
17358 (org-pos-in-match-range pos 3))
17359 (setq m (string-to-number (match-string 3 s))
17360 h (string-to-number (match-string 2 s)))
17361 (if (org-pos-in-match-range pos 2)
17362 (setq h (+ h n))
17363 (setq n (* dm (org-no-warnings (signum n))))
17364 (when (not (= 0 (setq rem (% m dm))))
17365 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17366 (setq m (+ m n)))
17367 (if (< m 0) (setq m (+ m 60) h (1- h)))
17368 (if (> m 59) (setq m (- m 60) h (1+ h)))
17369 (setq h (min 24 (max 0 h)))
17370 (setq ng 1 new (format "-%02d:%02d" h m)))
17371 ((org-pos-in-match-range pos 6)
17372 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17373 ((org-pos-in-match-range pos 5)
17374 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17376 ((org-pos-in-match-range pos 9)
17377 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17378 ((org-pos-in-match-range pos 8)
17379 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17381 (when ng
17382 (setq s (concat
17383 (substring s 0 (match-beginning ng))
17385 (substring s (match-end ng))))))
17388 (defun org-recenter-calendar (date)
17389 "If the calendar is visible, recenter it to DATE."
17390 (let ((cwin (get-buffer-window "*Calendar*" t)))
17391 (when cwin
17392 (let ((calendar-move-hook nil))
17393 (with-selected-window cwin
17394 (calendar-goto-date (if (listp date) date
17395 (calendar-gregorian-from-absolute date))))))))
17397 (defun org-goto-calendar (&optional arg)
17398 "Go to the Emacs calendar at the current date.
17399 If there is a time stamp in the current line, go to that date.
17400 A prefix ARG can be used to force the current date."
17401 (interactive "P")
17402 (let ((tsr org-ts-regexp) diff
17403 (calendar-move-hook nil)
17404 (calendar-view-holidays-initially-flag nil)
17405 (calendar-view-diary-initially-flag nil))
17406 (if (or (org-at-timestamp-p)
17407 (save-excursion
17408 (beginning-of-line 1)
17409 (looking-at (concat ".*" tsr))))
17410 (let ((d1 (time-to-days (current-time)))
17411 (d2 (time-to-days
17412 (org-time-string-to-time (match-string 1)))))
17413 (setq diff (- d2 d1))))
17414 (calendar)
17415 (calendar-goto-today)
17416 (if (and diff (not arg)) (calendar-forward-day diff))))
17418 (defun org-get-date-from-calendar ()
17419 "Return a list (month day year) of date at point in calendar."
17420 (with-current-buffer "*Calendar*"
17421 (save-match-data
17422 (calendar-cursor-to-date))))
17424 (defun org-date-from-calendar ()
17425 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17426 If there is already a time stamp at the cursor position, update it."
17427 (interactive)
17428 (if (org-at-timestamp-p t)
17429 (org-timestamp-change 0 'calendar)
17430 (let ((cal-date (org-get-date-from-calendar)))
17431 (org-insert-time-stamp
17432 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17434 (defcustom org-effort-durations
17435 `(("h" . 60)
17436 ("d" . ,(* 60 8))
17437 ("w" . ,(* 60 8 5))
17438 ("m" . ,(* 60 8 5 4))
17439 ("y" . ,(* 60 8 5 40)))
17440 "Conversion factor to minutes for an effort modifier.
17442 Each entry has the form (MODIFIER . MINUTES).
17444 In an effort string, a number followed by MODIFIER is multiplied
17445 by the specified number of MINUTES to obtain an effort in
17446 minutes.
17448 For example, if the value of this variable is ((\"hours\" . 60)), then an
17449 effort string \"2hours\" is equivalent to 120 minutes."
17450 :group 'org-agenda
17451 :version "24.1"
17452 :type '(alist :key-type (string :tag "Modifier")
17453 :value-type (number :tag "Minutes")))
17455 (defun org-minutes-to-clocksum-string (m)
17456 "Format number of minutes as a clocksum string.
17457 The format is determined by `org-time-clocksum-format',
17458 `org-time-clocksum-use-fractional' and
17459 `org-time-clocksum-fractional-format' and
17460 `org-time-clocksum-use-effort-durations'."
17461 (let ((clocksum "")
17462 (m (round m)) ; Don't allow fractions of minutes
17463 h d w mo y fmt n)
17464 (setq h (if org-time-clocksum-use-effort-durations
17465 (cdr (assoc "h" org-effort-durations)) 60)
17466 d (if org-time-clocksum-use-effort-durations
17467 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17468 w (if org-time-clocksum-use-effort-durations
17469 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17470 mo (if org-time-clocksum-use-effort-durations
17471 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17472 y (if org-time-clocksum-use-effort-durations
17473 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17474 ;; fractional format
17475 (if org-time-clocksum-use-fractional
17476 (cond
17477 ;; single format string
17478 ((stringp org-time-clocksum-fractional-format)
17479 (format org-time-clocksum-fractional-format (/ m (float h))))
17480 ;; choice of fractional formats for different time units
17481 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17482 (> (/ (truncate m) (* y d h)) 0))
17483 (format fmt (/ m (* y d (float h)))))
17484 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17485 (> (/ (truncate m) (* mo d h)) 0))
17486 (format fmt (/ m (* mo d (float h)))))
17487 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17488 (> (/ (truncate m) (* w d h)) 0))
17489 (format fmt (/ m (* w d (float h)))))
17490 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17491 (> (/ (truncate m) (* d h)) 0))
17492 (format fmt (/ m (* d (float h)))))
17493 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17494 (> (/ (truncate m) h) 0))
17495 (format fmt (/ m (float h))))
17496 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17497 (format fmt m))
17498 ;; fall back to smallest time unit with a format
17499 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17500 (format fmt (/ m (float h))))
17501 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17502 (format fmt (/ m (* d (float h)))))
17503 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17504 (format fmt (/ m (* w d (float h)))))
17505 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17506 (format fmt (/ m (* mo d (float h)))))
17507 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17508 (format fmt (/ m (* y d (float h))))))
17509 ;; standard (non-fractional) format, with single format string
17510 (if (stringp org-time-clocksum-format)
17511 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17512 ;; separate formats components
17513 (and (setq fmt (plist-get org-time-clocksum-format :years))
17514 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17515 (plist-get org-time-clocksum-format :require-years))
17516 (setq clocksum (concat clocksum (format fmt n))
17517 m (- m (* n y d h))))
17518 (and (setq fmt (plist-get org-time-clocksum-format :months))
17519 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17520 (plist-get org-time-clocksum-format :require-months))
17521 (setq clocksum (concat clocksum (format fmt n))
17522 m (- m (* n mo d h))))
17523 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17524 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17525 (plist-get org-time-clocksum-format :require-weeks))
17526 (setq clocksum (concat clocksum (format fmt n))
17527 m (- m (* n w d h))))
17528 (and (setq fmt (plist-get org-time-clocksum-format :days))
17529 (or (> (setq n (/ (truncate m) (* d h))) 0)
17530 (plist-get org-time-clocksum-format :require-days))
17531 (setq clocksum (concat clocksum (format fmt n))
17532 m (- m (* n d h))))
17533 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17534 (or (> (setq n (/ (truncate m) h)) 0)
17535 (plist-get org-time-clocksum-format :require-hours))
17536 (setq clocksum (concat clocksum (format fmt n))
17537 m (- m (* n h))))
17538 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17539 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17540 (setq clocksum (concat clocksum (format fmt m))))
17541 ;; return formatted time duration
17542 clocksum))))
17544 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17545 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17546 "Org mode version 8.0")
17548 (defun org-hours-to-clocksum-string (n)
17549 (org-minutes-to-clocksum-string (* n 60)))
17551 (defun org-hh:mm-string-to-minutes (s)
17552 "Convert a string H:MM to a number of minutes.
17553 If the string is just a number, interpret it as minutes.
17554 In fact, the first hh:mm or number in the string will be taken,
17555 there can be extra stuff in the string.
17556 If no number is found, the return value is 0."
17557 (cond
17558 ((integerp s) s)
17559 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17560 (+ (* (string-to-number (match-string 1 s)) 60)
17561 (string-to-number (match-string 2 s))))
17562 ((string-match "\\([0-9]+\\)" s)
17563 (string-to-number (match-string 1 s)))
17564 (t 0)))
17566 (defcustom org-image-actual-width t
17567 "Should we use the actual width of images when inlining them?
17569 When set to `t', always use the image width.
17571 When set to a number, use imagemagick (when available) to set
17572 the image's width to this value.
17574 When set to a number in a list, try to get the width from any
17575 #+ATTR.* keyword if it matches a width specification like
17577 #+ATTR_HTML: :width 300px
17579 and fall back on that number if none is found.
17581 When set to nil, try to get the width from an #+ATTR.* keyword
17582 and fall back on the original width if none is found.
17584 This requires Emacs >= 24.1, build with imagemagick support."
17585 :group 'org-appearance
17586 :version "24.4"
17587 :package-version '(Org . "8.0")
17588 :type '(choice
17589 (const :tag "Use the image width" t)
17590 (integer :tag "Use a number of pixels")
17591 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17592 (const :tag "Use #+ATTR* or don't resize" nil)))
17594 (defcustom org-agenda-inhibit-startup nil
17595 "Inhibit startup when preparing agenda buffers.
17596 When this variable is `t' (the default), the initialization of
17597 the Org agenda buffers is inhibited: e.g. the visibility state
17598 is not set, the tables are not re-aligned, etc."
17599 :type 'boolean
17600 :version "24.3"
17601 :group 'org-agenda)
17603 (defun org-duration-string-to-minutes (s &optional output-to-string)
17604 "Convert a duration string S to minutes.
17606 A bare number is interpreted as minutes, modifiers can be set by
17607 customizing `org-effort-durations' (which see).
17609 Entries containing a colon are interpreted as H:MM by
17610 `org-hh:mm-string-to-minutes'."
17611 (let ((result 0)
17612 (re (concat "\\([0-9.]+\\) *\\("
17613 (regexp-opt (mapcar 'car org-effort-durations))
17614 "\\)")))
17615 (while (string-match re s)
17616 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17617 (string-to-number (match-string 1 s))))
17618 (setq s (replace-match "" nil t s)))
17619 (setq result (floor result))
17620 (incf result (org-hh:mm-string-to-minutes s))
17621 (if output-to-string (number-to-string result) result)))
17623 ;;;; Files
17625 (defun org-save-all-org-buffers ()
17626 "Save all Org-mode buffers without user confirmation."
17627 (interactive)
17628 (message "Saving all Org-mode buffers...")
17629 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17630 (when (featurep 'org-id) (org-id-locations-save))
17631 (message "Saving all Org-mode buffers... done"))
17633 (defun org-revert-all-org-buffers ()
17634 "Revert all Org-mode buffers.
17635 Prompt for confirmation when there are unsaved changes.
17636 Be sure you know what you are doing before letting this function
17637 overwrite your changes.
17639 This function is useful in a setup where one tracks org files
17640 with a version control system, to revert on one machine after pulling
17641 changes from another. I believe the procedure must be like this:
17643 1. M-x org-save-all-org-buffers
17644 2. Pull changes from the other machine, resolve conflicts
17645 3. M-x org-revert-all-org-buffers"
17646 (interactive)
17647 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17648 (error "Abort"))
17649 (save-excursion
17650 (save-window-excursion
17651 (mapc
17652 (lambda (b)
17653 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17654 (with-current-buffer b buffer-file-name))
17655 (org-pop-to-buffer-same-window b)
17656 (revert-buffer t 'no-confirm)))
17657 (buffer-list))
17658 (when (and (featurep 'org-id) org-id-track-globally)
17659 (org-id-locations-load)))))
17661 ;;;; Agenda files
17663 ;;;###autoload
17664 (defun org-switchb (&optional arg)
17665 "Switch between Org buffers.
17666 With one prefix argument, restrict available buffers to files.
17667 With two prefix arguments, restrict available buffers to agenda files.
17669 Defaults to `iswitchb' for buffer name completion.
17670 Set `org-completion-use-ido' to make it use ido instead."
17671 (interactive "P")
17672 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17673 ((equal arg '(16)) (org-buffer-list 'agenda))
17674 (t (org-buffer-list))))
17675 (org-completion-use-iswitchb org-completion-use-iswitchb)
17676 (org-completion-use-ido org-completion-use-ido))
17677 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17678 (setq org-completion-use-iswitchb t))
17679 (org-pop-to-buffer-same-window
17680 (org-icompleting-read "Org buffer: "
17681 (mapcar 'list (mapcar 'buffer-name blist))
17682 nil t))))
17684 ;;; Define some older names previously used for this functionality
17685 ;;;###autoload
17686 (defalias 'org-ido-switchb 'org-switchb)
17687 ;;;###autoload
17688 (defalias 'org-iswitchb 'org-switchb)
17690 (defun org-buffer-list (&optional predicate exclude-tmp)
17691 "Return a list of Org buffers.
17692 PREDICATE can be `export', `files' or `agenda'.
17694 export restrict the list to Export buffers.
17695 files restrict the list to buffers visiting Org files.
17696 agenda restrict the list to buffers visiting agenda files.
17698 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17699 (let* ((bfn nil)
17700 (agenda-files (and (eq predicate 'agenda)
17701 (mapcar 'file-truename (org-agenda-files t))))
17702 (filter
17703 (cond
17704 ((eq predicate 'files)
17705 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17706 ((eq predicate 'export)
17707 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17708 ((eq predicate 'agenda)
17709 (lambda (b)
17710 (with-current-buffer b
17711 (and (derived-mode-p 'org-mode)
17712 (setq bfn (buffer-file-name b))
17713 (member (file-truename bfn) agenda-files)))))
17714 (t (lambda (b) (with-current-buffer b
17715 (or (derived-mode-p 'org-mode)
17716 (string-match "\*Org .*Export"
17717 (buffer-name b)))))))))
17718 (delq nil
17719 (mapcar
17720 (lambda(b)
17721 (if (and (funcall filter b)
17722 (or (not exclude-tmp)
17723 (not (string-match "tmp" (buffer-name b)))))
17725 nil))
17726 (buffer-list)))))
17728 (defun org-agenda-files (&optional unrestricted archives)
17729 "Get the list of agenda files.
17730 Optional UNRESTRICTED means return the full list even if a restriction
17731 is currently in place.
17732 When ARCHIVES is t, include all archive files that are really being
17733 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17734 `org-agenda-archives-mode' is t."
17735 (let ((files
17736 (cond
17737 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17738 ((stringp org-agenda-files) (org-read-agenda-file-list))
17739 ((listp org-agenda-files) org-agenda-files)
17740 (t (error "Invalid value of `org-agenda-files'")))))
17741 (setq files (apply 'append
17742 (mapcar (lambda (f)
17743 (if (file-directory-p f)
17744 (directory-files
17745 f t org-agenda-file-regexp)
17746 (list f)))
17747 files)))
17748 (when org-agenda-skip-unavailable-files
17749 (setq files (delq nil
17750 (mapcar (function
17751 (lambda (file)
17752 (and (file-readable-p file) file)))
17753 files))))
17754 (when (or (eq archives t)
17755 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17756 (setq files (org-add-archive-files files)))
17757 files))
17759 (defun org-agenda-file-p (&optional file)
17760 "Return non-nil, if FILE is an agenda file.
17761 If FILE is omitted, use the file associated with the current
17762 buffer."
17763 (member (or file (buffer-file-name))
17764 (org-agenda-files t)))
17766 (defun org-edit-agenda-file-list ()
17767 "Edit the list of agenda files.
17768 Depending on setup, this either uses customize to edit the variable
17769 `org-agenda-files', or it visits the file that is holding the list. In the
17770 latter case, the buffer is set up in a way that saving it automatically kills
17771 the buffer and restores the previous window configuration."
17772 (interactive)
17773 (if (stringp org-agenda-files)
17774 (let ((cw (current-window-configuration)))
17775 (find-file org-agenda-files)
17776 (org-set-local 'org-window-configuration cw)
17777 (org-add-hook 'after-save-hook
17778 (lambda ()
17779 (set-window-configuration
17780 (prog1 org-window-configuration
17781 (kill-buffer (current-buffer))))
17782 (org-install-agenda-files-menu)
17783 (message "New agenda file list installed"))
17784 nil 'local)
17785 (message "%s" (substitute-command-keys
17786 "Edit list and finish with \\[save-buffer]")))
17787 (customize-variable 'org-agenda-files)))
17789 (defun org-store-new-agenda-file-list (list)
17790 "Set new value for the agenda file list and save it correctly."
17791 (if (stringp org-agenda-files)
17792 (let ((fe (org-read-agenda-file-list t)) b u)
17793 (while (setq b (find-buffer-visiting org-agenda-files))
17794 (kill-buffer b))
17795 (with-temp-file org-agenda-files
17796 (insert
17797 (mapconcat
17798 (lambda (f) ;; Keep un-expanded entries.
17799 (if (setq u (assoc f fe))
17800 (cdr u)
17802 list "\n")
17803 "\n")))
17804 (let ((org-mode-hook nil) (org-inhibit-startup t)
17805 (org-insert-mode-line-in-empty-file nil))
17806 (setq org-agenda-files list)
17807 (customize-save-variable 'org-agenda-files org-agenda-files))))
17809 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17810 "Read the list of agenda files from a file.
17811 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17812 filenames, used by `org-store-new-agenda-file-list' to write back
17813 un-expanded file names."
17814 (when (file-directory-p org-agenda-files)
17815 (error "`org-agenda-files' cannot be a single directory"))
17816 (when (stringp org-agenda-files)
17817 (with-temp-buffer
17818 (insert-file-contents org-agenda-files)
17819 (mapcar
17820 (lambda (f)
17821 (let ((e (expand-file-name (substitute-in-file-name f)
17822 org-directory)))
17823 (if pair-with-expansion
17824 (cons e f)
17825 e)))
17826 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17828 ;;;###autoload
17829 (defun org-cycle-agenda-files ()
17830 "Cycle through the files in `org-agenda-files'.
17831 If the current buffer visits an agenda file, find the next one in the list.
17832 If the current buffer does not, find the first agenda file."
17833 (interactive)
17834 (let* ((fs (org-agenda-files t))
17835 (files (append fs (list (car fs))))
17836 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17837 file)
17838 (unless files (error "No agenda files"))
17839 (catch 'exit
17840 (while (setq file (pop files))
17841 (if (equal (file-truename file) tcf)
17842 (when (car files)
17843 (find-file (car files))
17844 (throw 'exit t))))
17845 (find-file (car fs)))
17846 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17848 (defun org-agenda-file-to-front (&optional to-end)
17849 "Move/add the current file to the top of the agenda file list.
17850 If the file is not present in the list, it is added to the front. If it is
17851 present, it is moved there. With optional argument TO-END, add/move to the
17852 end of the list."
17853 (interactive "P")
17854 (let ((org-agenda-skip-unavailable-files nil)
17855 (file-alist (mapcar (lambda (x)
17856 (cons (file-truename x) x))
17857 (org-agenda-files t)))
17858 (ctf (file-truename
17859 (or buffer-file-name
17860 (error "Please save the current buffer to a file"))))
17861 x had)
17862 (setq x (assoc ctf file-alist) had x)
17864 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17865 (if to-end
17866 (setq file-alist (append (delq x file-alist) (list x)))
17867 (setq file-alist (cons x (delq x file-alist))))
17868 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17869 (org-install-agenda-files-menu)
17870 (message "File %s to %s of agenda file list"
17871 (if had "moved" "added") (if to-end "end" "front"))))
17873 (defun org-remove-file (&optional file)
17874 "Remove current file from the list of files in variable `org-agenda-files'.
17875 These are the files which are being checked for agenda entries.
17876 Optional argument FILE means use this file instead of the current."
17877 (interactive)
17878 (let* ((org-agenda-skip-unavailable-files nil)
17879 (file (or file buffer-file-name
17880 (error "Current buffer does not visit a file")))
17881 (true-file (file-truename file))
17882 (afile (abbreviate-file-name file))
17883 (files (delq nil (mapcar
17884 (lambda (x)
17885 (if (equal true-file
17886 (file-truename x))
17887 nil x))
17888 (org-agenda-files t)))))
17889 (if (not (= (length files) (length (org-agenda-files t))))
17890 (progn
17891 (org-store-new-agenda-file-list files)
17892 (org-install-agenda-files-menu)
17893 (message "Removed file: %s" afile))
17894 (message "File was not in list: %s (not removed)" afile))))
17896 (defun org-file-menu-entry (file)
17897 (vector file (list 'find-file file) t))
17899 (defun org-check-agenda-file (file)
17900 "Make sure FILE exists. If not, ask user what to do."
17901 (when (not (file-exists-p file))
17902 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17903 (abbreviate-file-name file))
17904 (let ((r (downcase (read-char-exclusive))))
17905 (cond
17906 ((equal r ?r)
17907 (org-remove-file file)
17908 (throw 'nextfile t))
17909 (t (error "Abort"))))))
17911 (defun org-get-agenda-file-buffer (file)
17912 "Get a buffer visiting FILE. If the buffer needs to be created, add
17913 it to the list of buffers which might be released later."
17914 (let ((buf (org-find-base-buffer-visiting file)))
17915 (if buf
17916 buf ; just return it
17917 ;; Make a new buffer and remember it
17918 (setq buf (find-file-noselect file))
17919 (if buf (push buf org-agenda-new-buffers))
17920 buf)))
17922 (defun org-release-buffers (blist)
17923 "Release all buffers in list, asking the user for confirmation when needed.
17924 When a buffer is unmodified, it is just killed. When modified, it is saved
17925 \(if the user agrees) and then killed."
17926 (let (buf file)
17927 (while (setq buf (pop blist))
17928 (setq file (buffer-file-name buf))
17929 (when (and (buffer-modified-p buf)
17930 file
17931 (y-or-n-p (format "Save file %s? " file)))
17932 (with-current-buffer buf (save-buffer)))
17933 (kill-buffer buf))))
17935 (defun org-agenda-prepare-buffers (files)
17936 "Create buffers for all agenda files, protect archived trees and comments."
17937 (interactive)
17938 (let ((pa '(:org-archived t))
17939 (pc '(:org-comment t))
17940 (pall '(:org-archived t :org-comment t))
17941 (inhibit-read-only t)
17942 (org-inhibit-startup org-agenda-inhibit-startup)
17943 (rea (concat ":" org-archive-tag ":"))
17944 file re)
17945 (setq org-tag-alist-for-agenda nil
17946 org-tag-groups-alist-for-agenda nil)
17947 (save-excursion
17948 (save-restriction
17949 (while (setq file (pop files))
17950 (catch 'nextfile
17951 (if (bufferp file)
17952 (set-buffer file)
17953 (org-check-agenda-file file)
17954 (set-buffer (org-get-agenda-file-buffer file)))
17955 (widen)
17956 (org-set-regexps-and-options-for-tags)
17957 (org-refresh-category-properties)
17958 (org-refresh-properties org-effort-property 'org-effort)
17959 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17960 (setq org-todo-keywords-for-agenda
17961 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17962 (setq org-done-keywords-for-agenda
17963 (append org-done-keywords-for-agenda org-done-keywords))
17964 (setq org-todo-keyword-alist-for-agenda
17965 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17966 (setq org-drawers-for-agenda
17967 (append org-drawers-for-agenda org-drawers))
17968 (unless (equal org-tag-alist-for-agenda org-tag-alist)
17969 (setq org-tag-alist-for-agenda
17970 (append org-tag-alist-for-agenda org-tag-alist)))
17971 (if org-group-tags
17972 (setq org-tag-groups-alist-for-agenda
17973 (org-uniquify-alist
17974 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17975 (org-with-silent-modifications
17976 (save-excursion
17977 (remove-text-properties (point-min) (point-max) pall)
17978 (when org-agenda-skip-archived-trees
17979 (goto-char (point-min))
17980 (while (re-search-forward rea nil t)
17981 (if (org-at-heading-p t)
17982 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17983 (goto-char (point-min))
17984 (setq re (format org-heading-keyword-regexp-format
17985 org-comment-string))
17986 (while (re-search-forward re nil t)
17987 (add-text-properties
17988 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17989 (setq org-todo-keywords-for-agenda
17990 (org-uniquify org-todo-keywords-for-agenda))
17991 (setq org-todo-keyword-alist-for-agenda
17992 (org-uniquify org-todo-keyword-alist-for-agenda))))
17995 ;;;; CDLaTeX minor mode
17997 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17998 "Keymap for the minor `org-cdlatex-mode'.")
18000 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18001 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18002 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18003 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18004 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18006 (defvar org-cdlatex-texmathp-advice-is-done nil
18007 "Flag remembering if we have applied the advice to texmathp already.")
18009 (define-minor-mode org-cdlatex-mode
18010 "Toggle the minor `org-cdlatex-mode'.
18011 This mode supports entering LaTeX environment and math in LaTeX fragments
18012 in Org-mode.
18013 \\{org-cdlatex-mode-map}"
18014 nil " OCDL" nil
18015 (when org-cdlatex-mode
18016 (require 'cdlatex)
18017 (run-hooks 'cdlatex-mode-hook)
18018 (cdlatex-compute-tables))
18019 (unless org-cdlatex-texmathp-advice-is-done
18020 (setq org-cdlatex-texmathp-advice-is-done t)
18021 (defadvice texmathp (around org-math-always-on activate)
18022 "Always return t in org-mode buffers.
18023 This is because we want to insert math symbols without dollars even outside
18024 the LaTeX math segments. If Orgmode thinks that point is actually inside
18025 an embedded LaTeX fragment, let texmathp do its job.
18026 \\[org-cdlatex-mode-map]"
18027 (interactive)
18028 (let (p)
18029 (cond
18030 ((not (derived-mode-p 'org-mode)) ad-do-it)
18031 ((eq this-command 'cdlatex-math-symbol)
18032 (setq ad-return-value t
18033 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18035 (let ((p (org-inside-LaTeX-fragment-p)))
18036 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18037 (setq ad-return-value t
18038 texmathp-why '("Org-mode embedded math" . 0))
18039 (if p ad-do-it)))))))))
18041 (defun turn-on-org-cdlatex ()
18042 "Unconditionally turn on `org-cdlatex-mode'."
18043 (org-cdlatex-mode 1))
18045 (defun org-try-cdlatex-tab ()
18046 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18047 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18048 - inside a LaTeX fragment, or
18049 - after the first word in a line, where an abbreviation expansion could
18050 insert a LaTeX environment."
18051 (when org-cdlatex-mode
18052 (cond
18053 ;; Before any word on the line: No expansion possible.
18054 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18055 ;; Just after first word on the line: Expand it. Make sure it
18056 ;; cannot happen on headlines, though.
18057 ((save-excursion
18058 (skip-chars-backward "a-zA-Z0-9*")
18059 (skip-chars-backward " \t")
18060 (and (bolp) (not (org-at-heading-p))))
18061 (cdlatex-tab) t)
18062 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18064 (defun org-cdlatex-underscore-caret (&optional arg)
18065 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18066 Revert to the normal definition outside of these fragments."
18067 (interactive "P")
18068 (if (org-inside-LaTeX-fragment-p)
18069 (call-interactively 'cdlatex-sub-superscript)
18070 (let (org-cdlatex-mode)
18071 (call-interactively (key-binding (vector last-input-event))))))
18073 (defun org-cdlatex-math-modify (&optional arg)
18074 "Execute `cdlatex-math-modify' in LaTeX fragments.
18075 Revert to the normal definition outside of these fragments."
18076 (interactive "P")
18077 (if (org-inside-LaTeX-fragment-p)
18078 (call-interactively 'cdlatex-math-modify)
18079 (let (org-cdlatex-mode)
18080 (call-interactively (key-binding (vector last-input-event))))))
18084 ;;;; LaTeX fragments
18086 (defvar org-latex-regexps
18087 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18088 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18089 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18090 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18091 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18092 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18093 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18094 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18095 "Regular expressions for matching embedded LaTeX.")
18097 (defun org-inside-LaTeX-fragment-p ()
18098 "Test if point is inside a LaTeX fragment.
18099 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18100 sequence appearing also before point.
18101 Even though the matchers for math are configurable, this function assumes
18102 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18103 delimiters are skipped when they have been removed by customization.
18104 The return value is nil, or a cons cell with the delimiter and the
18105 position of this delimiter.
18107 This function does a reasonably good job, but can locally be fooled by
18108 for example currency specifications. For example it will assume being in
18109 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18110 fragments that are properly closed, but during editing, we have to live
18111 with the uncertainty caused by missing closing delimiters. This function
18112 looks only before point, not after."
18113 (catch 'exit
18114 (let ((pos (point))
18115 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18116 (lim (progn
18117 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18118 (point)))
18119 dd-on str (start 0) m re)
18120 (goto-char pos)
18121 (when dodollar
18122 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18123 re (nth 1 (assoc "$" org-latex-regexps)))
18124 (while (string-match re str start)
18125 (cond
18126 ((= (match-end 0) (length str))
18127 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18128 ((= (match-end 0) (- (length str) 5))
18129 (throw 'exit nil))
18130 (t (setq start (match-end 0))))))
18131 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18132 (goto-char pos)
18133 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18134 (and (match-beginning 2) (throw 'exit nil))
18135 ;; count $$
18136 (while (re-search-backward "\\$\\$" lim t)
18137 (setq dd-on (not dd-on)))
18138 (goto-char pos)
18139 (if dd-on (cons "$$" m))))))
18141 (defun org-inside-latex-macro-p ()
18142 "Is point inside a LaTeX macro or its arguments?"
18143 (save-match-data
18144 (org-in-regexp
18145 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18147 (defvar org-latex-fragment-image-overlays nil
18148 "List of overlays carrying the images of latex fragments.")
18149 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18151 (defun org-remove-latex-fragment-image-overlays ()
18152 "Remove all overlays with LaTeX fragment images in current buffer."
18153 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18154 (setq org-latex-fragment-image-overlays nil))
18156 (defun org-preview-latex-fragment (&optional subtree)
18157 "Preview the LaTeX fragment at point, or all locally or globally.
18158 If the cursor is in a LaTeX fragment, create the image and overlay
18159 it over the source code. If there is no fragment at point, display
18160 all fragments in the current text, from one headline to the next. With
18161 prefix SUBTREE, display all fragments in the current subtree. With a
18162 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18163 the cursor is before the first headline,
18164 display all fragments in the buffer.
18165 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18166 (interactive "P")
18167 (unless buffer-file-name
18168 (error "Can't preview LaTeX fragment in a non-file buffer"))
18169 (org-remove-latex-fragment-image-overlays)
18170 (save-excursion
18171 (save-restriction
18172 (let (beg end at msg)
18173 (cond
18174 ((or (equal subtree '(16))
18175 (not (save-excursion
18176 (re-search-backward org-outline-regexp-bol nil t))))
18177 (setq beg (point-min) end (point-max)
18178 msg "Creating images for buffer...%s"))
18179 ((equal subtree '(4))
18180 (org-back-to-heading)
18181 (setq beg (point) end (org-end-of-subtree t)
18182 msg "Creating images for subtree...%s"))
18184 (if (setq at (org-inside-LaTeX-fragment-p))
18185 (goto-char (max (point-min) (- (cdr at) 2)))
18186 (org-back-to-heading))
18187 (setq beg (point) end (progn (outline-next-heading) (point))
18188 msg (if at "Creating image...%s"
18189 "Creating images for entry...%s"))))
18190 (message msg "")
18191 (narrow-to-region beg end)
18192 (goto-char beg)
18193 (org-format-latex
18194 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18195 (file-name-nondirectory
18196 buffer-file-name)))
18197 default-directory 'overlays msg at 'forbuffer
18198 org-latex-create-formula-image-program)
18199 (message msg "done. Use `C-c C-c' to remove images.")))))
18201 (defun org-format-latex (prefix &optional dir overlays msg at
18202 forbuffer processing-type)
18203 "Replace LaTeX fragments with links to an image, and produce images.
18204 Some of the options can be changed using the variable
18205 `org-format-latex-options'."
18206 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18207 (let* ((prefixnodir (file-name-nondirectory prefix))
18208 (absprefix (expand-file-name prefix dir))
18209 (todir (file-name-directory absprefix))
18210 (opt org-format-latex-options)
18211 (optnew org-format-latex-options)
18212 (matchers (plist-get opt :matchers))
18213 (re-list org-latex-regexps)
18214 (cnt 0) txt hash link beg end re e checkdir
18215 string
18216 m n block-type block linkfile movefile ov)
18217 ;; Check the different regular expressions
18218 (while (setq e (pop re-list))
18219 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18220 block (if block-type "\n\n" ""))
18221 (when (member m matchers)
18222 (goto-char (point-min))
18223 (while (re-search-forward re nil t)
18224 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18225 (or (not overlays)
18226 (not (eq (get-char-property (match-beginning n)
18227 'org-overlay-type)
18228 'org-latex-overlay))))
18229 (cond
18230 ((eq processing-type 'verbatim))
18231 ((eq processing-type 'mathjax)
18232 ;; Prepare for MathJax processing.
18233 (setq string (match-string n))
18234 (when (member m '("$" "$1"))
18235 (save-excursion
18236 (delete-region (match-beginning n) (match-end n))
18237 (goto-char (match-beginning n))
18238 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18239 ((or (eq processing-type 'dvipng)
18240 (eq processing-type 'imagemagick))
18241 ;; Process to an image.
18242 (setq txt (match-string n)
18243 beg (match-beginning n) end (match-end n)
18244 cnt (1+ cnt))
18245 (let ((face (face-at-point))
18246 (fg (plist-get opt :foreground))
18247 (bg (plist-get opt :background))
18248 ;; Ensure full list is printed.
18249 print-length print-level)
18250 (when forbuffer
18251 ;; Get the colors from the face at point.
18252 (goto-char beg)
18253 (when (eq fg 'auto)
18254 (setq fg (face-attribute face :foreground nil 'default)))
18255 (when (eq bg 'auto)
18256 (setq bg (face-attribute face :background nil 'default)))
18257 (setq optnew (copy-sequence opt))
18258 (plist-put optnew :foreground fg)
18259 (plist-put optnew :background bg))
18260 (setq hash (sha1 (prin1-to-string
18261 (list org-format-latex-header
18262 org-latex-default-packages-alist
18263 org-latex-packages-alist
18264 org-format-latex-options
18265 forbuffer txt fg bg)))
18266 linkfile (format "%s_%s.png" prefix hash)
18267 movefile (format "%s_%s.png" absprefix hash)))
18268 (setq link (concat block "[[file:" linkfile "]]" block))
18269 (if msg (message msg cnt))
18270 (goto-char beg)
18271 (unless checkdir ; Ensure the directory exists.
18272 (setq checkdir t)
18273 (or (file-directory-p todir) (make-directory todir t)))
18274 (unless (file-exists-p movefile)
18275 (org-create-formula-image
18276 txt movefile optnew forbuffer processing-type))
18277 (if overlays
18278 (progn
18279 (mapc (lambda (o)
18280 (if (eq (overlay-get o 'org-overlay-type)
18281 'org-latex-overlay)
18282 (delete-overlay o)))
18283 (overlays-in beg end))
18284 (setq ov (make-overlay beg end))
18285 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18286 (if (featurep 'xemacs)
18287 (progn
18288 (overlay-put ov 'invisible t)
18289 (overlay-put
18290 ov 'end-glyph
18291 (make-glyph (vector 'png :file movefile))))
18292 (overlay-put
18293 ov 'display
18294 (list 'image :type 'png :file movefile :ascent 'center)))
18295 (push ov org-latex-fragment-image-overlays)
18296 (goto-char end))
18297 (delete-region beg end)
18298 (insert (org-add-props link
18299 (list 'org-latex-src
18300 (replace-regexp-in-string
18301 "\"" "" txt)
18302 'org-latex-src-embed-type
18303 (if block-type 'paragraph 'character))))))
18304 ((eq processing-type 'mathml)
18305 ;; Process to MathML
18306 (unless (save-match-data (org-format-latex-mathml-available-p))
18307 (error "LaTeX to MathML converter not configured"))
18308 (setq txt (match-string n)
18309 beg (match-beginning n) end (match-end n)
18310 cnt (1+ cnt))
18311 (if msg (message msg cnt))
18312 (goto-char beg)
18313 (delete-region beg end)
18314 (insert (org-format-latex-as-mathml
18315 txt block-type prefix dir)))
18317 (error "Unknown conversion type %s for latex fragments"
18318 processing-type)))))))))
18320 (defun org-create-math-formula (latex-frag &optional mathml-file)
18321 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18322 Use `org-latex-to-mathml-convert-command'. If the conversion is
18323 sucessful, return the portion between \"<math...> </math>\"
18324 elements otherwise return nil. When MATHML-FILE is specified,
18325 write the results in to that file. When invoked as an
18326 interactive command, prompt for LATEX-FRAG, with initial value
18327 set to the current active region and echo the results for user
18328 inspection."
18329 (interactive (list (let ((frag (when (org-region-active-p)
18330 (buffer-substring-no-properties
18331 (region-beginning) (region-end)))))
18332 (read-string "LaTeX Fragment: " frag nil frag))))
18333 (unless latex-frag (error "Invalid latex-frag"))
18334 (let* ((tmp-in-file (file-relative-name
18335 (make-temp-name (expand-file-name "ltxmathml-in"))))
18336 (ignore (write-region latex-frag nil tmp-in-file))
18337 (tmp-out-file (file-relative-name
18338 (make-temp-name (expand-file-name "ltxmathml-out"))))
18339 (cmd (format-spec
18340 org-latex-to-mathml-convert-command
18341 `((?j . ,(shell-quote-argument
18342 (expand-file-name org-latex-to-mathml-jar-file)))
18343 (?I . ,(shell-quote-argument tmp-in-file))
18344 (?o . ,(shell-quote-argument tmp-out-file)))))
18345 mathml shell-command-output)
18346 (when (org-called-interactively-p 'any)
18347 (unless (org-format-latex-mathml-available-p)
18348 (error "LaTeX to MathML converter not configured")))
18349 (message "Running %s" cmd)
18350 (setq shell-command-output (shell-command-to-string cmd))
18351 (setq mathml
18352 (when (file-readable-p tmp-out-file)
18353 (with-current-buffer (find-file-noselect tmp-out-file t)
18354 (goto-char (point-min))
18355 (when (re-search-forward
18356 (concat
18357 (regexp-quote
18358 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18359 "\\(.\\|\n\\)*"
18360 (regexp-quote "</math>")) nil t)
18361 (prog1 (match-string 0) (kill-buffer))))))
18362 (cond
18363 (mathml
18364 (setq mathml
18365 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18366 (when mathml-file
18367 (write-region mathml nil mathml-file))
18368 (when (org-called-interactively-p 'any)
18369 (message mathml)))
18370 ((message "LaTeX to MathML conversion failed")
18371 (message shell-command-output)))
18372 (delete-file tmp-in-file)
18373 (when (file-exists-p tmp-out-file)
18374 (delete-file tmp-out-file))
18375 mathml))
18377 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18378 prefix &optional dir)
18379 "Use `org-create-math-formula' but check local cache first."
18380 (let* ((absprefix (expand-file-name prefix dir))
18381 (print-length nil) (print-level nil)
18382 (formula-id (concat
18383 "formula-"
18384 (sha1
18385 (prin1-to-string
18386 (list latex-frag
18387 org-latex-to-mathml-convert-command)))))
18388 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18389 (formula-cache-dir (file-name-directory formula-cache)))
18391 (unless (file-directory-p formula-cache-dir)
18392 (make-directory formula-cache-dir t))
18394 (unless (file-exists-p formula-cache)
18395 (org-create-math-formula latex-frag formula-cache))
18397 (if (file-exists-p formula-cache)
18398 ;; Successful conversion. Return the link to MathML file.
18399 (org-add-props
18400 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18401 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18402 'org-latex-src-embed-type (if latex-frag-type
18403 'paragraph 'character)))
18404 ;; Failed conversion. Return the LaTeX fragment verbatim
18405 latex-frag)))
18407 (defun org-create-formula-image (string tofile options buffer &optional type)
18408 "Create an image from LaTeX source using dvipng or convert.
18409 This function calls either `org-create-formula-image-with-dvipng'
18410 or `org-create-formula-image-with-imagemagick' depending on the
18411 value of `org-latex-create-formula-image-program' or on the value
18412 of the optional TYPE variable.
18414 Note: ultimately these two function should be combined as they
18415 share a good deal of logic."
18416 (org-check-external-command
18417 "latex" "needed to convert LaTeX fragments to images")
18418 (funcall
18419 (case (or type org-latex-create-formula-image-program)
18420 ('dvipng
18421 (org-check-external-command
18422 "dvipng" "needed to convert LaTeX fragments to images")
18423 #'org-create-formula-image-with-dvipng)
18424 ('imagemagick
18425 (org-check-external-command
18426 "convert" "you need to install imagemagick")
18427 #'org-create-formula-image-with-imagemagick)
18428 (t (error
18429 "invalid value of `org-latex-create-formula-image-program'")))
18430 string tofile options buffer))
18432 (declare-function org-export--get-global-options "ox" (&optional backend))
18433 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18434 (defun org-create-formula--latex-header ()
18435 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18436 (org-latex-guess-inputenc
18437 (org-splice-latex-header
18438 org-format-latex-header
18439 org-latex-default-packages-alist
18440 org-latex-packages-alist t
18441 (plist-get
18442 (org-combine-plists
18443 (org-export--get-global-options 'latex)
18444 (org-export--get-inbuffer-options 'latex))
18445 :latex-header))))
18447 ;; This function borrows from Ganesh Swami's latex2png.el
18448 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18449 "This calls dvipng."
18450 (require 'ox-latex)
18451 (let* ((tmpdir (if (featurep 'xemacs)
18452 (temp-directory)
18453 temporary-file-directory))
18454 (texfilebase (make-temp-name
18455 (expand-file-name "orgtex" tmpdir)))
18456 (texfile (concat texfilebase ".tex"))
18457 (dvifile (concat texfilebase ".dvi"))
18458 (pngfile (concat texfilebase ".png"))
18459 (fnh (if (featurep 'xemacs)
18460 (font-height (face-font 'default))
18461 (face-attribute 'default :height nil)))
18462 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18463 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18464 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18465 "Black"))
18466 (bg (or (plist-get options (if buffer :background :html-background))
18467 "Transparent")))
18468 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18469 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18470 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18471 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18472 (let ((latex-header (org-create-formula--latex-header)))
18473 (with-temp-file texfile
18474 (insert latex-header)
18475 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18476 (let ((dir default-directory))
18477 (condition-case nil
18478 (progn
18479 (cd tmpdir)
18480 (call-process "latex" nil nil nil texfile))
18481 (error nil))
18482 (cd dir))
18483 (if (not (file-exists-p dvifile))
18484 (progn (message "Failed to create dvi file from %s" texfile) nil)
18485 (condition-case nil
18486 (if (featurep 'xemacs)
18487 (call-process "dvipng" nil nil nil
18488 "-fg" fg "-bg" bg
18489 "-T" "tight"
18490 "-o" pngfile
18491 dvifile)
18492 (call-process "dvipng" nil nil nil
18493 "-fg" fg "-bg" bg
18494 "-D" dpi
18495 ;;"-x" scale "-y" scale
18496 "-T" "tight"
18497 "-o" pngfile
18498 dvifile))
18499 (error nil))
18500 (if (not (file-exists-p pngfile))
18501 (if org-format-latex-signal-error
18502 (error "Failed to create png file from %s" texfile)
18503 (message "Failed to create png file from %s" texfile)
18504 nil)
18505 ;; Use the requested file name and clean up
18506 (copy-file pngfile tofile 'replace)
18507 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18508 (if (file-exists-p (concat texfilebase e))
18509 (delete-file (concat texfilebase e))))
18510 pngfile))))
18512 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18513 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18514 "This calls convert, which is included into imagemagick."
18515 (require 'ox-latex)
18516 (let* ((tmpdir (if (featurep 'xemacs)
18517 (temp-directory)
18518 temporary-file-directory))
18519 (texfilebase (make-temp-name
18520 (expand-file-name "orgtex" tmpdir)))
18521 (texfile (concat texfilebase ".tex"))
18522 (pdffile (concat texfilebase ".pdf"))
18523 (pngfile (concat texfilebase ".png"))
18524 (fnh (if (featurep 'xemacs)
18525 (font-height (face-font 'default))
18526 (face-attribute 'default :height nil)))
18527 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18528 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18529 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18530 "black"))
18531 (bg (or (plist-get options (if buffer :background :html-background))
18532 "white")))
18533 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18534 (setq fg (org-latex-color-format fg)))
18535 (if (eq bg 'default) (setq bg (org-latex-color :background))
18536 (setq bg (org-latex-color-format
18537 (if (string= bg "Transparent") "white" bg))))
18538 (let ((latex-header (org-create-formula--latex-header)))
18539 (with-temp-file texfile
18540 (insert latex-header)
18541 (insert "\n\\begin{document}\n"
18542 "\\definecolor{fg}{rgb}{" fg "}\n"
18543 "\\definecolor{bg}{rgb}{" bg "}\n"
18544 "\n\\pagecolor{bg}\n"
18545 "\n{\\color{fg}\n"
18546 string
18547 "\n}\n"
18548 "\n\\end{document}\n")))
18549 (org-latex-compile texfile t)
18550 (if (not (file-exists-p pdffile))
18551 (progn (message "Failed to create pdf file from %s" texfile) nil)
18552 (condition-case nil
18553 (if (featurep 'xemacs)
18554 (call-process "convert" nil nil nil
18555 "-density" "96"
18556 "-trim"
18557 "-antialias"
18558 pdffile
18559 "-quality" "100"
18560 ;; "-sharpen" "0x1.0"
18561 pngfile)
18562 (call-process "convert" nil nil nil
18563 "-density" dpi
18564 "-trim"
18565 "-antialias"
18566 pdffile
18567 "-quality" "100"
18568 ;; "-sharpen" "0x1.0"
18569 pngfile))
18570 (error nil))
18571 (if (not (file-exists-p pngfile))
18572 (if org-format-latex-signal-error
18573 (error "Failed to create png file from %s" texfile)
18574 (message "Failed to create png file from %s" texfile)
18575 nil)
18576 ;; Use the requested file name and clean up
18577 (copy-file pngfile tofile 'replace)
18578 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18579 (if (file-exists-p (concat texfilebase e))
18580 (delete-file (concat texfilebase e))))
18581 pngfile))))
18583 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18584 "Fill a LaTeX header template TPL.
18585 In the template, the following place holders will be recognized:
18587 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18588 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18589 [PACKAGES] \\usepackage statements for PKG
18590 [NO-PACKAGES] do not include PKG
18591 [EXTRA] the string EXTRA
18592 [NO-EXTRA] do not include EXTRA
18594 For backward compatibility, if both the positive and the negative place
18595 holder is missing, the positive one (without the \"NO-\") will be
18596 assumed to be present at the end of the template.
18597 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18598 EXTRA is a string.
18599 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18600 (let (rpl (end ""))
18601 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18602 (setq rpl (if (or (match-end 1) (not def-pkg))
18603 "" (org-latex-packages-to-string def-pkg snippets-p t))
18604 tpl (replace-match rpl t t tpl))
18605 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18607 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18608 (setq rpl (if (or (match-end 1) (not pkg))
18609 "" (org-latex-packages-to-string pkg snippets-p t))
18610 tpl (replace-match rpl t t tpl))
18611 (if pkg (setq end
18612 (concat end "\n"
18613 (org-latex-packages-to-string pkg snippets-p)))))
18615 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18616 (setq rpl (if (or (match-end 1) (not extra))
18617 "" (concat extra "\n"))
18618 tpl (replace-match rpl t t tpl))
18619 (if (and extra (string-match "\\S-" extra))
18620 (setq end (concat end "\n" extra))))
18622 (if (string-match "\\S-" end)
18623 (concat tpl "\n" end)
18624 tpl)))
18626 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18627 "Turn an alist of packages into a string with the \\usepackage macros."
18628 (setq pkg (mapconcat (lambda(p)
18629 (cond
18630 ((stringp p) p)
18631 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18632 (format "%% Package %s omitted" (cadr p)))
18633 ((equal "" (car p))
18634 (format "\\usepackage{%s}" (cadr p)))
18636 (format "\\usepackage[%s]{%s}"
18637 (car p) (cadr p)))))
18639 "\n"))
18640 (if newline (concat pkg "\n") pkg))
18642 (defun org-dvipng-color (attr)
18643 "Return a RGB color specification for dvipng."
18644 (apply 'format "rgb %s %s %s"
18645 (mapcar 'org-normalize-color
18646 (if (featurep 'xemacs)
18647 (color-rgb-components
18648 (face-property 'default
18649 (cond ((eq attr :foreground) 'foreground)
18650 ((eq attr :background) 'background))))
18651 (color-values (face-attribute 'default attr nil))))))
18653 (defun org-dvipng-color-format (color-name)
18654 "Convert COLOR-NAME to a RGB color value for dvipng."
18655 (apply 'format "rgb %s %s %s"
18656 (mapcar 'org-normalize-color
18657 (color-values color-name))))
18659 (defun org-latex-color (attr)
18660 "Return a RGB color for the LaTeX color package."
18661 (apply 'format "%s,%s,%s"
18662 (mapcar 'org-normalize-color
18663 (if (featurep 'xemacs)
18664 (color-rgb-components
18665 (face-property 'default
18666 (cond ((eq attr :foreground) 'foreground)
18667 ((eq attr :background) 'background))))
18668 (color-values (face-attribute 'default attr nil))))))
18670 (defun org-latex-color-format (color-name)
18671 "Convert COLOR-NAME to a RGB color value."
18672 (apply 'format "%s,%s,%s"
18673 (mapcar 'org-normalize-color
18674 (color-values color-name))))
18676 (defun org-normalize-color (value)
18677 "Return string to be used as color value for an RGB component."
18678 (format "%g" (/ value 65535.0)))
18682 ;; Image display
18684 (defvar org-inline-image-overlays nil)
18685 (make-variable-buffer-local 'org-inline-image-overlays)
18687 (defun org-toggle-inline-images (&optional include-linked)
18688 "Toggle the display of inline images.
18689 INCLUDE-LINKED is passed to `org-display-inline-images'."
18690 (interactive "P")
18691 (if org-inline-image-overlays
18692 (progn
18693 (org-remove-inline-images)
18694 (message "Inline image display turned off"))
18695 (org-display-inline-images include-linked)
18696 (if (and (org-called-interactively-p)
18697 org-inline-image-overlays)
18698 (message "%d images displayed inline"
18699 (length org-inline-image-overlays))
18700 (message "No images to display inline"))))
18702 (defun org-redisplay-inline-images ()
18703 "Refresh the display of inline images."
18704 (interactive)
18705 (if (not org-inline-image-overlays)
18706 (org-toggle-inline-images)
18707 (org-toggle-inline-images)
18708 (org-toggle-inline-images)))
18710 (defun org-display-inline-images (&optional include-linked refresh beg end)
18711 "Display inline images.
18712 Normally only links without a description part are inlined, because this
18713 is how it will work for export. When INCLUDE-LINKED is set, also links
18714 with a description part will be inlined. This can be nice for a quick
18715 look at those images, but it does not reflect what exported files will look
18716 like.
18717 When REFRESH is set, refresh existing images between BEG and END.
18718 This will create new image displays only if necessary.
18719 BEG and END default to the buffer boundaries."
18720 (interactive "P")
18721 (unless refresh
18722 (org-remove-inline-images)
18723 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18724 (save-excursion
18725 (save-restriction
18726 (widen)
18727 (setq beg (or beg (point-min)) end (or end (point-max)))
18728 (goto-char beg)
18729 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18730 (substring (org-image-file-name-regexp) 0 -2)
18731 "\\)\\]" (if include-linked "" "\\]")))
18732 (case-fold-search t)
18733 old file ov img type attrwidth width)
18734 (while (re-search-forward re end t)
18735 (setq old (get-char-property-and-overlay (match-beginning 1)
18736 'org-image-overlay)
18737 file (expand-file-name
18738 (concat (or (match-string 3) "") (match-string 4))))
18739 (when (image-type-available-p 'imagemagick)
18740 (setq attrwidth (if (or (listp org-image-actual-width)
18741 (null org-image-actual-width))
18742 (save-excursion
18743 (save-match-data
18744 (when (re-search-backward
18745 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18746 (save-excursion
18747 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18748 (string-to-number (match-string 1))))))
18749 width (cond ((eq org-image-actual-width t) nil)
18750 ((null org-image-actual-width) attrwidth)
18751 ((numberp org-image-actual-width)
18752 org-image-actual-width)
18753 ((listp org-image-actual-width)
18754 (or attrwidth (car org-image-actual-width))))
18755 type (if width 'imagemagick)))
18756 (when (file-exists-p file)
18757 (if (and (car-safe old) refresh)
18758 (image-refresh (overlay-get (cdr old) 'display))
18759 (setq img (save-match-data (create-image file type nil :width width)))
18760 (when img
18761 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18762 (overlay-put ov 'display img)
18763 (overlay-put ov 'face 'default)
18764 (overlay-put ov 'org-image-overlay t)
18765 (overlay-put ov 'modification-hooks
18766 (list 'org-display-inline-remove-overlay))
18767 (push ov org-inline-image-overlays)))))))))
18769 (define-obsolete-function-alias
18770 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18772 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18773 "Remove inline-display overlay if a corresponding region is modified."
18774 (let ((inhibit-modification-hooks t))
18775 (when (and ov after)
18776 (delete ov org-inline-image-overlays)
18777 (delete-overlay ov))))
18779 (defun org-remove-inline-images ()
18780 "Remove inline display of images."
18781 (interactive)
18782 (mapc 'delete-overlay org-inline-image-overlays)
18783 (setq org-inline-image-overlays nil))
18785 ;;;; Key bindings
18787 ;; Outline functions from `outline-mode-prefix-map'
18788 ;; that can be remapped in Org:
18789 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18790 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18791 (define-key org-mode-map [remap outline-forward-same-level]
18792 'org-forward-heading-same-level)
18793 (define-key org-mode-map [remap outline-backward-same-level]
18794 'org-backward-heading-same-level)
18795 (define-key org-mode-map [remap show-branches]
18796 'org-kill-note-or-show-branches)
18797 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18798 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18799 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18801 ;; Outline functions from `outline-mode-prefix-map' that can not
18802 ;; be remapped in Org:
18804 ;; - the column "key binding" shows whether the Outline function is still
18805 ;; available in Org mode on the same key that it has been bound to in
18806 ;; Outline mode:
18807 ;; - "overridden": key used for a different functionality in Org mode
18808 ;; - else: key still bound to the same Outline function in Org mode
18810 ;; | Outline function | key binding | Org replacement |
18811 ;; |------------------------------------+-------------+-----------------------|
18812 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18813 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18814 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18815 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18816 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18817 ;; | `show-entry' | overridden | no replacement |
18818 ;; | `show-children' | `C-c C-i' | visibility cycling |
18819 ;; | `show-branches' | `C-c C-k' | still same function |
18820 ;; | `show-subtree' | overridden | visibility cycling |
18821 ;; | `show-all' | overridden | no replacement |
18822 ;; | `hide-subtree' | overridden | visibility cycling |
18823 ;; | `hide-body' | overridden | no replacement |
18824 ;; | `hide-entry' | overridden | visibility cycling |
18825 ;; | `hide-leaves' | overridden | no replacement |
18826 ;; | `hide-sublevels' | overridden | no replacement |
18827 ;; | `hide-other' | overridden | no replacement |
18829 ;; Make `C-c C-x' a prefix key
18830 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18832 ;; TAB key with modifiers
18833 (org-defkey org-mode-map "\C-i" 'org-cycle)
18834 (org-defkey org-mode-map [(tab)] 'org-cycle)
18835 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18836 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18837 ;; The following line is necessary under Suse GNU/Linux
18838 (unless (featurep 'xemacs)
18839 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18840 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18841 (define-key org-mode-map [backtab] 'org-shifttab)
18843 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18844 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18845 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18847 ;; Cursor keys with modifiers
18848 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18849 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18850 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18851 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18853 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18854 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18855 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18856 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18858 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18859 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18860 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18861 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18863 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18864 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18865 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18866 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18868 ;; Babel keys
18869 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18870 (mapc (lambda (pair)
18871 (define-key org-babel-map (car pair) (cdr pair)))
18872 org-babel-key-bindings)
18874 ;;; Extra keys for tty access.
18875 ;; We only set them when really needed because otherwise the
18876 ;; menus don't show the simple keys
18878 (when (or org-use-extra-keys
18879 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18880 (not window-system))
18881 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18882 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18883 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18884 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18885 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18886 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18887 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18888 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18889 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18890 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18891 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18892 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18893 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18894 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18895 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18896 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18897 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18898 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18899 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18900 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18901 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18902 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18903 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18904 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18905 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18906 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18907 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18908 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18910 ;; All the other keys
18912 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18913 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18914 (if (boundp 'narrow-map)
18915 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18916 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18917 (if (boundp 'narrow-map)
18918 (org-defkey narrow-map "b" 'org-narrow-to-block)
18919 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18920 (if (boundp 'narrow-map)
18921 (org-defkey narrow-map "e" 'org-narrow-to-element)
18922 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18923 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18924 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18925 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18926 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18927 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18928 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18929 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18930 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18931 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18932 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18933 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18934 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18935 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18936 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18937 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18938 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18939 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18940 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18941 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18942 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18943 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18944 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18945 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18946 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18947 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18948 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18949 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18950 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18951 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18952 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18953 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18954 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18955 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18956 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18957 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18958 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18959 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18960 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18961 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18962 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18963 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18964 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18965 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18966 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18967 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18968 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18969 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18970 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18971 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18972 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18973 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18974 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18975 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18976 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18977 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18978 (org-defkey org-mode-map "\C-c^" 'org-sort)
18979 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18980 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18981 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18982 (org-defkey org-mode-map [remap open-line] 'org-open-line)
18983 (org-defkey org-mode-map "\C-m" 'org-return)
18984 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18985 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18986 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18987 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18988 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18989 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18990 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18991 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18992 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18993 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18994 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18995 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18996 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18997 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18998 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18999 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19000 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19001 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19002 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19003 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19004 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19005 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19006 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19008 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19009 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19010 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19012 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19013 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19014 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19015 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19016 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19017 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19018 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19019 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19020 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19021 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19022 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19023 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19024 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19025 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19026 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19027 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19028 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19029 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19030 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19031 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19032 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19033 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19034 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19036 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19037 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19038 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19039 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19040 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19042 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19044 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19046 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19047 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19049 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19052 (when (featurep 'xemacs)
19053 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19056 (defconst org-speed-commands-default
19058 ("Outline Navigation")
19059 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19060 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19061 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19062 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19063 ("F" . org-next-block)
19064 ("B" . org-previous-block)
19065 ("u" . (org-speed-move-safe 'outline-up-heading))
19066 ("j" . org-goto)
19067 ("g" . (org-refile t))
19068 ("Outline Visibility")
19069 ("c" . org-cycle)
19070 ("C" . org-shifttab)
19071 (" " . org-display-outline-path)
19072 ("s" . org-narrow-to-subtree)
19073 ("=" . org-columns)
19074 ("Outline Structure Editing")
19075 ("U" . org-shiftmetaup)
19076 ("D" . org-shiftmetadown)
19077 ("r" . org-metaright)
19078 ("l" . org-metaleft)
19079 ("R" . org-shiftmetaright)
19080 ("L" . org-shiftmetaleft)
19081 ("i" . (progn (forward-char 1) (call-interactively
19082 'org-insert-heading-respect-content)))
19083 ("^" . org-sort)
19084 ("w" . org-refile)
19085 ("a" . org-archive-subtree-default-with-confirmation)
19086 ("@" . org-mark-subtree)
19087 ("#" . org-toggle-comment)
19088 ("Clock Commands")
19089 ("I" . org-clock-in)
19090 ("O" . org-clock-out)
19091 ("Meta Data Editing")
19092 ("t" . org-todo)
19093 ("," . (org-priority))
19094 ("0" . (org-priority ?\ ))
19095 ("1" . (org-priority ?A))
19096 ("2" . (org-priority ?B))
19097 ("3" . (org-priority ?C))
19098 (":" . org-set-tags-command)
19099 ("e" . org-set-effort)
19100 ("E" . org-inc-effort)
19101 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19102 (org-entry-put (point) "APPT_WARNTIME" m)))
19103 ("Agenda Views etc")
19104 ("v" . org-agenda)
19105 ("/" . org-sparse-tree)
19106 ("Misc")
19107 ("o" . org-open-at-point)
19108 ("?" . org-speed-command-help)
19109 ("<" . (org-agenda-set-restriction-lock 'subtree))
19110 (">" . (org-agenda-remove-restriction-lock))
19112 "The default speed commands.")
19114 (defun org-print-speed-command (e)
19115 (if (> (length (car e)) 1)
19116 (progn
19117 (princ "\n")
19118 (princ (car e))
19119 (princ "\n")
19120 (princ (make-string (length (car e)) ?-))
19121 (princ "\n"))
19122 (princ (car e))
19123 (princ " ")
19124 (if (symbolp (cdr e))
19125 (princ (symbol-name (cdr e)))
19126 (prin1 (cdr e)))
19127 (princ "\n")))
19129 (defun org-speed-command-help ()
19130 "Show the available speed commands."
19131 (interactive)
19132 (if (not org-use-speed-commands)
19133 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19134 (with-output-to-temp-buffer "*Help*"
19135 (princ "User-defined Speed commands\n===========================\n")
19136 (mapc 'org-print-speed-command org-speed-commands-user)
19137 (princ "\n")
19138 (princ "Built-in Speed commands\n=======================\n")
19139 (mapc 'org-print-speed-command org-speed-commands-default))
19140 (with-current-buffer "*Help*"
19141 (setq truncate-lines t))))
19143 (defun org-speed-move-safe (cmd)
19144 "Execute CMD, but make sure that the cursor always ends up in a headline.
19145 If not, return to the original position and throw an error."
19146 (interactive)
19147 (let ((pos (point)))
19148 (call-interactively cmd)
19149 (unless (and (bolp) (org-at-heading-p))
19150 (goto-char pos)
19151 (error "Boundary reached while executing %s" cmd))))
19153 (defvar org-self-insert-command-undo-counter 0)
19155 (defvar org-table-auto-blank-field) ; defined in org-table.el
19156 (defvar org-speed-command nil)
19158 (define-obsolete-function-alias
19159 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19161 (defun org-speed-command-activate (keys)
19162 "Hook for activating single-letter speed commands.
19163 `org-speed-commands-default' specifies a minimal command set.
19164 Use `org-speed-commands-user' for further customization."
19165 (when (or (and (bolp) (looking-at org-outline-regexp))
19166 (and (functionp org-use-speed-commands)
19167 (funcall org-use-speed-commands)))
19168 (cdr (assoc keys (append org-speed-commands-user
19169 org-speed-commands-default)))))
19171 (define-obsolete-function-alias
19172 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19174 (defun org-babel-speed-command-activate (keys)
19175 "Hook for activating single-letter code block commands."
19176 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19177 (cdr (assoc keys org-babel-key-bindings))))
19179 (defcustom org-speed-command-hook
19180 '(org-speed-command-default-hook org-babel-speed-command-hook)
19181 "Hook for activating speed commands at strategic locations.
19182 Hook functions are called in sequence until a valid handler is
19183 found.
19185 Each hook takes a single argument, a user-pressed command key
19186 which is also a `self-insert-command' from the global map.
19188 Within the hook, examine the cursor position and the command key
19189 and return nil or a valid handler as appropriate. Handler could
19190 be one of an interactive command, a function, or a form.
19192 Set `org-use-speed-commands' to non-nil value to enable this
19193 hook. The default setting is `org-speed-command-activate'."
19194 :group 'org-structure
19195 :version "24.1"
19196 :type 'hook)
19198 (defun org-self-insert-command (N)
19199 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19200 If the cursor is in a table looking at whitespace, the whitespace is
19201 overwritten, and the table is not marked as requiring realignment."
19202 (interactive "p")
19203 (org-check-before-invisible-edit 'insert)
19204 (cond
19205 ((and org-use-speed-commands
19206 (setq org-speed-command
19207 (run-hook-with-args-until-success
19208 'org-speed-command-hook (this-command-keys))))
19209 (cond
19210 ((commandp org-speed-command)
19211 (setq this-command org-speed-command)
19212 (call-interactively org-speed-command))
19213 ((functionp org-speed-command)
19214 (funcall org-speed-command))
19215 ((and org-speed-command (listp org-speed-command))
19216 (eval org-speed-command))
19217 (t (let (org-use-speed-commands)
19218 (call-interactively 'org-self-insert-command)))))
19219 ((and
19220 (org-table-p)
19221 (progn
19222 ;; check if we blank the field, and if that triggers align
19223 (and (featurep 'org-table) org-table-auto-blank-field
19224 (member last-command
19225 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19226 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19227 ;; got extra space, this field does not determine column width
19228 (let (org-table-may-need-update) (org-table-blank-field))
19229 ;; no extra space, this field may determine column width
19230 (org-table-blank-field)))
19232 (eq N 1)
19233 (looking-at "[^|\n]* |"))
19234 (let (org-table-may-need-update)
19235 (goto-char (1- (match-end 0)))
19236 (backward-delete-char 1)
19237 (goto-char (match-beginning 0))
19238 (self-insert-command N)))
19240 (setq org-table-may-need-update t)
19241 (self-insert-command N)
19242 (org-fix-tags-on-the-fly)
19243 (if org-self-insert-cluster-for-undo
19244 (if (not (eq last-command 'org-self-insert-command))
19245 (setq org-self-insert-command-undo-counter 1)
19246 (if (>= org-self-insert-command-undo-counter 20)
19247 (setq org-self-insert-command-undo-counter 1)
19248 (and (> org-self-insert-command-undo-counter 0)
19249 buffer-undo-list (listp buffer-undo-list)
19250 (not (cadr buffer-undo-list)) ; remove nil entry
19251 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19252 (setq org-self-insert-command-undo-counter
19253 (1+ org-self-insert-command-undo-counter))))))))
19255 (defun org-check-before-invisible-edit (kind)
19256 "Check is editing if kind KIND would be dangerous with invisible text around.
19257 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19258 ;; First, try to get out of here as quickly as possible, to reduce overhead
19259 (if (and org-catch-invisible-edits
19260 (or (not (boundp 'visible-mode)) (not visible-mode))
19261 (or (get-char-property (point) 'invisible)
19262 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19263 ;; OK, we need to take a closer look
19264 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19265 (invisible-before-point (if (bobp) nil (get-char-property
19266 (1- (point)) 'invisible)))
19267 (border-and-ok-direction
19269 ;; Check if we are acting predictably before invisible text
19270 (and invisible-at-point (not invisible-before-point)
19271 (memq kind '(insert delete-backward)))
19272 ;; Check if we are acting predictably after invisible text
19273 ;; This works not well, and I have turned it off. It seems
19274 ;; better to always show and stop after invisible text.
19275 ;; (and (not invisible-at-point) invisible-before-point
19276 ;; (memq kind '(insert delete)))
19278 (when (or (memq invisible-at-point '(outline org-hide-block t))
19279 (memq invisible-before-point '(outline org-hide-block t)))
19280 (if (eq org-catch-invisible-edits 'error)
19281 (error "Editing in invisible areas is prohibited - make visible first"))
19282 (if (and org-custom-properties-overlays
19283 (y-or-n-p "Display invisible properties in this buffer? "))
19284 (org-toggle-custom-properties-visibility)
19285 ;; Make the area visible
19286 (save-excursion
19287 (if invisible-before-point
19288 (goto-char (previous-single-char-property-change
19289 (point) 'invisible)))
19290 (org-cycle))
19291 (cond
19292 ((eq org-catch-invisible-edits 'show)
19293 ;; That's it, we do the edit after showing
19294 (message
19295 "Unfolding invisible region around point before editing")
19296 (sit-for 1))
19297 ((and (eq org-catch-invisible-edits 'smart)
19298 border-and-ok-direction)
19299 (message "Unfolding invisible region around point before editing"))
19301 ;; Don't do the edit, make the user repeat it in full visibility
19302 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19304 (defun org-fix-tags-on-the-fly ()
19305 (when (and (equal (char-after (point-at-bol)) ?*)
19306 (org-at-heading-p))
19307 (org-align-tags-here org-tags-column)))
19309 (defun org-delete-backward-char (N)
19310 "Like `delete-backward-char', insert whitespace at field end in tables.
19311 When deleting backwards, in tables this function will insert whitespace in
19312 front of the next \"|\" separator, to keep the table aligned. The table will
19313 still be marked for re-alignment if the field did fill the entire column,
19314 because, in this case the deletion might narrow the column."
19315 (interactive "p")
19316 (save-match-data
19317 (org-check-before-invisible-edit 'delete-backward)
19318 (if (and (org-table-p)
19319 (eq N 1)
19320 (string-match "|" (buffer-substring (point-at-bol) (point)))
19321 (looking-at ".*?|"))
19322 (let ((pos (point))
19323 (noalign (looking-at "[^|\n\r]* |"))
19324 (c org-table-may-need-update))
19325 (backward-delete-char N)
19326 (if (not overwrite-mode)
19327 (progn
19328 (skip-chars-forward "^|")
19329 (insert " ")
19330 (goto-char (1- pos))))
19331 ;; noalign: if there were two spaces at the end, this field
19332 ;; does not determine the width of the column.
19333 (if noalign (setq org-table-may-need-update c)))
19334 (backward-delete-char N)
19335 (org-fix-tags-on-the-fly))))
19337 (defun org-delete-char (N)
19338 "Like `delete-char', but insert whitespace at field end in tables.
19339 When deleting characters, in tables this function will insert whitespace in
19340 front of the next \"|\" separator, to keep the table aligned. The table will
19341 still be marked for re-alignment if the field did fill the entire column,
19342 because, in this case the deletion might narrow the column."
19343 (interactive "p")
19344 (save-match-data
19345 (org-check-before-invisible-edit 'delete)
19346 (if (and (org-table-p)
19347 (not (bolp))
19348 (not (= (char-after) ?|))
19349 (eq N 1))
19350 (if (looking-at ".*?|")
19351 (let ((pos (point))
19352 (noalign (looking-at "[^|\n\r]* |"))
19353 (c org-table-may-need-update))
19354 (replace-match
19355 (concat (substring (match-string 0) 1 -1) " |") nil t)
19356 (goto-char pos)
19357 ;; noalign: if there were two spaces at the end, this field
19358 ;; does not determine the width of the column.
19359 (if noalign (setq org-table-may-need-update c)))
19360 (delete-char N))
19361 (delete-char N)
19362 (org-fix-tags-on-the-fly))))
19364 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19365 (put 'org-self-insert-command 'delete-selection t)
19366 (put 'orgtbl-self-insert-command 'delete-selection t)
19367 (put 'org-delete-char 'delete-selection 'supersede)
19368 (put 'org-delete-backward-char 'delete-selection 'supersede)
19369 (put 'org-yank 'delete-selection 'yank)
19371 ;; Make `flyspell-mode' delay after some commands
19372 (put 'org-self-insert-command 'flyspell-delayed t)
19373 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19374 (put 'org-delete-char 'flyspell-delayed t)
19375 (put 'org-delete-backward-char 'flyspell-delayed t)
19377 ;; Make pabbrev-mode expand after org-mode commands
19378 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19379 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19381 ;; How to do this: Measure non-white length of current string
19382 ;; If equal to column width, we should realign.
19384 (defun org-remap (map &rest commands)
19385 "In MAP, remap the functions given in COMMANDS.
19386 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19387 (let (new old)
19388 (while commands
19389 (setq old (pop commands) new (pop commands))
19390 (if (fboundp 'command-remapping)
19391 (org-defkey map (vector 'remap old) new)
19392 (substitute-key-definition old new map global-map)))))
19394 (defun org-transpose-words ()
19395 "Transpose words for Org.
19396 This uses the `org-mode-transpose-word-syntax-table' syntax
19397 table, which interprets characters in `org-emphasis-alist' as
19398 word constituants."
19399 (interactive)
19400 (with-syntax-table org-mode-transpose-word-syntax-table
19401 (call-interactively 'transpose-words)))
19402 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19404 (when (eq org-enable-table-editor 'optimized)
19405 ;; If the user wants maximum table support, we need to hijack
19406 ;; some standard editing functions
19407 (org-remap org-mode-map
19408 'self-insert-command 'org-self-insert-command
19409 'delete-char 'org-delete-char
19410 'delete-backward-char 'org-delete-backward-char)
19411 (org-defkey org-mode-map "|" 'org-force-self-insert))
19413 (defvar org-ctrl-c-ctrl-c-hook nil
19414 "Hook for functions attaching themselves to `C-c C-c'.
19416 This can be used to add additional functionality to the C-c C-c
19417 key which executes context-dependent commands. This hook is run
19418 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19419 run after the last test.
19421 Each function will be called with no arguments. The function
19422 must check if the context is appropriate for it to act. If yes,
19423 it should do its thing and then return a non-nil value. If the
19424 context is wrong, just do nothing and return nil.")
19426 (defvar org-ctrl-c-ctrl-c-final-hook nil
19427 "Hook for functions attaching themselves to `C-c C-c'.
19429 This can be used to add additional functionality to the C-c C-c
19430 key which executes context-dependent commands. This hook is run
19431 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19432 before the first test.
19434 Each function will be called with no arguments. The function
19435 must check if the context is appropriate for it to act. If yes,
19436 it should do its thing and then return a non-nil value. If the
19437 context is wrong, just do nothing and return nil.")
19439 (defvar org-tab-first-hook nil
19440 "Hook for functions to attach themselves to TAB.
19441 See `org-ctrl-c-ctrl-c-hook' for more information.
19442 This hook runs as the first action when TAB is pressed, even before
19443 `org-cycle' messes around with the `outline-regexp' to cater for
19444 inline tasks and plain list item folding.
19445 If any function in this hook returns t, any other actions that
19446 would have been caused by TAB (such as table field motion or visibility
19447 cycling) will not occur.")
19449 (defvar org-tab-after-check-for-table-hook nil
19450 "Hook for functions to attach themselves to TAB.
19451 See `org-ctrl-c-ctrl-c-hook' for more information.
19452 This hook runs after it has been established that the cursor is not in a
19453 table, but before checking if the cursor is in a headline or if global cycling
19454 should be done.
19455 If any function in this hook returns t, not other actions like visibility
19456 cycling will be done.")
19458 (defvar org-tab-after-check-for-cycling-hook nil
19459 "Hook for functions to attach themselves to TAB.
19460 See `org-ctrl-c-ctrl-c-hook' for more information.
19461 This hook runs after it has been established that not table field motion and
19462 not visibility should be done because of current context. This is probably
19463 the place where a package like yasnippets can hook in.")
19465 (defvar org-tab-before-tab-emulation-hook nil
19466 "Hook for functions to attach themselves to TAB.
19467 See `org-ctrl-c-ctrl-c-hook' for more information.
19468 This hook runs after every other options for TAB have been exhausted, but
19469 before indentation and \t insertion takes place.")
19471 (defvar org-metaleft-hook nil
19472 "Hook for functions attaching themselves to `M-left'.
19473 See `org-ctrl-c-ctrl-c-hook' for more information.")
19474 (defvar org-metaright-hook nil
19475 "Hook for functions attaching themselves to `M-right'.
19476 See `org-ctrl-c-ctrl-c-hook' for more information.")
19477 (defvar org-metaup-hook nil
19478 "Hook for functions attaching themselves to `M-up'.
19479 See `org-ctrl-c-ctrl-c-hook' for more information.")
19480 (defvar org-metadown-hook nil
19481 "Hook for functions attaching themselves to `M-down'.
19482 See `org-ctrl-c-ctrl-c-hook' for more information.")
19483 (defvar org-shiftmetaleft-hook nil
19484 "Hook for functions attaching themselves to `M-S-left'.
19485 See `org-ctrl-c-ctrl-c-hook' for more information.")
19486 (defvar org-shiftmetaright-hook nil
19487 "Hook for functions attaching themselves to `M-S-right'.
19488 See `org-ctrl-c-ctrl-c-hook' for more information.")
19489 (defvar org-shiftmetaup-hook nil
19490 "Hook for functions attaching themselves to `M-S-up'.
19491 See `org-ctrl-c-ctrl-c-hook' for more information.")
19492 (defvar org-shiftmetadown-hook nil
19493 "Hook for functions attaching themselves to `M-S-down'.
19494 See `org-ctrl-c-ctrl-c-hook' for more information.")
19495 (defvar org-metareturn-hook nil
19496 "Hook for functions attaching themselves to `M-RET'.
19497 See `org-ctrl-c-ctrl-c-hook' for more information.")
19498 (defvar org-shiftup-hook nil
19499 "Hook for functions attaching themselves to `S-up'.
19500 See `org-ctrl-c-ctrl-c-hook' for more information.")
19501 (defvar org-shiftup-final-hook nil
19502 "Hook for functions attaching themselves to `S-up'.
19503 This one runs after all other options except shift-select have been excluded.
19504 See `org-ctrl-c-ctrl-c-hook' for more information.")
19505 (defvar org-shiftdown-hook nil
19506 "Hook for functions attaching themselves to `S-down'.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.")
19508 (defvar org-shiftdown-final-hook nil
19509 "Hook for functions attaching themselves to `S-down'.
19510 This one runs after all other options except shift-select have been excluded.
19511 See `org-ctrl-c-ctrl-c-hook' for more information.")
19512 (defvar org-shiftleft-hook nil
19513 "Hook for functions attaching themselves to `S-left'.
19514 See `org-ctrl-c-ctrl-c-hook' for more information.")
19515 (defvar org-shiftleft-final-hook nil
19516 "Hook for functions attaching themselves to `S-left'.
19517 This one runs after all other options except shift-select have been excluded.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.")
19519 (defvar org-shiftright-hook nil
19520 "Hook for functions attaching themselves to `S-right'.
19521 See `org-ctrl-c-ctrl-c-hook' for more information.")
19522 (defvar org-shiftright-final-hook nil
19523 "Hook for functions attaching themselves to `S-right'.
19524 This one runs after all other options except shift-select have been excluded.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defun org-modifier-cursor-error ()
19528 "Throw an error, a modified cursor command was applied in wrong context."
19529 (error "This command is active in special context like tables, headlines or items"))
19531 (defun org-shiftselect-error ()
19532 "Throw an error because Shift-Cursor command was applied in wrong context."
19533 (if (and (boundp 'shift-select-mode) shift-select-mode)
19534 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19535 (error "This command works only in special context like headlines or timestamps")))
19537 (defun org-call-for-shift-select (cmd)
19538 (let ((this-command-keys-shift-translated t))
19539 (call-interactively cmd)))
19541 (defun org-shifttab (&optional arg)
19542 "Global visibility cycling or move to previous table field.
19543 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19544 on context.
19545 See the individual commands for more information."
19546 (interactive "P")
19547 (cond
19548 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19549 ((integerp arg)
19550 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19551 (message "Content view to level: %d" arg)
19552 (org-content (prefix-numeric-value arg2))
19553 (setq org-cycle-global-status 'overview)))
19554 (t (call-interactively 'org-global-cycle))))
19556 (defun org-shiftmetaleft ()
19557 "Promote subtree or delete table column.
19558 Calls `org-promote-subtree', `org-outdent-item-tree', or
19559 `org-table-delete-column', depending on context. See the
19560 individual commands for more information."
19561 (interactive)
19562 (cond
19563 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19564 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19565 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19566 ((if (not (org-region-active-p)) (org-at-item-p)
19567 (save-excursion (goto-char (region-beginning))
19568 (org-at-item-p)))
19569 (call-interactively 'org-outdent-item-tree))
19570 (t (org-modifier-cursor-error))))
19572 (defun org-shiftmetaright ()
19573 "Demote subtree or insert table column.
19574 Calls `org-demote-subtree', `org-indent-item-tree', or
19575 `org-table-insert-column', depending on context. See the
19576 individual commands for more information."
19577 (interactive)
19578 (cond
19579 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19580 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19581 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19582 ((if (not (org-region-active-p)) (org-at-item-p)
19583 (save-excursion (goto-char (region-beginning))
19584 (org-at-item-p)))
19585 (call-interactively 'org-indent-item-tree))
19586 (t (org-modifier-cursor-error))))
19588 (defun org-shiftmetaup (&optional arg)
19589 "Move subtree up or kill table row.
19590 Calls `org-move-subtree-up' or `org-table-kill-row' or
19591 `org-move-item-up' or `org-timestamp-up', depending on context.
19592 See the individual commands for more information."
19593 (interactive "P")
19594 (cond
19595 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19596 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19597 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19598 ((org-at-item-p) (call-interactively 'org-move-item-up))
19599 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19600 (call-interactively 'org-timestamp-up)))
19601 (t (call-interactively 'org-drag-line-backward))))
19603 (defun org-shiftmetadown (&optional arg)
19604 "Move subtree down or insert table row.
19605 Calls `org-move-subtree-down' or `org-table-insert-row' or
19606 `org-move-item-down' or `org-timestamp-up', depending on context.
19607 See the individual commands for more information."
19608 (interactive "P")
19609 (cond
19610 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19611 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19612 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19613 ((org-at-item-p) (call-interactively 'org-move-item-down))
19614 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19615 (call-interactively 'org-timestamp-down)))
19616 (t (call-interactively 'org-drag-line-forward))))
19618 (defsubst org-hidden-tree-error ()
19619 (error
19620 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19622 (defun org-metaleft (&optional arg)
19623 "Promote heading or move table column to left.
19624 Calls `org-do-promote' or `org-table-move-column', depending on context.
19625 With no specific context, calls the Emacs default `backward-word'.
19626 See the individual commands for more information."
19627 (interactive "P")
19628 (cond
19629 ((run-hook-with-args-until-success 'org-metaleft-hook))
19630 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19631 ((org-with-limited-levels
19632 (or (org-at-heading-p)
19633 (and (org-region-active-p)
19634 (save-excursion
19635 (goto-char (region-beginning))
19636 (org-at-heading-p)))))
19637 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19638 (call-interactively 'org-do-promote))
19639 ;; At an inline task.
19640 ((org-at-heading-p)
19641 (call-interactively 'org-inlinetask-promote))
19642 ((or (org-at-item-p)
19643 (and (org-region-active-p)
19644 (save-excursion
19645 (goto-char (region-beginning))
19646 (org-at-item-p))))
19647 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19648 (call-interactively 'org-outdent-item))
19649 (t (call-interactively 'backward-word))))
19651 (defun org-metaright (&optional arg)
19652 "Demote a subtree, a list item or move table column to right.
19653 In front of a drawer or a block keyword, indent it correctly.
19654 With no specific context, calls the Emacs default `forward-word'.
19655 See the individual commands for more information."
19656 (interactive "P")
19657 (cond
19658 ((run-hook-with-args-until-success 'org-metaright-hook))
19659 ((org-at-table-p) (call-interactively 'org-table-move-column))
19660 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19661 ((org-at-block-p) (call-interactively 'org-indent-block))
19662 ((org-with-limited-levels
19663 (or (org-at-heading-p)
19664 (and (org-region-active-p)
19665 (save-excursion
19666 (goto-char (region-beginning))
19667 (org-at-heading-p)))))
19668 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19669 (call-interactively 'org-do-demote))
19670 ;; At an inline task.
19671 ((org-at-heading-p)
19672 (call-interactively 'org-inlinetask-demote))
19673 ((or (org-at-item-p)
19674 (and (org-region-active-p)
19675 (save-excursion
19676 (goto-char (region-beginning))
19677 (org-at-item-p))))
19678 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19679 (call-interactively 'org-indent-item))
19680 (t (call-interactively 'forward-word))))
19682 (defun org-check-for-hidden (what)
19683 "Check if there are hidden headlines/items in the current visual line.
19684 WHAT can be either `headlines' or `items'. If the current line is
19685 an outline or item heading and it has a folded subtree below it,
19686 this function returns t, nil otherwise."
19687 (let ((re (cond
19688 ((eq what 'headlines) org-outline-regexp-bol)
19689 ((eq what 'items) (org-item-beginning-re))
19690 (t (error "This should not happen"))))
19691 beg end)
19692 (save-excursion
19693 (catch 'exit
19694 (unless (org-region-active-p)
19695 (setq beg (point-at-bol))
19696 (beginning-of-line 2)
19697 (while (and (not (eobp)) ;; this is like `next-line'
19698 (get-char-property (1- (point)) 'invisible))
19699 (beginning-of-line 2))
19700 (setq end (point))
19701 (goto-char beg)
19702 (goto-char (point-at-eol))
19703 (setq end (max end (point)))
19704 (while (re-search-forward re end t)
19705 (if (get-char-property (match-beginning 0) 'invisible)
19706 (throw 'exit t))))
19707 nil))))
19709 (defun org-metaup (&optional arg)
19710 "Move subtree up or move table row up.
19711 Calls `org-move-subtree-up' or `org-table-move-row' or
19712 `org-move-item-up', depending on context. See the individual commands
19713 for more information."
19714 (interactive "P")
19715 (cond
19716 ((run-hook-with-args-until-success 'org-metaup-hook))
19717 ((org-region-active-p)
19718 (let* ((a (min (region-beginning) (region-end)))
19719 (b (1- (max (region-beginning) (region-end))))
19720 (c (save-excursion (goto-char a)
19721 (move-beginning-of-line 0)))
19722 (d (save-excursion (goto-char a)
19723 (move-end-of-line 0) (point))))
19724 (transpose-regions a b c d)
19725 (goto-char c)))
19726 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19727 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19728 ((org-at-item-p) (call-interactively 'org-move-item-up))
19729 (t (org-drag-element-backward))))
19731 (defun org-metadown (&optional arg)
19732 "Move subtree down or move table row down.
19733 Calls `org-move-subtree-down' or `org-table-move-row' or
19734 `org-move-item-down', depending on context. See the individual
19735 commands for more information."
19736 (interactive "P")
19737 (cond
19738 ((run-hook-with-args-until-success 'org-metadown-hook))
19739 ((org-region-active-p)
19740 (let* ((a (min (region-beginning) (region-end)))
19741 (b (max (region-beginning) (region-end)))
19742 (c (save-excursion (goto-char b)
19743 (move-beginning-of-line 1)))
19744 (d (save-excursion (goto-char b)
19745 (move-end-of-line 1) (1+ (point)))))
19746 (transpose-regions a b c d)
19747 (goto-char d)))
19748 ((org-at-table-p) (call-interactively 'org-table-move-row))
19749 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19750 ((org-at-item-p) (call-interactively 'org-move-item-down))
19751 (t (org-drag-element-forward))))
19753 (defun org-shiftup (&optional arg)
19754 "Increase item in timestamp or increase priority of current headline.
19755 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19756 depending on context. See the individual commands for more information."
19757 (interactive "P")
19758 (cond
19759 ((run-hook-with-args-until-success 'org-shiftup-hook))
19760 ((and org-support-shift-select (org-region-active-p))
19761 (org-call-for-shift-select 'previous-line))
19762 ((org-at-timestamp-p t)
19763 (call-interactively (if org-edit-timestamp-down-means-later
19764 'org-timestamp-down 'org-timestamp-up)))
19765 ((and (not (eq org-support-shift-select 'always))
19766 org-enable-priority-commands
19767 (org-at-heading-p))
19768 (call-interactively 'org-priority-up))
19769 ((and (not org-support-shift-select) (org-at-item-p))
19770 (call-interactively 'org-previous-item))
19771 ((org-clocktable-try-shift 'up arg))
19772 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19773 (org-support-shift-select
19774 (org-call-for-shift-select 'previous-line))
19775 (t (org-shiftselect-error))))
19777 (defun org-shiftdown (&optional arg)
19778 "Decrease item in timestamp or decrease priority of current headline.
19779 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19780 depending on context. See the individual commands for more information."
19781 (interactive "P")
19782 (cond
19783 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19784 ((and org-support-shift-select (org-region-active-p))
19785 (org-call-for-shift-select 'next-line))
19786 ((org-at-timestamp-p t)
19787 (call-interactively (if org-edit-timestamp-down-means-later
19788 'org-timestamp-up 'org-timestamp-down)))
19789 ((and (not (eq org-support-shift-select 'always))
19790 org-enable-priority-commands
19791 (org-at-heading-p))
19792 (call-interactively 'org-priority-down))
19793 ((and (not org-support-shift-select) (org-at-item-p))
19794 (call-interactively 'org-next-item))
19795 ((org-clocktable-try-shift 'down arg))
19796 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19797 (org-support-shift-select
19798 (org-call-for-shift-select 'next-line))
19799 (t (org-shiftselect-error))))
19801 (defun org-shiftright (&optional arg)
19802 "Cycle the thing at point or in the current line, depending on context.
19803 Depending on context, this does one of the following:
19805 - switch a timestamp at point one day into the future
19806 - on a headline, switch to the next TODO keyword.
19807 - on an item, switch entire list to the next bullet type
19808 - on a property line, switch to the next allowed value
19809 - on a clocktable definition line, move time block into the future"
19810 (interactive "P")
19811 (cond
19812 ((run-hook-with-args-until-success 'org-shiftright-hook))
19813 ((and org-support-shift-select (org-region-active-p))
19814 (org-call-for-shift-select 'forward-char))
19815 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19816 ((and (not (eq org-support-shift-select 'always))
19817 (org-at-heading-p))
19818 (let ((org-inhibit-logging
19819 (not org-treat-S-cursor-todo-selection-as-state-change))
19820 (org-inhibit-blocking
19821 (not org-treat-S-cursor-todo-selection-as-state-change)))
19822 (org-call-with-arg 'org-todo 'right)))
19823 ((or (and org-support-shift-select
19824 (not (eq org-support-shift-select 'always))
19825 (org-at-item-bullet-p))
19826 (and (not org-support-shift-select) (org-at-item-p)))
19827 (org-call-with-arg 'org-cycle-list-bullet nil))
19828 ((and (not (eq org-support-shift-select 'always))
19829 (org-at-property-p))
19830 (call-interactively 'org-property-next-allowed-value))
19831 ((org-clocktable-try-shift 'right arg))
19832 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19833 (org-support-shift-select
19834 (org-call-for-shift-select 'forward-char))
19835 (t (org-shiftselect-error))))
19837 (defun org-shiftleft (&optional arg)
19838 "Cycle the thing at point or in the current line, depending on context.
19839 Depending on context, this does one of the following:
19841 - switch a timestamp at point one day into the past
19842 - on a headline, switch to the previous TODO keyword.
19843 - on an item, switch entire list to the previous bullet type
19844 - on a property line, switch to the previous allowed value
19845 - on a clocktable definition line, move time block into the past"
19846 (interactive "P")
19847 (cond
19848 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19849 ((and org-support-shift-select (org-region-active-p))
19850 (org-call-for-shift-select 'backward-char))
19851 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19852 ((and (not (eq org-support-shift-select 'always))
19853 (org-at-heading-p))
19854 (let ((org-inhibit-logging
19855 (not org-treat-S-cursor-todo-selection-as-state-change))
19856 (org-inhibit-blocking
19857 (not org-treat-S-cursor-todo-selection-as-state-change)))
19858 (org-call-with-arg 'org-todo 'left)))
19859 ((or (and org-support-shift-select
19860 (not (eq org-support-shift-select 'always))
19861 (org-at-item-bullet-p))
19862 (and (not org-support-shift-select) (org-at-item-p)))
19863 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19864 ((and (not (eq org-support-shift-select 'always))
19865 (org-at-property-p))
19866 (call-interactively 'org-property-previous-allowed-value))
19867 ((org-clocktable-try-shift 'left arg))
19868 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19869 (org-support-shift-select
19870 (org-call-for-shift-select 'backward-char))
19871 (t (org-shiftselect-error))))
19873 (defun org-shiftcontrolright ()
19874 "Switch to next TODO set."
19875 (interactive)
19876 (cond
19877 ((and org-support-shift-select (org-region-active-p))
19878 (org-call-for-shift-select 'forward-word))
19879 ((and (not (eq org-support-shift-select 'always))
19880 (org-at-heading-p))
19881 (org-call-with-arg 'org-todo 'nextset))
19882 (org-support-shift-select
19883 (org-call-for-shift-select 'forward-word))
19884 (t (org-shiftselect-error))))
19886 (defun org-shiftcontrolleft ()
19887 "Switch to previous TODO set."
19888 (interactive)
19889 (cond
19890 ((and org-support-shift-select (org-region-active-p))
19891 (org-call-for-shift-select 'backward-word))
19892 ((and (not (eq org-support-shift-select 'always))
19893 (org-at-heading-p))
19894 (org-call-with-arg 'org-todo 'previousset))
19895 (org-support-shift-select
19896 (org-call-for-shift-select 'backward-word))
19897 (t (org-shiftselect-error))))
19899 (defun org-shiftcontrolup (&optional n)
19900 "Change timestamps synchronously up in CLOCK log lines.
19901 Optional argument N tells to change by that many units."
19902 (interactive "P")
19903 (cond ((and (not org-support-shift-select)
19904 (org-at-clock-log-p)
19905 (org-at-timestamp-p t))
19906 (org-clock-timestamps-up n))
19907 (t (org-shiftselect-error))))
19909 (defun org-shiftcontroldown (&optional n)
19910 "Change timestamps synchronously down in CLOCK log lines.
19911 Optional argument N tells to change by that many units."
19912 (interactive "P")
19913 (cond ((and (not org-support-shift-select)
19914 (org-at-clock-log-p)
19915 (org-at-timestamp-p t))
19916 (org-clock-timestamps-down n))
19917 (t (org-shiftselect-error))))
19919 (defun org-ctrl-c-ret ()
19920 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19921 (interactive)
19922 (cond
19923 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19924 (t (call-interactively 'org-insert-heading))))
19926 (defun org-find-visible ()
19927 (let ((s (point)))
19928 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19929 (get-char-property s 'invisible)))
19931 (defun org-find-invisible ()
19932 (let ((s (point)))
19933 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19934 (not (get-char-property s 'invisible))))
19937 (defun org-copy-visible (beg end)
19938 "Copy the visible parts of the region."
19939 (interactive "r")
19940 (let (snippets s)
19941 (save-excursion
19942 (save-restriction
19943 (narrow-to-region beg end)
19944 (setq s (goto-char (point-min)))
19945 (while (not (= (point) (point-max)))
19946 (goto-char (org-find-invisible))
19947 (push (buffer-substring s (point)) snippets)
19948 (setq s (goto-char (org-find-visible))))))
19949 (kill-new (apply 'concat (nreverse snippets)))))
19951 (defun org-copy-special ()
19952 "Copy region in table or copy current subtree.
19953 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19954 See the individual commands for more information."
19955 (interactive)
19956 (call-interactively
19957 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19959 (defun org-cut-special ()
19960 "Cut region in table or cut current subtree.
19961 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19962 See the individual commands for more information."
19963 (interactive)
19964 (call-interactively
19965 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19967 (defun org-paste-special (arg)
19968 "Paste rectangular region into table, or past subtree relative to level.
19969 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19970 See the individual commands for more information."
19971 (interactive "P")
19972 (if (org-at-table-p)
19973 (org-table-paste-rectangle)
19974 (org-paste-subtree arg)))
19976 (defsubst org-in-fixed-width-region-p ()
19977 "Is point in a fixed-width region?"
19978 (save-match-data
19979 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19981 (defun org-edit-special (&optional arg)
19982 "Call a special editor for the element at point.
19983 When at a table, call the formula editor with `org-table-edit-formulas'.
19984 When in a source code block, call `org-edit-src-code'.
19985 When in a fixed-width region, call `org-edit-fixed-width-region'.
19986 When at an #+INCLUDE keyword, visit the included file.
19987 On a link, call `ffap' to visit the link at point.
19988 Otherwise, return a user error."
19989 (interactive "P")
19990 (let ((element (org-element-at-point)))
19991 (assert (not buffer-read-only) nil
19992 "Buffer is read-only: %s" (buffer-name))
19993 (case (org-element-type element)
19994 (src-block
19995 (if (not arg) (org-edit-src-code)
19996 (let* ((info (org-babel-get-src-block-info))
19997 (lang (nth 0 info))
19998 (params (nth 2 info))
19999 (session (cdr (assq :session params))))
20000 (if (not session) (org-edit-src-code)
20001 ;; At a src-block with a session and function called with
20002 ;; an ARG: switch to the buffer related to the inferior
20003 ;; process.
20004 (switch-to-buffer
20005 (funcall (intern (concat "org-babel-prep-session:" lang))
20006 session params))))))
20007 (keyword
20008 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20009 (find-file
20010 (org-remove-double-quotes
20011 (car (org-split-string (org-element-property :value element)))))
20012 (user-error "No special environment to edit here")))
20013 (table
20014 (if (eq (org-element-property :type element) 'table.el)
20015 (org-edit-src-code)
20016 (call-interactively 'org-table-edit-formulas)))
20017 ;; Only Org tables contain `table-row' type elements.
20018 (table-row (call-interactively 'org-table-edit-formulas))
20019 ((example-block export-block) (org-edit-src-code))
20020 (fixed-width (org-edit-fixed-width-region))
20021 (otherwise
20022 ;; No notable element at point. Though, we may be at a link,
20023 ;; which is an object. Thus, scan deeper.
20024 (if (eq (org-element-type (org-element-context element)) 'link)
20025 (call-interactively 'ffap)
20026 (user-error "No special environment to edit here"))))))
20028 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20029 (defun org-ctrl-c-ctrl-c (&optional arg)
20030 "Set tags in headline, or update according to changed information at point.
20032 This command does many different things, depending on context:
20034 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20035 this is what we do.
20037 - If the cursor is on a statistics cookie, update it.
20039 - If the cursor is in a headline, prompt for tags and insert them
20040 into the current line, aligned to `org-tags-column'. When called
20041 with prefix arg, realign all tags in the current buffer.
20043 - If the cursor is in one of the special #+KEYWORD lines, this
20044 triggers scanning the buffer for these lines and updating the
20045 information.
20047 - If the cursor is inside a table, realign the table. This command
20048 works even if the automatic table editor has been turned off.
20050 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20051 the entire table.
20053 - If the cursor is at a footnote reference or definition, jump to
20054 the corresponding definition or references, respectively.
20056 - If the cursor is a the beginning of a dynamic block, update it.
20058 - If the current buffer is a capture buffer, close note and file it.
20060 - If the cursor is on a <<<target>>>, update radio targets and
20061 corresponding links in this buffer.
20063 - If the cursor is on a numbered item in a plain list, renumber the
20064 ordered list.
20066 - If the cursor is on a checkbox, toggle it.
20068 - If the cursor is on a code block, evaluate it. The variable
20069 `org-confirm-babel-evaluate' can be used to control prompting
20070 before code block evaluation, by default every code block
20071 evaluation requires confirmation. Code block evaluation can be
20072 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20073 (interactive "P")
20074 (cond
20075 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20076 org-occur-highlights
20077 org-latex-fragment-image-overlays)
20078 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20079 (org-remove-occur-highlights)
20080 (org-remove-latex-fragment-image-overlays)
20081 (message "Temporary highlights/overlays removed from current buffer"))
20082 ((and (local-variable-p 'org-finish-function (current-buffer))
20083 (fboundp org-finish-function))
20084 (funcall org-finish-function))
20085 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20087 (let* ((context (org-element-context)) (type (org-element-type context)))
20088 ;; Test if point is within a blank line.
20089 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20090 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20091 (user-error "C-c C-c can do nothing useful at this location"))
20092 ;; For convenience: at the first line of a paragraph on the
20093 ;; same line as an item, apply function on that item instead.
20094 (when (eq type 'paragraph)
20095 (let ((parent (org-element-property :parent context)))
20096 (when (and (eq (org-element-type parent) 'item)
20097 (= (point-at-bol) (org-element-property :begin parent)))
20098 (setq context parent type 'item))))
20099 ;; Act according to type of element or object at point.
20100 (case type
20101 (clock (org-clock-update-time-maybe))
20102 (dynamic-block
20103 (save-excursion
20104 (goto-char (org-element-property :post-affiliated context))
20105 (org-update-dblock)))
20106 (footnote-definition
20107 (goto-char (org-element-property :post-affiliated context))
20108 (call-interactively 'org-footnote-action))
20109 (footnote-reference (call-interactively 'org-footnote-action))
20110 ((headline inlinetask)
20111 (save-excursion (goto-char (org-element-property :begin context))
20112 (call-interactively 'org-set-tags)))
20113 (item
20114 ;; At an item: a double C-u set checkbox to "[-]"
20115 ;; unconditionally, whereas a single one will toggle its
20116 ;; presence. Without an universal argument, if the item
20117 ;; has a checkbox, toggle it. Otherwise repair the list.
20118 (let* ((box (org-element-property :checkbox context))
20119 (struct (org-element-property :structure context))
20120 (old-struct (copy-tree struct))
20121 (parents (org-list-parents-alist struct))
20122 (prevs (org-list-prevs-alist struct))
20123 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20124 (org-list-set-checkbox
20125 (org-element-property :begin context) struct
20126 (cond ((equal arg '(16)) "[-]")
20127 ((and (not box) (equal arg '(4))) "[ ]")
20128 ((or (not box) (equal arg '(4))) nil)
20129 ((eq box 'on) "[ ]")
20130 (t "[X]")))
20131 ;; Mimic `org-list-write-struct' but with grabbing
20132 ;; a return value from `org-list-struct-fix-box'.
20133 (org-list-struct-fix-ind struct parents 2)
20134 (org-list-struct-fix-item-end struct)
20135 (org-list-struct-fix-bul struct prevs)
20136 (org-list-struct-fix-ind struct parents)
20137 (let ((block-item
20138 (org-list-struct-fix-box struct parents prevs orderedp)))
20139 (if (and box (equal struct old-struct))
20140 (if (equal arg '(16))
20141 (message "Checkboxes already reset")
20142 (user-error "Cannot toggle this checkbox: %s"
20143 (if (eq box 'on)
20144 "all subitems checked"
20145 "unchecked subitems")))
20146 (org-list-struct-apply-struct struct old-struct)
20147 (org-update-checkbox-count-maybe))
20148 (when block-item
20149 (message "Checkboxes were removed due to empty box at line %d"
20150 (org-current-line block-item))))))
20151 (keyword
20152 (let ((org-inhibit-startup-visibility-stuff t)
20153 (org-startup-align-all-tables nil))
20154 (when (boundp 'org-table-coordinate-overlays)
20155 (mapc 'delete-overlay org-table-coordinate-overlays)
20156 (setq org-table-coordinate-overlays nil))
20157 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20158 (message "Local setup has been refreshed"))
20159 (plain-list
20160 ;; At a plain list, with a double C-u argument, set
20161 ;; checkboxes of each item to "[-]", whereas a single one
20162 ;; will toggle their presence according to the state of the
20163 ;; first item in the list. Without an argument, repair the
20164 ;; list.
20165 (let* ((begin (org-element-property :contents-begin context))
20166 (beginm (move-marker (make-marker) begin))
20167 (struct (org-element-property :structure context))
20168 (old-struct (copy-tree struct))
20169 (first-box (save-excursion
20170 (goto-char begin)
20171 (looking-at org-list-full-item-re)
20172 (match-string-no-properties 3)))
20173 (new-box (cond ((equal arg '(16)) "[-]")
20174 ((equal arg '(4)) (unless first-box "[ ]"))
20175 ((equal first-box "[X]") "[ ]")
20176 (t "[X]"))))
20177 (cond
20178 (arg
20179 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20180 (org-list-get-all-items
20181 begin struct (org-list-prevs-alist struct))))
20182 ((and first-box (eq (point) begin))
20183 ;; For convenience, when point is at bol on the first
20184 ;; item of the list and no argument is provided, simply
20185 ;; toggle checkbox of that item, if any.
20186 (org-list-set-checkbox begin struct new-box)))
20187 (org-list-write-struct
20188 struct (org-list-parents-alist struct) old-struct)
20189 (org-update-checkbox-count-maybe)
20190 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20191 ((property-drawer node-property)
20192 (call-interactively 'org-property-action))
20193 ((radio-target target)
20194 (call-interactively 'org-update-radio-target-regexp))
20195 (statistics-cookie
20196 (call-interactively 'org-update-statistics-cookies))
20197 ((table table-cell table-row)
20198 ;; At a table, recalculate every field and align it. Also
20199 ;; send the table if necessary. If the table has
20200 ;; a `table.el' type, just give up. At a table row or
20201 ;; cell, maybe recalculate line but always align table.
20202 (if (eq (org-element-property :type context) 'table.el)
20203 (message "Use C-c ' to edit table.el tables")
20204 (let ((org-enable-table-editor t))
20205 (if (or (eq type 'table)
20206 ;; Check if point is at a TBLFM line.
20207 (and (eq type 'table-row)
20208 (= (point) (org-element-property :end context))))
20209 (save-excursion
20210 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20211 (goto-char (org-element-property :contents-begin context))
20212 (org-call-with-arg 'org-table-recalculate (or arg t))
20213 (orgtbl-send-table 'maybe)))
20214 (org-table-maybe-eval-formula)
20215 (cond (arg (call-interactively 'org-table-recalculate))
20216 ((org-table-maybe-recalculate-line))
20217 (t (org-table-align)))))))
20218 (timestamp (org-timestamp-change 0 'day))
20219 (otherwise
20220 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20221 (user-error
20222 "C-c C-c can do nothing useful at this location")))))))))
20224 (defun org-mode-restart ()
20225 "Restart Org-mode, to scan again for special lines.
20226 Also updates the keyword regular expressions."
20227 (interactive)
20228 (org-mode)
20229 (message "Org-mode restarted"))
20231 (defun org-kill-note-or-show-branches ()
20232 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20233 (interactive)
20234 (if (not org-finish-function)
20235 (progn
20236 (hide-subtree)
20237 (call-interactively 'show-branches))
20238 (let ((org-note-abort t))
20239 (funcall org-finish-function))))
20241 (defun org-open-line (n)
20242 "Insert a new row in tables, call `open-line' elsewhere."
20243 (interactive "*p")
20244 (if (org-at-table-p)
20245 (org-table-insert-row)
20246 (open-line n)))
20248 (defun org-return (&optional indent)
20249 "Goto next table row or insert a newline.
20250 Calls `org-table-next-row' or `newline', depending on context.
20251 See the individual commands for more information."
20252 (interactive)
20253 (let (org-ts-what)
20254 (cond
20255 ((or (bobp) (org-in-src-block-p))
20256 (if indent (newline-and-indent) (newline)))
20257 ((org-at-table-p)
20258 (org-table-justify-field-maybe)
20259 (call-interactively 'org-table-next-row))
20260 ;; when `newline-and-indent' is called within a list, make sure
20261 ;; text moved stays inside the item.
20262 ((and (org-in-item-p) indent)
20263 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20264 (progn
20265 (save-match-data (newline))
20266 (org-indent-line-to (length (match-string 0))))
20267 (let ((ind (org-get-indentation)))
20268 (newline)
20269 (if (org-looking-back org-list-end-re)
20270 (org-indent-line)
20271 (org-indent-line-to ind)))))
20272 ((and org-return-follows-link
20273 (org-at-timestamp-p t)
20274 (not (eq org-ts-what 'after)))
20275 (org-follow-timestamp-link))
20276 ((and org-return-follows-link
20277 (let ((tprop (get-text-property (point) 'face)))
20278 (or (eq tprop 'org-link)
20279 (and (listp tprop) (memq 'org-link tprop)))))
20280 (call-interactively 'org-open-at-point))
20281 ((and (org-at-heading-p)
20282 (looking-at
20283 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20284 (org-show-entry)
20285 (end-of-line 1)
20286 (newline))
20287 (t (if indent (newline-and-indent) (newline))))))
20289 (defun org-return-indent ()
20290 "Goto next table row or insert a newline and indent.
20291 Calls `org-table-next-row' or `newline-and-indent', depending on
20292 context. See the individual commands for more information."
20293 (interactive)
20294 (org-return t))
20296 (defun org-ctrl-c-star ()
20297 "Compute table, or change heading status of lines.
20298 Calls `org-table-recalculate' or `org-toggle-heading',
20299 depending on context."
20300 (interactive)
20301 (cond
20302 ((org-at-table-p)
20303 (call-interactively 'org-table-recalculate))
20305 ;; Convert all lines in region to list items
20306 (call-interactively 'org-toggle-heading))))
20308 (defun org-ctrl-c-minus ()
20309 "Insert separator line in table or modify bullet status of line.
20310 Also turns a plain line or a region of lines into list items.
20311 Calls `org-table-insert-hline', `org-toggle-item', or
20312 `org-cycle-list-bullet', depending on context."
20313 (interactive)
20314 (cond
20315 ((org-at-table-p)
20316 (call-interactively 'org-table-insert-hline))
20317 ((org-region-active-p)
20318 (call-interactively 'org-toggle-item))
20319 ((org-in-item-p)
20320 (call-interactively 'org-cycle-list-bullet))
20322 (call-interactively 'org-toggle-item))))
20324 (defun org-toggle-item (arg)
20325 "Convert headings or normal lines to items, items to normal lines.
20326 If there is no active region, only the current line is considered.
20328 If the first non blank line in the region is a headline, convert
20329 all headlines to items, shifting text accordingly.
20331 If it is an item, convert all items to normal lines.
20333 If it is normal text, change region into a list of items.
20334 With a prefix argument ARG, change the region in a single item."
20335 (interactive "P")
20336 (let ((shift-text
20337 (function
20338 ;; Shift text in current section to IND, from point to END.
20339 ;; The function leaves point to END line.
20340 (lambda (ind end)
20341 (let ((min-i 1000) (end (copy-marker end)))
20342 ;; First determine the minimum indentation (MIN-I) of
20343 ;; the text.
20344 (save-excursion
20345 (catch 'exit
20346 (while (< (point) end)
20347 (let ((i (org-get-indentation)))
20348 (cond
20349 ;; Skip blank lines and inline tasks.
20350 ((looking-at "^[ \t]*$"))
20351 ((looking-at org-outline-regexp-bol))
20352 ;; We can't find less than 0 indentation.
20353 ((zerop i) (throw 'exit (setq min-i 0)))
20354 ((< i min-i) (setq min-i i))))
20355 (forward-line))))
20356 ;; Then indent each line so that a line indented to
20357 ;; MIN-I becomes indented to IND. Ignore blank lines
20358 ;; and inline tasks in the process.
20359 (let ((delta (- ind min-i)))
20360 (while (< (point) end)
20361 (unless (or (looking-at "^[ \t]*$")
20362 (looking-at org-outline-regexp-bol))
20363 (org-indent-line-to (+ (org-get-indentation) delta)))
20364 (forward-line)))))))
20365 (skip-blanks
20366 (function
20367 ;; Return beginning of first non-blank line, starting from
20368 ;; line at POS.
20369 (lambda (pos)
20370 (save-excursion
20371 (goto-char pos)
20372 (skip-chars-forward " \r\t\n")
20373 (point-at-bol)))))
20374 beg end)
20375 ;; Determine boundaries of changes.
20376 (if (org-region-active-p)
20377 (setq beg (funcall skip-blanks (region-beginning))
20378 end (copy-marker (region-end)))
20379 (setq beg (funcall skip-blanks (point-at-bol))
20380 end (copy-marker (point-at-eol))))
20381 ;; Depending on the starting line, choose an action on the text
20382 ;; between BEG and END.
20383 (org-with-limited-levels
20384 (save-excursion
20385 (goto-char beg)
20386 (cond
20387 ;; Case 1. Start at an item: de-itemize. Note that it only
20388 ;; happens when a region is active: `org-ctrl-c-minus'
20389 ;; would call `org-cycle-list-bullet' otherwise.
20390 ((org-at-item-p)
20391 (while (< (point) end)
20392 (when (org-at-item-p)
20393 (skip-chars-forward " \t")
20394 (delete-region (point) (match-end 0)))
20395 (forward-line)))
20396 ;; Case 2. Start at an heading: convert to items.
20397 ((org-at-heading-p)
20398 (let* ((bul (org-list-bullet-string "-"))
20399 (bul-len (length bul))
20400 ;; Indentation of the first heading. It should be
20401 ;; relative to the indentation of its parent, if any.
20402 (start-ind (save-excursion
20403 (cond
20404 ((not org-adapt-indentation) 0)
20405 ((not (outline-previous-heading)) 0)
20406 (t (length (match-string 0))))))
20407 ;; Level of first heading. Further headings will be
20408 ;; compared to it to determine hierarchy in the list.
20409 (ref-level (org-reduced-level (org-outline-level))))
20410 (while (< (point) end)
20411 (let* ((level (org-reduced-level (org-outline-level)))
20412 (delta (max 0 (- level ref-level))))
20413 ;; If current headline is less indented than the first
20414 ;; one, set it as reference, in order to preserve
20415 ;; subtrees.
20416 (when (< level ref-level) (setq ref-level level))
20417 (replace-match bul t t)
20418 (org-indent-line-to (+ start-ind (* delta bul-len)))
20419 ;; Ensure all text down to END (or SECTION-END) belongs
20420 ;; to the newly created item.
20421 (let ((section-end (save-excursion
20422 (or (outline-next-heading) (point)))))
20423 (forward-line)
20424 (funcall shift-text
20425 (+ start-ind (* (1+ delta) bul-len))
20426 (min end section-end)))))))
20427 ;; Case 3. Normal line with ARG: make the first line of region
20428 ;; an item, and shift indentation of others lines to
20429 ;; set them as item's body.
20430 (arg (let* ((bul (org-list-bullet-string "-"))
20431 (bul-len (length bul))
20432 (ref-ind (org-get-indentation)))
20433 (skip-chars-forward " \t")
20434 (insert bul)
20435 (forward-line)
20436 (while (< (point) end)
20437 ;; Ensure that lines less indented than first one
20438 ;; still get included in item body.
20439 (funcall shift-text
20440 (+ ref-ind bul-len)
20441 (min end (save-excursion (or (outline-next-heading)
20442 (point)))))
20443 (forward-line))))
20444 ;; Case 4. Normal line without ARG: turn each non-item line
20445 ;; into an item.
20447 (while (< (point) end)
20448 (unless (or (org-at-heading-p) (org-at-item-p))
20449 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20450 (replace-match
20451 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20452 (forward-line))))))))
20454 (defun org-toggle-heading (&optional nstars)
20455 "Convert headings to normal text, or items or text to headings.
20456 If there is no active region, only convert the current line.
20458 With a \\[universal-argument] prefix, convert the whole list at
20459 point into heading.
20461 In a region:
20463 - If the first non blank line is a headline, remove the stars
20464 from all headlines in the region.
20466 - If it is a normal line, turn each and every normal line (i.e.,
20467 not an heading or an item) in the region into headings. If you
20468 want to convert only the first line of this region, use one
20469 universal prefix argument.
20471 - If it is a plain list item, turn all plain list items into headings.
20473 When converting a line into a heading, the number of stars is chosen
20474 such that the lines become children of the current entry. However,
20475 when a numeric prefix argument is given, its value determines the
20476 number of stars to add."
20477 (interactive "P")
20478 (let ((skip-blanks
20479 (function
20480 ;; Return beginning of first non-blank line, starting from
20481 ;; line at POS.
20482 (lambda (pos)
20483 (save-excursion
20484 (goto-char pos)
20485 (while (org-at-comment-p) (forward-line))
20486 (skip-chars-forward " \r\t\n")
20487 (point-at-bol)))))
20488 beg end toggled)
20489 ;; Determine boundaries of changes. If a universal prefix has
20490 ;; been given, put the list in a region. If region ends at a bol,
20491 ;; do not consider the last line to be in the region.
20493 (when (and current-prefix-arg (org-at-item-p))
20494 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20495 (org-mark-element))
20497 (if (org-region-active-p)
20498 (setq beg (funcall skip-blanks (region-beginning))
20499 end (copy-marker (save-excursion
20500 (goto-char (region-end))
20501 (if (bolp) (point) (point-at-eol)))))
20502 (setq beg (funcall skip-blanks (point-at-bol))
20503 end (copy-marker (point-at-eol))))
20504 ;; Ensure inline tasks don't count as headings.
20505 (org-with-limited-levels
20506 (save-excursion
20507 (goto-char beg)
20508 (cond
20509 ;; Case 1. Started at an heading: de-star headings.
20510 ((org-at-heading-p)
20511 (while (< (point) end)
20512 (when (org-at-heading-p t)
20513 (looking-at org-outline-regexp) (replace-match "")
20514 (setq toggled t))
20515 (forward-line)))
20516 ;; Case 2. Started at an item: change items into headlines.
20517 ;; One star will be added by `org-list-to-subtree'.
20518 ((org-at-item-p)
20519 (let* ((stars (make-string
20520 ;; subtract the star that will be added again by
20521 ;; `org-list-to-subtree'
20522 (if (numberp nstars) (1- nstars)
20523 (or (org-current-level) 0))
20524 ?*))
20525 (add-stars
20526 (cond (nstars "") ; stars from prefix only
20527 ((equal stars "") "") ; before first heading
20528 (org-odd-levels-only "*") ; inside heading, odd
20529 (t "")))) ; inside heading, oddeven
20530 (while (< (point) end)
20531 (when (org-at-item-p)
20532 ;; Pay attention to cases when region ends before list.
20533 (let* ((struct (org-list-struct))
20534 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20535 (save-restriction
20536 (narrow-to-region (point) list-end)
20537 (insert
20538 (org-list-to-subtree
20539 (org-list-parse-list t)
20540 '(:istart (concat stars add-stars (funcall get-stars depth))
20541 :icount (concat stars add-stars (funcall get-stars depth)))))))
20542 (setq toggled t))
20543 (forward-line))))
20544 ;; Case 3. Started at normal text: make every line an heading,
20545 ;; skipping headlines and items.
20546 (t (let* ((stars
20547 (make-string
20548 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20549 (add-stars
20550 (cond (nstars "") ; stars from prefix only
20551 ((equal stars "") "*") ; before first heading
20552 (org-odd-levels-only "**") ; inside heading, odd
20553 (t "*"))) ; inside heading, oddeven
20554 (rpl (concat stars add-stars " "))
20555 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20556 (while (< (point) (if (equal nstars '(4)) lend end))
20557 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20558 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20559 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20560 (forward-line)))))))
20561 (unless toggled (message "Cannot toggle heading from here"))))
20563 (defun org-meta-return (&optional arg)
20564 "Insert a new heading or wrap a region in a table.
20565 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20566 See the individual commands for more information."
20567 (interactive "P")
20568 (cond
20569 ((run-hook-with-args-until-success 'org-metareturn-hook))
20570 ((or (org-at-drawer-p) (org-at-property-p))
20571 (newline-and-indent))
20572 ((org-at-table-p)
20573 (call-interactively 'org-table-wrap-region))
20574 (t (call-interactively 'org-insert-heading))))
20576 ;;; Menu entries
20578 (defsubst org-in-subtree-not-table-p ()
20579 "Are we in a subtree and not in a table?"
20580 (and (not (org-before-first-heading-p))
20581 (not (org-at-table-p))))
20583 ;; Define the Org-mode menus
20584 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20585 '("Tbl"
20586 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20587 ["Next Field" org-cycle (org-at-table-p)]
20588 ["Previous Field" org-shifttab (org-at-table-p)]
20589 ["Next Row" org-return (org-at-table-p)]
20590 "--"
20591 ["Blank Field" org-table-blank-field (org-at-table-p)]
20592 ["Edit Field" org-table-edit-field (org-at-table-p)]
20593 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20594 "--"
20595 ("Column"
20596 ["Move Column Left" org-metaleft (org-at-table-p)]
20597 ["Move Column Right" org-metaright (org-at-table-p)]
20598 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20599 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20600 ("Row"
20601 ["Move Row Up" org-metaup (org-at-table-p)]
20602 ["Move Row Down" org-metadown (org-at-table-p)]
20603 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20604 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20605 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20606 "--"
20607 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20608 ("Rectangle"
20609 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20610 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20611 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20612 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20613 "--"
20614 ("Calculate"
20615 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20616 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20617 ["Edit Formulas" org-edit-special (org-at-table-p)]
20618 "--"
20619 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20620 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20621 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20622 "--"
20623 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20624 "--"
20625 ["Sum Column/Rectangle" org-table-sum
20626 (or (org-at-table-p) (org-region-active-p))]
20627 ["Which Column?" org-table-current-column (org-at-table-p)])
20628 ["Debug Formulas"
20629 org-table-toggle-formula-debugger
20630 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20631 ["Show Col/Row Numbers"
20632 org-table-toggle-coordinate-overlays
20633 :style toggle
20634 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20635 "--"
20636 ["Create" org-table-create (and (not (org-at-table-p))
20637 org-enable-table-editor)]
20638 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20639 ["Import from File" org-table-import (not (org-at-table-p))]
20640 ["Export to File" org-table-export (org-at-table-p)]
20641 "--"
20642 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20644 (easy-menu-define org-org-menu org-mode-map "Org menu"
20645 '("Org"
20646 ("Show/Hide"
20647 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20648 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20649 ["Sparse Tree..." org-sparse-tree t]
20650 ["Reveal Context" org-reveal t]
20651 ["Show All" show-all t]
20652 "--"
20653 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20654 "--"
20655 ["New Heading" org-insert-heading t]
20656 ("Navigate Headings"
20657 ["Up" outline-up-heading t]
20658 ["Next" outline-next-visible-heading t]
20659 ["Previous" outline-previous-visible-heading t]
20660 ["Next Same Level" outline-forward-same-level t]
20661 ["Previous Same Level" outline-backward-same-level t]
20662 "--"
20663 ["Jump" org-goto t])
20664 ("Edit Structure"
20665 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20666 "--"
20667 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20668 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20669 "--"
20670 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20671 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20672 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20673 "--"
20674 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20675 "--"
20676 ["Copy visible text" org-copy-visible t]
20677 "--"
20678 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20679 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20680 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20681 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20682 "--"
20683 ["Sort Region/Children" org-sort t]
20684 "--"
20685 ["Convert to odd levels" org-convert-to-odd-levels t]
20686 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20687 ("Editing"
20688 ["Emphasis..." org-emphasize t]
20689 ["Edit Source Example" org-edit-special t]
20690 "--"
20691 ["Footnote new/jump" org-footnote-action t]
20692 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20693 ("Archive"
20694 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20695 "--"
20696 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20697 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20698 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20700 "--"
20701 ("Hyperlinks"
20702 ["Store Link (Global)" org-store-link t]
20703 ["Find existing link to here" org-occur-link-in-agenda-files t]
20704 ["Insert Link" org-insert-link t]
20705 ["Follow Link" org-open-at-point t]
20706 "--"
20707 ["Next link" org-next-link t]
20708 ["Previous link" org-previous-link t]
20709 "--"
20710 ["Descriptive Links"
20711 org-toggle-link-display
20712 :style radio
20713 :selected org-descriptive-links
20715 ["Literal Links"
20716 org-toggle-link-display
20717 :style radio
20718 :selected (not org-descriptive-links)])
20719 "--"
20720 ("TODO Lists"
20721 ["TODO/DONE/-" org-todo t]
20722 ("Select keyword"
20723 ["Next keyword" org-shiftright (org-at-heading-p)]
20724 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20725 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20726 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20727 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20728 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20729 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20730 "--"
20731 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20732 :selected org-enforce-todo-dependencies :style toggle :active t]
20733 "Settings for tree at point"
20734 ["Do Children sequentially" org-toggle-ordered-property :style radio
20735 :selected (org-entry-get nil "ORDERED")
20736 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20737 ["Do Children parallel" org-toggle-ordered-property :style radio
20738 :selected (not (org-entry-get nil "ORDERED"))
20739 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20740 "--"
20741 ["Set Priority" org-priority t]
20742 ["Priority Up" org-shiftup t]
20743 ["Priority Down" org-shiftdown t]
20744 "--"
20745 ["Get news from all feeds" org-feed-update-all t]
20746 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20747 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20748 ("TAGS and Properties"
20749 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20750 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20751 "--"
20752 ["Set property" org-set-property (not (org-before-first-heading-p))]
20753 ["Column view of properties" org-columns t]
20754 ["Insert Column View DBlock" org-insert-columns-dblock t])
20755 ("Dates and Scheduling"
20756 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20757 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20758 ("Change Date"
20759 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20760 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20761 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20762 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20763 ["Compute Time Range" org-evaluate-time-range t]
20764 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20765 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20766 "--"
20767 ["Custom time format" org-toggle-time-stamp-overlays
20768 :style radio :selected org-display-custom-times]
20769 "--"
20770 ["Goto Calendar" org-goto-calendar t]
20771 ["Date from Calendar" org-date-from-calendar t]
20772 "--"
20773 ["Start/Restart Timer" org-timer-start t]
20774 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20775 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20776 ["Insert Timer String" org-timer t]
20777 ["Insert Timer Item" org-timer-item t])
20778 ("Logging work"
20779 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20780 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20781 ["Clock out" org-clock-out t]
20782 ["Clock cancel" org-clock-cancel t]
20783 "--"
20784 ["Mark as default task" org-clock-mark-default-task t]
20785 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20786 ["Goto running clock" org-clock-goto t]
20787 "--"
20788 ["Display times" org-clock-display t]
20789 ["Create clock table" org-clock-report t]
20790 "--"
20791 ["Record DONE time"
20792 (progn (setq org-log-done (not org-log-done))
20793 (message "Switching to %s will %s record a timestamp"
20794 (car org-done-keywords)
20795 (if org-log-done "automatically" "not")))
20796 :style toggle :selected org-log-done])
20797 "--"
20798 ["Agenda Command..." org-agenda t]
20799 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20800 ("File List for Agenda")
20801 ("Special views current file"
20802 ["TODO Tree" org-show-todo-tree t]
20803 ["Check Deadlines" org-check-deadlines t]
20804 ["Timeline" org-timeline t]
20805 ["Tags/Property tree" org-match-sparse-tree t])
20806 "--"
20807 ["Export/Publish..." org-export-dispatch t]
20808 ("LaTeX"
20809 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20810 :selected org-cdlatex-mode]
20811 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20812 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20813 ["Modify math symbol" org-cdlatex-math-modify
20814 (org-inside-LaTeX-fragment-p)]
20815 ["Insert citation" org-reftex-citation t]
20816 "--"
20817 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20818 "--"
20819 ("MobileOrg"
20820 ["Push Files and Views" org-mobile-push t]
20821 ["Get Captured and Flagged" org-mobile-pull t]
20822 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20823 "--"
20824 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20825 "--"
20826 ("Documentation"
20827 ["Show Version" org-version t]
20828 ["Info Documentation" org-info t])
20829 ("Customize"
20830 ["Browse Org Group" org-customize t]
20831 "--"
20832 ["Expand This Menu" org-create-customize-menu
20833 (fboundp 'customize-menu-create)])
20834 ["Send bug report" org-submit-bug-report t]
20835 "--"
20836 ("Refresh/Reload"
20837 ["Refresh setup current buffer" org-mode-restart t]
20838 ["Reload Org (after update)" org-reload t]
20839 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20842 (defun org-info (&optional node)
20843 "Read documentation for Org-mode in the info system.
20844 With optional NODE, go directly to that node."
20845 (interactive)
20846 (info (format "(org)%s" (or node ""))))
20848 ;;;###autoload
20849 (defun org-submit-bug-report ()
20850 "Submit a bug report on Org-mode via mail.
20852 Don't hesitate to report any problems or inaccurate documentation.
20854 If you don't have setup sending mail from (X)Emacs, please copy the
20855 output buffer into your mail program, as it gives us important
20856 information about your Org-mode version and configuration."
20857 (interactive)
20858 (require 'reporter)
20859 (org-load-modules-maybe)
20860 (org-require-autoloaded-modules)
20861 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20862 (reporter-submit-bug-report
20863 "emacs-orgmode@gnu.org"
20864 (org-version nil 'full)
20865 (let (list)
20866 (save-window-excursion
20867 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20868 (delete-other-windows)
20869 (erase-buffer)
20870 (insert "You are about to submit a bug report to the Org-mode mailing list.
20872 We would like to add your full Org-mode and Outline configuration to the
20873 bug report. This greatly simplifies the work of the maintainer and
20874 other experts on the mailing list.
20876 HOWEVER, some variables you have customized may contain private
20877 information. The names of customers, colleagues, or friends, might
20878 appear in the form of file names, tags, todo states, or search strings.
20879 If you answer yes to the prompt, you might want to check and remove
20880 such private information before sending the email.")
20881 (add-text-properties (point-min) (point-max) '(face org-warning))
20882 (when (yes-or-no-p "Include your Org-mode configuration ")
20883 (mapatoms
20884 (lambda (v)
20885 (and (boundp v)
20886 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20887 (or (and (symbol-value v)
20888 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20889 (and
20890 (get v 'custom-type) (get v 'standard-value)
20891 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20892 (push v list)))))
20893 (kill-buffer (get-buffer "*Warn about privacy*"))
20894 list))
20895 nil nil
20896 "Remember to cover the basics, that is, what you expected to happen and
20897 what in fact did happen. You don't know how to make a good report? See
20899 http://orgmode.org/manual/Feedback.html#Feedback
20901 Your bug report will be posted to the Org-mode mailing list.
20902 ------------------------------------------------------------------------")
20903 (save-excursion
20904 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20905 (replace-match "\\1Bug: \\3 [\\2]")))))
20908 (defun org-install-agenda-files-menu ()
20909 (let ((bl (buffer-list)))
20910 (save-excursion
20911 (while bl
20912 (set-buffer (pop bl))
20913 (if (derived-mode-p 'org-mode) (setq bl nil)))
20914 (when (derived-mode-p 'org-mode)
20915 (easy-menu-change
20916 '("Org") "File List for Agenda"
20917 (append
20918 (list
20919 ["Edit File List" (org-edit-agenda-file-list) t]
20920 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20921 ["Remove Current File from List" org-remove-file t]
20922 ["Cycle through agenda files" org-cycle-agenda-files t]
20923 ["Occur in all agenda files" org-occur-in-agenda-files t]
20924 "--")
20925 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20927 ;;;; Documentation
20929 (defun org-require-autoloaded-modules ()
20930 (interactive)
20931 (mapc 'require
20932 '(org-agenda org-archive org-attach org-clock org-colview org-id
20933 org-remember org-table org-timer)))
20935 ;;;###autoload
20936 (defun org-reload (&optional uncompiled)
20937 "Reload all org lisp files.
20938 With prefix arg UNCOMPILED, load the uncompiled versions."
20939 (interactive "P")
20940 (require 'loadhist)
20941 (let* ((org-dir (org-find-library-dir "org"))
20942 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20943 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20944 (remove-re (mapconcat 'identity
20945 (mapcar (lambda (f) (concat "^" f "$"))
20946 (list (if (featurep 'xemacs)
20947 "org-colview"
20948 "org-colview-xemacs")
20949 "org" "org-loaddefs" "org-version"))
20950 "\\|"))
20951 (feats (delete-dups
20952 (mapcar 'file-name-sans-extension
20953 (mapcar 'file-name-nondirectory
20954 (delq nil
20955 (mapcar 'feature-file
20956 features))))))
20957 (lfeat (append
20958 (sort
20959 (setq feats
20960 (delq nil (mapcar
20961 (lambda (f)
20962 (if (and (string-match feature-re f)
20963 (not (string-match remove-re f)))
20964 f nil))
20965 feats)))
20966 'string-lessp)
20967 (list "org-version" "org")))
20968 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20969 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20970 load-uncore load-misses)
20971 (setq load-misses
20972 (delq 't
20973 (mapcar (lambda (f)
20974 (or (org-load-noerror-mustsuffix (concat org-dir f))
20975 (and (string= org-dir contrib-dir)
20976 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20977 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20978 (add-to-list 'load-uncore f 'append)
20981 lfeat)))
20982 (if load-uncore
20983 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20984 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20985 (if load-misses
20986 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20987 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20988 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20990 ;;;###autoload
20991 (defun org-customize ()
20992 "Call the customize function with org as argument."
20993 (interactive)
20994 (org-load-modules-maybe)
20995 (org-require-autoloaded-modules)
20996 (customize-browse 'org))
20998 (defun org-create-customize-menu ()
20999 "Create a full customization menu for Org-mode, insert it into the menu."
21000 (interactive)
21001 (org-load-modules-maybe)
21002 (org-require-autoloaded-modules)
21003 (if (fboundp 'customize-menu-create)
21004 (progn
21005 (easy-menu-change
21006 '("Org") "Customize"
21007 `(["Browse Org group" org-customize t]
21008 "--"
21009 ,(customize-menu-create 'org)
21010 ["Set" Custom-set t]
21011 ["Save" Custom-save t]
21012 ["Reset to Current" Custom-reset-current t]
21013 ["Reset to Saved" Custom-reset-saved t]
21014 ["Reset to Standard Settings" Custom-reset-standard t]))
21015 (message "\"Org\"-menu now contains full customization menu"))
21016 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21018 ;;;; Miscellaneous stuff
21020 ;;; Generally useful functions
21022 (defun org-get-at-bol (property)
21023 "Get text property PROPERTY at beginning of line."
21024 (get-text-property (point-at-bol) property))
21026 (defun org-find-text-property-in-string (prop s)
21027 "Return the first non-nil value of property PROP in string S."
21028 (or (get-text-property 0 prop s)
21029 (get-text-property (or (next-single-property-change 0 prop s) 0)
21030 prop s)))
21032 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21033 "Display the given MESSAGE as a warning."
21034 (if (fboundp 'display-warning)
21035 (display-warning 'org message
21036 (if (featurep 'xemacs) 'warning :warning))
21037 (let ((buf (get-buffer-create "*Org warnings*")))
21038 (with-current-buffer buf
21039 (goto-char (point-max))
21040 (insert "Warning (Org): " message)
21041 (unless (bolp)
21042 (newline)))
21043 (display-buffer buf)
21044 (sit-for 0))))
21046 (defun org-eval (form)
21047 "Eval FORM and return result."
21048 (condition-case error
21049 (eval form)
21050 (error (format "%%![Error: %s]" error))))
21052 (defun org-in-clocktable-p ()
21053 "Check if the cursor is in a clocktable."
21054 (let ((pos (point)) start)
21055 (save-excursion
21056 (end-of-line 1)
21057 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21058 (setq start (match-beginning 0))
21059 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21060 (>= (match-end 0) pos)
21061 start))))
21063 (defun org-in-commented-line ()
21064 "Is point in a line starting with `#'?"
21065 (equal (char-after (point-at-bol)) ?#))
21067 (defun org-in-indented-comment-line ()
21068 "Is point in a line starting with `#' after some white space?"
21069 (save-excursion
21070 (save-match-data
21071 (goto-char (point-at-bol))
21072 (looking-at "[ \t]*#"))))
21074 (defun org-in-verbatim-emphasis ()
21075 (save-match-data
21076 (and (org-in-regexp org-emph-re 2)
21077 (>= (point) (match-beginning 3))
21078 (<= (point) (match-end 4))
21079 (member (match-string 3) '("=" "~")))))
21081 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21082 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21083 (if (and marker (marker-buffer marker)
21084 (buffer-live-p (marker-buffer marker)))
21085 (progn
21086 (org-pop-to-buffer-same-window (marker-buffer marker))
21087 (if (or (> marker (point-max)) (< marker (point-min)))
21088 (widen))
21089 (goto-char marker)
21090 (org-show-context 'org-goto))
21091 (if bookmark
21092 (bookmark-jump bookmark)
21093 (error "Cannot find location"))))
21095 (defun org-quote-csv-field (s)
21096 "Quote field for inclusion in CSV material."
21097 (if (string-match "[\",]" s)
21098 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21101 (defun org-force-self-insert (N)
21102 "Needed to enforce self-insert under remapping."
21103 (interactive "p")
21104 (self-insert-command N))
21106 (defun org-string-width (s)
21107 "Compute width of string, ignoring invisible characters.
21108 This ignores character with invisibility property `org-link', and also
21109 characters with property `org-cwidth', because these will become invisible
21110 upon the next fontification round."
21111 (let (b l)
21112 (when (or (eq t buffer-invisibility-spec)
21113 (assq 'org-link buffer-invisibility-spec))
21114 (while (setq b (text-property-any 0 (length s)
21115 'invisible 'org-link s))
21116 (setq s (concat (substring s 0 b)
21117 (substring s (or (next-single-property-change
21118 b 'invisible s) (length s)))))))
21119 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21120 (setq s (concat (substring s 0 b)
21121 (substring s (or (next-single-property-change
21122 b 'org-cwidth s) (length s))))))
21123 (setq l (string-width s) b -1)
21124 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21125 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21128 (defun org-shorten-string (s maxlength)
21129 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21130 If the string is shorter or has length MAXLENGTH, just return the
21131 original string. If it is longer, the functions finds a space in the
21132 string, breaks this string off at that locations and adds three dots
21133 as ellipsis. Including the ellipsis, the string will not be longer
21134 than MAXLENGTH. If finding a good breaking point in the string does
21135 not work, the string is just chopped off in the middle of a word
21136 if necessary."
21137 (if (<= (length s) maxlength)
21139 (let* ((n (max (- maxlength 4) 1))
21140 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21141 (if (string-match re s)
21142 (concat (match-string 1 s) "...")
21143 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21145 (defun org-get-indentation (&optional line)
21146 "Get the indentation of the current line, interpreting tabs.
21147 When LINE is given, assume it represents a line and compute its indentation."
21148 (if line
21149 (if (string-match "^ *" (org-remove-tabs line))
21150 (match-end 0))
21151 (save-excursion
21152 (beginning-of-line 1)
21153 (skip-chars-forward " \t")
21154 (current-column))))
21156 (defun org-get-string-indentation (s)
21157 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21158 (let ((n -1) (i 0) (w tab-width) c)
21159 (catch 'exit
21160 (while (< (setq n (1+ n)) (length s))
21161 (setq c (aref s n))
21162 (cond ((= c ?\ ) (setq i (1+ i)))
21163 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21164 (t (throw 'exit t)))))
21167 (defun org-remove-tabs (s &optional width)
21168 "Replace tabulators in S with spaces.
21169 Assumes that s is a single line, starting in column 0."
21170 (setq width (or width tab-width))
21171 (while (string-match "\t" s)
21172 (setq s (replace-match
21173 (make-string
21174 (- (* width (/ (+ (match-beginning 0) width) width))
21175 (match-beginning 0)) ?\ )
21176 t t s)))
21179 (defun org-fix-indentation (line ind)
21180 "Fix indentation in LINE.
21181 IND is a cons cell with target and minimum indentation.
21182 If the current indentation in LINE is smaller than the minimum,
21183 leave it alone. If it is larger than ind, set it to the target."
21184 (let* ((l (org-remove-tabs line))
21185 (i (org-get-indentation l))
21186 (i1 (car ind)) (i2 (cdr ind)))
21187 (if (>= i i2) (setq l (substring line i2)))
21188 (if (> i1 0)
21189 (concat (make-string i1 ?\ ) l)
21190 l)))
21192 (defun org-remove-indentation (code &optional n)
21193 "Remove the maximum common indentation from the lines in CODE.
21194 N may optionally be the number of spaces to remove."
21195 (with-temp-buffer
21196 (insert code)
21197 (org-do-remove-indentation n)
21198 (buffer-string)))
21200 (defun org-do-remove-indentation (&optional n)
21201 "Remove the maximum common indentation from the buffer."
21202 (untabify (point-min) (point-max))
21203 (let ((min 10000) re)
21204 (if n
21205 (setq min n)
21206 (goto-char (point-min))
21207 (while (re-search-forward "^ *[^ \n]" nil t)
21208 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21209 (unless (or (= min 0) (= min 10000))
21210 (setq re (format "^ \\{%d\\}" min))
21211 (goto-char (point-min))
21212 (while (re-search-forward re nil t)
21213 (replace-match "")
21214 (end-of-line 1))
21215 min)))
21217 (defun org-fill-template (template alist)
21218 "Find each %key of ALIST in TEMPLATE and replace it."
21219 (let ((case-fold-search nil)
21220 entry key value)
21221 (setq alist (sort (copy-sequence alist)
21222 (lambda (a b) (< (length (car a)) (length (car b))))))
21223 (while (setq entry (pop alist))
21224 (setq template
21225 (replace-regexp-in-string
21226 (concat "%" (regexp-quote (car entry)))
21227 (or (cdr entry) "") template t t)))
21228 template))
21230 (defun org-base-buffer (buffer)
21231 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21232 (if (not buffer)
21233 buffer
21234 (or (buffer-base-buffer buffer)
21235 buffer)))
21237 (defun org-trim (s)
21238 "Remove whitespace at beginning and end of string."
21239 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21240 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21243 (defun org-wrap (string &optional width lines)
21244 "Wrap string to either a number of lines, or a width in characters.
21245 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21246 that costs. If there is a word longer than WIDTH, the text is actually
21247 wrapped to the length of that word.
21248 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21249 many lines, whatever width that takes.
21250 The return value is a list of lines, without newlines at the end."
21251 (let* ((words (org-split-string string "[ \t\n]+"))
21252 (maxword (apply 'max (mapcar 'org-string-width words)))
21253 w ll)
21254 (cond (width
21255 (org-do-wrap words (max maxword width)))
21256 (lines
21257 (setq w maxword)
21258 (setq ll (org-do-wrap words maxword))
21259 (if (<= (length ll) lines)
21261 (setq ll words)
21262 (while (> (length ll) lines)
21263 (setq w (1+ w))
21264 (setq ll (org-do-wrap words w)))
21265 ll))
21266 (t (error "Cannot wrap this")))))
21268 (defun org-do-wrap (words width)
21269 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21270 (let (lines line)
21271 (while words
21272 (setq line (pop words))
21273 (while (and words (< (+ (length line) (length (car words))) width))
21274 (setq line (concat line " " (pop words))))
21275 (setq lines (push line lines)))
21276 (nreverse lines)))
21278 (defun org-split-string (string &optional separators)
21279 "Splits STRING into substrings at SEPARATORS.
21280 No empty strings are returned if there are matches at the beginning
21281 and end of string."
21282 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21283 (start 0)
21284 notfirst
21285 (list nil))
21286 (while (and (string-match rexp string
21287 (if (and notfirst
21288 (= start (match-beginning 0))
21289 (< start (length string)))
21290 (1+ start) start))
21291 (< (match-beginning 0) (length string)))
21292 (setq notfirst t)
21293 (or (eq (match-beginning 0) 0)
21294 (and (eq (match-beginning 0) (match-end 0))
21295 (eq (match-beginning 0) start))
21296 (setq list
21297 (cons (substring string start (match-beginning 0))
21298 list)))
21299 (setq start (match-end 0)))
21300 (or (eq start (length string))
21301 (setq list
21302 (cons (substring string start)
21303 list)))
21304 (nreverse list)))
21306 (defun org-quote-vert (s)
21307 "Replace \"|\" with \"\\vert\"."
21308 (while (string-match "|" s)
21309 (setq s (replace-match "\\vert" t t s)))
21312 (defun org-uuidgen-p (s)
21313 "Is S an ID created by UUIDGEN?"
21314 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21316 (defun org-in-src-block-p (&optional inside)
21317 "Whether point is in a code source block.
21318 When INSIDE is non-nil, don't consider we are within a src block
21319 when point is at #+BEGIN_SRC or #+END_SRC."
21320 (let ((case-fold-search t) ov)
21321 (or (and (setq ov (overlays-at (point)))
21322 (memq 'org-block-background
21323 (overlay-properties (car ov))))
21324 (and (not inside)
21325 (save-match-data
21326 (save-excursion
21327 (beginning-of-line)
21328 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21330 (defun org-context ()
21331 "Return a list of contexts of the current cursor position.
21332 If several contexts apply, all are returned.
21333 Each context entry is a list with a symbol naming the context, and
21334 two positions indicating start and end of the context. Possible
21335 contexts are:
21337 :headline anywhere in a headline
21338 :headline-stars on the leading stars in a headline
21339 :todo-keyword on a TODO keyword (including DONE) in a headline
21340 :tags on the TAGS in a headline
21341 :priority on the priority cookie in a headline
21342 :item on the first line of a plain list item
21343 :item-bullet on the bullet/number of a plain list item
21344 :checkbox on the checkbox in a plain list item
21345 :table in an org-mode table
21346 :table-special on a special filed in a table
21347 :table-table in a table.el table
21348 :clocktable in a clocktable
21349 :src-block in a source block
21350 :link on a hyperlink
21351 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21352 :target on a <<target>>
21353 :radio-target on a <<<radio-target>>>
21354 :latex-fragment on a LaTeX fragment
21355 :latex-preview on a LaTeX fragment with overlaid preview image
21357 This function expects the position to be visible because it uses font-lock
21358 faces as a help to recognize the following contexts: :table-special, :link,
21359 and :keyword."
21360 (let* ((f (get-text-property (point) 'face))
21361 (faces (if (listp f) f (list f)))
21362 (case-fold-search t)
21363 (p (point)) clist o)
21364 ;; First the large context
21365 (cond
21366 ((org-at-heading-p t)
21367 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21368 (when (progn
21369 (beginning-of-line 1)
21370 (looking-at org-todo-line-tags-regexp))
21371 (push (org-point-in-group p 1 :headline-stars) clist)
21372 (push (org-point-in-group p 2 :todo-keyword) clist)
21373 (push (org-point-in-group p 4 :tags) clist))
21374 (goto-char p)
21375 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21376 (if (looking-at "\\[#[A-Z0-9]\\]")
21377 (push (org-point-in-group p 0 :priority) clist)))
21379 ((org-at-item-p)
21380 (push (org-point-in-group p 2 :item-bullet) clist)
21381 (push (list :item (point-at-bol)
21382 (save-excursion (org-end-of-item) (point)))
21383 clist)
21384 (and (org-at-item-checkbox-p)
21385 (push (org-point-in-group p 0 :checkbox) clist)))
21387 ((org-at-table-p)
21388 (push (list :table (org-table-begin) (org-table-end)) clist)
21389 (if (memq 'org-formula faces)
21390 (push (list :table-special
21391 (previous-single-property-change p 'face)
21392 (next-single-property-change p 'face)) clist)))
21393 ((org-at-table-p 'any)
21394 (push (list :table-table) clist)))
21395 (goto-char p)
21397 (let ((case-fold-search t))
21398 ;; New the "medium" contexts: clocktables, source blocks
21399 (cond ((org-in-clocktable-p)
21400 (push (list :clocktable
21401 (and (or (looking-at "#\\+BEGIN: clocktable")
21402 (search-backward "#+BEGIN: clocktable" nil t))
21403 (match-beginning 0))
21404 (and (re-search-forward "#\\+END:?" nil t)
21405 (match-end 0))) clist))
21406 ((org-in-src-block-p)
21407 (push (list :src-block
21408 (and (or (looking-at "#\\+BEGIN_SRC")
21409 (search-backward "#+BEGIN_SRC" nil t))
21410 (match-beginning 0))
21411 (and (search-forward "#+END_SRC" nil t)
21412 (match-beginning 0))) clist))))
21413 (goto-char p)
21415 ;; Now the small context
21416 (cond
21417 ((org-at-timestamp-p)
21418 (push (org-point-in-group p 0 :timestamp) clist))
21419 ((memq 'org-link faces)
21420 (push (list :link
21421 (previous-single-property-change p 'face)
21422 (next-single-property-change p 'face)) clist))
21423 ((memq 'org-special-keyword faces)
21424 (push (list :keyword
21425 (previous-single-property-change p 'face)
21426 (next-single-property-change p 'face)) clist))
21427 ((org-at-target-p)
21428 (push (org-point-in-group p 0 :target) clist)
21429 (goto-char (1- (match-beginning 0)))
21430 (if (looking-at org-radio-target-regexp)
21431 (push (org-point-in-group p 0 :radio-target) clist))
21432 (goto-char p))
21433 ((setq o (car (delq nil
21434 (mapcar
21435 (lambda (x)
21436 (if (memq x org-latex-fragment-image-overlays) x))
21437 (overlays-at (point))))))
21438 (push (list :latex-fragment
21439 (overlay-start o) (overlay-end o)) clist)
21440 (push (list :latex-preview
21441 (overlay-start o) (overlay-end o)) clist))
21442 ((org-inside-LaTeX-fragment-p)
21443 ;; FIXME: positions wrong.
21444 (push (list :latex-fragment (point) (point)) clist)))
21446 (setq clist (nreverse (delq nil clist)))
21447 clist))
21449 ;; FIXME: Compare with at-regexp-p Do we need both?
21450 (defun org-in-regexp (re &optional nlines visually)
21451 "Check if point is inside a match of regexp.
21452 Normally only the current line is checked, but you can include NLINES extra
21453 lines both before and after point into the search.
21454 If VISUALLY is set, require that the cursor is not after the match but
21455 really on, so that the block visually is on the match."
21456 (catch 'exit
21457 (let ((pos (point))
21458 (eol (point-at-eol (+ 1 (or nlines 0))))
21459 (inc (if visually 1 0)))
21460 (save-excursion
21461 (beginning-of-line (- 1 (or nlines 0)))
21462 (while (re-search-forward re eol t)
21463 (if (and (<= (match-beginning 0) pos)
21464 (>= (+ inc (match-end 0)) pos))
21465 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21467 (defun org-at-regexp-p (regexp)
21468 "Is point inside a match of REGEXP in the current line?"
21469 (catch 'exit
21470 (save-excursion
21471 (let ((pos (point)) (end (point-at-eol)))
21472 (beginning-of-line 1)
21473 (while (re-search-forward regexp end t)
21474 (if (and (<= (match-beginning 0) pos)
21475 (>= (match-end 0) pos))
21476 (throw 'exit t)))
21477 nil))))
21479 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21480 "Non-nil when point is between matches of START-RE and END-RE.
21482 Also return a non-nil value when point is on one of the matches.
21484 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21485 buffer positions. Default values are the positions of headlines
21486 surrounding the point.
21488 The functions returns a cons cell whose car (resp. cdr) is the
21489 position before START-RE (resp. after END-RE)."
21490 (save-match-data
21491 (let ((pos (point))
21492 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21493 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21494 beg end)
21495 (save-excursion
21496 ;; Point is on a block when on START-RE or if START-RE can be
21497 ;; found before it...
21498 (and (or (org-at-regexp-p start-re)
21499 (re-search-backward start-re limit-up t))
21500 (setq beg (match-beginning 0))
21501 ;; ... and END-RE after it...
21502 (goto-char (match-end 0))
21503 (re-search-forward end-re limit-down t)
21504 (> (setq end (match-end 0)) pos)
21505 ;; ... without another START-RE in-between.
21506 (goto-char (match-beginning 0))
21507 (not (re-search-backward start-re (1+ beg) t))
21508 ;; Return value.
21509 (cons beg end))))))
21511 (defun org-in-block-p (names)
21512 "Non-nil when point belongs to a block whose name belongs to NAMES.
21514 NAMES is a list of strings containing names of blocks.
21516 Return first block name matched, or nil. Beware that in case of
21517 nested blocks, the returned name may not belong to the closest
21518 block from point."
21519 (save-match-data
21520 (catch 'exit
21521 (let ((case-fold-search t)
21522 (lim-up (save-excursion (outline-previous-heading)))
21523 (lim-down (save-excursion (outline-next-heading))))
21524 (mapc (lambda (name)
21525 (let ((n (regexp-quote name)))
21526 (when (org-between-regexps-p
21527 (concat "^[ \t]*#\\+begin_" n)
21528 (concat "^[ \t]*#\\+end_" n)
21529 lim-up lim-down)
21530 (throw 'exit n))))
21531 names))
21532 nil)))
21534 (defun org-occur-in-agenda-files (regexp &optional nlines)
21535 "Call `multi-occur' with buffers for all agenda files."
21536 (interactive "sOrg-files matching: \np")
21537 (let* ((files (org-agenda-files))
21538 (tnames (mapcar 'file-truename files))
21539 (extra org-agenda-text-search-extra-files)
21541 (when (eq (car extra) 'agenda-archives)
21542 (setq extra (cdr extra))
21543 (setq files (org-add-archive-files files)))
21544 (while (setq f (pop extra))
21545 (unless (member (file-truename f) tnames)
21546 (add-to-list 'files f 'append)
21547 (add-to-list 'tnames (file-truename f) 'append)))
21548 (multi-occur
21549 (mapcar (lambda (x)
21550 (with-current-buffer
21551 (or (get-file-buffer x) (find-file-noselect x))
21552 (widen)
21553 (current-buffer)))
21554 files)
21555 regexp)))
21557 (if (boundp 'occur-mode-find-occurrence-hook)
21558 ;; Emacs 23
21559 (add-hook 'occur-mode-find-occurrence-hook
21560 (lambda ()
21561 (when (derived-mode-p 'org-mode)
21562 (org-reveal))))
21563 ;; Emacs 22
21564 (defadvice occur-mode-goto-occurrence
21565 (after org-occur-reveal activate)
21566 (and (derived-mode-p 'org-mode) (org-reveal)))
21567 (defadvice occur-mode-goto-occurrence-other-window
21568 (after org-occur-reveal activate)
21569 (and (derived-mode-p 'org-mode) (org-reveal)))
21570 (defadvice occur-mode-display-occurrence
21571 (after org-occur-reveal activate)
21572 (when (derived-mode-p 'org-mode)
21573 (let ((pos (occur-mode-find-occurrence)))
21574 (with-current-buffer (marker-buffer pos)
21575 (save-excursion
21576 (goto-char pos)
21577 (org-reveal)))))))
21579 (defun org-occur-link-in-agenda-files ()
21580 "Create a link and search for it in the agendas.
21581 The link is not stored in `org-stored-links', it is just created
21582 for the search purpose."
21583 (interactive)
21584 (let ((link (condition-case nil
21585 (org-store-link nil)
21586 (error "Unable to create a link to here"))))
21587 (org-occur-in-agenda-files (regexp-quote link))))
21589 (defun org-reverse-string (string)
21590 "Return the reverse of STRING."
21591 (apply 'string (reverse (string-to-list string))))
21593 (defsubst org-uniquify (list)
21594 "Non-destructively remove duplicate elements from LIST."
21595 (let ((res (copy-seq list))) (delete-dups res)))
21597 (defun org-uniquify-alist (alist)
21598 "Merge elements of ALIST with the same key.
21600 For example, in this alist:
21602 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21603 => '((a 1 3) (b 2))
21605 merge (a 1) and (a 3) into (a 1 3).
21607 The function returns the new ALIST."
21608 (let (rtn)
21609 (mapc
21610 (lambda (e)
21611 (let (n)
21612 (if (not (assoc (car e) rtn))
21613 (push e rtn)
21614 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21615 (setq rtn (assq-delete-all (car e) rtn))
21616 (push n rtn))))
21617 alist)
21618 rtn))
21620 (defun org-delete-all (elts list)
21621 "Remove all elements in ELTS from LIST."
21622 (while elts
21623 (setq list (delete (pop elts) list)))
21624 list)
21626 (defun org-count (cl-item cl-seq)
21627 "Count the number of occurrences of ITEM in SEQ.
21628 Taken from `count' in cl-seq.el with all keyword arguments removed."
21629 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21630 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21631 (while (< cl-start cl-end)
21632 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21633 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21634 (setq cl-start (1+ cl-start)))
21635 cl-count))
21637 (defun org-remove-if (predicate seq)
21638 "Remove everything from SEQ that fulfills PREDICATE."
21639 (let (res e)
21640 (while seq
21641 (setq e (pop seq))
21642 (if (not (funcall predicate e)) (push e res)))
21643 (nreverse res)))
21645 (defun org-remove-if-not (predicate seq)
21646 "Remove everything from SEQ that does not fulfill PREDICATE."
21647 (let (res e)
21648 (while seq
21649 (setq e (pop seq))
21650 (if (funcall predicate e) (push e res)))
21651 (nreverse res)))
21653 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21654 "Reduce two-argument FUNCTION across SEQ.
21655 Taken from `reduce' in cl-seq.el with all keyword arguments but
21656 \":initial-value\" removed."
21657 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21658 (cadr (memq :initial-value cl-keys)))
21659 (cl-seq (pop cl-seq))
21660 (t (funcall cl-func)))))
21661 (while cl-seq
21662 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21663 cl-accum))
21665 (defun org-back-over-empty-lines ()
21666 "Move backwards over whitespace, to the beginning of the first empty line.
21667 Returns the number of empty lines passed."
21668 (let ((pos (point)))
21669 (if (cdr (assoc 'heading org-blank-before-new-entry))
21670 (skip-chars-backward " \t\n\r")
21671 (unless (eobp)
21672 (forward-line -1)))
21673 (beginning-of-line 2)
21674 (goto-char (min (point) pos))
21675 (count-lines (point) pos)))
21677 (defun org-skip-whitespace ()
21678 (skip-chars-forward " \t\n\r"))
21680 (defun org-point-in-group (point group &optional context)
21681 "Check if POINT is in match-group GROUP.
21682 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21683 match. If the match group does not exist or point is not inside it,
21684 return nil."
21685 (and (match-beginning group)
21686 (>= point (match-beginning group))
21687 (<= point (match-end group))
21688 (if context
21689 (list context (match-beginning group) (match-end group))
21690 t)))
21692 (defun org-switch-to-buffer-other-window (&rest args)
21693 "Switch to buffer in a second window on the current frame.
21694 In particular, do not allow pop-up frames.
21695 Returns the newly created buffer."
21696 (org-no-popups
21697 (apply 'switch-to-buffer-other-window args)))
21699 (defun org-combine-plists (&rest plists)
21700 "Create a single property list from all plists in PLISTS.
21701 The process starts by copying the first list, and then setting properties
21702 from the other lists. Settings in the last list are the most significant
21703 ones and overrule settings in the other lists."
21704 (let ((rtn (copy-sequence (pop plists)))
21705 p v ls)
21706 (while plists
21707 (setq ls (pop plists))
21708 (while ls
21709 (setq p (pop ls) v (pop ls))
21710 (setq rtn (plist-put rtn p v))))
21711 rtn))
21713 (defun org-replace-escapes (string table)
21714 "Replace %-escapes in STRING with values in TABLE.
21715 TABLE is an association list with keys like \"%a\" and string values.
21716 The sequences in STRING may contain normal field width and padding information,
21717 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21718 so values can contain further %-escapes if they are define later in TABLE."
21719 (let ((tbl (copy-alist table))
21720 (case-fold-search nil)
21721 (pchg 0)
21722 e re rpl)
21723 (while (setq e (pop tbl))
21724 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21725 (when (and (cdr e) (string-match re (cdr e)))
21726 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21727 (safe "SREF"))
21728 (add-text-properties 0 3 (list 'sref sref) safe)
21729 (setcdr e (replace-match safe t t (cdr e)))))
21730 (while (string-match re string)
21731 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21732 (cdr e)))
21733 (setq string (replace-match rpl t t string))))
21734 (while (setq pchg (next-property-change pchg string))
21735 (let ((sref (get-text-property pchg 'sref string)))
21736 (when (and sref (string-match "SREF" string pchg))
21737 (setq string (replace-match sref t t string)))))
21738 string))
21740 (defun org-sublist (list start end)
21741 "Return a section of LIST, from START to END.
21742 Counting starts at 1."
21743 (let (rtn (c start))
21744 (setq list (nthcdr (1- start) list))
21745 (while (and list (<= c end))
21746 (push (pop list) rtn)
21747 (setq c (1+ c)))
21748 (nreverse rtn)))
21750 (defun org-find-base-buffer-visiting (file)
21751 "Like `find-buffer-visiting' but always return the base buffer and
21752 not an indirect buffer."
21753 (let ((buf (or (get-file-buffer file)
21754 (find-buffer-visiting file))))
21755 (if buf
21756 (or (buffer-base-buffer buf) buf)
21757 nil)))
21759 (defun org-image-file-name-regexp (&optional extensions)
21760 "Return regexp matching the file names of images.
21761 If EXTENSIONS is given, only match these."
21762 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21763 (image-file-name-regexp)
21764 (let ((image-file-name-extensions
21765 (or extensions
21766 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21767 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21768 (concat "\\."
21769 (regexp-opt (nconc (mapcar 'upcase
21770 image-file-name-extensions)
21771 image-file-name-extensions)
21773 "\\'"))))
21775 (defun org-file-image-p (file &optional extensions)
21776 "Return non-nil if FILE is an image."
21777 (save-match-data
21778 (string-match (org-image-file-name-regexp extensions) file)))
21780 (defun org-get-cursor-date (&optional with-time)
21781 "Return the date at cursor in as a time.
21782 This works in the calendar and in the agenda, anywhere else it just
21783 returns the current time.
21784 If WITH-TIME is non-nil, returns the time of the event at point (in
21785 the agenda) or the current time of the day."
21786 (let (date day defd tp tm hod mod)
21787 (when with-time
21788 (setq tp (get-text-property (point) 'time))
21789 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21790 (setq hod (string-to-number (match-string 1 tp))
21791 mod (string-to-number (match-string 2 tp))))
21792 (or tp (setq hod (nth 2 (decode-time (current-time)))
21793 mod (nth 1 (decode-time (current-time))))))
21794 (cond
21795 ((eq major-mode 'calendar-mode)
21796 (setq date (calendar-cursor-to-date)
21797 defd (encode-time 0 (or mod 0) (or hod 0)
21798 (nth 1 date) (nth 0 date) (nth 2 date))))
21799 ((eq major-mode 'org-agenda-mode)
21800 (setq day (get-text-property (point) 'day))
21801 (if day
21802 (setq date (calendar-gregorian-from-absolute day)
21803 defd (encode-time 0 (or mod 0) (or hod 0)
21804 (nth 1 date) (nth 0 date) (nth 2 date))))))
21805 (or defd (current-time))))
21807 (defun org-mark-subtree (&optional up)
21808 "Mark the current subtree.
21809 This puts point at the start of the current subtree, and mark at
21810 the end. If a numeric prefix UP is given, move up into the
21811 hierarchy of headlines by UP levels before marking the subtree."
21812 (interactive "P")
21813 (org-with-limited-levels
21814 (cond ((org-at-heading-p) (beginning-of-line))
21815 ((org-before-first-heading-p) (error "Not in a subtree"))
21816 (t (outline-previous-visible-heading 1))))
21817 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21818 (if (org-called-interactively-p 'any)
21819 (call-interactively 'org-mark-element)
21820 (org-mark-element)))
21823 ;;; Indentation
21825 (defun org-indent-line ()
21826 "Indent line depending on context."
21827 (interactive)
21828 (let* ((pos (point))
21829 (itemp (org-at-item-p))
21830 (case-fold-search t)
21831 (org-drawer-regexp (or org-drawer-regexp "\000"))
21832 (inline-task-p (and (featurep 'org-inlinetask)
21833 (org-inlinetask-in-task-p)))
21834 (inline-re (and inline-task-p
21835 (org-inlinetask-outline-regexp)))
21836 column)
21837 (if (and orgstruct-is-++ (eq pos (point)))
21838 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21839 (indent-according-to-mode))
21840 (beginning-of-line 1)
21841 (cond
21842 ;; Headings
21843 ((looking-at org-outline-regexp) (setq column 0))
21844 ;; Footnote definition
21845 ((looking-at org-footnote-definition-re) (setq column 0))
21846 ;; Literal examples
21847 ((looking-at "[ \t]*:\\( \\|$\\)")
21848 (setq column (org-get-indentation))) ; do nothing
21849 ;; Lists
21850 ((ignore-errors (goto-char (org-in-item-p)))
21851 (setq column (if itemp
21852 (org-get-indentation)
21853 (org-list-item-body-column (point))))
21854 (goto-char pos))
21855 ;; Drawers
21856 ((and (looking-at "[ \t]*:END:")
21857 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21858 (save-excursion
21859 (goto-char (1- (match-beginning 1)))
21860 (setq column (current-column))))
21861 ;; Special blocks
21862 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21863 (save-excursion
21864 (re-search-backward
21865 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21866 (setq column (org-get-indentation (match-string 0))))
21867 ((and (not (looking-at "[ \t]*#\\+begin_"))
21868 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21869 (save-excursion
21870 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21871 (setq column
21872 (cond ((equal (downcase (match-string 1)) "src")
21873 ;; src blocks: let `org-edit-src-exit' handle them
21874 (org-get-indentation))
21875 ((equal (downcase (match-string 1)) "example")
21876 (max (org-get-indentation)
21877 (org-get-indentation (match-string 0))))
21879 (org-get-indentation (match-string 0))))))
21880 ;; This line has nothing special, look at the previous relevant
21881 ;; line to compute indentation
21883 (beginning-of-line 0)
21884 (while (and (not (bobp))
21885 (not (looking-at org-table-line-regexp))
21886 (not (looking-at org-drawer-regexp))
21887 ;; When point started in an inline task, do not move
21888 ;; above task starting line.
21889 (not (and inline-task-p (looking-at inline-re)))
21890 ;; Skip drawers, blocks, empty lines, verbatim,
21891 ;; comments, tables, footnotes definitions, lists,
21892 ;; inline tasks.
21893 (or (and (looking-at "[ \t]*:END:")
21894 (re-search-backward org-drawer-regexp nil t))
21895 (and (looking-at "[ \t]*#\\+end_")
21896 (re-search-backward "[ \t]*#\\+begin_"nil t))
21897 (looking-at "[ \t]*[\n:#|]")
21898 (looking-at org-footnote-definition-re)
21899 (and (not inline-task-p)
21900 (featurep 'org-inlinetask)
21901 (org-inlinetask-in-task-p)
21902 (or (org-inlinetask-goto-beginning) t))))
21903 (beginning-of-line 0))
21904 (cond
21905 ;; There was a list item above.
21906 ((save-excursion
21907 (and (ignore-errors (goto-char (org-in-item-p)))
21908 (goto-char
21909 (org-list-get-top-point (org-list-struct)))))
21910 (looking-at org-list-full-item-re)
21911 (setq column (length (match-string 0))))
21912 ;; There was an heading above.
21913 ((looking-at "\\*+[ \t]+")
21914 (if (not org-adapt-indentation)
21915 (setq column 0)
21916 (goto-char (match-end 0))
21917 (setq column (current-column))))
21918 ;; A drawer had started and is unfinished
21919 ((looking-at org-drawer-regexp)
21920 (goto-char (1- (match-beginning 1)))
21921 (setq column (current-column)))
21922 ;; Else, nothing noticeable found: get indentation and go on.
21923 (t (setq column (org-get-indentation))))))
21924 ;; Now apply indentation and move cursor accordingly
21925 (goto-char pos)
21926 (if (<= (current-column) (current-indentation))
21927 (org-indent-line-to column)
21928 (save-excursion (org-indent-line-to column)))
21929 ;; Special polishing for properties, see `org-property-format'
21930 (setq column (current-column))
21931 (beginning-of-line 1)
21932 (if (looking-at
21933 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21934 (replace-match (concat (match-string 1)
21935 (format org-property-format
21936 (match-string 2) (match-string 3)))
21937 t t))
21938 (org-move-to-column column))))
21940 (defun org-indent-drawer ()
21941 "Indent the drawer at point."
21942 (interactive)
21943 (let ((p (point))
21944 (e (and (save-excursion (re-search-forward ":END:" nil t))
21945 (match-end 0)))
21946 (folded
21947 (save-excursion
21948 (end-of-line)
21949 (when (overlays-at (point))
21950 (member 'invisible (overlay-properties
21951 (car (overlays-at (point)))))))))
21952 (when folded (org-cycle))
21953 (indent-for-tab-command)
21954 (while (and (move-beginning-of-line 2) (< (point) e))
21955 (indent-for-tab-command))
21956 (goto-char p)
21957 (when folded (org-cycle)))
21958 (message "Drawer at point indented"))
21960 (defun org-indent-block ()
21961 "Indent the block at point."
21962 (interactive)
21963 (let ((p (point))
21964 (case-fold-search t)
21965 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21966 (match-end 0)))
21967 (folded
21968 (save-excursion
21969 (end-of-line)
21970 (when (overlays-at (point))
21971 (member 'invisible (overlay-properties
21972 (car (overlays-at (point)))))))))
21973 (when folded (org-cycle))
21974 (indent-for-tab-command)
21975 (while (and (move-beginning-of-line 2) (< (point) e))
21976 (indent-for-tab-command))
21977 (goto-char p)
21978 (when folded (org-cycle)))
21979 (message "Block at point indented"))
21981 (defun org-indent-region (start end)
21982 "Indent region."
21983 (interactive "r")
21984 (save-excursion
21985 (let ((line-end (org-current-line end)))
21986 (goto-char start)
21987 (while (< (org-current-line) line-end)
21988 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21989 (t (call-interactively 'org-indent-line)))
21990 (move-beginning-of-line 2)))))
21993 ;;; Filling
21995 ;; We use our own fill-paragraph and auto-fill functions.
21997 ;; `org-fill-paragraph' relies on adaptive filling and context
21998 ;; checking. Appropriate `fill-prefix' is computed with
21999 ;; `org-adaptive-fill-function'.
22001 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22002 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22003 ;; `org-adaptive-fill-function' value. Internally,
22004 ;; `org-comment-line-break-function' breaks the line.
22006 ;; `org-setup-filling' installs filling and auto-filling related
22007 ;; variables during `org-mode' initialization.
22009 (defun org-setup-filling ()
22010 (interactive)
22011 ;; Prevent auto-fill from inserting unwanted new items.
22012 (when (boundp 'fill-nobreak-predicate)
22013 (org-set-local
22014 'fill-nobreak-predicate
22015 (org-uniquify
22016 (append fill-nobreak-predicate
22017 '(org-fill-paragraph-separate-nobreak-p
22018 org-fill-line-break-nobreak-p
22019 org-fill-paragraph-with-timestamp-nobreak-p)))))
22020 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22021 (org-set-local 'auto-fill-inhibit-regexp nil)
22022 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22023 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22024 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22026 (defvar org-element-paragraph-separate) ; org-element.el
22027 (defun org-fill-paragraph-separate-nobreak-p ()
22028 "Non-nil when a line break at point would insert a new item."
22029 (looking-at (substring org-element-paragraph-separate 1)))
22031 (defun org-fill-line-break-nobreak-p ()
22032 "Non-nil when a line break at point would create an Org line break."
22033 (save-excursion
22034 (skip-chars-backward "[ \t]")
22035 (skip-chars-backward "\\\\")
22036 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22038 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22039 "Non-nil when a line break at point would insert a new item."
22040 (and (org-at-timestamp-p t)
22041 (not (looking-at org-ts-regexp-both))))
22043 (declare-function message-in-body-p "message" ())
22044 (defvar orgtbl-line-start-regexp) ; From org-table.el
22045 (defun org-adaptive-fill-function ()
22046 "Compute a fill prefix for the current line.
22047 Return fill prefix, as a string, or nil if current line isn't
22048 meant to be filled."
22049 (let (prefix)
22050 (catch 'exit
22051 (when (derived-mode-p 'message-mode)
22052 (save-excursion
22053 (beginning-of-line)
22054 (cond ((or (not (message-in-body-p))
22055 (looking-at orgtbl-line-start-regexp))
22056 (throw 'exit nil))
22057 ((looking-at message-cite-prefix-regexp)
22058 (throw 'exit (match-string-no-properties 0)))
22059 ((looking-at org-outline-regexp)
22060 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22061 (org-with-wide-buffer
22062 (let* ((p (line-beginning-position))
22063 (element (save-excursion
22064 (beginning-of-line)
22065 (or (ignore-errors (org-element-at-point))
22066 (user-error "An element cannot be parsed line %d"
22067 (line-number-at-pos (point))))))
22068 (type (org-element-type element))
22069 (post-affiliated (org-element-property :post-affiliated element)))
22070 (unless (and post-affiliated (< p post-affiliated))
22071 (case type
22072 (comment (looking-at "[ \t]*# ?") (match-string 0))
22073 (footnote-definition "")
22074 ((item plain-list)
22075 (make-string (org-list-item-body-column
22076 (or post-affiliated
22077 (org-element-property :begin element)))
22078 ? ))
22079 (paragraph
22080 ;; Fill prefix is usually the same as the current line,
22081 ;; except if the paragraph is at the beginning of an item.
22082 (let ((parent (org-element-property :parent element)))
22083 (cond ((eq (org-element-type parent) 'item)
22084 (make-string (org-list-item-body-column
22085 (org-element-property :begin parent))
22086 ? ))
22087 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22088 (match-string 0))
22089 (t ""))))
22090 (comment-block
22091 ;; Only fill contents if P is within block boundaries.
22092 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22093 (forward-line)
22094 (point)))
22095 (cend (save-excursion
22096 (goto-char (org-element-property :end element))
22097 (skip-chars-backward " \r\t\n")
22098 (line-beginning-position))))
22099 (when (and (>= p cbeg) (< p cend))
22100 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22101 (match-string 0)
22102 "")))))))))))
22104 (declare-function message-goto-body "message" ())
22105 (defvar message-cite-prefix-regexp) ; From message.el
22106 (defun org-fill-paragraph (&optional justify)
22107 "Fill element at point, when applicable.
22109 This function only applies to comment blocks, comments, example
22110 blocks and paragraphs. Also, as a special case, re-align table
22111 when point is at one.
22113 If JUSTIFY is non-nil (interactively, with prefix argument),
22114 justify as well. If `sentence-end-double-space' is non-nil, then
22115 period followed by one space does not end a sentence, so don't
22116 break a line there. The variable `fill-column' controls the
22117 width for filling.
22119 For convenience, when point is at a plain list, an item or
22120 a footnote definition, try to fill the first paragraph within."
22121 (interactive)
22122 (if (and (derived-mode-p 'message-mode)
22123 (or (not (message-in-body-p))
22124 (save-excursion (move-beginning-of-line 1)
22125 (looking-at message-cite-prefix-regexp))))
22126 ;; First ensure filling is correct in message-mode.
22127 (let ((fill-paragraph-function
22128 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22129 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22130 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22131 (paragraph-separate
22132 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22133 (fill-paragraph nil))
22134 (with-syntax-table org-mode-transpose-word-syntax-table
22135 ;; Move to end of line in order to get the first paragraph
22136 ;; within a plain list or a footnote definition.
22137 (let ((element (save-excursion
22138 (end-of-line)
22139 (or (ignore-errors (org-element-at-point))
22140 (user-error "An element cannot be parsed line %d"
22141 (line-number-at-pos (point)))))))
22142 ;; First check if point is in a blank line at the beginning of
22143 ;; the buffer. In that case, ignore filling.
22144 (case (org-element-type element)
22145 ;; Use major mode filling function is src blocks.
22146 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22147 ;; Align Org tables, leave table.el tables as-is.
22148 (table-row (org-table-align) t)
22149 (table
22150 (when (eq (org-element-property :type element) 'org)
22151 (org-table-align))
22153 (paragraph
22154 ;; Paragraphs may contain `line-break' type objects.
22155 (let ((beg (max (point-min)
22156 (org-element-property :contents-begin element)))
22157 (end (min (point-max)
22158 (org-element-property :contents-end element))))
22159 ;; Do nothing if point is at an affiliated keyword.
22160 (if (< (line-end-position) beg) t
22161 (when (derived-mode-p 'message-mode)
22162 ;; In `message-mode', do not fill following citation
22163 ;; in current paragraph nor text before message body.
22164 (let ((body-start (save-excursion (message-goto-body))))
22165 (when body-start (setq beg (max body-start beg))))
22166 (when (save-excursion
22167 (re-search-forward
22168 (concat "^" message-cite-prefix-regexp) end t))
22169 (setq end (match-beginning 0))))
22170 ;; Fill paragraph, taking line breaks into account.
22171 ;; For that, slice the paragraph using line breaks as
22172 ;; separators, and fill the parts in reverse order to
22173 ;; avoid messing with markers.
22174 (save-excursion
22175 (goto-char end)
22176 (mapc
22177 (lambda (pos)
22178 (fill-region-as-paragraph pos (point) justify)
22179 (goto-char pos))
22180 ;; Find the list of ending positions for line breaks
22181 ;; in the current paragraph. Add paragraph
22182 ;; beginning to include first slice.
22183 (nreverse
22184 (cons beg
22185 (org-element-map
22186 (org-element--parse-objects
22187 beg end nil (org-element-restriction 'paragraph))
22188 'line-break
22189 (lambda (lb) (org-element-property :end lb)))))))
22190 t)))
22191 ;; Contents of `comment-block' type elements should be
22192 ;; filled as plain text, but only if point is within block
22193 ;; markers.
22194 (comment-block
22195 (let* ((case-fold-search t)
22196 (beg (save-excursion
22197 (goto-char (org-element-property :begin element))
22198 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22199 (forward-line)
22200 (point)))
22201 (end (save-excursion
22202 (goto-char (org-element-property :end element))
22203 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22204 (line-beginning-position))))
22205 (when (and (>= (point) beg) (< (point) end))
22206 (fill-region-as-paragraph
22207 (save-excursion
22208 (end-of-line)
22209 (re-search-backward "^[ \t]*$" beg 'move)
22210 (line-beginning-position))
22211 (save-excursion
22212 (beginning-of-line)
22213 (re-search-forward "^[ \t]*$" end 'move)
22214 (line-beginning-position))
22215 justify)))
22217 ;; Fill comments.
22218 (comment (fill-comment-paragraph justify))
22219 ;; Ignore every other element.
22220 (otherwise t))))))
22222 (defun org-auto-fill-function ()
22223 "Auto-fill function."
22224 ;; Check if auto-filling is meaningful.
22225 (let ((fc (current-fill-column)))
22226 (when (and fc (> (current-column) fc))
22227 (let* ((fill-prefix (org-adaptive-fill-function))
22228 ;; Enforce empty fill prefix, if required. Otherwise, it
22229 ;; will be computed again.
22230 (adaptive-fill-mode (not (equal fill-prefix ""))))
22231 (when fill-prefix (do-auto-fill))))))
22233 (defun org-comment-line-break-function (&optional soft)
22234 "Break line at point and indent, continuing comment if within one.
22235 The inserted newline is marked hard if variable
22236 `use-hard-newlines' is true, unless optional argument SOFT is
22237 non-nil."
22238 (if soft (insert-and-inherit ?\n) (newline 1))
22239 (save-excursion (forward-char -1) (delete-horizontal-space))
22240 (delete-horizontal-space)
22241 (indent-to-left-margin)
22242 (insert-before-markers-and-inherit fill-prefix))
22245 ;;; Comments
22247 ;; Org comments syntax is quite complex. It requires the entire line
22248 ;; to be just a comment. Also, even with the right syntax at the
22249 ;; beginning of line, some some elements (i.e. verse-block or
22250 ;; example-block) don't accept comments. Usual Emacs comment commands
22251 ;; cannot cope with those requirements. Therefore, Org replaces them.
22253 ;; Org still relies on `comment-dwim', but cannot trust
22254 ;; `comment-only-p'. So, `comment-region-function' and
22255 ;; `uncomment-region-function' both point
22256 ;; to`org-comment-or-uncomment-region'. Eventually,
22257 ;; `org-insert-comment' takes care of insertion of comments at the
22258 ;; beginning of line.
22260 ;; `org-setup-comments-handling' install comments related variables
22261 ;; during `org-mode' initialization.
22263 (defun org-setup-comments-handling ()
22264 (interactive)
22265 (org-set-local 'comment-use-syntax nil)
22266 (org-set-local 'comment-start "# ")
22267 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22268 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22269 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22270 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22272 (defun org-insert-comment ()
22273 "Insert an empty comment above current line.
22274 If the line is empty, insert comment at its beginning."
22275 (beginning-of-line)
22276 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22277 (org-indent-line)
22278 (insert "# "))
22280 (defvar comment-empty-lines) ; From newcomment.el.
22281 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22282 "Comment or uncomment each non-blank line in the region.
22283 Uncomment each non-blank line between BEG and END if it only
22284 contains commented lines. Otherwise, comment them."
22285 (save-restriction
22286 ;; Restrict region
22287 (narrow-to-region (save-excursion (goto-char beg)
22288 (skip-chars-forward " \r\t\n" end)
22289 (line-beginning-position))
22290 (save-excursion (goto-char end)
22291 (skip-chars-backward " \r\t\n" beg)
22292 (line-end-position)))
22293 (let ((uncommentp
22294 ;; UNCOMMENTP is non-nil when every non blank line between
22295 ;; BEG and END is a comment.
22296 (save-excursion
22297 (goto-char (point-min))
22298 (while (and (not (eobp))
22299 (let ((element (org-element-at-point)))
22300 (and (eq (org-element-type element) 'comment)
22301 (goto-char (min (point-max)
22302 (org-element-property
22303 :end element)))))))
22304 (eobp))))
22305 (if uncommentp
22306 ;; Only blank lines and comments in region: uncomment it.
22307 (save-excursion
22308 (goto-char (point-min))
22309 (while (not (eobp))
22310 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22311 (replace-match "" nil nil nil 1))
22312 (forward-line)))
22313 ;; Comment each line in region.
22314 (let ((min-indent (point-max)))
22315 ;; First find the minimum indentation across all lines.
22316 (save-excursion
22317 (goto-char (point-min))
22318 (while (and (not (eobp)) (not (zerop min-indent)))
22319 (unless (looking-at "[ \t]*$")
22320 (setq min-indent (min min-indent (current-indentation))))
22321 (forward-line)))
22322 ;; Then loop over all lines.
22323 (save-excursion
22324 (goto-char (point-min))
22325 (while (not (eobp))
22326 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22327 ;; Don't get fooled by invisible text (e.g. link path)
22328 ;; when moving to column MIN-INDENT.
22329 (let ((buffer-invisibility-spec nil))
22330 (org-move-to-column min-indent t))
22331 (insert comment-start))
22332 (forward-line))))))))
22335 ;;; Planning
22337 ;; This section contains tools to operate on timestamp objects, as
22338 ;; returned by, e.g. `org-element-context'.
22340 (defun org-timestamp-has-time-p (timestamp)
22341 "Non-nil when TIMESTAMP has a time specified."
22342 (org-element-property :hour-start timestamp))
22344 (defun org-timestamp-format (timestamp format &optional end utc)
22345 "Format a TIMESTAMP element into a string.
22347 FORMAT is a format specifier to be passed to
22348 `format-time-string'.
22350 When optional argument END is non-nil, use end of date-range or
22351 time-range, if possible.
22353 When optional argument UTC is non-nil, time will be expressed as
22354 Universal Time."
22355 (format-time-string
22356 format
22357 (apply 'encode-time
22358 (cons 0
22359 (mapcar
22360 (lambda (prop) (or (org-element-property prop timestamp) 0))
22361 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22362 '(:minute-start :hour-start :day-start :month-start
22363 :year-start)))))
22364 utc))
22366 (defun org-timestamp-split-range (timestamp &optional end)
22367 "Extract a timestamp object from a date or time range.
22369 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22370 the end of the range. Otherwise, extract its start.
22372 Return a new timestamp object sharing the same parent as
22373 TIMESTAMP."
22374 (let ((type (org-element-property :type timestamp)))
22375 (if (memq type '(active inactive diary)) timestamp
22376 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22377 ;; Set new type.
22378 (org-element-put-property
22379 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22380 ;; Copy start properties over end properties if END is
22381 ;; non-nil. Otherwise, copy end properties over `start' ones.
22382 (let ((p-alist '((:minute-start . :minute-end)
22383 (:hour-start . :hour-end)
22384 (:day-start . :day-end)
22385 (:month-start . :month-end)
22386 (:year-start . :year-end))))
22387 (dolist (p-cell p-alist)
22388 (org-element-put-property
22389 split-ts
22390 (funcall (if end 'car 'cdr) p-cell)
22391 (org-element-property
22392 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22393 ;; Eventually refresh `:raw-value'.
22394 (org-element-put-property split-ts :raw-value nil)
22395 (org-element-put-property
22396 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22398 (defun org-timestamp-translate (timestamp &optional boundary)
22399 "Apply `org-translate-time' on a TIMESTAMP object.
22400 When optional argument BOUNDARY is non-nil, it is either the
22401 symbol `start' or `end'. In this case, only translate the
22402 starting or ending part of TIMESTAMP if it is a date or time
22403 range. Otherwise, translate both parts."
22404 (if (and (not boundary)
22405 (memq (org-element-property :type timestamp)
22406 '(active-range inactive-range)))
22407 (concat
22408 (org-translate-time
22409 (org-element-property :raw-value
22410 (org-timestamp-split-range timestamp)))
22411 "--"
22412 (org-translate-time
22413 (org-element-property :raw-value
22414 (org-timestamp-split-range timestamp t))))
22415 (org-translate-time
22416 (org-element-property
22417 :raw-value
22418 (if (not boundary) timestamp
22419 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22423 ;;; Other stuff.
22425 (defun org-toggle-fixed-width-section (arg)
22426 "Toggle the fixed-width export.
22427 If there is no active region, the QUOTE keyword at the current headline is
22428 inserted or removed. When present, it causes the text between this headline
22429 and the next to be exported as fixed-width text, and unmodified.
22430 If there is an active region, this command adds or removes a colon as the
22431 first character of this line. If the first character of a line is a colon,
22432 this line is also exported in fixed-width font."
22433 (interactive "P")
22434 (let* ((cc 0)
22435 (regionp (org-region-active-p))
22436 (beg (if regionp (region-beginning) (point)))
22437 (end (if regionp (region-end)))
22438 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22439 (case-fold-search nil)
22440 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22441 off)
22442 (if regionp
22443 (save-excursion
22444 (goto-char beg)
22445 (setq cc (current-column))
22446 (beginning-of-line 1)
22447 (setq off (looking-at re))
22448 (while (> nlines 0)
22449 (setq nlines (1- nlines))
22450 (beginning-of-line 1)
22451 (cond
22452 (arg
22453 (org-move-to-column cc t)
22454 (insert ": \n")
22455 (forward-line -1))
22456 ((and off (looking-at re))
22457 (replace-match "" t t nil 1))
22458 ((not off) (org-move-to-column cc t) (insert ": ")))
22459 (forward-line 1)))
22460 (save-excursion
22461 (org-back-to-heading)
22462 (cond
22463 ((looking-at (format org-heading-keyword-regexp-format
22464 org-quote-string))
22465 (goto-char (match-end 1))
22466 (looking-at (concat " +" org-quote-string))
22467 (replace-match "" t t)
22468 (when (eolp) (insert " ")))
22469 ((looking-at org-outline-regexp)
22470 (goto-char (match-end 0))
22471 (insert org-quote-string " ")))))))
22473 (defun org-reftex-citation ()
22474 "Use reftex-citation to insert a citation into the buffer.
22475 This looks for a line like
22477 #+BIBLIOGRAPHY: foo plain option:-d
22479 and derives from it that foo.bib is the bibliography file relevant
22480 for this document. It then installs the necessary environment for RefTeX
22481 to work in this buffer and calls `reftex-citation' to insert a citation
22482 into the buffer.
22484 Export of such citations to both LaTeX and HTML is handled by the contributed
22485 package org-exp-bibtex by Taru Karttunen."
22486 (interactive)
22487 (let ((reftex-docstruct-symbol 'rds)
22488 (reftex-cite-format "\\cite{%l}")
22489 rds bib)
22490 (save-excursion
22491 (save-restriction
22492 (widen)
22493 (let ((case-fold-search t)
22494 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22495 (if (not (save-excursion
22496 (or (re-search-forward re nil t)
22497 (re-search-backward re nil t))))
22498 (error "No bibliography defined in file")
22499 (setq bib (concat (match-string 1) ".bib")
22500 rds (list (list 'bib bib)))))))
22501 (call-interactively 'reftex-citation)))
22503 ;;;; Functions extending outline functionality
22505 (defun org-beginning-of-line (&optional arg)
22506 "Go to the beginning of the current line. If that is invisible, continue
22507 to a visible line beginning. This makes the function of C-a more intuitive.
22508 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22509 first attempt, and only move to after the tags when the cursor is already
22510 beyond the end of the headline."
22511 (interactive "P")
22512 (let ((pos (point))
22513 (special (if (consp org-special-ctrl-a/e)
22514 (car org-special-ctrl-a/e)
22515 org-special-ctrl-a/e))
22516 refpos)
22517 (if (org-bound-and-true-p visual-line-mode)
22518 (beginning-of-visual-line 1)
22519 (beginning-of-line 1))
22520 (if (and arg (fboundp 'move-beginning-of-line))
22521 (call-interactively 'move-beginning-of-line)
22522 (if (bobp)
22524 (backward-char 1)
22525 (if (org-truely-invisible-p)
22526 (while (and (not (bobp)) (org-truely-invisible-p))
22527 (backward-char 1)
22528 (beginning-of-line 1))
22529 (forward-char 1))))
22530 (when special
22531 (cond
22532 ((and (looking-at org-complex-heading-regexp)
22533 (= (char-after (match-end 1)) ?\ ))
22534 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22535 (point-at-eol)))
22536 (goto-char
22537 (if (eq special t)
22538 (cond ((> pos refpos) refpos)
22539 ((= pos (point)) refpos)
22540 (t (point)))
22541 (cond ((> pos (point)) (point))
22542 ((not (eq last-command this-command)) (point))
22543 (t refpos)))))
22544 ((org-at-item-p)
22545 ;; Being at an item and not looking at an the item means point
22546 ;; was previously moved to beginning of a visual line, which
22547 ;; doesn't contain the item. Therefore, do nothing special,
22548 ;; just stay here.
22549 (when (looking-at org-list-full-item-re)
22550 ;; Set special position at first white space character after
22551 ;; bullet, and check-box, if any.
22552 (let ((after-bullet
22553 (let ((box (match-end 3)))
22554 (if (not box) (match-end 1)
22555 (let ((after (char-after box)))
22556 (if (and after (= after ? )) (1+ box) box))))))
22557 ;; Special case: Move point to special position when
22558 ;; currently after it or at beginning of line.
22559 (if (eq special t)
22560 (when (or (> pos after-bullet) (= (point) pos))
22561 (goto-char after-bullet))
22562 ;; Reversed case: Move point to special position when
22563 ;; point was already at beginning of line and command is
22564 ;; repeated.
22565 (when (and (= (point) pos) (eq last-command this-command))
22566 (goto-char after-bullet))))))))
22567 (org-no-warnings
22568 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22570 (defun org-end-of-line (&optional arg)
22571 "Go to the end of the line.
22572 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22573 tags on the first attempt, and only move to after the tags when
22574 the cursor is already beyond the end of the headline."
22575 (interactive "P")
22576 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22577 org-special-ctrl-a/e))
22578 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22579 'end-of-visual-line)
22580 ((fboundp 'move-end-of-line) 'move-end-of-line)
22581 (t 'end-of-line))))
22582 (if (or (not special) arg) (call-interactively move-fun)
22583 (let* ((element (save-excursion (beginning-of-line)
22584 (org-element-at-point)))
22585 (type (org-element-type element)))
22586 (cond
22587 ((memq type '(headline inlinetask))
22588 (let ((pos (point)))
22589 (beginning-of-line 1)
22590 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22591 (if (eq special t)
22592 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22593 (goto-char (match-beginning 1))
22594 (goto-char (match-end 0)))
22595 (if (or (< pos (match-end 0))
22596 (not (eq this-command last-command)))
22597 (goto-char (match-end 0))
22598 (goto-char (match-beginning 1))))
22599 (call-interactively move-fun))))
22600 ((org-element-property :hiddenp element)
22601 ;; If element is hidden, `move-end-of-line' would put point
22602 ;; after it. Use `end-of-line' to stay on current line.
22603 (call-interactively 'end-of-line))
22604 (t (call-interactively move-fun)))))
22605 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22607 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22608 (define-key org-mode-map "\C-e" 'org-end-of-line)
22610 (defun org-backward-sentence (&optional arg)
22611 "Go to beginning of sentence, or beginning of table field.
22612 This will call `backward-sentence' or `org-table-beginning-of-field',
22613 depending on context."
22614 (interactive "P")
22615 (cond
22616 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22617 (t (call-interactively 'backward-sentence))))
22619 (defun org-forward-sentence (&optional arg)
22620 "Go to end of sentence, or end of table field.
22621 This will call `forward-sentence' or `org-table-end-of-field',
22622 depending on context."
22623 (interactive "P")
22624 (cond
22625 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22626 (t (call-interactively 'forward-sentence))))
22628 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22629 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22631 (defun org-kill-line (&optional arg)
22632 "Kill line, to tags or end of line."
22633 (interactive "P")
22634 (cond
22635 ((or (not org-special-ctrl-k)
22636 (bolp)
22637 (not (org-at-heading-p)))
22638 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22639 org-ctrl-k-protect-subtree)
22640 (if (or (eq org-ctrl-k-protect-subtree 'error)
22641 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22642 (error "C-k aborted - would kill hidden subtree")))
22643 (call-interactively
22644 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22645 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22646 (kill-region (point) (match-beginning 1))
22647 (org-set-tags nil t))
22648 (t (kill-region (point) (point-at-eol)))))
22650 (define-key org-mode-map "\C-k" 'org-kill-line)
22652 (defun org-yank (&optional arg)
22653 "Yank. If the kill is a subtree, treat it specially.
22654 This command will look at the current kill and check if is a single
22655 subtree, or a series of subtrees[1]. If it passes the test, and if the
22656 cursor is at the beginning of a line or after the stars of a currently
22657 empty headline, then the yank is handled specially. How exactly depends
22658 on the value of the following variables, both set by default.
22660 org-yank-folded-subtrees
22661 When set, the subtree(s) will be folded after insertion, but only
22662 if doing so would now swallow text after the yanked text.
22664 org-yank-adjusted-subtrees
22665 When set, the subtree will be promoted or demoted in order to
22666 fit into the local outline tree structure, which means that the level
22667 will be adjusted so that it becomes the smaller one of the two
22668 *visible* surrounding headings.
22670 Any prefix to this command will cause `yank' to be called directly with
22671 no special treatment. In particular, a simple \\[universal-argument] prefix \
22672 will just
22673 plainly yank the text as it is.
22675 \[1] The test checks if the first non-white line is a heading
22676 and if there are no other headings with fewer stars."
22677 (interactive "P")
22678 (org-yank-generic 'yank arg))
22680 (defun org-yank-generic (command arg)
22681 "Perform some yank-like command.
22683 This function implements the behavior described in the `org-yank'
22684 documentation. However, it has been generalized to work for any
22685 interactive command with similar behavior."
22687 ;; pretend to be command COMMAND
22688 (setq this-command command)
22690 (if arg
22691 (call-interactively command)
22693 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22694 (and (org-kill-is-subtree-p)
22695 (or (bolp)
22696 (and (looking-at "[ \t]*$")
22697 (string-match
22698 "\\`\\*+\\'"
22699 (buffer-substring (point-at-bol) (point)))))))
22700 swallowp)
22701 (cond
22702 ((and subtreep org-yank-folded-subtrees)
22703 (let ((beg (point))
22704 end)
22705 (if (and subtreep org-yank-adjusted-subtrees)
22706 (org-paste-subtree nil nil 'for-yank)
22707 (call-interactively command))
22709 (setq end (point))
22710 (goto-char beg)
22711 (when (and (bolp) subtreep
22712 (not (setq swallowp
22713 (org-yank-folding-would-swallow-text beg end))))
22714 (org-with-limited-levels
22715 (or (looking-at org-outline-regexp)
22716 (re-search-forward org-outline-regexp-bol end t))
22717 (while (and (< (point) end) (looking-at org-outline-regexp))
22718 (hide-subtree)
22719 (org-cycle-show-empty-lines 'folded)
22720 (condition-case nil
22721 (outline-forward-same-level 1)
22722 (error (goto-char end))))))
22723 (when swallowp
22724 (message
22725 "Inserted text not folded because that would swallow text"))
22727 (goto-char end)
22728 (skip-chars-forward " \t\n\r")
22729 (beginning-of-line 1)
22730 (push-mark beg 'nomsg)))
22731 ((and subtreep org-yank-adjusted-subtrees)
22732 (let ((beg (point-at-bol)))
22733 (org-paste-subtree nil nil 'for-yank)
22734 (push-mark beg 'nomsg)))
22736 (call-interactively command))))))
22738 (defun org-yank-folding-would-swallow-text (beg end)
22739 "Would hide-subtree at BEG swallow any text after END?"
22740 (let (level)
22741 (org-with-limited-levels
22742 (save-excursion
22743 (goto-char beg)
22744 (when (or (looking-at org-outline-regexp)
22745 (re-search-forward org-outline-regexp-bol end t))
22746 (setq level (org-outline-level)))
22747 (goto-char end)
22748 (skip-chars-forward " \t\r\n\v\f")
22749 (if (or (eobp)
22750 (and (bolp) (looking-at org-outline-regexp)
22751 (<= (org-outline-level) level)))
22752 nil ; Nothing would be swallowed
22753 t))))) ; something would swallow
22755 (define-key org-mode-map "\C-y" 'org-yank)
22757 (defun org-truely-invisible-p ()
22758 "Check if point is at a character currently not visible.
22759 This version does not only check the character property, but also
22760 `visible-mode'."
22761 ;; Early versions of noutline don't have `outline-invisible-p'.
22762 (if (org-bound-and-true-p visible-mode)
22764 (outline-invisible-p)))
22766 (defun org-invisible-p2 ()
22767 "Check if point is at a character currently not visible."
22768 (save-excursion
22769 (if (and (eolp) (not (bobp))) (backward-char 1))
22770 ;; Early versions of noutline don't have `outline-invisible-p'.
22771 (outline-invisible-p)))
22773 (defun org-back-to-heading (&optional invisible-ok)
22774 "Call `outline-back-to-heading', but provide a better error message."
22775 (condition-case nil
22776 (outline-back-to-heading invisible-ok)
22777 (error (error "Before first headline at position %d in buffer %s"
22778 (point) (current-buffer)))))
22780 (defun org-before-first-heading-p ()
22781 "Before first heading?"
22782 (save-excursion
22783 (end-of-line)
22784 (null (re-search-backward org-outline-regexp-bol nil t))))
22786 (defun org-at-heading-p (&optional ignored)
22787 (outline-on-heading-p t))
22788 ;; Compatibility alias with Org versions < 7.8.03
22789 (defalias 'org-on-heading-p 'org-at-heading-p)
22791 (defun org-at-comment-p nil
22792 "Is cursor in a line starting with a # character?"
22793 (save-excursion
22794 (beginning-of-line)
22795 (looking-at "^#")))
22797 (defun org-at-drawer-p nil
22798 "Is cursor at a drawer keyword?"
22799 (save-excursion
22800 (move-beginning-of-line 1)
22801 (looking-at org-drawer-regexp)))
22803 (defun org-at-block-p nil
22804 "Is cursor at a block keyword?"
22805 (save-excursion
22806 (move-beginning-of-line 1)
22807 (looking-at org-block-regexp)))
22809 (defun org-point-at-end-of-empty-headline ()
22810 "If point is at the end of an empty headline, return t, else nil.
22811 If the heading only contains a TODO keyword, it is still still considered
22812 empty."
22813 (and (looking-at "[ \t]*$")
22814 (when org-todo-line-regexp
22815 (save-excursion
22816 (beginning-of-line 1)
22817 (let ((case-fold-search nil))
22818 (looking-at org-todo-line-regexp)
22819 (string= (match-string 3) ""))))))
22821 (defun org-at-heading-or-item-p ()
22822 (or (org-at-heading-p) (org-at-item-p)))
22824 (defun org-at-target-p ()
22825 (or (org-in-regexp org-radio-target-regexp)
22826 (org-in-regexp org-target-regexp)))
22827 ;; Compatibility alias with Org versions < 7.8.03
22828 (defalias 'org-on-target-p 'org-at-target-p)
22830 (defun org-up-heading-all (arg)
22831 "Move to the heading line of which the present line is a subheading.
22832 This function considers both visible and invisible heading lines.
22833 With argument, move up ARG levels."
22834 (if (fboundp 'outline-up-heading-all)
22835 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22836 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22838 (defun org-up-heading-safe ()
22839 "Move to the heading line of which the present line is a subheading.
22840 This version will not throw an error. It will return the level of the
22841 headline found, or nil if no higher level is found.
22843 Also, this function will be a lot faster than `outline-up-heading',
22844 because it relies on stars being the outline starters. This can really
22845 make a significant difference in outlines with very many siblings."
22846 (let (start-level re)
22847 (org-back-to-heading t)
22848 (setq start-level (funcall outline-level))
22849 (if (equal start-level 1)
22851 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22852 (if (re-search-backward re nil t)
22853 (funcall outline-level)))))
22855 (defun org-first-sibling-p ()
22856 "Is this heading the first child of its parents?"
22857 (interactive)
22858 (let ((re org-outline-regexp-bol)
22859 level l)
22860 (unless (org-at-heading-p t)
22861 (error "Not at a heading"))
22862 (setq level (funcall outline-level))
22863 (save-excursion
22864 (if (not (re-search-backward re nil t))
22866 (setq l (funcall outline-level))
22867 (< l level)))))
22869 (defun org-goto-sibling (&optional previous)
22870 "Goto the next sibling, even if it is invisible.
22871 When PREVIOUS is set, go to the previous sibling instead. Returns t
22872 when a sibling was found. When none is found, return nil and don't
22873 move point."
22874 (let ((fun (if previous 're-search-backward 're-search-forward))
22875 (pos (point))
22876 (re org-outline-regexp-bol)
22877 level l)
22878 (when (condition-case nil (org-back-to-heading t) (error nil))
22879 (setq level (funcall outline-level))
22880 (catch 'exit
22881 (or previous (forward-char 1))
22882 (while (funcall fun re nil t)
22883 (setq l (funcall outline-level))
22884 (when (< l level) (goto-char pos) (throw 'exit nil))
22885 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22886 (goto-char pos)
22887 nil))))
22889 (defun org-show-siblings ()
22890 "Show all siblings of the current headline."
22891 (save-excursion
22892 (while (org-goto-sibling) (org-flag-heading nil)))
22893 (save-excursion
22894 (while (org-goto-sibling 'previous)
22895 (org-flag-heading nil))))
22897 (defun org-goto-first-child ()
22898 "Goto the first child, even if it is invisible.
22899 Return t when a child was found. Otherwise don't move point and
22900 return nil."
22901 (let (level (pos (point)) (re org-outline-regexp-bol))
22902 (when (condition-case nil (org-back-to-heading t) (error nil))
22903 (setq level (outline-level))
22904 (forward-char 1)
22905 (if (and (re-search-forward re nil t) (> (outline-level) level))
22906 (progn (goto-char (match-beginning 0)) t)
22907 (goto-char pos) nil))))
22909 (defun org-show-hidden-entry ()
22910 "Show an entry where even the heading is hidden."
22911 (save-excursion
22912 (org-show-entry)))
22914 (defun org-flag-heading (flag &optional entry)
22915 "Flag the current heading. FLAG non-nil means make invisible.
22916 When ENTRY is non-nil, show the entire entry."
22917 (save-excursion
22918 (org-back-to-heading t)
22919 ;; Check if we should show the entire entry
22920 (if entry
22921 (progn
22922 (org-show-entry)
22923 (save-excursion
22924 (and (outline-next-heading)
22925 (org-flag-heading nil))))
22926 (outline-flag-region (max (point-min) (1- (point)))
22927 (save-excursion (outline-end-of-heading) (point))
22928 flag))))
22930 (defun org-get-next-sibling ()
22931 "Move to next heading of the same level, and return point.
22932 If there is no such heading, return nil.
22933 This is like outline-next-sibling, but invisible headings are ok."
22934 (let ((level (funcall outline-level)))
22935 (outline-next-heading)
22936 (while (and (not (eobp)) (> (funcall outline-level) level))
22937 (outline-next-heading))
22938 (if (or (eobp) (< (funcall outline-level) level))
22940 (point))))
22942 (defun org-get-last-sibling ()
22943 "Move to previous heading of the same level, and return point.
22944 If there is no such heading, return nil."
22945 (let ((opoint (point))
22946 (level (funcall outline-level)))
22947 (outline-previous-heading)
22948 (when (and (/= (point) opoint) (outline-on-heading-p t))
22949 (while (and (> (funcall outline-level) level)
22950 (not (bobp)))
22951 (outline-previous-heading))
22952 (if (< (funcall outline-level) level)
22954 (point)))))
22956 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22957 "Goto to the end of a subtree."
22958 ;; This contains an exact copy of the original function, but it uses
22959 ;; `org-back-to-heading', to make it work also in invisible
22960 ;; trees. And is uses an invisible-ok argument.
22961 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22962 ;; Furthermore, when used inside Org, finding the end of a large subtree
22963 ;; with many children and grandchildren etc, this can be much faster
22964 ;; than the outline version.
22965 (org-back-to-heading invisible-ok)
22966 (let ((first t)
22967 (level (funcall outline-level)))
22968 (if (and (derived-mode-p 'org-mode) (< level 1000))
22969 ;; A true heading (not a plain list item), in Org-mode
22970 ;; This means we can easily find the end by looking
22971 ;; only for the right number of stars. Using a regexp to do
22972 ;; this is so much faster than using a Lisp loop.
22973 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22974 (forward-char 1)
22975 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22976 ;; something else, do it the slow way
22977 (while (and (not (eobp))
22978 (or first (> (funcall outline-level) level)))
22979 (setq first nil)
22980 (outline-next-heading)))
22981 (unless to-heading
22982 (if (memq (preceding-char) '(?\n ?\^M))
22983 (progn
22984 ;; Go to end of line before heading
22985 (forward-char -1)
22986 (if (memq (preceding-char) '(?\n ?\^M))
22987 ;; leave blank line before heading
22988 (forward-char -1))))))
22989 (point))
22991 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22992 "Use Org version in org-mode, for dramatic speed-up."
22993 (if (derived-mode-p 'org-mode)
22994 (progn
22995 (org-end-of-subtree nil t)
22996 (unless (eobp) (backward-char 1)))
22997 ad-do-it))
22999 (defun org-end-of-meta-data-and-drawers ()
23000 "Jump to the first text after meta data and drawers in the current entry.
23001 This will move over empty lines, lines with planning time stamps,
23002 clocking lines, and drawers."
23003 (org-back-to-heading t)
23004 (let ((end (save-excursion (outline-next-heading) (point)))
23005 (re (concat "\\(" org-drawer-regexp "\\)"
23006 "\\|" "[ \t]*" org-keyword-time-regexp)))
23007 (forward-line 1)
23008 (while (re-search-forward re end t)
23009 (if (not (match-end 1))
23010 ;; empty or planning line
23011 (forward-line 1)
23012 ;; a drawer, find the end
23013 (re-search-forward "^[ \t]*:END:" end 'move)
23014 (forward-line 1)))
23015 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23016 (point)))
23018 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23019 "Move forward to the ARG'th subheading at same level as this one.
23020 Stop at the first and last subheadings of a superior heading.
23021 Normally this only looks at visible headings, but when INVISIBLE-OK is
23022 non-nil it will also look at invisible ones."
23023 (interactive "p")
23024 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23025 (if (and arg (< arg 0))
23026 (goto-char (point-min))
23027 (outline-next-heading))
23028 (org-at-heading-p)
23029 (let ((level (- (match-end 0) (match-beginning 0) 1))
23030 (f (if (and arg (< arg 0))
23031 're-search-backward
23032 're-search-forward))
23033 (count (if arg (abs arg) 1))
23034 (result (point)))
23035 (while (and (prog1 (> count 0)
23036 (forward-char (if (and arg (< arg 0)) -1 1)))
23037 (funcall f org-outline-regexp-bol nil 'move))
23038 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23039 (cond ((< l level) (setq count 0))
23040 ((and (= l level)
23041 (or invisible-ok
23042 (progn
23043 (goto-char (line-beginning-position))
23044 (not (outline-invisible-p)))))
23045 (setq count (1- count))
23046 (when (eq l level)
23047 (setq result (point)))))))
23048 (goto-char result))
23049 (beginning-of-line 1)))
23051 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23052 "Move backward to the ARG'th subheading at same level as this one.
23053 Stop at the first and last subheadings of a superior heading."
23054 (interactive "p")
23055 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23057 (defun org-next-block (arg &optional backward block-regexp)
23058 "Jump to the next block.
23059 With a prefix argument ARG, jump forward ARG many source blocks.
23060 When BACKWARD is non-nil, jump to the previous block.
23061 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23062 (interactive "p")
23063 (let ((re (or block-regexp org-block-regexp))
23064 (re-search-fn (or (and backward 're-search-backward)
23065 're-search-forward)))
23066 (if (looking-at re) (forward-char 1))
23067 (condition-case nil
23068 (funcall re-search-fn re nil nil arg)
23069 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23070 (goto-char (match-beginning 0)) (org-show-context)))
23072 (defun org-previous-block (arg &optional block-regexp)
23073 "Jump to the previous block.
23074 With a prefix argument ARG, jump backward ARG many source blocks.
23075 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23076 (interactive "p")
23077 (org-next-block arg t block-regexp))
23079 (defun org-forward-element ()
23080 "Move forward by one element.
23081 Move to the next element at the same level, when possible."
23082 (interactive)
23083 (cond ((eobp) (user-error "Cannot move further down"))
23084 ((org-with-limited-levels (org-at-heading-p))
23085 (let ((origin (point)))
23086 (goto-char (org-end-of-subtree nil t))
23087 (unless (org-with-limited-levels (org-at-heading-p))
23088 (goto-char origin)
23089 (user-error "Cannot move further down"))))
23091 (let* ((elem (org-element-at-point))
23092 (end (org-element-property :end elem))
23093 (parent (org-element-property :parent elem)))
23094 (if (and parent (= (org-element-property :contents-end parent) end))
23095 (goto-char (org-element-property :end parent))
23096 (goto-char end))))))
23098 (defun org-backward-element ()
23099 "Move backward by one element.
23100 Move to the previous element at the same level, when possible."
23101 (interactive)
23102 (cond ((bobp) (user-error "Cannot move further up"))
23103 ((org-with-limited-levels (org-at-heading-p))
23104 ;; At a headline, move to the previous one, if any, or stay
23105 ;; here.
23106 (let ((origin (point)))
23107 (org-with-limited-levels (org-backward-heading-same-level 1))
23108 ;; When current headline has no sibling above, move to its
23109 ;; parent.
23110 (when (= (point) origin)
23111 (or (org-with-limited-levels (org-up-heading-safe))
23112 (progn (goto-char origin)
23113 (user-error "Cannot move further up"))))))
23115 (let* ((trail (org-element-at-point 'keep-trail))
23116 (elem (car trail))
23117 (prev-elem (nth 1 trail))
23118 (beg (org-element-property :begin elem)))
23119 (cond
23120 ;; Move to beginning of current element if point isn't
23121 ;; there already.
23122 ((/= (point) beg) (goto-char beg))
23123 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23124 ((org-before-first-heading-p) (goto-char (point-min)))
23125 (t (org-back-to-heading)))))))
23127 (defun org-up-element ()
23128 "Move to upper element."
23129 (interactive)
23130 (if (org-with-limited-levels (org-at-heading-p))
23131 (unless (org-up-heading-safe) (error "No surrounding element"))
23132 (let* ((elem (org-element-at-point))
23133 (parent (org-element-property :parent elem)))
23134 (if parent (goto-char (org-element-property :begin parent))
23135 (if (org-with-limited-levels (org-before-first-heading-p))
23136 (error "No surrounding element")
23137 (org-with-limited-levels (org-back-to-heading)))))))
23139 (defvar org-element-greater-elements)
23140 (defun org-down-element ()
23141 "Move to inner element."
23142 (interactive)
23143 (let ((element (org-element-at-point)))
23144 (cond
23145 ((memq (org-element-type element) '(plain-list table))
23146 (goto-char (org-element-property :contents-begin element))
23147 (forward-char))
23148 ((memq (org-element-type element) org-element-greater-elements)
23149 ;; If contents are hidden, first disclose them.
23150 (when (org-element-property :hiddenp element) (org-cycle))
23151 (goto-char (or (org-element-property :contents-begin element)
23152 (error "No content for this element"))))
23153 (t (error "No inner element")))))
23155 (defun org-drag-element-backward ()
23156 "Move backward element at point."
23157 (interactive)
23158 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23159 (let* ((trail (org-element-at-point 'keep-trail))
23160 (elem (car trail))
23161 (prev-elem (nth 1 trail)))
23162 ;; Error out if no previous element or previous element is
23163 ;; a parent of the current one.
23164 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23165 (error "Cannot drag element backward")
23166 (let ((pos (point)))
23167 (org-element-swap-A-B prev-elem elem)
23168 (goto-char (+ (org-element-property :begin prev-elem)
23169 (- pos (org-element-property :begin elem)))))))))
23171 (defun org-drag-element-forward ()
23172 "Move forward element at point."
23173 (interactive)
23174 (let* ((pos (point))
23175 (elem (org-element-at-point)))
23176 (when (= (point-max) (org-element-property :end elem))
23177 (error "Cannot drag element forward"))
23178 (goto-char (org-element-property :end elem))
23179 (let ((next-elem (org-element-at-point)))
23180 (when (or (org-element-nested-p elem next-elem)
23181 (and (eq (org-element-type next-elem) 'headline)
23182 (not (eq (org-element-type elem) 'headline))))
23183 (goto-char pos)
23184 (error "Cannot drag element forward"))
23185 ;; Compute new position of point: it's shifted by NEXT-ELEM
23186 ;; body's length (without final blanks) and by the length of
23187 ;; blanks between ELEM and NEXT-ELEM.
23188 (let ((size-next (- (save-excursion
23189 (goto-char (org-element-property :end next-elem))
23190 (skip-chars-backward " \r\t\n")
23191 (forward-line)
23192 ;; Small correction if buffer doesn't end
23193 ;; with a newline character.
23194 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23195 (org-element-property :begin next-elem)))
23196 (size-blank (- (org-element-property :end elem)
23197 (save-excursion
23198 (goto-char (org-element-property :end elem))
23199 (skip-chars-backward " \r\t\n")
23200 (forward-line)
23201 (point)))))
23202 (org-element-swap-A-B elem next-elem)
23203 (goto-char (+ pos size-next size-blank))))))
23205 (defun org-drag-line-forward (arg)
23206 "Drag the line at point ARG lines forward."
23207 (interactive "p")
23208 (dotimes (n (abs arg))
23209 (let ((c (current-column)))
23210 (if (< 0 arg)
23211 (progn
23212 (beginning-of-line 2)
23213 (transpose-lines 1)
23214 (beginning-of-line 0))
23215 (transpose-lines 1)
23216 (beginning-of-line -1))
23217 (org-move-to-column c))))
23219 (defun org-drag-line-backward (arg)
23220 "Drag the line at point ARG lines backward."
23221 (interactive "p")
23222 (org-drag-line-forward (- arg)))
23224 (defun org-mark-element ()
23225 "Put point at beginning of this element, mark at end.
23227 Interactively, if this command is repeated or (in Transient Mark
23228 mode) if the mark is active, it marks the next element after the
23229 ones already marked."
23230 (interactive)
23231 (let (deactivate-mark)
23232 (if (and (org-called-interactively-p 'any)
23233 (or (and (eq last-command this-command) (mark t))
23234 (and transient-mark-mode mark-active)))
23235 (set-mark
23236 (save-excursion
23237 (goto-char (mark))
23238 (goto-char (org-element-property :end (org-element-at-point)))))
23239 (let ((element (org-element-at-point)))
23240 (end-of-line)
23241 (push-mark (org-element-property :end element) t t)
23242 (goto-char (org-element-property :begin element))))))
23244 (defun org-narrow-to-element ()
23245 "Narrow buffer to current element."
23246 (interactive)
23247 (let ((elem (org-element-at-point)))
23248 (cond
23249 ((eq (car elem) 'headline)
23250 (narrow-to-region
23251 (org-element-property :begin elem)
23252 (org-element-property :end elem)))
23253 ((memq (car elem) org-element-greater-elements)
23254 (narrow-to-region
23255 (org-element-property :contents-begin elem)
23256 (org-element-property :contents-end elem)))
23258 (narrow-to-region
23259 (org-element-property :begin elem)
23260 (org-element-property :end elem))))))
23262 (defun org-transpose-element ()
23263 "Transpose current and previous elements, keeping blank lines between.
23264 Point is moved after both elements."
23265 (interactive)
23266 (org-skip-whitespace)
23267 (let ((end (org-element-property :end (org-element-at-point))))
23268 (org-drag-element-backward)
23269 (goto-char end)))
23271 (defun org-unindent-buffer ()
23272 "Un-indent the visible part of the buffer.
23273 Relative indentation (between items, inside blocks, etc.) isn't
23274 modified."
23275 (interactive)
23276 (unless (eq major-mode 'org-mode)
23277 (error "Cannot un-indent a buffer not in Org mode"))
23278 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23279 unindent-tree ; For byte-compiler.
23280 (unindent-tree
23281 (function
23282 (lambda (contents)
23283 (mapc
23284 (lambda (element)
23285 (if (memq (org-element-type element) '(headline section))
23286 (funcall unindent-tree (org-element-contents element))
23287 (save-excursion
23288 (save-restriction
23289 (narrow-to-region
23290 (org-element-property :begin element)
23291 (org-element-property :end element))
23292 (org-do-remove-indentation)))))
23293 (reverse contents))))))
23294 (funcall unindent-tree (org-element-contents parse-tree))))
23296 (defun org-show-subtree ()
23297 "Show everything after this heading at deeper levels."
23298 (interactive)
23299 (outline-flag-region
23300 (point)
23301 (save-excursion
23302 (org-end-of-subtree t t))
23303 nil))
23305 (defun org-show-entry ()
23306 "Show the body directly following this heading.
23307 Show the heading too, if it is currently invisible."
23308 (interactive)
23309 (save-excursion
23310 (condition-case nil
23311 (progn
23312 (org-back-to-heading t)
23313 (outline-flag-region
23314 (max (point-min) (1- (point)))
23315 (save-excursion
23316 (if (re-search-forward
23317 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23318 (match-beginning 1)
23319 (point-max)))
23320 nil)
23321 (org-cycle-hide-drawers 'children))
23322 (error nil))))
23324 (defun org-make-options-regexp (kwds &optional extra)
23325 "Make a regular expression for keyword lines."
23326 (concat
23327 "^#\\+\\("
23328 (mapconcat 'regexp-quote kwds "\\|")
23329 (if extra (concat "\\|" extra))
23330 "\\):[ \t]*\\(.*\\)"))
23332 ;; Make isearch reveal the necessary context
23333 (defun org-isearch-end ()
23334 "Reveal context after isearch exits."
23335 (when isearch-success ; only if search was successful
23336 (if (featurep 'xemacs)
23337 ;; Under XEmacs, the hook is run in the correct place,
23338 ;; we directly show the context.
23339 (org-show-context 'isearch)
23340 ;; In Emacs the hook runs *before* restoring the overlays.
23341 ;; So we have to use a one-time post-command-hook to do this.
23342 ;; (Emacs 22 has a special variable, see function `org-mode')
23343 (unless (and (boundp 'isearch-mode-end-hook-quit)
23344 isearch-mode-end-hook-quit)
23345 ;; Only when the isearch was not quitted.
23346 (org-add-hook 'post-command-hook 'org-isearch-post-command
23347 'append 'local)))
23348 (org-fix-ellipsis-at-bol)))
23350 (defun org-isearch-post-command ()
23351 "Remove self from hook, and show context."
23352 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23353 (org-show-context 'isearch))
23356 ;;;; Integration with and fixes for other packages
23358 ;;; Imenu support
23360 (defvar org-imenu-markers nil
23361 "All markers currently used by Imenu.")
23362 (make-variable-buffer-local 'org-imenu-markers)
23364 (defun org-imenu-new-marker (&optional pos)
23365 "Return a new marker for use by Imenu, and remember the marker."
23366 (let ((m (make-marker)))
23367 (move-marker m (or pos (point)))
23368 (push m org-imenu-markers)
23371 (defun org-imenu-get-tree ()
23372 "Produce the index for Imenu."
23373 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23374 (setq org-imenu-markers nil)
23375 (let* ((n org-imenu-depth)
23376 (re (concat "^" (org-get-limited-outline-regexp)))
23377 (subs (make-vector (1+ n) nil))
23378 (last-level 0)
23379 m level head0 head)
23380 (save-excursion
23381 (save-restriction
23382 (widen)
23383 (goto-char (point-max))
23384 (while (re-search-backward re nil t)
23385 (setq level (org-reduced-level (funcall outline-level)))
23386 (when (and (<= level n)
23387 (looking-at org-complex-heading-regexp)
23388 (setq head0 (org-match-string-no-properties 4)))
23389 (setq head (org-link-display-format head0)
23390 m (org-imenu-new-marker))
23391 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23392 (if (>= level last-level)
23393 (push (cons head m) (aref subs level))
23394 (push (cons head (aref subs (1+ level))) (aref subs level))
23395 (loop for i from (1+ level) to n do (aset subs i nil)))
23396 (setq last-level level)))))
23397 (aref subs 1)))
23399 (eval-after-load "imenu"
23400 '(progn
23401 (add-hook 'imenu-after-jump-hook
23402 (lambda ()
23403 (if (derived-mode-p 'org-mode)
23404 (org-show-context 'org-goto))))))
23406 (defun org-link-display-format (link)
23407 "Replace a link with its the description.
23408 If there is no description, use the link target."
23409 (save-match-data
23410 (if (string-match org-bracket-link-analytic-regexp link)
23411 (replace-match (if (match-end 5)
23412 (match-string 5 link)
23413 (concat (match-string 1 link)
23414 (match-string 3 link)))
23415 nil t link)
23416 link)))
23418 (defun org-toggle-link-display ()
23419 "Toggle the literal or descriptive display of links."
23420 (interactive)
23421 (if org-descriptive-links
23422 (progn (org-remove-from-invisibility-spec '(org-link))
23423 (org-restart-font-lock)
23424 (setq org-descriptive-links nil))
23425 (progn (add-to-invisibility-spec '(org-link))
23426 (org-restart-font-lock)
23427 (setq org-descriptive-links t))))
23429 ;; Speedbar support
23431 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23432 "Overlay marking the agenda restriction line in speedbar.")
23433 (overlay-put org-speedbar-restriction-lock-overlay
23434 'face 'org-agenda-restriction-lock)
23435 (overlay-put org-speedbar-restriction-lock-overlay
23436 'help-echo "Agendas are currently limited to this item.")
23437 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23439 (defun org-speedbar-set-agenda-restriction ()
23440 "Restrict future agenda commands to the location at point in speedbar.
23441 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23442 (interactive)
23443 (require 'org-agenda)
23444 (let (p m tp np dir txt)
23445 (cond
23446 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23447 'org-imenu t))
23448 (setq m (get-text-property p 'org-imenu-marker))
23449 (with-current-buffer (marker-buffer m)
23450 (goto-char m)
23451 (org-agenda-set-restriction-lock 'subtree)))
23452 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23453 'speedbar-function 'speedbar-find-file))
23454 (setq tp (previous-single-property-change
23455 (1+ p) 'speedbar-function)
23456 np (next-single-property-change
23457 tp 'speedbar-function)
23458 dir (speedbar-line-directory)
23459 txt (buffer-substring-no-properties (or tp (point-min))
23460 (or np (point-max))))
23461 (with-current-buffer (find-file-noselect
23462 (let ((default-directory dir))
23463 (expand-file-name txt)))
23464 (unless (derived-mode-p 'org-mode)
23465 (error "Cannot restrict to non-Org-mode file"))
23466 (org-agenda-set-restriction-lock 'file)))
23467 (t (error "Don't know how to restrict Org-mode's agenda")))
23468 (move-overlay org-speedbar-restriction-lock-overlay
23469 (point-at-bol) (point-at-eol))
23470 (setq current-prefix-arg nil)
23471 (org-agenda-maybe-redo)))
23473 (eval-after-load "speedbar"
23474 '(progn
23475 (speedbar-add-supported-extension ".org")
23476 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23477 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23478 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23479 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23480 (add-hook 'speedbar-visiting-tag-hook
23481 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23483 ;;; Fixes and Hacks for problems with other packages
23485 ;; Make flyspell not check words in links, to not mess up our keymap
23486 (defvar org-element-affiliated-keywords) ; From org-element.el
23487 (defvar org-element-block-name-alist) ; From org-element.el
23488 (defun org-mode-flyspell-verify ()
23489 "Don't let flyspell put overlays at active buttons, or on
23490 {todo,all-time,additional-option-like}-keywords."
23491 (require 'org-element) ; For `org-element-affiliated-keywords'
23492 (let ((pos (max (1- (point)) (point-min)))
23493 (word (thing-at-point 'word)))
23494 (and (not (get-text-property pos 'keymap))
23495 (not (get-text-property pos 'org-no-flyspell))
23496 (not (member word org-todo-keywords-1))
23497 (not (member word org-all-time-keywords))
23498 (not (member word org-options-keywords))
23499 (not (member word (mapcar 'car org-startup-options)))
23500 (not (member-ignore-case word org-element-affiliated-keywords))
23501 (not (member-ignore-case word (org-get-export-keywords)))
23502 (not (member-ignore-case
23503 word (mapcar 'car org-element-block-name-alist)))
23504 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23506 (defun org-remove-flyspell-overlays-in (beg end)
23507 "Remove flyspell overlays in region."
23508 (and (org-bound-and-true-p flyspell-mode)
23509 (fboundp 'flyspell-delete-region-overlays)
23510 (flyspell-delete-region-overlays beg end))
23511 (add-text-properties beg end '(org-no-flyspell t)))
23513 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23514 (eval-after-load "bookmark"
23515 '(if (boundp 'bookmark-after-jump-hook)
23516 ;; We can use the hook
23517 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23518 ;; Hook not available, use advice
23519 (defadvice bookmark-jump (after org-make-visible activate)
23520 "Make the position visible."
23521 (org-bookmark-jump-unhide))))
23523 ;; Make sure saveplace shows the location if it was hidden
23524 (eval-after-load "saveplace"
23525 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23526 "Make the position visible."
23527 (org-bookmark-jump-unhide)))
23529 ;; Make sure ecb shows the location if it was hidden
23530 (eval-after-load "ecb"
23531 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23532 "Make hierarchy visible when jumping into location from ECB tree buffer."
23533 (if (derived-mode-p 'org-mode)
23534 (org-show-context))))
23536 (defun org-bookmark-jump-unhide ()
23537 "Unhide the current position, to show the bookmark location."
23538 (and (derived-mode-p 'org-mode)
23539 (or (outline-invisible-p)
23540 (save-excursion (goto-char (max (point-min) (1- (point))))
23541 (outline-invisible-p)))
23542 (org-show-context 'bookmark-jump)))
23544 ;; Make session.el ignore our circular variable
23545 (eval-after-load "session"
23546 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23548 ;;;; Finish up
23550 (provide 'org)
23552 (run-hooks 'org-load-hook)
23554 ;;; org.el ends here