org.el (org-store-link, org-link-search): Fix handling of links to #+NAME and #+TARGE...
[org-mode.git] / lisp / org.el
blob377b8a06aa6a16b837e2e30627c24d51547f0079
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 (defcustom org-babel-load-languages '((emacs-lisp . t))
183 "Languages which can be evaluated in Org-mode buffers.
184 This list can be used to load support for any of the languages
185 below, note that each language will depend on a different set of
186 system executables and/or Emacs modes. When a language is
187 \"loaded\", then code blocks in that language can be evaluated
188 with `org-babel-execute-src-block' bound by default to C-c
189 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
190 be set to remove code block evaluation from the C-c C-c
191 keybinding. By default only Emacs Lisp (which has no
192 requirements) is loaded."
193 :group 'org-babel
194 :set 'org-babel-do-load-languages
195 :version "24.1"
196 :type '(alist :tag "Babel Languages"
197 :key-type
198 (choice
199 (const :tag "Awk" awk)
200 (const :tag "C" C)
201 (const :tag "R" R)
202 (const :tag "Asymptote" asymptote)
203 (const :tag "Calc" calc)
204 (const :tag "Clojure" clojure)
205 (const :tag "CSS" css)
206 (const :tag "Ditaa" ditaa)
207 (const :tag "Dot" dot)
208 (const :tag "Emacs Lisp" emacs-lisp)
209 (const :tag "Fortran" fortran)
210 (const :tag "Gnuplot" gnuplot)
211 (const :tag "Haskell" haskell)
212 (const :tag "IO" io)
213 (const :tag "Java" java)
214 (const :tag "Javascript" js)
215 (const :tag "LaTeX" latex)
216 (const :tag "Ledger" ledger)
217 (const :tag "Lilypond" lilypond)
218 (const :tag "Lisp" lisp)
219 (const :tag "Makefile" makefile)
220 (const :tag "Maxima" maxima)
221 (const :tag "Matlab" matlab)
222 (const :tag "Mscgen" mscgen)
223 (const :tag "Ocaml" ocaml)
224 (const :tag "Octave" octave)
225 (const :tag "Org" org)
226 (const :tag "Perl" perl)
227 (const :tag "Pico Lisp" picolisp)
228 (const :tag "PlantUML" plantuml)
229 (const :tag "Python" python)
230 (const :tag "Ruby" ruby)
231 (const :tag "Sass" sass)
232 (const :tag "Scala" scala)
233 (const :tag "Scheme" scheme)
234 (const :tag "Screen" screen)
235 (const :tag "Shell Script" sh)
236 (const :tag "Shen" shen)
237 (const :tag "Sql" sql)
238 (const :tag "Sqlite" sqlite))
239 :value-type (boolean :tag "Activate" :value t)))
241 ;;;; Customization variables
242 (defcustom org-clone-delete-id nil
243 "Remove ID property of clones of a subtree.
244 When non-nil, clones of a subtree don't inherit the ID property.
245 Otherwise they inherit the ID property with a new unique
246 identifier."
247 :type 'boolean
248 :version "24.1"
249 :group 'org-id)
251 ;;; Version
252 (org-check-version)
254 ;;;###autoload
255 (defun org-version (&optional here full message)
256 "Show the org-mode version in the echo area.
257 With prefix argument HERE, insert it at point.
258 When FULL is non-nil, use a verbose version string.
259 When MESSAGE is non-nil, display a message with the version."
260 (interactive "P")
261 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
262 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
263 (load-suffixes (list ".el"))
264 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
265 (org-trash (or
266 (and (fboundp 'org-release) (fboundp 'org-git-version))
267 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
268 (load-suffixes save-load-suffixes)
269 (org-version (org-release))
270 (git-version (org-git-version))
271 (version (format "Org-mode version %s (%s @ %s)"
272 org-version
273 git-version
274 (if org-install-dir
275 (if (string= org-dir org-install-dir)
276 org-install-dir
277 (concat "mixed installation! " org-install-dir " and " org-dir))
278 "org-loaddefs.el can not be found!")))
279 (_version (if full version org-version)))
280 (if (org-called-interactively-p 'interactive)
281 (if here
282 (insert version)
283 (message version))
284 (if message (message _version))
285 _version)))
287 (defconst org-version (org-version))
289 ;;; Compatibility constants
291 ;;; The custom variables
293 (defgroup org nil
294 "Outline-based notes management and organizer."
295 :tag "Org"
296 :group 'outlines
297 :group 'calendar)
299 (defcustom org-mode-hook nil
300 "Mode hook for Org-mode, run after the mode was turned on."
301 :group 'org
302 :type 'hook)
304 (defcustom org-load-hook nil
305 "Hook that is run after org.el has been loaded."
306 :group 'org
307 :type 'hook)
309 (defcustom org-log-buffer-setup-hook nil
310 "Hook that is run after an Org log buffer is created."
311 :group 'org
312 :version "24.1"
313 :type 'hook)
315 (defvar org-modules) ; defined below
316 (defvar org-modules-loaded nil
317 "Have the modules been loaded already?")
319 (defun org-load-modules-maybe (&optional force)
320 "Load all extensions listed in `org-modules'."
321 (when (or force (not org-modules-loaded))
322 (mapc (lambda (ext)
323 (condition-case nil (require ext)
324 (error (message "Problems while trying to load feature `%s'" ext))))
325 org-modules)
326 (setq org-modules-loaded t)))
328 (defun org-set-modules (var value)
329 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
330 (set var value)
331 (when (featurep 'org)
332 (org-load-modules-maybe 'force)))
334 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
335 "Modules that should always be loaded together with org.el.
337 If a description starts with <C>, the file is not part of Emacs
338 and loading it will require that you have downloaded and properly
339 installed the Org mode distribution.
341 You can also use this system to load external packages (i.e. neither Org
342 core modules, nor modules from the CONTRIB directory). Just add symbols
343 to the end of the list. If the package is called org-xyz.el, then you need
344 to add the symbol `xyz', and the package must have a call to:
346 \(provide 'org-xyz)
348 For export specific modules, see also `org-export-backends'."
349 :group 'org
350 :set 'org-set-modules
351 :version "24.4"
352 :package-version '(Org . "8.0")
353 :type
354 '(set :greedy t
355 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
356 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
357 (const :tag " crypt: Encryption of subtrees" org-crypt)
358 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
359 (const :tag " docview: Links to doc-view buffers" org-docview)
360 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
361 (const :tag " id: Global IDs for identifying entries" org-id)
362 (const :tag " info: Links to Info nodes" org-info)
363 (const :tag " habit: Track your consistency with habits" org-habit)
364 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
365 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
366 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
367 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
368 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
369 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
370 (const :tag " mouse: Additional mouse support" org-mouse)
372 (const :tag "C vm: Links to VM folders/messages" org-vm)
373 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
374 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
375 (const :tag "C mew: Links to Mew folders/messages" org-mew)
376 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
377 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
378 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
379 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
380 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
381 (const :tag "C collector: Collect properties into tables" org-collector)
382 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
383 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
384 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
385 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
386 (const :tag "C eval: Include command output as text" org-eval)
387 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
388 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
389 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
390 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
391 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
393 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
395 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
396 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
397 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
398 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
399 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
400 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
401 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
402 (const :tag "C mtags: Support for muse-like tags" org-mtags)
403 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
404 (const :tag "C registry: A registry for Org-mode links" org-registry)
405 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
406 (const :tag "C secretary: Team management with org-mode" org-secretary)
407 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
408 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
409 (const :tag "C track: Keep up with Org-mode development" org-track)
410 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
411 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
412 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
414 (defvar org-export-registered-backends) ; From ox.el
415 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
416 (defcustom org-export-backends '(ascii html icalendar latex)
417 "List of export back-ends that should be always available.
419 If a description starts with <C>, the file is not part of Emacs
420 and loading it will require that you have downloaded and properly
421 installed the Org mode distribution.
423 Unlike to `org-modules', libraries in this list will not be
424 loaded along with Org, but only once the export framework is
425 needed.
427 This variable needs to be set before org.el is loaded. If you
428 need to make a change while Emacs is running, use the customize
429 interface or run the following code, where VALUE stands for the
430 new value of the variable, after updating it:
432 \(progn
433 \(setq org-export-registered-backends
434 \(org-remove-if-not
435 \(lambda (backend)
436 \(or (memq backend val)
437 \(catch 'parentp
438 \(mapc
439 \(lambda (b)
440 \(and (org-export-derived-backend-p b (car backend))
441 \(throw 'parentp t)))
442 val)
443 nil)))
444 org-export-registered-backends))
445 \(let ((new-list (mapcar 'car org-export-registered-backends)))
446 \(dolist (backend val)
447 \(cond
448 \((not (load (format \"ox-%s\" backend) t t))
449 \(message \"Problems while trying to load export back-end `%s'\"
450 backend))
451 \((not (memq backend new-list)) (push backend new-list))))
452 \(set-default var new-list)))
454 Adding a back-end to this list will also pull the back-end it
455 depends on, if any."
456 :group 'org
457 :group 'org-export
458 :version "24.4"
459 :package-version '(Org . "8.0")
460 :initialize 'custom-initialize-set
461 :set (lambda (var val)
462 (if (not (featurep 'ox)) (set-default var val)
463 ;; Any back-end not required anymore (not present in VAL and not
464 ;; a parent of any back-end in the new value) is removed from the
465 ;; list of registered back-ends.
466 (setq org-export-registered-backends
467 (org-remove-if-not
468 (lambda (backend)
469 (or (memq backend val)
470 (catch 'parentp
471 (mapc
472 (lambda (b)
473 (and (org-export-derived-backend-p b (car backend))
474 (throw 'parentp t)))
475 val)
476 nil)))
477 org-export-registered-backends))
478 ;; Now build NEW-LIST of both new back-ends and required
479 ;; parents.
480 (let ((new-list (mapcar 'car org-export-registered-backends)))
481 (dolist (backend val)
482 (cond
483 ((not (load (format "ox-%s" backend) t t))
484 (message "Problems while trying to load export back-end `%s'"
485 backend))
486 ((not (memq backend new-list)) (push backend new-list))))
487 ;; Set VAR to that list with fixed dependencies.
488 (set-default var new-list))))
489 :type '(set :greedy t
490 (const :tag " ascii Export buffer to ASCII format" ascii)
491 (const :tag " beamer Export buffer to Beamer presentation" beamer)
492 (const :tag " html Export buffer to HTML format" html)
493 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
494 (const :tag " latex Export buffer to LaTeX format" latex)
495 (const :tag " man Export buffer to MAN format" man)
496 (const :tag " md Export buffer to Markdown format" md)
497 (const :tag " odt Export buffer to ODT format" odt)
498 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
499 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
500 (const :tag "C deck Export buffer to deck.js presentations" deck)
501 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
502 (const :tag "C groff Export buffer to Groff format" groff)
503 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
504 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
505 (const :tag "C s5 Export buffer to s5 presentations" s5)
506 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
508 (eval-after-load 'ox
509 '(mapc
510 (lambda (backend)
511 (condition-case nil (require (intern (format "ox-%s" backend)))
512 (error (message "Problems while trying to load export back-end `%s'"
513 backend))))
514 org-export-backends))
516 (defcustom org-support-shift-select nil
517 "Non-nil means make shift-cursor commands select text when possible.
519 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
520 start selecting a region, or enlarge regions started in this way.
521 In Org-mode, in special contexts, these same keys are used for
522 other purposes, important enough to compete with shift selection.
523 Org tries to balance these needs by supporting `shift-select-mode'
524 outside these special contexts, under control of this variable.
526 The default of this variable is nil, to avoid confusing behavior. Shifted
527 cursor keys will then execute Org commands in the following contexts:
528 - on a headline, changing TODO state (left/right) and priority (up/down)
529 - on a time stamp, changing the time
530 - in a plain list item, changing the bullet type
531 - in a property definition line, switching between allowed values
532 - in the BEGIN line of a clock table (changing the time block).
533 Outside these contexts, the commands will throw an error.
535 When this variable is t and the cursor is not in a special
536 context, Org-mode will support shift-selection for making and
537 enlarging regions. To make this more effective, the bullet
538 cycling will no longer happen anywhere in an item line, but only
539 if the cursor is exactly on the bullet.
541 If you set this variable to the symbol `always', then the keys
542 will not be special in headlines, property lines, and item lines,
543 to make shift selection work there as well. If this is what you
544 want, you can use the following alternative commands: `C-c C-t'
545 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
546 can be used to switch TODO sets, `C-c -' to cycle item bullet
547 types, and properties can be edited by hand or in column view.
549 However, when the cursor is on a timestamp, shift-cursor commands
550 will still edit the time stamp - this is just too good to give up.
552 XEmacs user should have this variable set to nil, because
553 `shift-select-mode' is in Emacs 23 or later only."
554 :group 'org
555 :type '(choice
556 (const :tag "Never" nil)
557 (const :tag "When outside special context" t)
558 (const :tag "Everywhere except timestamps" always)))
560 (defcustom org-loop-over-headlines-in-active-region nil
561 "Shall some commands act upon headlines in the active region?
563 When set to `t', some commands will be performed in all headlines
564 within the active region.
566 When set to `start-level', some commands will be performed in all
567 headlines within the active region, provided that these headlines
568 are of the same level than the first one.
570 When set to a string, those commands will be performed on the
571 matching headlines within the active region. Such string must be
572 a tags/property/todo match as it is used in the agenda tags view.
574 The list of commands is: `org-schedule', `org-deadline',
575 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
576 `org-archive-to-archive-sibling'. The archiving commands skip
577 already archived entries."
578 :type '(choice (const :tag "Don't loop" nil)
579 (const :tag "All headlines in active region" t)
580 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
581 (string :tag "Tags/Property/Todo matcher"))
582 :version "24.1"
583 :group 'org-todo
584 :group 'org-archive)
586 (defgroup org-startup nil
587 "Options concerning startup of Org-mode."
588 :tag "Org Startup"
589 :group 'org)
591 (defcustom org-startup-folded t
592 "Non-nil means entering Org-mode will switch to OVERVIEW.
593 This can also be configured on a per-file basis by adding one of
594 the following lines anywhere in the buffer:
596 #+STARTUP: fold (or `overview', this is equivalent)
597 #+STARTUP: nofold (or `showall', this is equivalent)
598 #+STARTUP: content
599 #+STARTUP: showeverything
601 By default, this option is ignored when Org opens agenda files
602 for the first time. If you want the agenda to honor the startup
603 option, set `org-agenda-inhibit-startup' to nil."
604 :group 'org-startup
605 :type '(choice
606 (const :tag "nofold: show all" nil)
607 (const :tag "fold: overview" t)
608 (const :tag "content: all headlines" content)
609 (const :tag "show everything, even drawers" showeverything)))
611 (defcustom org-startup-truncated t
612 "Non-nil means entering Org-mode will set `truncate-lines'.
613 This is useful since some lines containing links can be very long and
614 uninteresting. Also tables look terrible when wrapped."
615 :group 'org-startup
616 :type 'boolean)
618 (defcustom org-startup-indented nil
619 "Non-nil means turn on `org-indent-mode' on startup.
620 This can also be configured on a per-file basis by adding one of
621 the following lines anywhere in the buffer:
623 #+STARTUP: indent
624 #+STARTUP: noindent"
625 :group 'org-structure
626 :type '(choice
627 (const :tag "Not" nil)
628 (const :tag "Globally (slow on startup in large files)" t)))
630 (defcustom org-use-sub-superscripts t
631 "Non-nil means interpret \"_\" and \"^\" for display.
632 When this option is turned on, you can use TeX-like syntax for sub- and
633 superscripts. Several characters after \"_\" or \"^\" will be
634 considered as a single item - so grouping with {} is normally not
635 needed. For example, the following things will be parsed as single
636 sub- or superscripts.
638 10^24 or 10^tau several digits will be considered 1 item.
639 10^-12 or 10^-tau a leading sign with digits or a word
640 x^2-y^3 will be read as x^2 - y^3, because items are
641 terminated by almost any nonword/nondigit char.
642 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
644 Still, ambiguity is possible - so when in doubt use {} to enclose
645 the sub/superscript. If you set this variable to the symbol
646 `{}', the braces are *required* in order to trigger
647 interpretations as sub/superscript. This can be helpful in
648 documents that need \"_\" frequently in plain text."
649 :group 'org-startup
650 :version "24.1"
651 :type '(choice
652 (const :tag "Always interpret" t)
653 (const :tag "Only with braces" {})
654 (const :tag "Never interpret" nil)))
656 (defcustom org-startup-with-beamer-mode nil
657 "Non-nil means turn on `org-beamer-mode' on startup.
658 This can also be configured on a per-file basis by adding one of
659 the following lines anywhere in the buffer:
661 #+STARTUP: beamer"
662 :group 'org-startup
663 :version "24.1"
664 :type 'boolean)
666 (defcustom org-startup-align-all-tables nil
667 "Non-nil means align all tables when visiting a file.
668 This is useful when the column width in tables is forced with <N> cookies
669 in table fields. Such tables will look correct only after the first re-align.
670 This can also be configured on a per-file basis by adding one of
671 the following lines anywhere in the buffer:
672 #+STARTUP: align
673 #+STARTUP: noalign"
674 :group 'org-startup
675 :type 'boolean)
677 (defcustom org-startup-with-inline-images nil
678 "Non-nil means show inline images when loading a new Org file.
679 This can also be configured on a per-file basis by adding one of
680 the following lines anywhere in the buffer:
681 #+STARTUP: inlineimages
682 #+STARTUP: noinlineimages"
683 :group 'org-startup
684 :version "24.1"
685 :type 'boolean)
687 (defcustom org-startup-with-latex-preview nil
688 "Non-nil means preview LaTeX fragments when loading a new Org file.
690 This can also be configured on a per-file basis by adding one of
691 the followinglines anywhere in the buffer:
692 #+STARTUP: latexpreview
693 #+STARTUP: nolatexpreview"
694 :group 'org-startup
695 :version "24.4"
696 :package-version '(Org . "8.0")
697 :type 'boolean)
699 (defcustom org-insert-mode-line-in-empty-file nil
700 "Non-nil means insert the first line setting Org-mode in empty files.
701 When the function `org-mode' is called interactively in an empty file, this
702 normally means that the file name does not automatically trigger Org-mode.
703 To ensure that the file will always be in Org-mode in the future, a
704 line enforcing Org-mode will be inserted into the buffer, if this option
705 has been set."
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-replace-disputed-keys nil
710 "Non-nil means use alternative key bindings for some keys.
711 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
712 These keys are also used by other packages like shift-selection-mode'
713 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
714 If you want to use Org-mode together with one of these other modes,
715 or more generally if you would like to move some Org-mode commands to
716 other keys, set this variable and configure the keys with the variable
717 `org-disputed-keys'.
719 This option is only relevant at load-time of Org-mode, and must be set
720 *before* org.el is loaded. Changing it requires a restart of Emacs to
721 become effective."
722 :group 'org-startup
723 :type 'boolean)
725 (defcustom org-use-extra-keys nil
726 "Non-nil means use extra key sequence definitions for certain commands.
727 This happens automatically if you run XEmacs or if `window-system'
728 is nil. This variable lets you do the same manually. You must
729 set it before loading org.
731 Example: on Carbon Emacs 22 running graphically, with an external
732 keyboard on a Powerbook, the default way of setting M-left might
733 not work for either Alt or ESC. Setting this variable will make
734 it work for ESC."
735 :group 'org-startup
736 :type 'boolean)
738 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
740 (defcustom org-disputed-keys
741 '(([(shift up)] . [(meta p)])
742 ([(shift down)] . [(meta n)])
743 ([(shift left)] . [(meta -)])
744 ([(shift right)] . [(meta +)])
745 ([(control shift right)] . [(meta shift +)])
746 ([(control shift left)] . [(meta shift -)]))
747 "Keys for which Org-mode and other modes compete.
748 This is an alist, cars are the default keys, second element specifies
749 the alternative to use when `org-replace-disputed-keys' is t.
751 Keys can be specified in any syntax supported by `define-key'.
752 The value of this option takes effect only at Org-mode's startup,
753 therefore you'll have to restart Emacs to apply it after changing."
754 :group 'org-startup
755 :type 'alist)
757 (defun org-key (key)
758 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
759 Or return the original if not disputed.
760 Also apply the translations defined in `org-xemacs-key-equivalents'."
761 (when org-replace-disputed-keys
762 (let* ((nkey (key-description key))
763 (x (org-find-if (lambda (x)
764 (equal (key-description (car x)) nkey))
765 org-disputed-keys)))
766 (setq key (if x (cdr x) key))))
767 (when (featurep 'xemacs)
768 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
769 key)
771 (defun org-find-if (predicate seq)
772 (catch 'exit
773 (while seq
774 (if (funcall predicate (car seq))
775 (throw 'exit (car seq))
776 (pop seq)))))
778 (defun org-defkey (keymap key def)
779 "Define a key, possibly translated, as returned by `org-key'."
780 (define-key keymap (org-key key) def))
782 (defcustom org-ellipsis nil
783 "The ellipsis to use in the Org-mode outline.
784 When nil, just use the standard three dots. When a string, use that instead,
785 When a face, use the standard 3 dots, but with the specified face.
786 The change affects only Org-mode (which will then use its own display table).
787 Changing this requires executing `M-x org-mode' in a buffer to become
788 effective."
789 :group 'org-startup
790 :type '(choice (const :tag "Default" nil)
791 (face :tag "Face" :value org-warning)
792 (string :tag "String" :value "...#")))
794 (defvar org-display-table nil
795 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
797 (defgroup org-keywords nil
798 "Keywords in Org-mode."
799 :tag "Org Keywords"
800 :group 'org)
802 (defcustom org-deadline-string "DEADLINE:"
803 "String to mark deadline entries.
804 A deadline is this string, followed by a time stamp. Should be a word,
805 terminated by a colon. You can insert a schedule keyword and
806 a timestamp with \\[org-deadline].
807 Changes become only effective after restarting Emacs."
808 :group 'org-keywords
809 :type 'string)
811 (defcustom org-scheduled-string "SCHEDULED:"
812 "String to mark scheduled TODO entries.
813 A schedule is this string, followed by a time stamp. Should be a word,
814 terminated by a colon. You can insert a schedule keyword and
815 a timestamp with \\[org-schedule].
816 Changes become only effective after restarting Emacs."
817 :group 'org-keywords
818 :type 'string)
820 (defcustom org-closed-string "CLOSED:"
821 "String used as the prefix for timestamps logging closing a TODO entry."
822 :group 'org-keywords
823 :type 'string)
825 (defcustom org-clock-string "CLOCK:"
826 "String used as prefix for timestamps clocking work hours on an item."
827 :group 'org-keywords
828 :type 'string)
830 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
831 org-scheduled-string "\\|"
832 org-deadline-string "\\|"
833 org-closed-string "\\|"
834 org-clock-string "\\)")
835 "Matches a line with planning or clock info.")
837 (defcustom org-comment-string "COMMENT"
838 "Entries starting with this keyword will never be exported.
839 An entry can be toggled between COMMENT and normal with
840 \\[org-toggle-comment].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-quote-string "QUOTE"
846 "Entries starting with this keyword will be exported in fixed-width font.
847 Quoting applies only to the text in the entry following the headline, and does
848 not extend beyond the next headline, even if that is lower level.
849 An entry can be toggled between QUOTE and normal with
850 \\[org-toggle-fixed-width-section]."
851 :group 'org-keywords
852 :type 'string)
854 (defconst org-repeat-re
855 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
856 "Regular expression for specifying repeated events.
857 After a match, group 1 contains the repeat expression.")
859 (defgroup org-structure nil
860 "Options concerning the general structure of Org-mode files."
861 :tag "Org Structure"
862 :group 'org)
864 (defgroup org-reveal-location nil
865 "Options about how to make context of a location visible."
866 :tag "Org Reveal Location"
867 :group 'org-structure)
869 (defconst org-context-choice
870 '(choice
871 (const :tag "Always" t)
872 (const :tag "Never" nil)
873 (repeat :greedy t :tag "Individual contexts"
874 (cons
875 (choice :tag "Context"
876 (const agenda)
877 (const org-goto)
878 (const occur-tree)
879 (const tags-tree)
880 (const link-search)
881 (const mark-goto)
882 (const bookmark-jump)
883 (const isearch)
884 (const default))
885 (boolean))))
886 "Contexts for the reveal options.")
888 (defcustom org-show-hierarchy-above '((default . t))
889 "Non-nil means show full hierarchy when revealing a location.
890 Org-mode often shows locations in an org-mode file which might have
891 been invisible before. When this is set, the hierarchy of headings
892 above the exposed location is shown.
893 Turning this off for example for sparse trees makes them very compact.
894 Instead of t, this can also be an alist specifying this option for different
895 contexts. Valid contexts are
896 agenda when exposing an entry from the agenda
897 org-goto when using the command `org-goto' on key C-c C-j
898 occur-tree when using the command `org-occur' on key C-c /
899 tags-tree when constructing a sparse tree based on tags matches
900 link-search when exposing search matches associated with a link
901 mark-goto when exposing the jump goal of a mark
902 bookmark-jump when exposing a bookmark location
903 isearch when exiting from an incremental search
904 default default for all contexts not set explicitly"
905 :group 'org-reveal-location
906 :type org-context-choice)
908 (defcustom org-show-following-heading '((default . nil))
909 "Non-nil means show following heading when revealing a location.
910 Org-mode often shows locations in an org-mode file which might have
911 been invisible before. When this is set, the heading following the
912 match is shown.
913 Turning this off for example for sparse trees makes them very compact,
914 but makes it harder to edit the location of the match. In such a case,
915 use the command \\[org-reveal] to show more context.
916 Instead of t, this can also be an alist specifying this option for different
917 contexts. See `org-show-hierarchy-above' for valid contexts."
918 :group 'org-reveal-location
919 :type org-context-choice)
921 (defcustom org-show-siblings '((default . nil) (isearch t))
922 "Non-nil means show all sibling heading when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the sibling of the current entry
925 heading are all made visible. If `org-show-hierarchy-above' is t,
926 the same happens on each level of the hierarchy above the current entry.
928 By default this is on for the isearch context, off for all other contexts.
929 Turning this off for example for sparse trees makes them very compact,
930 but makes it harder to edit the location of the match. In such a case,
931 use the command \\[org-reveal] to show more context.
932 Instead of t, this can also be an alist specifying this option for different
933 contexts. See `org-show-hierarchy-above' for valid contexts."
934 :group 'org-reveal-location
935 :type org-context-choice)
937 (defcustom org-show-entry-below '((default . nil))
938 "Non-nil means show the entry below a headline when revealing a location.
939 Org-mode often shows locations in an org-mode file which might have
940 been invisible before. When this is set, the text below the headline that is
941 exposed is also shown.
943 By default this is off for all contexts.
944 Instead of t, this can also be an alist specifying this option for different
945 contexts. See `org-show-hierarchy-above' for valid contexts."
946 :group 'org-reveal-location
947 :type org-context-choice)
949 (defcustom org-indirect-buffer-display 'other-window
950 "How should indirect tree buffers be displayed?
951 This applies to indirect buffers created with the commands
952 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
953 Valid values are:
954 current-window Display in the current window
955 other-window Just display in another window.
956 dedicated-frame Create one new frame, and re-use it each time.
957 new-frame Make a new frame each time. Note that in this case
958 previously-made indirect buffers are kept, and you need to
959 kill these buffers yourself."
960 :group 'org-structure
961 :group 'org-agenda-windows
962 :type '(choice
963 (const :tag "In current window" current-window)
964 (const :tag "In current frame, other window" other-window)
965 (const :tag "Each time a new frame" new-frame)
966 (const :tag "One dedicated frame" dedicated-frame)))
968 (defcustom org-use-speed-commands nil
969 "Non-nil means activate single letter commands at beginning of a headline.
970 This may also be a function to test for appropriate locations where speed
971 commands should be active."
972 :group 'org-structure
973 :type '(choice
974 (const :tag "Never" nil)
975 (const :tag "At beginning of headline stars" t)
976 (function)))
978 (defcustom org-speed-commands-user nil
979 "Alist of additional speed commands.
980 This list will be checked before `org-speed-commands-default'
981 when the variable `org-use-speed-commands' is non-nil
982 and when the cursor is at the beginning of a headline.
983 The car if each entry is a string with a single letter, which must
984 be assigned to `self-insert-command' in the global map.
985 The cdr is either a command to be called interactively, a function
986 to be called, or a form to be evaluated.
987 An entry that is just a list with a single string will be interpreted
988 as a descriptive headline that will be added when listing the speed
989 commands in the Help buffer using the `?' speed command."
990 :group 'org-structure
991 :type '(repeat :value ("k" . ignore)
992 (choice :value ("k" . ignore)
993 (list :tag "Descriptive Headline" (string :tag "Headline"))
994 (cons :tag "Letter and Command"
995 (string :tag "Command letter")
996 (choice
997 (function)
998 (sexp))))))
1000 (defgroup org-cycle nil
1001 "Options concerning visibility cycling in Org-mode."
1002 :tag "Org Cycle"
1003 :group 'org-structure)
1005 (defcustom org-cycle-skip-children-state-if-no-children t
1006 "Non-nil means skip CHILDREN state in entries that don't have any."
1007 :group 'org-cycle
1008 :type 'boolean)
1010 (defcustom org-cycle-max-level nil
1011 "Maximum level which should still be subject to visibility cycling.
1012 Levels higher than this will, for cycling, be treated as text, not a headline.
1013 When `org-odd-levels-only' is set, a value of N in this variable actually
1014 means 2N-1 stars as the limiting headline.
1015 When nil, cycle all levels.
1016 Note that the limiting level of cycling is also influenced by
1017 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1018 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1019 than its value."
1020 :group 'org-cycle
1021 :type '(choice
1022 (const :tag "No limit" nil)
1023 (integer :tag "Maximum level")))
1025 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1026 "Names of drawers. Drawers are not opened by cycling on the headline above.
1027 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1028 this:
1029 :DRAWERNAME:
1030 .....
1031 :END:
1032 The drawer \"PROPERTIES\" is special for capturing properties through
1033 the property API.
1035 Drawers can be defined on the per-file basis with a line like:
1037 #+DRAWERS: HIDDEN STATE PROPERTIES"
1038 :group 'org-structure
1039 :group 'org-cycle
1040 :type '(repeat (string :tag "Drawer Name")))
1042 (defcustom org-hide-block-startup nil
1043 "Non-nil means entering Org-mode will fold all blocks.
1044 This can also be set in on a per-file basis with
1046 #+STARTUP: hideblocks
1047 #+STARTUP: showblocks"
1048 :group 'org-startup
1049 :group 'org-cycle
1050 :type 'boolean)
1052 (defcustom org-cycle-global-at-bob nil
1053 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1054 This makes it possible to do global cycling without having to use S-TAB or
1055 \\[universal-argument] TAB. For this special case to work, the first line
1056 of the buffer must not be a headline -- it may be empty or some other text.
1057 When used in this way, `org-cycle-hook' is disabled temporarily to make
1058 sure the cursor stays at the beginning of the buffer. When this option is
1059 nil, don't do anything special at the beginning of the buffer."
1060 :group 'org-cycle
1061 :type 'boolean)
1063 (defcustom org-cycle-level-after-item/entry-creation t
1064 "Non-nil means cycle entry level or item indentation in new empty entries.
1066 When the cursor is at the end of an empty headline, i.e., with only stars
1067 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1068 and then all possible ancestor states, before returning to the original state.
1069 This makes data entry extremely fast: M-RET to create a new headline,
1070 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1072 When the cursor is at the end of an empty plain list item, one TAB will
1073 make it a subitem, two or more tabs will back up to make this an item
1074 higher up in the item hierarchy."
1075 :group 'org-cycle
1076 :type 'boolean)
1078 (defcustom org-cycle-emulate-tab t
1079 "Where should `org-cycle' emulate TAB.
1080 nil Never
1081 white Only in completely white lines
1082 whitestart Only at the beginning of lines, before the first non-white char
1083 t Everywhere except in headlines
1084 exc-hl-bol Everywhere except at the start of a headline
1085 If TAB is used in a place where it does not emulate TAB, the current subtree
1086 visibility is cycled."
1087 :group 'org-cycle
1088 :type '(choice (const :tag "Never" nil)
1089 (const :tag "Only in completely white lines" white)
1090 (const :tag "Before first char in a line" whitestart)
1091 (const :tag "Everywhere except in headlines" t)
1092 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1095 (defcustom org-cycle-separator-lines 2
1096 "Number of empty lines needed to keep an empty line between collapsed trees.
1097 If you leave an empty line between the end of a subtree and the following
1098 headline, this empty line is hidden when the subtree is folded.
1099 Org-mode will leave (exactly) one empty line visible if the number of
1100 empty lines is equal or larger to the number given in this variable.
1101 So the default 2 means at least 2 empty lines after the end of a subtree
1102 are needed to produce free space between a collapsed subtree and the
1103 following headline.
1105 If the number is negative, and the number of empty lines is at least -N,
1106 all empty lines are shown.
1108 Special case: when 0, never leave empty lines in collapsed view."
1109 :group 'org-cycle
1110 :type 'integer)
1111 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1113 (defcustom org-pre-cycle-hook nil
1114 "Hook that is run before visibility cycling is happening.
1115 The function(s) in this hook must accept a single argument which indicates
1116 the new state that will be set right after running this hook. The
1117 argument is a symbol. Before a global state change, it can have the values
1118 `overview', `content', or `all'. Before a local state change, it can have
1119 the values `folded', `children', or `subtree'."
1120 :group 'org-cycle
1121 :type 'hook)
1123 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1124 org-cycle-hide-drawers
1125 org-cycle-hide-inline-tasks
1126 org-cycle-show-empty-lines
1127 org-optimize-window-after-visibility-change)
1128 "Hook that is run after `org-cycle' has changed the buffer visibility.
1129 The function(s) in this hook must accept a single argument which indicates
1130 the new state that was set by the most recent `org-cycle' command. The
1131 argument is a symbol. After a global state change, it can have the values
1132 `overview', `contents', or `all'. After a local state change, it can have
1133 the values `folded', `children', or `subtree'."
1134 :group 'org-cycle
1135 :type 'hook)
1137 (defgroup org-edit-structure nil
1138 "Options concerning structure editing in Org-mode."
1139 :tag "Org Edit Structure"
1140 :group 'org-structure)
1142 (defcustom org-odd-levels-only nil
1143 "Non-nil means skip even levels and only use odd levels for the outline.
1144 This has the effect that two stars are being added/taken away in
1145 promotion/demotion commands. It also influences how levels are
1146 handled by the exporters.
1147 Changing it requires restart of `font-lock-mode' to become effective
1148 for fontification also in regions already fontified.
1149 You may also set this on a per-file basis by adding one of the following
1150 lines to the buffer:
1152 #+STARTUP: odd
1153 #+STARTUP: oddeven"
1154 :group 'org-edit-structure
1155 :group 'org-appearance
1156 :type 'boolean)
1158 (defcustom org-adapt-indentation t
1159 "Non-nil means adapt indentation to outline node level.
1161 When this variable is set, Org assumes that you write outlines by
1162 indenting text in each node to align with the headline (after the stars).
1163 The following issues are influenced by this variable:
1165 - When this is set and the *entire* text in an entry is indented, the
1166 indentation is increased by one space in a demotion command, and
1167 decreased by one in a promotion command. If any line in the entry
1168 body starts with text at column 0, indentation is not changed at all.
1170 - Property drawers and planning information is inserted indented when
1171 this variable s set. When nil, they will not be indented.
1173 - TAB indents a line relative to context. The lines below a headline
1174 will be indented when this variable is set.
1176 Note that this is all about true indentation, by adding and removing
1177 space characters. See also `org-indent.el' which does level-dependent
1178 indentation in a virtual way, i.e. at display time in Emacs."
1179 :group 'org-edit-structure
1180 :type 'boolean)
1182 (defcustom org-special-ctrl-a/e nil
1183 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1185 When t, `C-a' will bring back the cursor to the beginning of the
1186 headline text, i.e. after the stars and after a possible TODO
1187 keyword. In an item, this will be the position after bullet and
1188 check-box, if any. When the cursor is already at that position,
1189 another `C-a' will bring it to the beginning of the line.
1191 `C-e' will jump to the end of the headline, ignoring the presence
1192 of tags in the headline. A second `C-e' will then jump to the
1193 true end of the line, after any tags. This also means that, when
1194 this variable is non-nil, `C-e' also will never jump beyond the
1195 end of the heading of a folded section, i.e. not after the
1196 ellipses.
1198 When set to the symbol `reversed', the first `C-a' or `C-e' works
1199 normally, going to the true line boundary first. Only a directly
1200 following, identical keypress will bring the cursor to the
1201 special positions.
1203 This may also be a cons cell where the behavior for `C-a' and
1204 `C-e' is set separately."
1205 :group 'org-edit-structure
1206 :type '(choice
1207 (const :tag "off" nil)
1208 (const :tag "on: after stars/bullet and before tags first" t)
1209 (const :tag "reversed: true line boundary first" reversed)
1210 (cons :tag "Set C-a and C-e separately"
1211 (choice :tag "Special C-a"
1212 (const :tag "off" nil)
1213 (const :tag "on: after stars/bullet first" t)
1214 (const :tag "reversed: before stars/bullet first" reversed))
1215 (choice :tag "Special C-e"
1216 (const :tag "off" nil)
1217 (const :tag "on: before tags first" t)
1218 (const :tag "reversed: after tags first" reversed)))))
1219 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1221 (defcustom org-special-ctrl-k nil
1222 "Non-nil means `C-k' will behave specially in headlines.
1223 When nil, `C-k' will call the default `kill-line' command.
1224 When t, the following will happen while the cursor is in the headline:
1226 - When the cursor is at the beginning of a headline, kill the entire
1227 line and possible the folded subtree below the line.
1228 - When in the middle of the headline text, kill the headline up to the tags.
1229 - When after the headline text, kill the tags."
1230 :group 'org-edit-structure
1231 :type 'boolean)
1233 (defcustom org-ctrl-k-protect-subtree nil
1234 "Non-nil means, do not delete a hidden subtree with C-k.
1235 When set to the symbol `error', simply throw an error when C-k is
1236 used to kill (part-of) a headline that has hidden text behind it.
1237 Any other non-nil value will result in a query to the user, if it is
1238 OK to kill that hidden subtree. When nil, kill without remorse."
1239 :group 'org-edit-structure
1240 :version "24.1"
1241 :type '(choice
1242 (const :tag "Do not protect hidden subtrees" nil)
1243 (const :tag "Protect hidden subtrees with a security query" t)
1244 (const :tag "Never kill a hidden subtree with C-k" error)))
1246 (defcustom org-catch-invisible-edits nil
1247 "Check if in invisible region before inserting or deleting a character.
1248 Valid values are:
1250 nil Do not check, so just do invisible edits.
1251 error Throw an error and do nothing.
1252 show Make point visible, and do the requested edit.
1253 show-and-error Make point visible, then throw an error and abort the edit.
1254 smart Make point visible, and do insertion/deletion if it is
1255 adjacent to visible text and the change feels predictable.
1256 Never delete a previously invisible character or add in the
1257 middle or right after an invisible region. Basically, this
1258 allows insertion and backward-delete right before ellipses.
1259 FIXME: maybe in this case we should not even show?"
1260 :group 'org-edit-structure
1261 :version "24.1"
1262 :type '(choice
1263 (const :tag "Do not check" nil)
1264 (const :tag "Throw error when trying to edit" error)
1265 (const :tag "Unhide, but do not do the edit" show-and-error)
1266 (const :tag "Show invisible part and do the edit" show)
1267 (const :tag "Be smart and do the right thing" smart)))
1269 (defcustom org-yank-folded-subtrees t
1270 "Non-nil means when yanking subtrees, fold them.
1271 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1272 it starts with a heading and all other headings in it are either children
1273 or siblings, then fold all the subtrees. However, do this only if no
1274 text after the yank would be swallowed into a folded tree by this action."
1275 :group 'org-edit-structure
1276 :type 'boolean)
1278 (defcustom org-yank-adjusted-subtrees nil
1279 "Non-nil means when yanking subtrees, adjust the level.
1280 With this setting, `org-paste-subtree' is used to insert the subtree, see
1281 this function for details."
1282 :group 'org-edit-structure
1283 :type 'boolean)
1285 (defcustom org-M-RET-may-split-line '((default . t))
1286 "Non-nil means M-RET will split the line at the cursor position.
1287 When nil, it will go to the end of the line before making a
1288 new line.
1289 You may also set this option in a different way for different
1290 contexts. Valid contexts are:
1292 headline when creating a new headline
1293 item when creating a new item
1294 table in a table field
1295 default the value to be used for all contexts not explicitly
1296 customized"
1297 :group 'org-structure
1298 :group 'org-table
1299 :type '(choice
1300 (const :tag "Always" t)
1301 (const :tag "Never" nil)
1302 (repeat :greedy t :tag "Individual contexts"
1303 (cons
1304 (choice :tag "Context"
1305 (const headline)
1306 (const item)
1307 (const table)
1308 (const default))
1309 (boolean)))))
1312 (defcustom org-insert-heading-respect-content nil
1313 "Non-nil means insert new headings after the current subtree.
1314 When nil, the new heading is created directly after the current line.
1315 The commands \\[org-insert-heading-respect-content] and
1316 \\[org-insert-todo-heading-respect-content] turn this variable on
1317 for the duration of the command."
1318 :group 'org-structure
1319 :type 'boolean)
1321 (defcustom org-blank-before-new-entry '((heading . auto)
1322 (plain-list-item . auto))
1323 "Should `org-insert-heading' leave a blank line before new heading/item?
1324 The value is an alist, with `heading' and `plain-list-item' as CAR,
1325 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1326 which case Org will look at the surrounding headings/items and try to
1327 make an intelligent decision whether to insert a blank line or not.
1329 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1330 the setting here is ignored and no empty line is inserted to avoid breaking
1331 the list structure."
1332 :group 'org-edit-structure
1333 :type '(list
1334 (cons (const heading)
1335 (choice (const :tag "Never" nil)
1336 (const :tag "Always" t)
1337 (const :tag "Auto" auto)))
1338 (cons (const plain-list-item)
1339 (choice (const :tag "Never" nil)
1340 (const :tag "Always" t)
1341 (const :tag "Auto" auto)))))
1343 (defcustom org-insert-heading-hook nil
1344 "Hook being run after inserting a new heading."
1345 :group 'org-edit-structure
1346 :type 'hook)
1348 (defcustom org-enable-fixed-width-editor t
1349 "Non-nil means lines starting with \":\" are treated as fixed-width.
1350 This currently only means they are never auto-wrapped.
1351 When nil, such lines will be treated like ordinary lines.
1352 See also the QUOTE keyword."
1353 :group 'org-edit-structure
1354 :type 'boolean)
1356 (defcustom org-goto-auto-isearch t
1357 "Non-nil means typing characters in `org-goto' starts incremental search.
1358 When nil, you can use these keybindings to navigate the buffer:
1360 q Quit the org-goto interface
1361 n Go to the next visible heading
1362 p Go to the previous visible heading
1363 f Go one heading forward on same level
1364 b Go one heading backward on same level
1365 u Go one heading up"
1366 :group 'org-edit-structure
1367 :type 'boolean)
1369 (defgroup org-sparse-trees nil
1370 "Options concerning sparse trees in Org-mode."
1371 :tag "Org Sparse Trees"
1372 :group 'org-structure)
1374 (defcustom org-highlight-sparse-tree-matches t
1375 "Non-nil means highlight all matches that define a sparse tree.
1376 The highlights will automatically disappear the next time the buffer is
1377 changed by an edit command."
1378 :group 'org-sparse-trees
1379 :type 'boolean)
1381 (defcustom org-remove-highlights-with-change t
1382 "Non-nil means any change to the buffer will remove temporary highlights.
1383 Such highlights are created by `org-occur' and `org-clock-display'.
1384 When nil, `C-c C-c needs to be used to get rid of the highlights.
1385 The highlights created by `org-preview-latex-fragment' always need
1386 `C-c C-c' to be removed."
1387 :group 'org-sparse-trees
1388 :group 'org-time
1389 :type 'boolean)
1392 (defcustom org-occur-hook '(org-first-headline-recenter)
1393 "Hook that is run after `org-occur' has constructed a sparse tree.
1394 This can be used to recenter the window to show as much of the structure
1395 as possible."
1396 :group 'org-sparse-trees
1397 :type 'hook)
1399 (defgroup org-imenu-and-speedbar nil
1400 "Options concerning imenu and speedbar in Org-mode."
1401 :tag "Org Imenu and Speedbar"
1402 :group 'org-structure)
1404 (defcustom org-imenu-depth 2
1405 "The maximum level for Imenu access to Org-mode headlines.
1406 This also applied for speedbar access."
1407 :group 'org-imenu-and-speedbar
1408 :type 'integer)
1410 (defgroup org-table nil
1411 "Options concerning tables in Org-mode."
1412 :tag "Org Table"
1413 :group 'org)
1415 (defcustom org-enable-table-editor 'optimized
1416 "Non-nil means lines starting with \"|\" are handled by the table editor.
1417 When nil, such lines will be treated like ordinary lines.
1419 When equal to the symbol `optimized', the table editor will be optimized to
1420 do the following:
1421 - Automatic overwrite mode in front of whitespace in table fields.
1422 This makes the structure of the table stay in tact as long as the edited
1423 field does not exceed the column width.
1424 - Minimize the number of realigns. Normally, the table is aligned each time
1425 TAB or RET are pressed to move to another field. With optimization this
1426 happens only if changes to a field might have changed the column width.
1427 Optimization requires replacing the functions `self-insert-command',
1428 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1429 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1430 very good at guessing when a re-align will be necessary, but you can always
1431 force one with \\[org-ctrl-c-ctrl-c].
1433 If you would like to use the optimized version in Org-mode, but the
1434 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1436 This variable can be used to turn on and off the table editor during a session,
1437 but in order to toggle optimization, a restart is required.
1439 See also the variable `org-table-auto-blank-field'."
1440 :group 'org-table
1441 :type '(choice
1442 (const :tag "off" nil)
1443 (const :tag "on" t)
1444 (const :tag "on, optimized" optimized)))
1446 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1447 (version<= emacs-version "24.1"))
1448 "Non-nil means cluster self-insert commands for undo when possible.
1449 If this is set, then, like in the Emacs command loop, 20 consecutive
1450 characters will be undone together.
1451 This is configurable, because there is some impact on typing performance."
1452 :group 'org-table
1453 :type 'boolean)
1455 (defcustom org-table-tab-recognizes-table.el t
1456 "Non-nil means TAB will automatically notice a table.el table.
1457 When it sees such a table, it moves point into it and - if necessary -
1458 calls `table-recognize-table'."
1459 :group 'org-table-editing
1460 :type 'boolean)
1462 (defgroup org-link nil
1463 "Options concerning links in Org-mode."
1464 :tag "Org Link"
1465 :group 'org)
1467 (defvar org-link-abbrev-alist-local nil
1468 "Buffer-local version of `org-link-abbrev-alist', which see.
1469 The value of this is taken from the #+LINK lines.")
1470 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1472 (defcustom org-link-abbrev-alist nil
1473 "Alist of link abbreviations.
1474 The car of each element is a string, to be replaced at the start of a link.
1475 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1476 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1478 [[linkkey:tag][description]]
1480 The 'linkkey' must be a word word, starting with a letter, followed
1481 by letters, numbers, '-' or '_'.
1483 If REPLACE is a string, the tag will simply be appended to create the link.
1484 If the string contains \"%s\", the tag will be inserted there. If the string
1485 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1486 at that point (see the function `url-hexify-string'). If the string contains
1487 the specifier \"%(my-function)\", then the custom function `my-function' will
1488 be invoked: this function takes the tag as its only argument and must return
1489 a string.
1491 REPLACE may also be a function that will be called with the tag as the
1492 only argument to create the link, which should be returned as a string.
1494 See the manual for examples."
1495 :group 'org-link
1496 :type '(repeat
1497 (cons
1498 (string :tag "Protocol")
1499 (choice
1500 (string :tag "Format")
1501 (function)))))
1503 (defcustom org-descriptive-links t
1504 "Non-nil means Org will display descriptive links.
1505 E.g. [[http://orgmode.org][Org website]] will be displayed as
1506 \"Org Website\", hiding the link itself and just displaying its
1507 description. When set to `nil', Org will display the full links
1508 literally.
1510 You can interactively set the value of this variable by calling
1511 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1512 :group 'org-link
1513 :type 'boolean)
1515 (defcustom org-link-file-path-type 'adaptive
1516 "How the path name in file links should be stored.
1517 Valid values are:
1519 relative Relative to the current directory, i.e. the directory of the file
1520 into which the link is being inserted.
1521 absolute Absolute path, if possible with ~ for home directory.
1522 noabbrev Absolute path, no abbreviation of home directory.
1523 adaptive Use relative path for files in the current directory and sub-
1524 directories of it. For other files, use an absolute path."
1525 :group 'org-link
1526 :type '(choice
1527 (const relative)
1528 (const absolute)
1529 (const noabbrev)
1530 (const adaptive)))
1532 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1533 "Types of links that should be activated in Org-mode files.
1534 This is a list of symbols, each leading to the activation of a certain link
1535 type. In principle, it does not hurt to turn on most link types - there may
1536 be a small gain when turning off unused link types. The types are:
1538 bracket The recommended [[link][description]] or [[link]] links with hiding.
1539 angle Links in angular brackets that may contain whitespace like
1540 <bbdb:Carsten Dominik>.
1541 plain Plain links in normal text, no whitespace, like http://google.com.
1542 radio Text that is matched by a radio target, see manual for details.
1543 tag Tag settings in a headline (link to tag search).
1544 date Time stamps (link to calendar).
1545 footnote Footnote labels.
1547 Changing this variable requires a restart of Emacs to become effective."
1548 :group 'org-link
1549 :type '(set :greedy t
1550 (const :tag "Double bracket links" bracket)
1551 (const :tag "Angular bracket links" angle)
1552 (const :tag "Plain text links" plain)
1553 (const :tag "Radio target matches" radio)
1554 (const :tag "Tags" tag)
1555 (const :tag "Timestamps" date)
1556 (const :tag "Footnotes" footnote)))
1558 (defcustom org-make-link-description-function nil
1559 "Function to use for generating link descriptions from links.
1560 When nil, the link location will be used. This function must take
1561 two parameters: the first one is the link, the second one is the
1562 description generated by `org-insert-link'. The function should
1563 return the description to use."
1564 :group 'org-link
1565 :type 'function)
1567 (defgroup org-link-store nil
1568 "Options concerning storing links in Org-mode."
1569 :tag "Org Store Link"
1570 :group 'org-link)
1572 (defcustom org-url-hexify-p t
1573 "When non-nil, hexify URL when creating a link."
1574 :type 'boolean
1575 :version "24.3"
1576 :group 'org-link-store)
1578 (defcustom org-email-link-description-format "Email %c: %.30s"
1579 "Format of the description part of a link to an email or usenet message.
1580 The following %-escapes will be replaced by corresponding information:
1582 %F full \"From\" field
1583 %f name, taken from \"From\" field, address if no name
1584 %T full \"To\" field
1585 %t first name in \"To\" field, address if no name
1586 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1587 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1588 %s subject
1589 %d date
1590 %m message-id.
1592 You may use normal field width specification between the % and the letter.
1593 This is for example useful to limit the length of the subject.
1595 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1596 :group 'org-link-store
1597 :type 'string)
1599 (defcustom org-from-is-user-regexp
1600 (let (r1 r2)
1601 (when (and user-mail-address (not (string= user-mail-address "")))
1602 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1603 (when (and user-full-name (not (string= user-full-name "")))
1604 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1605 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1606 "Regexp matched against the \"From:\" header of an email or usenet message.
1607 It should match if the message is from the user him/herself."
1608 :group 'org-link-store
1609 :type 'regexp)
1611 (defcustom org-context-in-file-links t
1612 "Non-nil means file links from `org-store-link' contain context.
1613 A search string will be added to the file name with :: as separator and
1614 used to find the context when the link is activated by the command
1615 `org-open-at-point'. When this option is t, the entire active region
1616 will be placed in the search string of the file link. If set to a
1617 positive integer, only the first n lines of context will be stored.
1619 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1620 negates this setting for the duration of the command."
1621 :group 'org-link-store
1622 :type '(choice boolean integer))
1624 (defcustom org-keep-stored-link-after-insertion nil
1625 "Non-nil means keep link in list for entire session.
1627 The command `org-store-link' adds a link pointing to the current
1628 location to an internal list. These links accumulate during a session.
1629 The command `org-insert-link' can be used to insert links into any
1630 Org-mode file (offering completion for all stored links). When this
1631 option is nil, every link which has been inserted once using \\[org-insert-link]
1632 will be removed from the list, to make completing the unused links
1633 more efficient."
1634 :group 'org-link-store
1635 :type 'boolean)
1637 (defgroup org-link-follow nil
1638 "Options concerning following links in Org-mode."
1639 :tag "Org Follow Link"
1640 :group 'org-link)
1642 (defcustom org-link-translation-function nil
1643 "Function to translate links with different syntax to Org syntax.
1644 This can be used to translate links created for example by the Planner
1645 or emacs-wiki packages to Org syntax.
1646 The function must accept two parameters, a TYPE containing the link
1647 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1648 which is everything after the link protocol. It should return a cons
1649 with possibly modified values of type and path.
1650 Org contains a function for this, so if you set this variable to
1651 `org-translate-link-from-planner', you should be able follow many
1652 links created by planner."
1653 :group 'org-link-follow
1654 :type 'function)
1656 (defcustom org-follow-link-hook nil
1657 "Hook that is run after a link has been followed."
1658 :group 'org-link-follow
1659 :type 'hook)
1661 (defcustom org-tab-follows-link nil
1662 "Non-nil means on links TAB will follow the link.
1663 Needs to be set before org.el is loaded.
1664 This really should not be used, it does not make sense, and the
1665 implementation is bad."
1666 :group 'org-link-follow
1667 :type 'boolean)
1669 (defcustom org-return-follows-link nil
1670 "Non-nil means on links RET will follow the link.
1671 In tables, the special behavior of RET has precedence."
1672 :group 'org-link-follow
1673 :type 'boolean)
1675 (defcustom org-mouse-1-follows-link
1676 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1677 "Non-nil means mouse-1 on a link will follow the link.
1678 A longer mouse click will still set point. Does not work on XEmacs.
1679 Needs to be set before org.el is loaded."
1680 :group 'org-link-follow
1681 :type 'boolean)
1683 (defcustom org-mark-ring-length 4
1684 "Number of different positions to be recorded in the ring.
1685 Changing this requires a restart of Emacs to work correctly."
1686 :group 'org-link-follow
1687 :type 'integer)
1689 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1690 "Non-nil means internal links in Org files must exactly match a headline.
1691 When nil, the link search tries to match a phrase with all words
1692 in the search text."
1693 :group 'org-link-follow
1694 :version "24.1"
1695 :type '(choice
1696 (const :tag "Use fuzzy text search" nil)
1697 (const :tag "Match only exact headline" t)
1698 (const :tag "Match exact headline or query to create it"
1699 query-to-create)))
1701 (defcustom org-link-frame-setup
1702 '((vm . vm-visit-folder-other-frame)
1703 (vm-imap . vm-visit-imap-folder-other-frame)
1704 (gnus . org-gnus-no-new-news)
1705 (file . find-file-other-window)
1706 (wl . wl-other-frame))
1707 "Setup the frame configuration for following links.
1708 When following a link with Emacs, it may often be useful to display
1709 this link in another window or frame. This variable can be used to
1710 set this up for the different types of links.
1711 For VM, use any of
1712 `vm-visit-folder'
1713 `vm-visit-folder-other-window'
1714 `vm-visit-folder-other-frame'
1715 For Gnus, use any of
1716 `gnus'
1717 `gnus-other-frame'
1718 `org-gnus-no-new-news'
1719 For FILE, use any of
1720 `find-file'
1721 `find-file-other-window'
1722 `find-file-other-frame'
1723 For Wanderlust use any of
1724 `wl'
1725 `wl-other-frame'
1726 For the calendar, use the variable `calendar-setup'.
1727 For BBDB, it is currently only possible to display the matches in
1728 another window."
1729 :group 'org-link-follow
1730 :type '(list
1731 (cons (const vm)
1732 (choice
1733 (const vm-visit-folder)
1734 (const vm-visit-folder-other-window)
1735 (const vm-visit-folder-other-frame)))
1736 (cons (const gnus)
1737 (choice
1738 (const gnus)
1739 (const gnus-other-frame)
1740 (const org-gnus-no-new-news)))
1741 (cons (const file)
1742 (choice
1743 (const find-file)
1744 (const find-file-other-window)
1745 (const find-file-other-frame)))
1746 (cons (const wl)
1747 (choice
1748 (const wl)
1749 (const wl-other-frame)))))
1751 (defcustom org-display-internal-link-with-indirect-buffer nil
1752 "Non-nil means use indirect buffer to display infile links.
1753 Activating internal links (from one location in a file to another location
1754 in the same file) normally just jumps to the location. When the link is
1755 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1756 is displayed in
1757 another window. When this option is set, the other window actually displays
1758 an indirect buffer clone of the current buffer, to avoid any visibility
1759 changes to the current buffer."
1760 :group 'org-link-follow
1761 :type 'boolean)
1763 (defcustom org-open-non-existing-files nil
1764 "Non-nil means `org-open-file' will open non-existing files.
1765 When nil, an error will be generated.
1766 This variable applies only to external applications because they
1767 might choke on non-existing files. If the link is to a file that
1768 will be opened in Emacs, the variable is ignored."
1769 :group 'org-link-follow
1770 :type 'boolean)
1772 (defcustom org-open-directory-means-index-dot-org nil
1773 "Non-nil means a link to a directory really means to index.org.
1774 When nil, following a directory link will run dired or open a finder/explorer
1775 window on that directory."
1776 :group 'org-link-follow
1777 :type 'boolean)
1779 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1780 "Function and arguments to call for following mailto links.
1781 This is a list with the first element being a Lisp function, and the
1782 remaining elements being arguments to the function. In string arguments,
1783 %a will be replaced by the address, and %s will be replaced by the subject
1784 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1785 :group 'org-link-follow
1786 :type '(choice
1787 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1788 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1789 (const :tag "message-mail" (message-mail "%a" "%s"))
1790 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1792 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1793 "Non-nil means ask for confirmation before executing shell links.
1794 Shell links can be dangerous: just think about a link
1796 [[shell:rm -rf ~/*][Google Search]]
1798 This link would show up in your Org-mode document as \"Google Search\",
1799 but really it would remove your entire home directory.
1800 Therefore we advise against setting this variable to nil.
1801 Just change it to `y-or-n-p' if you want to confirm with a
1802 single keystroke rather than having to type \"yes\"."
1803 :group 'org-link-follow
1804 :type '(choice
1805 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1806 (const :tag "with y-or-n (faster)" y-or-n-p)
1807 (const :tag "no confirmation (dangerous)" nil)))
1808 (put 'org-confirm-shell-link-function
1809 'safe-local-variable
1810 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1812 (defcustom org-confirm-shell-link-not-regexp ""
1813 "A regexp to skip confirmation for shell links."
1814 :group 'org-link-follow
1815 :version "24.1"
1816 :type 'regexp)
1818 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1819 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1820 Elisp links can be dangerous: just think about a link
1822 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1824 This link would show up in your Org-mode document as \"Google Search\",
1825 but really it would remove your entire home directory.
1826 Therefore we advise against setting this variable to nil.
1827 Just change it to `y-or-n-p' if you want to confirm with a
1828 single keystroke rather than having to type \"yes\"."
1829 :group 'org-link-follow
1830 :type '(choice
1831 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1832 (const :tag "with y-or-n (faster)" y-or-n-p)
1833 (const :tag "no confirmation (dangerous)" nil)))
1834 (put 'org-confirm-shell-link-function
1835 'safe-local-variable
1836 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1838 (defcustom org-confirm-elisp-link-not-regexp ""
1839 "A regexp to skip confirmation for Elisp links."
1840 :group 'org-link-follow
1841 :version "24.1"
1842 :type 'regexp)
1844 (defconst org-file-apps-defaults-gnu
1845 '((remote . emacs)
1846 (system . mailcap)
1847 (t . mailcap))
1848 "Default file applications on a UNIX or GNU/Linux system.
1849 See `org-file-apps'.")
1851 (defconst org-file-apps-defaults-macosx
1852 '((remote . emacs)
1853 (t . "open %s")
1854 (system . "open %s")
1855 ("ps.gz" . "gv %s")
1856 ("eps.gz" . "gv %s")
1857 ("dvi" . "xdvi %s")
1858 ("fig" . "xfig %s"))
1859 "Default file applications on a MacOS X system.
1860 The system \"open\" is known as a default, but we use X11 applications
1861 for some files for which the OS does not have a good default.
1862 See `org-file-apps'.")
1864 (defconst org-file-apps-defaults-windowsnt
1865 (list
1866 '(remote . emacs)
1867 (cons t
1868 (list (if (featurep 'xemacs)
1869 'mswindows-shell-execute
1870 'w32-shell-execute)
1871 "open" 'file))
1872 (cons 'system
1873 (list (if (featurep 'xemacs)
1874 'mswindows-shell-execute
1875 'w32-shell-execute)
1876 "open" 'file)))
1877 "Default file applications on a Windows NT system.
1878 The system \"open\" is used for most files.
1879 See `org-file-apps'.")
1881 (defcustom org-file-apps
1883 (auto-mode . emacs)
1884 ("\\.mm\\'" . default)
1885 ("\\.x?html?\\'" . default)
1886 ("\\.pdf\\'" . default)
1888 "External applications for opening `file:path' items in a document.
1889 Org-mode uses system defaults for different file types, but
1890 you can use this variable to set the application for a given file
1891 extension. The entries in this list are cons cells where the car identifies
1892 files and the cdr the corresponding command. Possible values for the
1893 file identifier are
1894 \"string\" A string as a file identifier can be interpreted in different
1895 ways, depending on its contents:
1897 - Alphanumeric characters only:
1898 Match links with this file extension.
1899 Example: (\"pdf\" . \"evince %s\")
1900 to open PDFs with evince.
1902 - Regular expression: Match links where the
1903 filename matches the regexp. If you want to
1904 use groups here, use shy groups.
1906 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1907 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1908 to open *.html and *.xhtml with firefox.
1910 - Regular expression which contains (non-shy) groups:
1911 Match links where the whole link, including \"::\", and
1912 anything after that, matches the regexp.
1913 In a custom command string, %1, %2, etc. are replaced with
1914 the parts of the link that were matched by the groups.
1915 For backwards compatibility, if a command string is given
1916 that does not use any of the group matches, this case is
1917 handled identically to the second one (i.e. match against
1918 file name only).
1919 In a custom lisp form, you can access the group matches with
1920 (match-string n link).
1922 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1923 to open [[file:document.pdf::5]] with evince at page 5.
1925 `directory' Matches a directory
1926 `remote' Matches a remote file, accessible through tramp or efs.
1927 Remote files most likely should be visited through Emacs
1928 because external applications cannot handle such paths.
1929 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1930 so all files Emacs knows how to handle. Using this with
1931 command `emacs' will open most files in Emacs. Beware that this
1932 will also open html files inside Emacs, unless you add
1933 (\"html\" . default) to the list as well.
1934 t Default for files not matched by any of the other options.
1935 `system' The system command to open files, like `open' on Windows
1936 and Mac OS X, and mailcap under GNU/Linux. This is the command
1937 that will be selected if you call `C-c C-o' with a double
1938 \\[universal-argument] \\[universal-argument] prefix.
1940 Possible values for the command are:
1941 `emacs' The file will be visited by the current Emacs process.
1942 `default' Use the default application for this file type, which is the
1943 association for t in the list, most likely in the system-specific
1944 part.
1945 This can be used to overrule an unwanted setting in the
1946 system-specific variable.
1947 `system' Use the system command for opening files, like \"open\".
1948 This command is specified by the entry whose car is `system'.
1949 Most likely, the system-specific version of this variable
1950 does define this command, but you can overrule/replace it
1951 here.
1952 string A command to be executed by a shell; %s will be replaced
1953 by the path to the file.
1954 sexp A Lisp form which will be evaluated. The file path will
1955 be available in the Lisp variable `file'.
1956 For more examples, see the system specific constants
1957 `org-file-apps-defaults-macosx'
1958 `org-file-apps-defaults-windowsnt'
1959 `org-file-apps-defaults-gnu'."
1960 :group 'org-link-follow
1961 :type '(repeat
1962 (cons (choice :value ""
1963 (string :tag "Extension")
1964 (const :tag "System command to open files" system)
1965 (const :tag "Default for unrecognized files" t)
1966 (const :tag "Remote file" remote)
1967 (const :tag "Links to a directory" directory)
1968 (const :tag "Any files that have Emacs modes"
1969 auto-mode))
1970 (choice :value ""
1971 (const :tag "Visit with Emacs" emacs)
1972 (const :tag "Use default" default)
1973 (const :tag "Use the system command" system)
1974 (string :tag "Command")
1975 (sexp :tag "Lisp form")))))
1977 (defcustom org-doi-server-url "http://dx.doi.org/"
1978 "The URL of the DOI server."
1979 :type 'string
1980 :version "24.3"
1981 :group 'org-link-follow)
1983 (defgroup org-refile nil
1984 "Options concerning refiling entries in Org-mode."
1985 :tag "Org Refile"
1986 :group 'org)
1988 (defcustom org-directory "~/org"
1989 "Directory with org files.
1990 This is just a default location to look for Org files. There is no need
1991 at all to put your files into this directory. It is only used in the
1992 following situations:
1994 1. When a capture template specifies a target file that is not an
1995 absolute path. The path will then be interpreted relative to
1996 `org-directory'
1997 2. When a capture note is filed away in an interactive way (when exiting the
1998 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1999 with `org-directory' as the default path."
2000 :group 'org-refile
2001 :group 'org-remember
2002 :group 'org-capture
2003 :type 'directory)
2005 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2006 "Default target for storing notes.
2007 Used as a fall back file for org-remember.el and org-capture.el, for
2008 templates that do not specify a target file."
2009 :group 'org-refile
2010 :group 'org-remember
2011 :group 'org-capture
2012 :type '(choice
2013 (const :tag "Default from remember-data-file" nil)
2014 file))
2016 (defcustom org-goto-interface 'outline
2017 "The default interface to be used for `org-goto'.
2018 Allowed values are:
2019 outline The interface shows an outline of the relevant file
2020 and the correct heading is found by moving through
2021 the outline or by searching with incremental search.
2022 outline-path-completion Headlines in the current buffer are offered via
2023 completion. This is the interface also used by
2024 the refile command."
2025 :group 'org-refile
2026 :type '(choice
2027 (const :tag "Outline" outline)
2028 (const :tag "Outline-path-completion" outline-path-completion)))
2030 (defcustom org-goto-max-level 5
2031 "Maximum target level when running `org-goto' with refile interface."
2032 :group 'org-refile
2033 :type 'integer)
2035 (defcustom org-reverse-note-order nil
2036 "Non-nil means store new notes at the beginning of a file or entry.
2037 When nil, new notes will be filed to the end of a file or entry.
2038 This can also be a list with cons cells of regular expressions that
2039 are matched against file names, and values."
2040 :group 'org-remember
2041 :group 'org-capture
2042 :group 'org-refile
2043 :type '(choice
2044 (const :tag "Reverse always" t)
2045 (const :tag "Reverse never" nil)
2046 (repeat :tag "By file name regexp"
2047 (cons regexp boolean))))
2049 (defcustom org-log-refile nil
2050 "Information to record when a task is refiled.
2052 Possible values are:
2054 nil Don't add anything
2055 time Add a time stamp to the task
2056 note Prompt for a note and add it with template `org-log-note-headings'
2058 This option can also be set with on a per-file-basis with
2060 #+STARTUP: nologrefile
2061 #+STARTUP: logrefile
2062 #+STARTUP: lognoterefile
2064 You can have local logging settings for a subtree by setting the LOGGING
2065 property to one or more of these keywords.
2067 When bulk-refiling from the agenda, the value `note' is forbidden and
2068 will temporarily be changed to `time'."
2069 :group 'org-refile
2070 :group 'org-progress
2071 :version "24.1"
2072 :type '(choice
2073 (const :tag "No logging" nil)
2074 (const :tag "Record timestamp" time)
2075 (const :tag "Record timestamp with note." note)))
2077 (defcustom org-refile-targets nil
2078 "Targets for refiling entries with \\[org-refile].
2079 This is a list of cons cells. Each cell contains:
2080 - a specification of the files to be considered, either a list of files,
2081 or a symbol whose function or variable value will be used to retrieve
2082 a file name or a list of file names. If you use `org-agenda-files' for
2083 that, all agenda files will be scanned for targets. Nil means consider
2084 headings in the current buffer.
2085 - A specification of how to find candidate refile targets. This may be
2086 any of:
2087 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2088 This tag has to be present in all target headlines, inheritance will
2089 not be considered.
2090 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2091 todo keyword.
2092 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2093 headlines that are refiling targets.
2094 - a cons cell (:level . N). Any headline of level N is considered a target.
2095 Note that, when `org-odd-levels-only' is set, level corresponds to
2096 order in hierarchy, not to the number of stars.
2097 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2098 Note that, when `org-odd-levels-only' is set, level corresponds to
2099 order in hierarchy, not to the number of stars.
2101 Each element of this list generates a set of possible targets.
2102 The union of these sets is presented (with completion) to
2103 the user by `org-refile'.
2105 You can set the variable `org-refile-target-verify-function' to a function
2106 to verify each headline found by the simple criteria above.
2108 When this variable is nil, all top-level headlines in the current buffer
2109 are used, equivalent to the value `((nil . (:level . 1))'."
2110 :group 'org-refile
2111 :type '(repeat
2112 (cons
2113 (choice :value org-agenda-files
2114 (const :tag "All agenda files" org-agenda-files)
2115 (const :tag "Current buffer" nil)
2116 (function) (variable) (file))
2117 (choice :tag "Identify target headline by"
2118 (cons :tag "Specific tag" (const :value :tag) (string))
2119 (cons :tag "TODO keyword" (const :value :todo) (string))
2120 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2121 (cons :tag "Level number" (const :value :level) (integer))
2122 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2124 (defcustom org-refile-target-verify-function nil
2125 "Function to verify if the headline at point should be a refile target.
2126 The function will be called without arguments, with point at the
2127 beginning of the headline. It should return t and leave point
2128 where it is if the headline is a valid target for refiling.
2130 If the target should not be selected, the function must return nil.
2131 In addition to this, it may move point to a place from where the search
2132 should be continued. For example, the function may decide that the entire
2133 subtree of the current entry should be excluded and move point to the end
2134 of the subtree."
2135 :group 'org-refile
2136 :type 'function)
2138 (defcustom org-refile-use-cache nil
2139 "Non-nil means cache refile targets to speed up the process.
2140 The cache for a particular file will be updated automatically when
2141 the buffer has been killed, or when any of the marker used for flagging
2142 refile targets no longer points at a live buffer.
2143 If you have added new entries to a buffer that might themselves be targets,
2144 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2145 find that easier, `C-u C-u C-u C-c C-w'."
2146 :group 'org-refile
2147 :version "24.1"
2148 :type 'boolean)
2150 (defcustom org-refile-use-outline-path nil
2151 "Non-nil means provide refile targets as paths.
2152 So a level 3 headline will be available as level1/level2/level3.
2154 When the value is `file', also include the file name (without directory)
2155 into the path. In this case, you can also stop the completion after
2156 the file name, to get entries inserted as top level in the file.
2158 When `full-file-path', include the full file path."
2159 :group 'org-refile
2160 :type '(choice
2161 (const :tag "Not" nil)
2162 (const :tag "Yes" t)
2163 (const :tag "Start with file name" file)
2164 (const :tag "Start with full file path" full-file-path)))
2166 (defcustom org-outline-path-complete-in-steps t
2167 "Non-nil means complete the outline path in hierarchical steps.
2168 When Org-mode uses the refile interface to select an outline path
2169 \(see variable `org-refile-use-outline-path'), the completion of
2170 the path can be done is a single go, or if can be done in steps down
2171 the headline hierarchy. Going in steps is probably the best if you
2172 do not use a special completion package like `ido' or `icicles'.
2173 However, when using these packages, going in one step can be very
2174 fast, while still showing the whole path to the entry."
2175 :group 'org-refile
2176 :type 'boolean)
2178 (defcustom org-refile-allow-creating-parent-nodes nil
2179 "Non-nil means allow to create new nodes as refile targets.
2180 New nodes are then created by adding \"/new node name\" to the completion
2181 of an existing node. When the value of this variable is `confirm',
2182 new node creation must be confirmed by the user (recommended)
2183 When nil, the completion must match an existing entry.
2185 Note that, if the new heading is not seen by the criteria
2186 listed in `org-refile-targets', multiple instances of the same
2187 heading would be created by trying again to file under the new
2188 heading."
2189 :group 'org-refile
2190 :type '(choice
2191 (const :tag "Never" nil)
2192 (const :tag "Always" t)
2193 (const :tag "Prompt for confirmation" confirm)))
2195 (defcustom org-refile-active-region-within-subtree nil
2196 "Non-nil means also refile active region within a subtree.
2198 By default `org-refile' doesn't allow refiling regions if they
2199 don't contain a set of subtrees, but it might be convenient to
2200 do so sometimes: in that case, the first line of the region is
2201 converted to a headline before refiling."
2202 :group 'org-refile
2203 :version "24.1"
2204 :type 'boolean)
2206 (defgroup org-todo nil
2207 "Options concerning TODO items in Org-mode."
2208 :tag "Org TODO"
2209 :group 'org)
2211 (defgroup org-progress nil
2212 "Options concerning Progress logging in Org-mode."
2213 :tag "Org Progress"
2214 :group 'org-time)
2216 (defvar org-todo-interpretation-widgets
2217 '((:tag "Sequence (cycling hits every state)" sequence)
2218 (:tag "Type (cycling directly to DONE)" type))
2219 "The available interpretation symbols for customizing `org-todo-keywords'.
2220 Interested libraries should add to this list.")
2222 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2223 "List of TODO entry keyword sequences and their interpretation.
2224 \\<org-mode-map>This is a list of sequences.
2226 Each sequence starts with a symbol, either `sequence' or `type',
2227 indicating if the keywords should be interpreted as a sequence of
2228 action steps, or as different types of TODO items. The first
2229 keywords are states requiring action - these states will select a headline
2230 for inclusion into the global TODO list Org-mode produces. If one of
2231 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2232 signify that no further action is necessary. If \"|\" is not found,
2233 the last keyword is treated as the only DONE state of the sequence.
2235 The command \\[org-todo] cycles an entry through these states, and one
2236 additional state where no keyword is present. For details about this
2237 cycling, see the manual.
2239 TODO keywords and interpretation can also be set on a per-file basis with
2240 the special #+SEQ_TODO and #+TYP_TODO lines.
2242 Each keyword can optionally specify a character for fast state selection
2243 \(in combination with the variable `org-use-fast-todo-selection')
2244 and specifiers for state change logging, using the same syntax that
2245 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2246 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2247 indicates to record a time stamp each time this state is selected.
2249 Each keyword may also specify if a timestamp or a note should be
2250 recorded when entering or leaving the state, by adding additional
2251 characters in the parenthesis after the keyword. This looks like this:
2252 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2253 record only the time of the state change. With X and Y being either
2254 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2255 Y when leaving the state if and only if the *target* state does not
2256 define X. You may omit any of the fast-selection key or X or /Y,
2257 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2259 For backward compatibility, this variable may also be just a list
2260 of keywords. In this case the interpretation (sequence or type) will be
2261 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2262 :group 'org-todo
2263 :group 'org-keywords
2264 :type '(choice
2265 (repeat :tag "Old syntax, just keywords"
2266 (string :tag "Keyword"))
2267 (repeat :tag "New syntax"
2268 (cons
2269 (choice
2270 :tag "Interpretation"
2271 ;;Quick and dirty way to see
2272 ;;`org-todo-interpretations'. This takes the
2273 ;;place of item arguments
2274 :convert-widget
2275 (lambda (widget)
2276 (widget-put widget
2277 :args (mapcar
2278 #'(lambda (x)
2279 (widget-convert
2280 (cons 'const x)))
2281 org-todo-interpretation-widgets))
2282 widget))
2283 (repeat
2284 (string :tag "Keyword"))))))
2286 (defvar org-todo-keywords-1 nil
2287 "All TODO and DONE keywords active in a buffer.")
2288 (make-variable-buffer-local 'org-todo-keywords-1)
2289 (defvar org-todo-keywords-for-agenda nil)
2290 (defvar org-done-keywords-for-agenda nil)
2291 (defvar org-drawers-for-agenda nil)
2292 (defvar org-todo-keyword-alist-for-agenda nil)
2293 (defvar org-tag-alist-for-agenda nil
2294 "Alist of all tags from all agenda files.")
2295 (defvar org-tag-groups-alist-for-agenda nil
2296 "Alist of all groups tags from all current agenda files.")
2297 (defvar org-tag-groups-alist nil)
2298 (make-variable-buffer-local 'org-tag-groups-alist)
2299 (defvar org-agenda-contributing-files nil)
2300 (defvar org-not-done-keywords nil)
2301 (make-variable-buffer-local 'org-not-done-keywords)
2302 (defvar org-done-keywords nil)
2303 (make-variable-buffer-local 'org-done-keywords)
2304 (defvar org-todo-heads nil)
2305 (make-variable-buffer-local 'org-todo-heads)
2306 (defvar org-todo-sets nil)
2307 (make-variable-buffer-local 'org-todo-sets)
2308 (defvar org-todo-log-states nil)
2309 (make-variable-buffer-local 'org-todo-log-states)
2310 (defvar org-todo-kwd-alist nil)
2311 (make-variable-buffer-local 'org-todo-kwd-alist)
2312 (defvar org-todo-key-alist nil)
2313 (make-variable-buffer-local 'org-todo-key-alist)
2314 (defvar org-todo-key-trigger nil)
2315 (make-variable-buffer-local 'org-todo-key-trigger)
2317 (defcustom org-todo-interpretation 'sequence
2318 "Controls how TODO keywords are interpreted.
2319 This variable is in principle obsolete and is only used for
2320 backward compatibility, if the interpretation of todo keywords is
2321 not given already in `org-todo-keywords'. See that variable for
2322 more information."
2323 :group 'org-todo
2324 :group 'org-keywords
2325 :type '(choice (const sequence)
2326 (const type)))
2328 (defcustom org-use-fast-todo-selection t
2329 "Non-nil means use the fast todo selection scheme with C-c C-t.
2330 This variable describes if and under what circumstances the cycling
2331 mechanism for TODO keywords will be replaced by a single-key, direct
2332 selection scheme.
2334 When nil, fast selection is never used.
2336 When the symbol `prefix', it will be used when `org-todo' is called
2337 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2338 `C-u t' in an agenda buffer.
2340 When t, fast selection is used by default. In this case, the prefix
2341 argument forces cycling instead.
2343 In all cases, the special interface is only used if access keys have
2344 actually been assigned by the user, i.e. if keywords in the configuration
2345 are followed by a letter in parenthesis, like TODO(t)."
2346 :group 'org-todo
2347 :type '(choice
2348 (const :tag "Never" nil)
2349 (const :tag "By default" t)
2350 (const :tag "Only with C-u C-c C-t" prefix)))
2352 (defcustom org-provide-todo-statistics t
2353 "Non-nil means update todo statistics after insert and toggle.
2354 ALL-HEADLINES means update todo statistics by including headlines
2355 with no TODO keyword as well, counting them as not done.
2356 A list of TODO keywords means the same, but skip keywords that are
2357 not in this list.
2359 When this is set, todo statistics is updated in the parent of the
2360 current entry each time a todo state is changed."
2361 :group 'org-todo
2362 :type '(choice
2363 (const :tag "Yes, only for TODO entries" t)
2364 (const :tag "Yes, including all entries" 'all-headlines)
2365 (repeat :tag "Yes, for TODOs in this list"
2366 (string :tag "TODO keyword"))
2367 (other :tag "No TODO statistics" nil)))
2369 (defcustom org-hierarchical-todo-statistics t
2370 "Non-nil means TODO statistics covers just direct children.
2371 When nil, all entries in the subtree are considered.
2372 This has only an effect if `org-provide-todo-statistics' is set.
2373 To set this to nil for only a single subtree, use a COOKIE_DATA
2374 property and include the word \"recursive\" into the value."
2375 :group 'org-todo
2376 :type 'boolean)
2378 (defcustom org-after-todo-state-change-hook nil
2379 "Hook which is run after the state of a TODO item was changed.
2380 The new state (a string with a TODO keyword, or nil) is available in the
2381 Lisp variable `org-state'."
2382 :group 'org-todo
2383 :type 'hook)
2385 (defvar org-blocker-hook nil
2386 "Hook for functions that are allowed to block a state change.
2388 Functions in this hook should not modify the buffer.
2389 Each function gets as its single argument a property list,
2390 see `org-trigger-hook' for more information about this list.
2392 If any of the functions in this hook returns nil, the state change
2393 is blocked.")
2395 (defvar org-trigger-hook nil
2396 "Hook for functions that are triggered by a state change.
2398 Each function gets as its single argument a property list with at
2399 least the following elements:
2401 (:type type-of-change :position pos-at-entry-start
2402 :from old-state :to new-state)
2404 Depending on the type, more properties may be present.
2406 This mechanism is currently implemented for:
2408 TODO state changes
2409 ------------------
2410 :type todo-state-change
2411 :from previous state (keyword as a string), or nil, or a symbol
2412 'todo' or 'done', to indicate the general type of state.
2413 :to new state, like in :from")
2415 (defcustom org-enforce-todo-dependencies nil
2416 "Non-nil means undone TODO entries will block switching the parent to DONE.
2417 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2418 be blocked if any prior sibling is not yet done.
2419 Finally, if the parent is blocked because of ordered siblings of its own,
2420 the child will also be blocked."
2421 :set (lambda (var val)
2422 (set var val)
2423 (if val
2424 (add-hook 'org-blocker-hook
2425 'org-block-todo-from-children-or-siblings-or-parent)
2426 (remove-hook 'org-blocker-hook
2427 'org-block-todo-from-children-or-siblings-or-parent)))
2428 :group 'org-todo
2429 :type 'boolean)
2431 (defcustom org-enforce-todo-checkbox-dependencies nil
2432 "Non-nil means unchecked boxes will block switching the parent to DONE.
2433 When this is nil, checkboxes have no influence on switching TODO states.
2434 When non-nil, you first need to check off all check boxes before the TODO
2435 entry can be switched to DONE.
2436 This variable needs to be set before org.el is loaded, and you need to
2437 restart Emacs after a change to make the change effective. The only way
2438 to change is while Emacs is running is through the customize interface."
2439 :set (lambda (var val)
2440 (set var val)
2441 (if val
2442 (add-hook 'org-blocker-hook
2443 'org-block-todo-from-checkboxes)
2444 (remove-hook 'org-blocker-hook
2445 'org-block-todo-from-checkboxes)))
2446 :group 'org-todo
2447 :type 'boolean)
2449 (defcustom org-treat-insert-todo-heading-as-state-change nil
2450 "Non-nil means inserting a TODO heading is treated as state change.
2451 So when the command \\[org-insert-todo-heading] is used, state change
2452 logging will apply if appropriate. When nil, the new TODO item will
2453 be inserted directly, and no logging will take place."
2454 :group 'org-todo
2455 :type 'boolean)
2457 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2458 "Non-nil means switching TODO states with S-cursor counts as state change.
2459 This is the default behavior. However, setting this to nil allows a
2460 convenient way to select a TODO state and bypass any logging associated
2461 with that."
2462 :group 'org-todo
2463 :type 'boolean)
2465 (defcustom org-todo-state-tags-triggers nil
2466 "Tag changes that should be triggered by TODO state changes.
2467 This is a list. Each entry is
2469 (state-change (tag . flag) .......)
2471 State-change can be a string with a state, and empty string to indicate the
2472 state that has no TODO keyword, or it can be one of the symbols `todo'
2473 or `done', meaning any not-done or done state, respectively."
2474 :group 'org-todo
2475 :group 'org-tags
2476 :type '(repeat
2477 (cons (choice :tag "When changing to"
2478 (const :tag "Not-done state" todo)
2479 (const :tag "Done state" done)
2480 (string :tag "State"))
2481 (repeat
2482 (cons :tag "Tag action"
2483 (string :tag "Tag")
2484 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2486 (defcustom org-log-done nil
2487 "Information to record when a task moves to the DONE state.
2489 Possible values are:
2491 nil Don't add anything, just change the keyword
2492 time Add a time stamp to the task
2493 note Prompt for a note and add it with template `org-log-note-headings'
2495 This option can also be set with on a per-file-basis with
2497 #+STARTUP: nologdone
2498 #+STARTUP: logdone
2499 #+STARTUP: lognotedone
2501 You can have local logging settings for a subtree by setting the LOGGING
2502 property to one or more of these keywords."
2503 :group 'org-todo
2504 :group 'org-progress
2505 :type '(choice
2506 (const :tag "No logging" nil)
2507 (const :tag "Record CLOSED timestamp" time)
2508 (const :tag "Record CLOSED timestamp with note." note)))
2510 ;; Normalize old uses of org-log-done.
2511 (cond
2512 ((eq org-log-done t) (setq org-log-done 'time))
2513 ((and (listp org-log-done) (memq 'done org-log-done))
2514 (setq org-log-done 'note)))
2516 (defcustom org-log-reschedule nil
2517 "Information to record when the scheduling date of a tasks is modified.
2519 Possible values are:
2521 nil Don't add anything, just change the date
2522 time Add a time stamp to the task
2523 note Prompt for a note and add it with template `org-log-note-headings'
2525 This option can also be set with on a per-file-basis with
2527 #+STARTUP: nologreschedule
2528 #+STARTUP: logreschedule
2529 #+STARTUP: lognotereschedule"
2530 :group 'org-todo
2531 :group 'org-progress
2532 :type '(choice
2533 (const :tag "No logging" nil)
2534 (const :tag "Record timestamp" time)
2535 (const :tag "Record timestamp with note." note)))
2537 (defcustom org-log-redeadline nil
2538 "Information to record when the deadline date of a tasks is modified.
2540 Possible values are:
2542 nil Don't add anything, just change the date
2543 time Add a time stamp to the task
2544 note Prompt for a note and add it with template `org-log-note-headings'
2546 This option can also be set with on a per-file-basis with
2548 #+STARTUP: nologredeadline
2549 #+STARTUP: logredeadline
2550 #+STARTUP: lognoteredeadline
2552 You can have local logging settings for a subtree by setting the LOGGING
2553 property to one or more of these keywords."
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type '(choice
2557 (const :tag "No logging" nil)
2558 (const :tag "Record timestamp" time)
2559 (const :tag "Record timestamp with note." note)))
2561 (defcustom org-log-note-clock-out nil
2562 "Non-nil means record a note when clocking out of an item.
2563 This can also be configured on a per-file basis by adding one of
2564 the following lines anywhere in the buffer:
2566 #+STARTUP: lognoteclock-out
2567 #+STARTUP: nolognoteclock-out"
2568 :group 'org-todo
2569 :group 'org-progress
2570 :type 'boolean)
2572 (defcustom org-log-done-with-time t
2573 "Non-nil means the CLOSED time stamp will contain date and time.
2574 When nil, only the date will be recorded."
2575 :group 'org-progress
2576 :type 'boolean)
2578 (defcustom org-log-note-headings
2579 '((done . "CLOSING NOTE %t")
2580 (state . "State %-12s from %-12S %t")
2581 (note . "Note taken on %t")
2582 (reschedule . "Rescheduled from %S on %t")
2583 (delschedule . "Not scheduled, was %S on %t")
2584 (redeadline . "New deadline from %S on %t")
2585 (deldeadline . "Removed deadline, was %S on %t")
2586 (refile . "Refiled on %t")
2587 (clock-out . ""))
2588 "Headings for notes added to entries.
2589 The value is an alist, with the car being a symbol indicating the note
2590 context, and the cdr is the heading to be used. The heading may also be the
2591 empty string.
2592 %t in the heading will be replaced by a time stamp.
2593 %T will be an active time stamp instead the default inactive one
2594 %d will be replaced by a short-format time stamp.
2595 %D will be replaced by an active short-format time stamp.
2596 %s will be replaced by the new TODO state, in double quotes.
2597 %S will be replaced by the old TODO state, in double quotes.
2598 %u will be replaced by the user name.
2599 %U will be replaced by the full user name.
2601 In fact, it is not a good idea to change the `state' entry, because
2602 agenda log mode depends on the format of these entries."
2603 :group 'org-todo
2604 :group 'org-progress
2605 :type '(list :greedy t
2606 (cons (const :tag "Heading when closing an item" done) string)
2607 (cons (const :tag
2608 "Heading when changing todo state (todo sequence only)"
2609 state) string)
2610 (cons (const :tag "Heading when just taking a note" note) string)
2611 (cons (const :tag "Heading when clocking out" clock-out) string)
2612 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2613 (cons (const :tag "Heading when rescheduling" reschedule) string)
2614 (cons (const :tag "Heading when changing deadline" redeadline) string)
2615 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2616 (cons (const :tag "Heading when refiling" refile) string)))
2618 (unless (assq 'note org-log-note-headings)
2619 (push '(note . "%t") org-log-note-headings))
2621 (defcustom org-log-into-drawer nil
2622 "Non-nil means insert state change notes and time stamps into a drawer.
2623 When nil, state changes notes will be inserted after the headline and
2624 any scheduling and clock lines, but not inside a drawer.
2626 The value of this variable should be the name of the drawer to use.
2627 LOGBOOK is proposed as the default drawer for this purpose, you can
2628 also set this to a string to define the drawer of your choice.
2630 A value of t is also allowed, representing \"LOGBOOK\".
2632 A value of t or nil can also be set with on a per-file-basis with
2634 #+STARTUP: logdrawer
2635 #+STARTUP: nologdrawer
2637 If this variable is set, `org-log-state-notes-insert-after-drawers'
2638 will be ignored.
2640 You can set the property LOG_INTO_DRAWER to overrule this setting for
2641 a subtree."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type '(choice
2645 (const :tag "Not into a drawer" nil)
2646 (const :tag "LOGBOOK" t)
2647 (string :tag "Other")))
2649 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2651 (defun org-log-into-drawer ()
2652 "Return the value of `org-log-into-drawer', but let properties overrule.
2653 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2654 used instead of the default value."
2655 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2656 (cond
2657 ((not p) org-log-into-drawer)
2658 ((equal p "nil") nil)
2659 ((equal p "t") "LOGBOOK")
2660 (t p))))
2662 (defcustom org-log-state-notes-insert-after-drawers nil
2663 "Non-nil means insert state change notes after any drawers in entry.
2664 Only the drawers that *immediately* follow the headline and the
2665 deadline/scheduled line are skipped.
2666 When nil, insert notes right after the heading and perhaps the line
2667 with deadline/scheduling if present.
2669 This variable will have no effect if `org-log-into-drawer' is
2670 set."
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type 'boolean)
2675 (defcustom org-log-states-order-reversed t
2676 "Non-nil means the latest state note will be directly after heading.
2677 When nil, the state change notes will be ordered according to time.
2679 This option can also be set with on a per-file-basis with
2681 #+STARTUP: logstatesreversed
2682 #+STARTUP: nologstatesreversed"
2683 :group 'org-todo
2684 :group 'org-progress
2685 :type 'boolean)
2687 (defcustom org-todo-repeat-to-state nil
2688 "The TODO state to which a repeater should return the repeating task.
2689 By default this is the first task in a TODO sequence, or the previous state
2690 in a TODO_TYP set. But you can specify another task here.
2691 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2692 :group 'org-todo
2693 :version "24.1"
2694 :type '(choice (const :tag "Head of sequence" nil)
2695 (string :tag "Specific state")))
2697 (defcustom org-log-repeat 'time
2698 "Non-nil means record moving through the DONE state when triggering repeat.
2699 An auto-repeating task is immediately switched back to TODO when
2700 marked DONE. If you are not logging state changes (by adding \"@\"
2701 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2702 record a closing note, there will be no record of the task moving
2703 through DONE. This variable forces taking a note anyway.
2705 nil Don't force a record
2706 time Record a time stamp
2707 note Prompt for a note and add it with template `org-log-note-headings'
2709 This option can also be set with on a per-file-basis with
2711 #+STARTUP: nologrepeat
2712 #+STARTUP: logrepeat
2713 #+STARTUP: lognoterepeat
2715 You can have local logging settings for a subtree by setting the LOGGING
2716 property to one or more of these keywords."
2717 :group 'org-todo
2718 :group 'org-progress
2719 :type '(choice
2720 (const :tag "Don't force a record" nil)
2721 (const :tag "Force recording the DONE state" time)
2722 (const :tag "Force recording a note with the DONE state" note)))
2725 (defgroup org-priorities nil
2726 "Priorities in Org-mode."
2727 :tag "Org Priorities"
2728 :group 'org-todo)
2730 (defcustom org-enable-priority-commands t
2731 "Non-nil means priority commands are active.
2732 When nil, these commands will be disabled, so that you never accidentally
2733 set a priority."
2734 :group 'org-priorities
2735 :type 'boolean)
2737 (defcustom org-highest-priority ?A
2738 "The highest priority of TODO items. A character like ?A, ?B etc.
2739 Must have a smaller ASCII number than `org-lowest-priority'."
2740 :group 'org-priorities
2741 :type 'character)
2743 (defcustom org-lowest-priority ?C
2744 "The lowest priority of TODO items. A character like ?A, ?B etc.
2745 Must have a larger ASCII number than `org-highest-priority'."
2746 :group 'org-priorities
2747 :type 'character)
2749 (defcustom org-default-priority ?B
2750 "The default priority of TODO items.
2751 This is the priority an item gets if no explicit priority is given.
2752 When starting to cycle on an empty priority the first step in the cycle
2753 depends on `org-priority-start-cycle-with-default'. The resulting first
2754 step priority must not exceed the range from `org-highest-priority' to
2755 `org-lowest-priority' which means that `org-default-priority' has to be
2756 in this range exclusive or inclusive the range boundaries. Else the
2757 first step refuses to set the default and the second will fall back
2758 to (depending on the command used) the highest or lowest priority."
2759 :group 'org-priorities
2760 :type 'character)
2762 (defcustom org-priority-start-cycle-with-default t
2763 "Non-nil means start with default priority when starting to cycle.
2764 When this is nil, the first step in the cycle will be (depending on the
2765 command used) one higher or lower than the default priority.
2766 See also `org-default-priority'."
2767 :group 'org-priorities
2768 :type 'boolean)
2770 (defcustom org-get-priority-function nil
2771 "Function to extract the priority from a string.
2772 The string is normally the headline. If this is nil Org computes the
2773 priority from the priority cookie like [#A] in the headline. It returns
2774 an integer, increasing by 1000 for each priority level.
2775 The user can set a different function here, which should take a string
2776 as an argument and return the numeric priority."
2777 :group 'org-priorities
2778 :version "24.1"
2779 :type 'function)
2781 (defgroup org-time nil
2782 "Options concerning time stamps and deadlines in Org-mode."
2783 :tag "Org Time"
2784 :group 'org)
2786 (defcustom org-insert-labeled-timestamps-at-point nil
2787 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2788 When nil, these labeled time stamps are forces into the second line of an
2789 entry, just after the headline. When scheduling from the global TODO list,
2790 the time stamp will always be forced into the second line."
2791 :group 'org-time
2792 :type 'boolean)
2794 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2795 "Formats for `format-time-string' which are used for time stamps.
2796 It is not recommended to change this constant.")
2798 (defcustom org-time-stamp-rounding-minutes '(0 5)
2799 "Number of minutes to round time stamps to.
2800 These are two values, the first applies when first creating a time stamp.
2801 The second applies when changing it with the commands `S-up' and `S-down'.
2802 When changing the time stamp, this means that it will change in steps
2803 of N minutes, as given by the second value.
2805 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2806 numbers should be factors of 60, so for example 5, 10, 15.
2808 When this is larger than 1, you can still force an exact time stamp by using
2809 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2810 and by using a prefix arg to `S-up/down' to specify the exact number
2811 of minutes to shift."
2812 :group 'org-time
2813 :get #'(lambda (var) ; Make sure both elements are there
2814 (if (integerp (default-value var))
2815 (list (default-value var) 5)
2816 (default-value var)))
2817 :type '(list
2818 (integer :tag "when inserting times")
2819 (integer :tag "when modifying times")))
2821 ;; Normalize old customizations of this variable.
2822 (when (integerp org-time-stamp-rounding-minutes)
2823 (setq org-time-stamp-rounding-minutes
2824 (list org-time-stamp-rounding-minutes
2825 org-time-stamp-rounding-minutes)))
2827 (defcustom org-display-custom-times nil
2828 "Non-nil means overlay custom formats over all time stamps.
2829 The formats are defined through the variable `org-time-stamp-custom-formats'.
2830 To turn this on on a per-file basis, insert anywhere in the file:
2831 #+STARTUP: customtime"
2832 :group 'org-time
2833 :set 'set-default
2834 :type 'sexp)
2835 (make-variable-buffer-local 'org-display-custom-times)
2837 (defcustom org-time-stamp-custom-formats
2838 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2839 "Custom formats for time stamps. See `format-time-string' for the syntax.
2840 These are overlaid over the default ISO format if the variable
2841 `org-display-custom-times' is set. Time like %H:%M should be at the
2842 end of the second format. The custom formats are also honored by export
2843 commands, if custom time display is turned on at the time of export."
2844 :group 'org-time
2845 :type 'sexp)
2847 (defun org-time-stamp-format (&optional long inactive)
2848 "Get the right format for a time string."
2849 (let ((f (if long (cdr org-time-stamp-formats)
2850 (car org-time-stamp-formats))))
2851 (if inactive
2852 (concat "[" (substring f 1 -1) "]")
2853 f)))
2855 (defcustom org-time-clocksum-format
2856 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2857 "The format string used when creating CLOCKSUM lines.
2858 This is also used when Org mode generates a time duration.
2860 The value can be a single format string containing two
2861 %-sequences, which will be filled with the number of hours and
2862 minutes in that order.
2864 Alternatively, the value can be a plist associating any of the
2865 keys :years, :months, :weeks, :days, :hours or :minutes with
2866 format strings. The time duration is formatted using only the
2867 time components that are needed and concatenating the results.
2868 If a time unit in absent, it falls back to the next smallest
2869 unit.
2871 The keys :require-years, :require-months, :require-days,
2872 :require-weeks, :require-hours, :require-minutes are also
2873 meaningful. A non-nil value for these keys indicates that the
2874 corresponding time component should always be included, even if
2875 its value is 0.
2878 For example,
2880 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2881 :require-minutes t)
2883 means durations longer than a day will be expressed in days,
2884 hours and minutes, and durations less than a day will always be
2885 expressed in hours and minutes (even for durations less than an
2886 hour).
2888 The value
2890 \(:days \"%dd\" :minutes \"%dm\")
2892 means durations longer than a day will be expressed in days and
2893 minutes, and durations less than a day will be expressed entirely
2894 in minutes (even for durations longer than an hour)."
2895 :group 'org-time
2896 :group 'org-clock
2897 :version "24.4"
2898 :package-version '(Org . "8.0")
2899 :type '(choice (string :tag "Format string")
2900 (set :tag "Plist"
2901 (group :inline t (const :tag "Years" :years)
2902 (string :tag "Format string"))
2903 (group :inline t
2904 (const :tag "Always show years" :require-years)
2905 (const t))
2906 (group :inline t (const :tag "Months" :months)
2907 (string :tag "Format string"))
2908 (group :inline t
2909 (const :tag "Always show months" :require-months)
2910 (const t))
2911 (group :inline t (const :tag "Weeks" :weeks)
2912 (string :tag "Format string"))
2913 (group :inline t
2914 (const :tag "Always show weeks" :require-weeks)
2915 (const t))
2916 (group :inline t (const :tag "Days" :days)
2917 (string :tag "Format string"))
2918 (group :inline t
2919 (const :tag "Always show days" :require-days)
2920 (const t))
2921 (group :inline t (const :tag "Hours" :hours)
2922 (string :tag "Format string"))
2923 (group :inline t
2924 (const :tag "Always show hours" :require-hours)
2925 (const t))
2926 (group :inline t (const :tag "Minutes" :minutes)
2927 (string :tag "Format string"))
2928 (group :inline t
2929 (const :tag "Always show minutes" :require-minutes)
2930 (const t)))))
2932 (defcustom org-time-clocksum-use-fractional nil
2933 "When non-nil, \\[org-clock-display] uses fractional times.
2934 See `org-time-clocksum-format' for more on time clock formats."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.3"
2938 :type 'boolean)
2940 (defcustom org-time-clocksum-use-effort-durations nil
2941 "When non-nil, \\[org-clock-display] uses effort durations.
2942 E.g. by default, one day is considered to be a 8 hours effort,
2943 so a task that has been clocked for 16 hours will be displayed
2944 as during 2 days in the clock display or in the clocktable.
2946 See `org-effort-durations' on how to set effort durations
2947 and `org-time-clocksum-format' for more on time clock formats."
2948 :group 'org-time
2949 :group 'org-clock
2950 :version "24.4"
2951 :package-version '(Org . "8.0")
2952 :type 'boolean)
2954 (defcustom org-time-clocksum-fractional-format "%.2f"
2955 "The format string used when creating CLOCKSUM lines,
2956 or when Org mode generates a time duration, if
2957 `org-time-clocksum-use-fractional' is enabled.
2959 The value can be a single format string containing one
2960 %-sequence, which will be filled with the number of hours as
2961 a float.
2963 Alternatively, the value can be a plist associating any of the
2964 keys :years, :months, :weeks, :days, :hours or :minutes with
2965 a format string. The time duration is formatted using the
2966 largest time unit which gives a non-zero integer part. If all
2967 specified formats have zero integer part, the smallest time unit
2968 is used."
2969 :group 'org-time
2970 :type '(choice (string :tag "Format string")
2971 (set (group :inline t (const :tag "Years" :years)
2972 (string :tag "Format string"))
2973 (group :inline t (const :tag "Months" :months)
2974 (string :tag "Format string"))
2975 (group :inline t (const :tag "Weeks" :weeks)
2976 (string :tag "Format string"))
2977 (group :inline t (const :tag "Days" :days)
2978 (string :tag "Format string"))
2979 (group :inline t (const :tag "Hours" :hours)
2980 (string :tag "Format string"))
2981 (group :inline t (const :tag "Minutes" :minutes)
2982 (string :tag "Format string")))))
2984 (defcustom org-deadline-warning-days 14
2985 "Number of days before expiration during which a deadline becomes active.
2986 This variable governs the display in sparse trees and in the agenda.
2987 When 0 or negative, it means use this number (the absolute value of it)
2988 even if a deadline has a different individual lead time specified.
2990 Custom commands can set this variable in the options section."
2991 :group 'org-time
2992 :group 'org-agenda-daily/weekly
2993 :type 'integer)
2995 (defcustom org-scheduled-delay-days 0
2996 "Number of days before a scheduled item becomes active.
2997 This variable governs the display in sparse trees and in the agenda.
2998 The default value (i.e. 0) means: don't delay scheduled item.
2999 When negative, it means use this number (the absolute value of it)
3000 even if a scheduled item has a different individual delay time
3001 specified.
3003 Custom commands can set this variable in the options section."
3004 :group 'org-time
3005 :group 'org-agenda-daily/weekly
3006 :version "24.4"
3007 :package-version '(Org . "8.0")
3008 :type 'integer)
3010 (defcustom org-read-date-prefer-future t
3011 "Non-nil means assume future for incomplete date input from user.
3012 This affects the following situations:
3013 1. The user gives a month but not a year.
3014 For example, if it is April and you enter \"feb 2\", this will be read
3015 as Feb 2, *next* year. \"May 5\", however, will be this year.
3016 2. The user gives a day, but no month.
3017 For example, if today is the 15th, and you enter \"3\", Org-mode will
3018 read this as the third of *next* month. However, if you enter \"17\",
3019 it will be considered as *this* month.
3021 If you set this variable to the symbol `time', then also the following
3022 will work:
3024 3. If the user gives a time.
3025 If the time is before now, it will be interpreted as tomorrow.
3027 Currently none of this works for ISO week specifications.
3029 When this option is nil, the current day, month and year will always be
3030 used as defaults.
3032 See also `org-agenda-jump-prefer-future'."
3033 :group 'org-time
3034 :type '(choice
3035 (const :tag "Never" nil)
3036 (const :tag "Check month and day" t)
3037 (const :tag "Check month, day, and time" time)))
3039 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3040 "Should the agenda jump command prefer the future for incomplete dates?
3041 The default is to do the same as configured in `org-read-date-prefer-future'.
3042 But you can also set a deviating value here.
3043 This may t or nil, or the symbol `org-read-date-prefer-future'."
3044 :group 'org-agenda
3045 :group 'org-time
3046 :version "24.1"
3047 :type '(choice
3048 (const :tag "Use org-read-date-prefer-future"
3049 org-read-date-prefer-future)
3050 (const :tag "Never" nil)
3051 (const :tag "Always" t)))
3053 (defcustom org-read-date-force-compatible-dates t
3054 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3056 Depending on the system Emacs is running on, certain dates cannot
3057 be represented with the type used internally to represent time.
3058 Dates between 1970-1-1 and 2038-1-1 can always be represented
3059 correctly. Some systems allow for earlier dates, some for later,
3060 some for both. One way to find out it to insert any date into an
3061 Org buffer, putting the cursor on the year and hitting S-up and
3062 S-down to test the range.
3064 When this variable is set to t, the date/time prompt will not let
3065 you specify dates outside the 1970-2037 range, so it is certain that
3066 these dates will work in whatever version of Emacs you are
3067 running, and also that you can move a file from one Emacs implementation
3068 to another. WHenever Org is forcing the year for you, it will display
3069 a message and beep.
3071 When this variable is nil, Org will check if the date is
3072 representable in the specific Emacs implementation you are using.
3073 If not, it will force a year, usually the current year, and beep
3074 to remind you. Currently this setting is not recommended because
3075 the likelihood that you will open your Org files in an Emacs that
3076 has limited date range is not negligible.
3078 A workaround for this problem is to use diary sexp dates for time
3079 stamps outside of this range."
3080 :group 'org-time
3081 :version "24.1"
3082 :type 'boolean)
3084 (defcustom org-read-date-display-live t
3085 "Non-nil means display current interpretation of date prompt live.
3086 This display will be in an overlay, in the minibuffer."
3087 :group 'org-time
3088 :type 'boolean)
3090 (defcustom org-read-date-popup-calendar t
3091 "Non-nil means pop up a calendar when prompting for a date.
3092 In the calendar, the date can be selected with mouse-1. However, the
3093 minibuffer will also be active, and you can simply enter the date as well.
3094 When nil, only the minibuffer will be available."
3095 :group 'org-time
3096 :type 'boolean)
3097 (org-defvaralias 'org-popup-calendar-for-date-prompt
3098 'org-read-date-popup-calendar)
3100 (make-obsolete-variable
3101 'org-read-date-minibuffer-setup-hook
3102 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3103 (defcustom org-read-date-minibuffer-setup-hook nil
3104 "Hook to be used to set up keys for the date/time interface.
3105 Add key definitions to `minibuffer-local-map', which will be a
3106 temporary copy.
3108 WARNING: This option is obsolete, you should use
3109 `org-read-date-minibuffer-local-map' to set up keys."
3110 :group 'org-time
3111 :type 'hook)
3113 (defcustom org-extend-today-until 0
3114 "The hour when your day really ends. Must be an integer.
3115 This has influence for the following applications:
3116 - When switching the agenda to \"today\". It it is still earlier than
3117 the time given here, the day recognized as TODAY is actually yesterday.
3118 - When a date is read from the user and it is still before the time given
3119 here, the current date and time will be assumed to be yesterday, 23:59.
3120 Also, timestamps inserted in capture templates follow this rule.
3122 IMPORTANT: This is a feature whose implementation is and likely will
3123 remain incomplete. Really, it is only here because past midnight seems to
3124 be the favorite working time of John Wiegley :-)"
3125 :group 'org-time
3126 :type 'integer)
3128 (defcustom org-use-effective-time nil
3129 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3130 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3131 \"effective time\" of any timestamps between midnight and 8am will be
3132 23:59 of the previous day."
3133 :group 'org-time
3134 :version "24.1"
3135 :type 'boolean)
3137 (defcustom org-use-last-clock-out-time-as-effective-time nil
3138 "When non-nil, use the last clock out time for `org-todo'.
3139 Note that this option has precedence over the combined use of
3140 `org-use-effective-time' and `org-extend-today-until'."
3141 :group 'org-time
3142 :version "24.4"
3143 :package-version '(Org . "8.0")
3144 :type 'boolean)
3146 (defcustom org-edit-timestamp-down-means-later nil
3147 "Non-nil means S-down will increase the time in a time stamp.
3148 When nil, S-up will increase."
3149 :group 'org-time
3150 :type 'boolean)
3152 (defcustom org-calendar-follow-timestamp-change t
3153 "Non-nil means make the calendar window follow timestamp changes.
3154 When a timestamp is modified and the calendar window is visible, it will be
3155 moved to the new date."
3156 :group 'org-time
3157 :type 'boolean)
3159 (defgroup org-tags nil
3160 "Options concerning tags in Org-mode."
3161 :tag "Org Tags"
3162 :group 'org)
3164 (defcustom org-tag-alist nil
3165 "List of tags allowed in Org-mode files.
3166 When this list is nil, Org-mode will base TAG input on what is already in the
3167 buffer.
3168 The value of this variable is an alist, the car of each entry must be a
3169 keyword as a string, the cdr may be a character that is used to select
3170 that tag through the fast-tag-selection interface.
3171 See the manual for details."
3172 :group 'org-tags
3173 :type '(repeat
3174 (choice
3175 (cons (string :tag "Tag name")
3176 (character :tag "Access char"))
3177 (list :tag "Start radio group"
3178 (const :startgroup)
3179 (option (string :tag "Group description")))
3180 (list :tag "Group tags delimiter"
3181 (const :grouptags))
3182 (list :tag "End radio group"
3183 (const :endgroup)
3184 (option (string :tag "Group description")))
3185 (const :tag "New line" (:newline)))))
3187 (defcustom org-tag-persistent-alist nil
3188 "List of tags that will always appear in all Org-mode files.
3189 This is in addition to any in buffer settings or customizations
3190 of `org-tag-alist'.
3191 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3192 The value of this variable is an alist, the car of each entry must be a
3193 keyword as a string, the cdr may be a character that is used to select
3194 that tag through the fast-tag-selection interface.
3195 See the manual for details.
3196 To disable these tags on a per-file basis, insert anywhere in the file:
3197 #+STARTUP: noptag"
3198 :group 'org-tags
3199 :type '(repeat
3200 (choice
3201 (cons (string :tag "Tag name")
3202 (character :tag "Access char"))
3203 (const :tag "Start radio group" (:startgroup))
3204 (const :tag "Group tags delimiter" (:grouptags))
3205 (const :tag "End radio group" (:endgroup))
3206 (const :tag "New line" (:newline)))))
3208 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3209 "If non-nil, always offer completion for all tags of all agenda files.
3210 Instead of customizing this variable directly, you might want to
3211 set it locally for capture buffers, because there no list of
3212 tags in that file can be created dynamically (there are none).
3214 (add-hook 'org-capture-mode-hook
3215 (lambda ()
3216 (set (make-local-variable
3217 'org-complete-tags-always-offer-all-agenda-tags)
3218 t)))"
3219 :group 'org-tags
3220 :version "24.1"
3221 :type 'boolean)
3223 (defvar org-file-tags nil
3224 "List of tags that can be inherited by all entries in the file.
3225 The tags will be inherited if the variable `org-use-tag-inheritance'
3226 says they should be.
3227 This variable is populated from #+FILETAGS lines.")
3229 (defcustom org-use-fast-tag-selection 'auto
3230 "Non-nil means use fast tag selection scheme.
3231 This is a special interface to select and deselect tags with single keys.
3232 When nil, fast selection is never used.
3233 When the symbol `auto', fast selection is used if and only if selection
3234 characters for tags have been configured, either through the variable
3235 `org-tag-alist' or through a #+TAGS line in the buffer.
3236 When t, fast selection is always used and selection keys are assigned
3237 automatically if necessary."
3238 :group 'org-tags
3239 :type '(choice
3240 (const :tag "Always" t)
3241 (const :tag "Never" nil)
3242 (const :tag "When selection characters are configured" 'auto)))
3244 (defcustom org-fast-tag-selection-single-key nil
3245 "Non-nil means fast tag selection exits after first change.
3246 When nil, you have to press RET to exit it.
3247 During fast tag selection, you can toggle this flag with `C-c'.
3248 This variable can also have the value `expert'. In this case, the window
3249 displaying the tags menu is not even shown, until you press C-c again."
3250 :group 'org-tags
3251 :type '(choice
3252 (const :tag "No" nil)
3253 (const :tag "Yes" t)
3254 (const :tag "Expert" expert)))
3256 (defvar org-fast-tag-selection-include-todo nil
3257 "Non-nil means fast tags selection interface will also offer TODO states.
3258 This is an undocumented feature, you should not rely on it.")
3260 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3261 "The column to which tags should be indented in a headline.
3262 If this number is positive, it specifies the column. If it is negative,
3263 it means that the tags should be flushright to that column. For example,
3264 -80 works well for a normal 80 character screen.
3265 When 0, place tags directly after headline text, with only one space in
3266 between."
3267 :group 'org-tags
3268 :type 'integer)
3270 (defcustom org-auto-align-tags t
3271 "Non-nil keeps tags aligned when modifying headlines.
3272 Some operations (i.e. demoting) change the length of a headline and
3273 therefore shift the tags around. With this option turned on, after
3274 each such operation the tags are again aligned to `org-tags-column'."
3275 :group 'org-tags
3276 :type 'boolean)
3278 (defcustom org-use-tag-inheritance t
3279 "Non-nil means tags in levels apply also for sublevels.
3280 When nil, only the tags directly given in a specific line apply there.
3281 This may also be a list of tags that should be inherited, or a regexp that
3282 matches tags that should be inherited. Additional control is possible
3283 with the variable `org-tags-exclude-from-inheritance' which gives an
3284 explicit list of tags to be excluded from inheritance, even if the value of
3285 `org-use-tag-inheritance' would select it for inheritance.
3287 If this option is t, a match early-on in a tree can lead to a large
3288 number of matches in the subtree when constructing the agenda or creating
3289 a sparse tree. If you only want to see the first match in a tree during
3290 a search, check out the variable `org-tags-match-list-sublevels'."
3291 :group 'org-tags
3292 :type '(choice
3293 (const :tag "Not" nil)
3294 (const :tag "Always" t)
3295 (repeat :tag "Specific tags" (string :tag "Tag"))
3296 (regexp :tag "Tags matched by regexp")))
3298 (defcustom org-tags-exclude-from-inheritance nil
3299 "List of tags that should never be inherited.
3300 This is a way to exclude a few tags from inheritance. For way to do
3301 the opposite, to actively allow inheritance for selected tags,
3302 see the variable `org-use-tag-inheritance'."
3303 :group 'org-tags
3304 :type '(repeat (string :tag "Tag")))
3306 (defun org-tag-inherit-p (tag)
3307 "Check if TAG is one that should be inherited."
3308 (cond
3309 ((member tag org-tags-exclude-from-inheritance) nil)
3310 ((eq org-use-tag-inheritance t) t)
3311 ((not org-use-tag-inheritance) nil)
3312 ((stringp org-use-tag-inheritance)
3313 (string-match org-use-tag-inheritance tag))
3314 ((listp org-use-tag-inheritance)
3315 (member tag org-use-tag-inheritance))
3316 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3318 (defcustom org-tags-match-list-sublevels t
3319 "Non-nil means list also sublevels of headlines matching a search.
3320 This variable applies to tags/property searches, and also to stuck
3321 projects because this search is based on a tags match as well.
3323 When set to the symbol `indented', sublevels are indented with
3324 leading dots.
3326 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3327 the sublevels of a headline matching a tag search often also match
3328 the same search. Listing all of them can create very long lists.
3329 Setting this variable to nil causes subtrees of a match to be skipped.
3331 This variable is semi-obsolete and probably should always be true. It
3332 is better to limit inheritance to certain tags using the variables
3333 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3334 :group 'org-tags
3335 :type '(choice
3336 (const :tag "No, don't list them" nil)
3337 (const :tag "Yes, do list them" t)
3338 (const :tag "List them, indented with leading dots" indented)))
3340 (defcustom org-tags-sort-function nil
3341 "When set, tags are sorted using this function as a comparator."
3342 :group 'org-tags
3343 :type '(choice
3344 (const :tag "No sorting" nil)
3345 (const :tag "Alphabetical" string<)
3346 (const :tag "Reverse alphabetical" string>)
3347 (function :tag "Custom function" nil)))
3349 (defvar org-tags-history nil
3350 "History of minibuffer reads for tags.")
3351 (defvar org-last-tags-completion-table nil
3352 "The last used completion table for tags.")
3353 (defvar org-after-tags-change-hook nil
3354 "Hook that is run after the tags in a line have changed.")
3356 (defgroup org-properties nil
3357 "Options concerning properties in Org-mode."
3358 :tag "Org Properties"
3359 :group 'org)
3361 (defcustom org-property-format "%-10s %s"
3362 "How property key/value pairs should be formatted by `indent-line'.
3363 When `indent-line' hits a property definition, it will format the line
3364 according to this format, mainly to make sure that the values are
3365 lined-up with respect to each other."
3366 :group 'org-properties
3367 :type 'string)
3369 (defcustom org-properties-postprocess-alist nil
3370 "Alist of properties and functions to adjust inserted values.
3371 Elements of this alist must be of the form
3373 ([string] [function])
3375 where [string] must be a property name and [function] must be a
3376 lambda expression: this lambda expression must take one argument,
3377 the value to adjust, and return the new value as a string.
3379 For example, this element will allow the property \"Remaining\"
3380 to be updated wrt the relation between the \"Effort\" property
3381 and the clock summary:
3383 ((\"Remaining\" (lambda(value)
3384 (let ((clocksum (org-clock-sum-current-item))
3385 (effort (org-duration-string-to-minutes
3386 (org-entry-get (point) \"Effort\"))))
3387 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3388 :group 'org-properties
3389 :version "24.1"
3390 :type '(alist :key-type (string :tag "Property")
3391 :value-type (function :tag "Function")))
3393 (defcustom org-use-property-inheritance nil
3394 "Non-nil means properties apply also for sublevels.
3396 This setting is chiefly used during property searches. Turning it on can
3397 cause significant overhead when doing a search, which is why it is not
3398 on by default.
3400 When nil, only the properties directly given in the current entry count.
3401 When t, every property is inherited. The value may also be a list of
3402 properties that should have inheritance, or a regular expression matching
3403 properties that should be inherited.
3405 However, note that some special properties use inheritance under special
3406 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3407 and the properties ending in \"_ALL\" when they are used as descriptor
3408 for valid values of a property.
3410 Note for programmers:
3411 When querying an entry with `org-entry-get', you can control if inheritance
3412 should be used. By default, `org-entry-get' looks only at the local
3413 properties. You can request inheritance by setting the inherit argument
3414 to t (to force inheritance) or to `selective' (to respect the setting
3415 in this variable)."
3416 :group 'org-properties
3417 :type '(choice
3418 (const :tag "Not" nil)
3419 (const :tag "Always" t)
3420 (repeat :tag "Specific properties" (string :tag "Property"))
3421 (regexp :tag "Properties matched by regexp")))
3423 (defun org-property-inherit-p (property)
3424 "Check if PROPERTY is one that should be inherited."
3425 (cond
3426 ((eq org-use-property-inheritance t) t)
3427 ((not org-use-property-inheritance) nil)
3428 ((stringp org-use-property-inheritance)
3429 (string-match org-use-property-inheritance property))
3430 ((listp org-use-property-inheritance)
3431 (member property org-use-property-inheritance))
3432 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3434 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3435 "The default column format, if no other format has been defined.
3436 This variable can be set on the per-file basis by inserting a line
3438 #+COLUMNS: %25ITEM ....."
3439 :group 'org-properties
3440 :type 'string)
3442 (defcustom org-columns-ellipses ".."
3443 "The ellipses to be used when a field in column view is truncated.
3444 When this is the empty string, as many characters as possible are shown,
3445 but then there will be no visual indication that the field has been truncated.
3446 When this is a string of length N, the last N characters of a truncated
3447 field are replaced by this string. If the column is narrower than the
3448 ellipses string, only part of the ellipses string will be shown."
3449 :group 'org-properties
3450 :type 'string)
3452 (defcustom org-columns-modify-value-for-display-function nil
3453 "Function that modifies values for display in column view.
3454 For example, it can be used to cut out a certain part from a time stamp.
3455 The function must take 2 arguments:
3457 column-title The title of the column (*not* the property name)
3458 value The value that should be modified.
3460 The function should return the value that should be displayed,
3461 or nil if the normal value should be used."
3462 :group 'org-properties
3463 :type 'function)
3465 (defcustom org-effort-property "Effort"
3466 "The property that is being used to keep track of effort estimates.
3467 Effort estimates given in this property need to have the format H:MM."
3468 :group 'org-properties
3469 :group 'org-progress
3470 :type '(string :tag "Property"))
3472 (defconst org-global-properties-fixed
3473 '(("VISIBILITY_ALL" . "folded children content all")
3474 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3475 "List of property/value pairs that can be inherited by any entry.
3477 These are fixed values, for the preset properties. The user variable
3478 that can be used to add to this list is `org-global-properties'.
3480 The entries in this list are cons cells where the car is a property
3481 name and cdr is a string with the value. If the value represents
3482 multiple items like an \"_ALL\" property, separate the items by
3483 spaces.")
3485 (defcustom org-global-properties nil
3486 "List of property/value pairs that can be inherited by any entry.
3488 This list will be combined with the constant `org-global-properties-fixed'.
3490 The entries in this list are cons cells where the car is a property
3491 name and cdr is a string with the value.
3493 You can set buffer-local values for the same purpose in the variable
3494 `org-file-properties' this by adding lines like
3496 #+PROPERTY: NAME VALUE"
3497 :group 'org-properties
3498 :type '(repeat
3499 (cons (string :tag "Property")
3500 (string :tag "Value"))))
3502 (defvar org-file-properties nil
3503 "List of property/value pairs that can be inherited by any entry.
3504 Valid for the current buffer.
3505 This variable is populated from #+PROPERTY lines.")
3506 (make-variable-buffer-local 'org-file-properties)
3508 (defgroup org-agenda nil
3509 "Options concerning agenda views in Org-mode."
3510 :tag "Org Agenda"
3511 :group 'org)
3513 (defvar org-category nil
3514 "Variable used by org files to set a category for agenda display.
3515 Such files should use a file variable to set it, for example
3517 # -*- mode: org; org-category: \"ELisp\"
3519 or contain a special line
3521 #+CATEGORY: ELisp
3523 If the file does not specify a category, then file's base name
3524 is used instead.")
3525 (make-variable-buffer-local 'org-category)
3526 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3528 (defcustom org-agenda-files nil
3529 "The files to be used for agenda display.
3530 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3531 \\[org-remove-file]. You can also use customize to edit the list.
3533 If an entry is a directory, all files in that directory that are matched by
3534 `org-agenda-file-regexp' will be part of the file list.
3536 If the value of the variable is not a list but a single file name, then
3537 the list of agenda files is actually stored and maintained in that file, one
3538 agenda file per line. In this file paths can be given relative to
3539 `org-directory'. Tilde expansion and environment variable substitution
3540 are also made."
3541 :group 'org-agenda
3542 :type '(choice
3543 (repeat :tag "List of files and directories" file)
3544 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3546 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3547 "Regular expression to match files for `org-agenda-files'.
3548 If any element in the list in that variable contains a directory instead
3549 of a normal file, all files in that directory that are matched by this
3550 regular expression will be included."
3551 :group 'org-agenda
3552 :type 'regexp)
3554 (defcustom org-agenda-text-search-extra-files nil
3555 "List of extra files to be searched by text search commands.
3556 These files will be search in addition to the agenda files by the
3557 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3558 Note that these files will only be searched for text search commands,
3559 not for the other agenda views like todo lists, tag searches or the weekly
3560 agenda. This variable is intended to list notes and possibly archive files
3561 that should also be searched by these two commands.
3562 In fact, if the first element in the list is the symbol `agenda-archives',
3563 than all archive files of all agenda files will be added to the search
3564 scope."
3565 :group 'org-agenda
3566 :type '(set :greedy t
3567 (const :tag "Agenda Archives" agenda-archives)
3568 (repeat :inline t (file))))
3570 (org-defvaralias 'org-agenda-multi-occur-extra-files
3571 'org-agenda-text-search-extra-files)
3573 (defcustom org-agenda-skip-unavailable-files nil
3574 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3575 A nil value means to remove them, after a query, from the list."
3576 :group 'org-agenda
3577 :type 'boolean)
3579 (defcustom org-calendar-to-agenda-key [?c]
3580 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3581 The command `org-calendar-goto-agenda' will be bound to this key. The
3582 default is the character `c' because then `c' can be used to switch back and
3583 forth between agenda and calendar."
3584 :group 'org-agenda
3585 :type 'sexp)
3587 (defcustom org-calendar-insert-diary-entry-key [?i]
3588 "The key to be installed in `calendar-mode-map' for adding diary entries.
3589 This option is irrelevant until `org-agenda-diary-file' has been configured
3590 to point to an Org-mode file. When that is the case, the command
3591 `org-agenda-diary-entry' will be bound to the key given here, by default
3592 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3593 if you want to continue doing this, you need to change this to a different
3594 key."
3595 :group 'org-agenda
3596 :type 'sexp)
3598 (defcustom org-agenda-diary-file 'diary-file
3599 "File to which to add new entries with the `i' key in agenda and calendar.
3600 When this is the symbol `diary-file', the functionality in the Emacs
3601 calendar will be used to add entries to the `diary-file'. But when this
3602 points to a file, `org-agenda-diary-entry' will be used instead."
3603 :group 'org-agenda
3604 :type '(choice
3605 (const :tag "The standard Emacs diary file" diary-file)
3606 (file :tag "Special Org file diary entries")))
3608 (eval-after-load "calendar"
3609 '(progn
3610 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3611 'org-calendar-goto-agenda)
3612 (add-hook 'calendar-mode-hook
3613 (lambda ()
3614 (unless (eq org-agenda-diary-file 'diary-file)
3615 (define-key calendar-mode-map
3616 org-calendar-insert-diary-entry-key
3617 'org-agenda-diary-entry))))))
3619 (defgroup org-latex nil
3620 "Options for embedding LaTeX code into Org-mode."
3621 :tag "Org LaTeX"
3622 :group 'org)
3624 (defcustom org-format-latex-options
3625 '(:foreground default :background default :scale 1.0
3626 :html-foreground "Black" :html-background "Transparent"
3627 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3628 "Options for creating images from LaTeX fragments.
3629 This is a property list with the following properties:
3630 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3631 `default' means use the foreground of the default face.
3632 `auto' means use the foreground from the text face.
3633 :background the background color, or \"Transparent\".
3634 `default' means use the background of the default face.
3635 `auto' means use the background from the text face.
3636 :scale a scaling factor for the size of the images, to get more pixels
3637 :html-foreground, :html-background, :html-scale
3638 the same numbers for HTML export.
3639 :matchers a list indicating which matchers should be used to
3640 find LaTeX fragments. Valid members of this list are:
3641 \"begin\" find environments
3642 \"$1\" find single characters surrounded by $.$
3643 \"$\" find math expressions surrounded by $...$
3644 \"$$\" find math expressions surrounded by $$....$$
3645 \"\\(\" find math expressions surrounded by \\(...\\)
3646 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3647 :group 'org-latex
3648 :type 'plist)
3650 (defcustom org-format-latex-signal-error t
3651 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3652 When nil, just push out a message."
3653 :group 'org-latex
3654 :version "24.1"
3655 :type 'boolean)
3657 (defcustom org-latex-to-mathml-jar-file nil
3658 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3659 Use this to specify additional executable file say a jar file.
3661 When using MathToWeb as the converter, specify the full-path to
3662 your mathtoweb.jar file."
3663 :group 'org-latex
3664 :version "24.1"
3665 :type '(choice
3666 (const :tag "None" nil)
3667 (file :tag "JAR file" :must-match t)))
3669 (defcustom org-latex-to-mathml-convert-command nil
3670 "Command to convert LaTeX fragments to MathML.
3671 Replace format-specifiers in the command as noted below and use
3672 `shell-command' to convert LaTeX to MathML.
3673 %j: Executable file in fully expanded form as specified by
3674 `org-latex-to-mathml-jar-file'.
3675 %I: Input LaTeX file in fully expanded form
3676 %o: Output MathML file
3677 This command is used by `org-create-math-formula'.
3679 When using MathToWeb as the converter, set this to
3680 \"java -jar %j -unicode -force -df %o %I\"."
3681 :group 'org-latex
3682 :version "24.1"
3683 :type '(choice
3684 (const :tag "None" nil)
3685 (string :tag "\nShell command")))
3687 (defcustom org-latex-create-formula-image-program 'dvipng
3688 "Program to convert LaTeX fragments with.
3690 dvipng Process the LaTeX fragments to dvi file, then convert
3691 dvi files to png files using dvipng.
3692 This will also include processing of non-math environments.
3693 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3694 to convert pdf files to png files"
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "dvipng" dvipng)
3699 (const :tag "imagemagick" imagemagick)))
3701 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3702 "Path to store latex preview images.
3703 A relative path here creates many directories relative to the
3704 processed org files paths. An absolute path puts all preview
3705 images at the same place."
3706 :group 'org-latex
3707 :version "24.3"
3708 :type 'string)
3710 (defun org-format-latex-mathml-available-p ()
3711 "Return t if `org-latex-to-mathml-convert-command' is usable."
3712 (save-match-data
3713 (when (and (boundp 'org-latex-to-mathml-convert-command)
3714 org-latex-to-mathml-convert-command)
3715 (let ((executable (car (split-string
3716 org-latex-to-mathml-convert-command))))
3717 (when (executable-find executable)
3718 (if (string-match
3719 "%j" org-latex-to-mathml-convert-command)
3720 (file-readable-p org-latex-to-mathml-jar-file)
3721 t))))))
3723 (defcustom org-format-latex-header "\\documentclass{article}
3724 \\usepackage[usenames]{color}
3725 \\usepackage{amsmath}
3726 \\usepackage[mathscr]{eucal}
3727 \\pagestyle{empty} % do not remove
3728 \[PACKAGES]
3729 \[DEFAULT-PACKAGES]
3730 % The settings below are copied from fullpage.sty
3731 \\setlength{\\textwidth}{\\paperwidth}
3732 \\addtolength{\\textwidth}{-3cm}
3733 \\setlength{\\oddsidemargin}{1.5cm}
3734 \\addtolength{\\oddsidemargin}{-2.54cm}
3735 \\setlength{\\evensidemargin}{\\oddsidemargin}
3736 \\setlength{\\textheight}{\\paperheight}
3737 \\addtolength{\\textheight}{-\\headheight}
3738 \\addtolength{\\textheight}{-\\headsep}
3739 \\addtolength{\\textheight}{-\\footskip}
3740 \\addtolength{\\textheight}{-3cm}
3741 \\setlength{\\topmargin}{1.5cm}
3742 \\addtolength{\\topmargin}{-2.54cm}"
3743 "The document header used for processing LaTeX fragments.
3744 It is imperative that this header make sure that no page number
3745 appears on the page. The package defined in the variables
3746 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3747 will either replace the placeholder \"[PACKAGES]\" in this
3748 header, or they will be appended."
3749 :group 'org-latex
3750 :type 'string)
3752 (defun org-set-packages-alist (var val)
3753 "Set the packages alist and make sure it has 3 elements per entry."
3754 (set var (mapcar (lambda (x)
3755 (if (and (consp x) (= (length x) 2))
3756 (list (car x) (nth 1 x) t)
3758 val)))
3760 (defun org-get-packages-alist (var)
3761 "Get the packages alist and make sure it has 3 elements per entry."
3762 (mapcar (lambda (x)
3763 (if (and (consp x) (= (length x) 2))
3764 (list (car x) (nth 1 x) t)
3766 (default-value var)))
3768 (defcustom org-latex-default-packages-alist
3769 '(("AUTO" "inputenc" t)
3770 ("T1" "fontenc" t)
3771 ("" "fixltx2e" nil)
3772 ("" "graphicx" t)
3773 ("" "longtable" nil)
3774 ("" "float" nil)
3775 ("" "wrapfig" nil)
3776 ("" "soul" t)
3777 ("" "textcomp" t)
3778 ("" "marvosym" t)
3779 ("" "wasysym" t)
3780 ("" "latexsym" t)
3781 ("" "amssymb" t)
3782 ("" "hyperref" nil)
3783 "\\tolerance=1000")
3784 "Alist of default packages to be inserted in the header.
3786 Change this only if one of the packages here causes an
3787 incompatibility with another package you are using.
3789 The packages in this list are needed by one part or another of
3790 Org mode to function properly:
3792 - inputenc, fontenc: for basic font and character selection
3793 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3794 symbols used for interpreting the entities in `org-entities'.
3795 You can skip some of these packages if you don't use any of the
3796 symbols in it.
3797 - graphicx: for including images
3798 - float, wrapfig: for figure placement
3799 - longtable: for long tables
3800 - hyperref: for cross references
3802 Therefore you should not modify this variable unless you know
3803 what you are doing. The one reason to change it anyway is that
3804 you might be loading some other package that conflicts with one
3805 of the default packages. Each cell is of the format
3806 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3807 the package also needs to be included when compiling LaTeX
3808 snippets into images for inclusion into non-LaTeX output."
3809 :group 'org-latex
3810 :group 'org-export-latex
3811 :set 'org-set-packages-alist
3812 :get 'org-get-packages-alist
3813 :version "24.1"
3814 :type '(repeat
3815 (choice
3816 (list :tag "options/package pair"
3817 (string :tag "options")
3818 (string :tag "package")
3819 (boolean :tag "Snippet"))
3820 (string :tag "A line of LaTeX"))))
3822 (defcustom org-latex-packages-alist nil
3823 "Alist of packages to be inserted in every LaTeX header.
3825 These will be inserted after `org-latex-default-packages-alist'.
3826 Each cell is of the format:
3828 \(\"options\" \"package\" snippet-flag)
3830 SNIPPET-FLAG, when t, indicates that this package is also needed
3831 when turning LaTeX snippets into images for inclusion into
3832 non-LaTeX output.
3834 Make sure that you only list packages here which:
3836 - you want in every file
3837 - do not conflict with the setup in `org-format-latex-header'.
3838 - do not conflict with the default packages in
3839 `org-latex-default-packages-alist'."
3840 :group 'org-latex
3841 :group 'org-export-latex
3842 :set 'org-set-packages-alist
3843 :get 'org-get-packages-alist
3844 :type '(repeat
3845 (choice
3846 (list :tag "options/package pair"
3847 (string :tag "options")
3848 (string :tag "package")
3849 (boolean :tag "Snippet"))
3850 (string :tag "A line of LaTeX"))))
3852 (defgroup org-appearance nil
3853 "Settings for Org-mode appearance."
3854 :tag "Org Appearance"
3855 :group 'org)
3857 (defcustom org-level-color-stars-only nil
3858 "Non-nil means fontify only the stars in each headline.
3859 When nil, the entire headline is fontified.
3860 Changing it requires restart of `font-lock-mode' to become effective
3861 also in regions already fontified."
3862 :group 'org-appearance
3863 :type 'boolean)
3865 (defcustom org-hide-leading-stars nil
3866 "Non-nil means hide the first N-1 stars in a headline.
3867 This works by using the face `org-hide' for these stars. This
3868 face is white for a light background, and black for a dark
3869 background. You may have to customize the face `org-hide' to
3870 make this work.
3871 Changing it requires restart of `font-lock-mode' to become effective
3872 also in regions already fontified.
3873 You may also set this on a per-file basis by adding one of the following
3874 lines to the buffer:
3876 #+STARTUP: hidestars
3877 #+STARTUP: showstars"
3878 :group 'org-appearance
3879 :type 'boolean)
3881 (defcustom org-hidden-keywords nil
3882 "List of symbols corresponding to keywords to be hidden the org buffer.
3883 For example, a value '(title) for this list will make the document's title
3884 appear in the buffer without the initial #+TITLE: keyword."
3885 :group 'org-appearance
3886 :version "24.1"
3887 :type '(set (const :tag "#+AUTHOR" author)
3888 (const :tag "#+DATE" date)
3889 (const :tag "#+EMAIL" email)
3890 (const :tag "#+TITLE" title)))
3892 (defcustom org-custom-properties nil
3893 "List of properties (as strings) with a special meaning.
3894 The default use of these custom properties is to let the user
3895 hide them with `org-toggle-custom-properties-visibility'."
3896 :group 'org-properties
3897 :group 'org-appearance
3898 :version "24.3"
3899 :type '(repeat (string :tag "Property Name")))
3901 (defcustom org-fontify-done-headline nil
3902 "Non-nil means change the face of a headline if it is marked DONE.
3903 Normally, only the TODO/DONE keyword indicates the state of a headline.
3904 When this is non-nil, the headline after the keyword is set to the
3905 `org-headline-done' as an additional indication."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-fontify-emphasized-text t
3910 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3911 Changing this variable requires a restart of Emacs to take effect."
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-fontify-whole-heading-line nil
3916 "Non-nil means fontify the whole line for headings.
3917 This is useful when setting a background color for the
3918 org-level-* faces."
3919 :group 'org-appearance
3920 :type 'boolean)
3922 (defcustom org-highlight-latex-and-related nil
3923 "Non-nil means highlight LaTeX related syntax in the buffer.
3924 When non nil, the value should be a list containing any of the
3925 following symbols:
3926 `latex' Highlight LaTeX snippets and environments.
3927 `script' Highlight subscript and superscript.
3928 `entities' Highlight entities."
3929 :group 'org-appearance
3930 :version "24.4"
3931 :package-version '(Org . "8.0")
3932 :type '(choice
3933 (const :tag "No highlighting" nil)
3934 (set :greedy t :tag "Highlight"
3935 (const :tag "LaTeX snippets and environments" latex)
3936 (const :tag "Subscript and superscript" script)
3937 (const :tag "Entities" entities))))
3939 (defcustom org-hide-emphasis-markers nil
3940 "Non-nil mean font-lock should hide the emphasis marker characters."
3941 :group 'org-appearance
3942 :type 'boolean)
3944 (defcustom org-pretty-entities nil
3945 "Non-nil means show entities as UTF8 characters.
3946 When nil, the \\name form remains in the buffer."
3947 :group 'org-appearance
3948 :version "24.1"
3949 :type 'boolean)
3951 (defcustom org-pretty-entities-include-sub-superscripts t
3952 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3953 :group 'org-appearance
3954 :version "24.1"
3955 :type 'boolean)
3957 (defvar org-emph-re nil
3958 "Regular expression for matching emphasis.
3959 After a match, the match groups contain these elements:
3960 0 The match of the full regular expression, including the characters
3961 before and after the proper match
3962 1 The character before the proper match, or empty at beginning of line
3963 2 The proper match, including the leading and trailing markers
3964 3 The leading marker like * or /, indicating the type of highlighting
3965 4 The text between the emphasis markers, not including the markers
3966 5 The character after the match, empty at the end of a line")
3967 (defvar org-verbatim-re nil
3968 "Regular expression for matching verbatim text.")
3969 (defvar org-emphasis-regexp-components) ; defined just below
3970 (defvar org-emphasis-alist) ; defined just below
3971 (defun org-set-emph-re (var val)
3972 "Set variable and compute the emphasis regular expression."
3973 (set var val)
3974 (when (and (boundp 'org-emphasis-alist)
3975 (boundp 'org-emphasis-regexp-components)
3976 org-emphasis-alist org-emphasis-regexp-components)
3977 (let* ((e org-emphasis-regexp-components)
3978 (pre (car e))
3979 (post (nth 1 e))
3980 (border (nth 2 e))
3981 (body (nth 3 e))
3982 (nl (nth 4 e))
3983 (body1 (concat body "*?"))
3984 (markers (mapconcat 'car org-emphasis-alist ""))
3985 (vmarkers (mapconcat
3986 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3987 org-emphasis-alist "")))
3988 ;; make sure special characters appear at the right position in the class
3989 (if (string-match "\\^" markers)
3990 (setq markers (concat (replace-match "" t t markers) "^")))
3991 (if (string-match "-" markers)
3992 (setq markers (concat (replace-match "" t t markers) "-")))
3993 (if (string-match "\\^" vmarkers)
3994 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3995 (if (string-match "-" vmarkers)
3996 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3997 (if (> nl 0)
3998 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3999 (int-to-string nl) "\\}")))
4000 ;; Make the regexp
4001 (setq org-emph-re
4002 (concat "\\([" pre "]\\|^\\)"
4003 "\\("
4004 "\\([" markers "]\\)"
4005 "\\("
4006 "[^" border "]\\|"
4007 "[^" border "]"
4008 body1
4009 "[^" border "]"
4010 "\\)"
4011 "\\3\\)"
4012 "\\([" post "]\\|$\\)"))
4013 (setq org-verbatim-re
4014 (concat "\\([" pre "]\\|^\\)"
4015 "\\("
4016 "\\([" vmarkers "]\\)"
4017 "\\("
4018 "[^" border "]\\|"
4019 "[^" border "]"
4020 body1
4021 "[^" border "]"
4022 "\\)"
4023 "\\3\\)"
4024 "\\([" post "]\\|$\\)")))))
4026 (defcustom org-emphasis-regexp-components
4027 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4028 "Components used to build the regular expression for emphasis.
4029 This is a list with five entries. Terminology: In an emphasis string
4030 like \" *strong word* \", we call the initial space PREMATCH, the final
4031 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4032 and \"trong wor\" is the body. The different components in this variable
4033 specify what is allowed/forbidden in each part:
4035 pre Chars allowed as prematch. Beginning of line will be allowed too.
4036 post Chars allowed as postmatch. End of line will be allowed too.
4037 border The chars *forbidden* as border characters.
4038 body-regexp A regexp like \".\" to match a body character. Don't use
4039 non-shy groups here, and don't allow newline here.
4040 newline The maximum number of newlines allowed in an emphasis exp.
4042 Use customize to modify this, or restart Emacs after changing it."
4043 :group 'org-appearance
4044 :set 'org-set-emph-re
4045 :type '(list
4046 (sexp :tag "Allowed chars in pre ")
4047 (sexp :tag "Allowed chars in post ")
4048 (sexp :tag "Forbidden chars in border ")
4049 (sexp :tag "Regexp for body ")
4050 (integer :tag "number of newlines allowed")
4051 (option (boolean :tag "Please ignore this button"))))
4053 (defcustom org-emphasis-alist
4054 `(("*" bold "<b>" "</b>")
4055 ("/" italic "<i>" "</i>")
4056 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4057 ("=" org-code "<code>" "</code>" verbatim)
4058 ("~" org-verbatim "<code>" "</code>" verbatim)
4059 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4060 "<del>" "</del>")
4062 "Special syntax for emphasized text.
4063 Text starting and ending with a special character will be emphasized, for
4064 example *bold*, _underlined_ and /italic/. This variable sets the marker
4065 characters, the face to be used by font-lock for highlighting in Org-mode
4066 Emacs buffers, and the HTML tags to be used for this.
4067 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4068 Use customize to modify this, or restart Emacs after changing it."
4069 :group 'org-appearance
4070 :set 'org-set-emph-re
4071 :type '(repeat
4072 (list
4073 (string :tag "Marker character")
4074 (choice
4075 (face :tag "Font-lock-face")
4076 (plist :tag "Face property list"))
4077 (string :tag "HTML start tag")
4078 (string :tag "HTML end tag")
4079 (option (const verbatim)))))
4081 (defvar org-protecting-blocks
4082 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4083 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4084 This is needed for font-lock setup.")
4086 ;;; Miscellaneous options
4088 (defgroup org-completion nil
4089 "Completion in Org-mode."
4090 :tag "Org Completion"
4091 :group 'org)
4093 (defcustom org-completion-use-ido nil
4094 "Non-nil means use ido completion wherever possible.
4095 Note that `ido-mode' must be active for this variable to be relevant.
4096 If you decide to turn this variable on, you might well want to turn off
4097 `org-outline-path-complete-in-steps'.
4098 See also `org-completion-use-iswitchb'."
4099 :group 'org-completion
4100 :type 'boolean)
4102 (defcustom org-completion-use-iswitchb nil
4103 "Non-nil means use iswitchb completion wherever possible.
4104 Note that `iswitchb-mode' must be active for this variable to be relevant.
4105 If you decide to turn this variable on, you might well want to turn off
4106 `org-outline-path-complete-in-steps'.
4107 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4108 :group 'org-completion
4109 :type 'boolean)
4111 (defcustom org-completion-fallback-command 'hippie-expand
4112 "The expansion command called by \\[pcomplete] in normal context.
4113 Normal means, no org-mode-specific context."
4114 :group 'org-completion
4115 :type 'function)
4117 ;;; Functions and variables from their packages
4118 ;; Declared here to avoid compiler warnings
4120 ;; XEmacs only
4121 (defvar outline-mode-menu-heading)
4122 (defvar outline-mode-menu-show)
4123 (defvar outline-mode-menu-hide)
4124 (defvar zmacs-regions) ; XEmacs regions
4126 ;; Emacs only
4127 (defvar mark-active)
4129 ;; Various packages
4130 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4131 (declare-function calendar-forward-day "cal-move" (arg))
4132 (declare-function calendar-goto-date "cal-move" (date))
4133 (declare-function calendar-goto-today "cal-move" ())
4134 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4135 (defvar calc-embedded-close-formula)
4136 (defvar calc-embedded-open-formula)
4137 (declare-function cdlatex-tab "ext:cdlatex" ())
4138 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4139 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4140 (defvar font-lock-unfontify-region-function)
4141 (declare-function iswitchb-read-buffer "iswitchb"
4142 (prompt &optional default require-match start matches-set))
4143 (defvar iswitchb-temp-buflist)
4144 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4145 (defvar org-agenda-tags-todo-honor-ignore-options)
4146 (declare-function org-agenda-skip "org-agenda" ())
4147 (declare-function
4148 org-agenda-format-item "org-agenda"
4149 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4150 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4151 (declare-function org-agenda-change-all-lines "org-agenda"
4152 (newhead hdmarker &optional fixface just-this))
4153 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4154 (declare-function org-agenda-maybe-redo "org-agenda" ())
4155 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4156 (beg end))
4157 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4158 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4159 "org-agenda" (&optional end))
4160 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4161 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4162 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4163 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4164 (declare-function org-indent-mode "org-indent" (&optional arg))
4165 (declare-function parse-time-string "parse-time" (string))
4166 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4167 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4168 (defvar remember-data-file)
4169 (defvar texmathp-why)
4170 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4171 (declare-function table--at-cell-p "table" (position &optional object at-column))
4173 (defvar org-latex-regexps)
4175 ;;; Autoload and prepare some org modules
4177 ;; Some table stuff that needs to be defined here, because it is used
4178 ;; by the functions setting up org-mode or checking for table context.
4180 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4181 "Detect an org-type or table-type table.")
4182 (defconst org-table-line-regexp "^[ \t]*|"
4183 "Detect an org-type table line.")
4184 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4185 "Detect an org-type table line.")
4186 (defconst org-table-hline-regexp "^[ \t]*|-"
4187 "Detect an org-type table hline.")
4188 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4189 "Detect a table-type table hline.")
4190 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4191 "Detect the first line outside a table when searching from within it.
4192 This works for both table types.")
4194 ;; Autoload the functions in org-table.el that are needed by functions here.
4196 (eval-and-compile
4197 (org-autoload "org-table"
4198 '(org-table-begin org-table-blank-field org-table-end)))
4200 ;;;###autoload
4201 (defun turn-on-orgtbl ()
4202 "Unconditionally turn on `orgtbl-mode'."
4203 (require 'org-table)
4204 (orgtbl-mode 1))
4206 (defun org-at-table-p (&optional table-type)
4207 "Return t if the cursor is inside an org-type table.
4208 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4209 (if org-enable-table-editor
4210 (save-excursion
4211 (beginning-of-line 1)
4212 (looking-at (if table-type org-table-any-line-regexp
4213 org-table-line-regexp)))
4214 nil))
4215 (defsubst org-table-p () (org-at-table-p))
4217 (defun org-at-table.el-p ()
4218 "Return t if and only if we are at a table.el table."
4219 (and (org-at-table-p 'any)
4220 (save-excursion
4221 (goto-char (org-table-begin 'any))
4222 (looking-at org-table1-hline-regexp))))
4224 (defun org-table-recognize-table.el ()
4225 "If there is a table.el table nearby, recognize it and move into it."
4226 (if org-table-tab-recognizes-table.el
4227 (if (org-at-table.el-p)
4228 (progn
4229 (beginning-of-line 1)
4230 (if (looking-at org-table-dataline-regexp)
4232 (if (looking-at org-table1-hline-regexp)
4233 (progn
4234 (beginning-of-line 2)
4235 (if (looking-at org-table-any-border-regexp)
4236 (beginning-of-line -1)))))
4237 (if (re-search-forward "|" (org-table-end t) t)
4238 (progn
4239 (require 'table)
4240 (if (table--at-cell-p (point))
4242 (message "recognizing table.el table...")
4243 (table-recognize-table)
4244 (message "recognizing table.el table...done")))
4245 (error "This should not happen"))
4247 nil)
4248 nil))
4250 (defun org-at-table-hline-p ()
4251 "Return t if the cursor is inside a hline in a table."
4252 (if org-enable-table-editor
4253 (save-excursion
4254 (beginning-of-line 1)
4255 (looking-at org-table-hline-regexp))
4256 nil))
4258 (defvar org-table-clean-did-remove-column nil)
4259 (defun org-table-map-tables (function &optional quietly)
4260 "Apply FUNCTION to the start of all tables in the buffer."
4261 (save-excursion
4262 (save-restriction
4263 (widen)
4264 (goto-char (point-min))
4265 (while (re-search-forward org-table-any-line-regexp nil t)
4266 (unless quietly
4267 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4268 (beginning-of-line 1)
4269 (when (and (looking-at org-table-line-regexp)
4270 ;; Exclude tables in src/example/verbatim/clocktable blocks
4271 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4272 (save-excursion (funcall function))
4273 (or (looking-at org-table-line-regexp)
4274 (forward-char 1)))
4275 (re-search-forward org-table-any-border-regexp nil 1))))
4276 (unless quietly (message "Mapping tables: done")))
4278 ;; Declare and autoload functions from ox.el and al.
4280 (declare-function org-export-get-environment "ox"
4281 (&optional backend subtreep ext-plist))
4282 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4284 ;; Declare and autoload functions from org-agenda.el
4286 (eval-and-compile
4287 (org-autoload "org-agenda"
4288 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4290 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4291 (declare-function org-clock-update-mode-line "org-clock" ())
4292 (declare-function org-resolve-clocks "org-clock"
4293 (&optional also-non-dangling-p prompt last-valid))
4294 (defvar org-clock-start-time)
4295 (defvar org-clock-marker (make-marker)
4296 "Marker recording the last clock-in.")
4297 (defvar org-clock-hd-marker (make-marker)
4298 "Marker recording the last clock-in, but the headline position.")
4299 (defvar org-clock-heading ""
4300 "The heading of the current clock entry.")
4301 (defun org-clock-is-active ()
4302 "Return non-nil if clock is currently running.
4303 The return value is actually the clock marker."
4304 (marker-buffer org-clock-marker))
4306 (eval-and-compile
4307 (org-autoload "org-clock" '(org-clock-remove-overlays
4308 org-clock-update-time-maybe
4309 org-clocktable-shift)))
4311 (defun org-check-running-clock ()
4312 "Check if the current buffer contains the running clock.
4313 If yes, offer to stop it and to save the buffer with the changes."
4314 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4315 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4316 (buffer-name))))
4317 (org-clock-out)
4318 (when (y-or-n-p "Save changed buffer?")
4319 (save-buffer))))
4321 (defun org-clocktable-try-shift (dir n)
4322 "Check if this line starts a clock table, if yes, shift the time block."
4323 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4324 (org-clocktable-shift dir n)))
4326 ;;;###autoload
4327 (defun org-clock-persistence-insinuate ()
4328 "Set up hooks for clock persistence."
4329 (require 'org-clock)
4330 (add-hook 'org-mode-hook 'org-clock-load)
4331 (add-hook 'kill-emacs-hook 'org-clock-save))
4333 ;; Define the variable already here, to make sure we have it.
4334 (defvar org-indent-mode nil
4335 "Non-nil if Org-Indent mode is enabled.
4336 Use the command `org-indent-mode' to change this variable.")
4338 ;; Autoload archiving code
4339 ;; The stuff that is needed for cycling and tags has to be defined here.
4341 (defgroup org-archive nil
4342 "Options concerning archiving in Org-mode."
4343 :tag "Org Archive"
4344 :group 'org-structure)
4346 (defcustom org-archive-location "%s_archive::"
4347 "The location where subtrees should be archived.
4349 The value of this variable is a string, consisting of two parts,
4350 separated by a double-colon. The first part is a filename and
4351 the second part is a headline.
4353 When the filename is omitted, archiving happens in the same file.
4354 %s in the filename will be replaced by the current file
4355 name (without the directory part). Archiving to a different file
4356 is useful to keep archived entries from contributing to the
4357 Org-mode Agenda.
4359 The archived entries will be filed as subtrees of the specified
4360 headline. When the headline is omitted, the subtrees are simply
4361 filed away at the end of the file, as top-level entries. Also in
4362 the heading you can use %s to represent the file name, this can be
4363 useful when using the same archive for a number of different files.
4365 Here are a few examples:
4366 \"%s_archive::\"
4367 If the current file is Projects.org, archive in file
4368 Projects.org_archive, as top-level trees. This is the default.
4370 \"::* Archived Tasks\"
4371 Archive in the current file, under the top-level headline
4372 \"* Archived Tasks\".
4374 \"~/org/archive.org::\"
4375 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4377 \"~/org/archive.org::* From %s\"
4378 Archive in file ~/org/archive.org (absolute path), under headlines
4379 \"From FILENAME\" where file name is the current file name.
4381 \"~/org/datetree.org::datetree/* Finished Tasks\"
4382 The \"datetree/\" string is special, signifying to archive
4383 items to the datetree. Items are placed in either the CLOSED
4384 date of the item, or the current date if there is no CLOSED date.
4385 The heading will be a subentry to the current date. There doesn't
4386 need to be a heading, but there always needs to be a slash after
4387 datetree. For example, to store archived items directly in the
4388 datetree, use \"~/org/datetree.org::datetree/\".
4390 \"basement::** Finished Tasks\"
4391 Archive in file ./basement (relative path), as level 3 trees
4392 below the level 2 heading \"** Finished Tasks\".
4394 You may set this option on a per-file basis by adding to the buffer a
4395 line like
4397 #+ARCHIVE: basement::** Finished Tasks
4399 You may also define it locally for a subtree by setting an ARCHIVE property
4400 in the entry. If such a property is found in an entry, or anywhere up
4401 the hierarchy, it will be used."
4402 :group 'org-archive
4403 :type 'string)
4405 (defcustom org-archive-tag "ARCHIVE"
4406 "The tag that marks a subtree as archived.
4407 An archived subtree does not open during visibility cycling, and does
4408 not contribute to the agenda listings.
4409 After changing this, font-lock must be restarted in the relevant buffers to
4410 get the proper fontification."
4411 :group 'org-archive
4412 :group 'org-keywords
4413 :type 'string)
4415 (defcustom org-agenda-skip-archived-trees t
4416 "Non-nil means the agenda will skip any items located in archived trees.
4417 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4418 variable is no longer recommended, you should leave it at the value t.
4419 Instead, use the key `v' to cycle the archives-mode in the agenda."
4420 :group 'org-archive
4421 :group 'org-agenda-skip
4422 :type 'boolean)
4424 (defcustom org-columns-skip-archived-trees t
4425 "Non-nil means ignore archived trees when creating column view."
4426 :group 'org-archive
4427 :group 'org-properties
4428 :type 'boolean)
4430 (defcustom org-cycle-open-archived-trees nil
4431 "Non-nil means `org-cycle' will open archived trees.
4432 An archived tree is a tree marked with the tag ARCHIVE.
4433 When nil, archived trees will stay folded. You can still open them with
4434 normal outline commands like `show-all', but not with the cycling commands."
4435 :group 'org-archive
4436 :group 'org-cycle
4437 :type 'boolean)
4439 (defcustom org-sparse-tree-open-archived-trees nil
4440 "Non-nil means sparse tree construction shows matches in archived trees.
4441 When nil, matches in these trees are highlighted, but the trees are kept in
4442 collapsed state."
4443 :group 'org-archive
4444 :group 'org-sparse-trees
4445 :type 'boolean)
4447 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4448 "The default date type when building a sparse tree.
4449 When this is nil, a date is a scheduled or a deadline timestamp.
4450 Otherwise, these types are allowed:
4452 all: all timestamps
4453 active: only active timestamps (<...>)
4454 inactive: only inactive timestamps (<...)
4455 scheduled: only scheduled timestamps
4456 deadline: only deadline timestamps"
4457 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4458 (const :tag "All timestamps" all)
4459 (const :tag "Only active timestamps" active)
4460 (const :tag "Only inactive timestamps" inactive)
4461 (const :tag "Only scheduled timestamps" scheduled)
4462 (const :tag "Only deadline timestamps" deadline))
4463 :version "24.3"
4464 :group 'org-sparse-trees)
4466 (defun org-cycle-hide-archived-subtrees (state)
4467 "Re-hide all archived subtrees after a visibility state change."
4468 (when (and (not org-cycle-open-archived-trees)
4469 (not (memq state '(overview folded))))
4470 (save-excursion
4471 (let* ((globalp (memq state '(contents all)))
4472 (beg (if globalp (point-min) (point)))
4473 (end (if globalp (point-max) (org-end-of-subtree t))))
4474 (org-hide-archived-subtrees beg end)
4475 (goto-char beg)
4476 (if (looking-at (concat ".*:" org-archive-tag ":"))
4477 (message "%s" (substitute-command-keys
4478 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4480 (defun org-force-cycle-archived ()
4481 "Cycle subtree even if it is archived."
4482 (interactive)
4483 (setq this-command 'org-cycle)
4484 (let ((org-cycle-open-archived-trees t))
4485 (call-interactively 'org-cycle)))
4487 (defun org-hide-archived-subtrees (beg end)
4488 "Re-hide all archived subtrees after a visibility state change."
4489 (save-excursion
4490 (let* ((re (concat ":" org-archive-tag ":")))
4491 (goto-char beg)
4492 (while (re-search-forward re end t)
4493 (when (org-at-heading-p)
4494 (org-flag-subtree t)
4495 (org-end-of-subtree t))))))
4497 (declare-function outline-end-of-heading "outline" ())
4498 (declare-function outline-flag-region "outline" (from to flag))
4499 (defun org-flag-subtree (flag)
4500 (save-excursion
4501 (org-back-to-heading t)
4502 (outline-end-of-heading)
4503 (outline-flag-region (point)
4504 (progn (org-end-of-subtree t) (point))
4505 flag)))
4507 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4509 (eval-and-compile
4510 (org-autoload "org-archive"
4511 '(org-add-archive-files)))
4513 ;; Autoload Column View Code
4515 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4516 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4517 (declare-function org-columns-compute "org-colview" (property))
4519 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4520 '(org-columns-number-to-string
4521 org-columns-get-format-and-top-level
4522 org-columns-compute
4523 org-columns-remove-overlays))
4525 ;; Autoload ID code
4527 (declare-function org-id-store-link "org-id")
4528 (declare-function org-id-locations-load "org-id")
4529 (declare-function org-id-locations-save "org-id")
4530 (defvar org-id-track-globally)
4531 (org-autoload "org-id"
4532 '(org-id-new
4533 org-id-copy
4534 org-id-get-with-outline-path-completion
4535 org-id-get-with-outline-drilling))
4537 ;;; Variables for pre-computed regular expressions, all buffer local
4539 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4540 "Matches first line of a hidden block.")
4541 (make-variable-buffer-local 'org-drawer-regexp)
4542 (defvar org-todo-regexp nil
4543 "Matches any of the TODO state keywords.")
4544 (make-variable-buffer-local 'org-todo-regexp)
4545 (defvar org-not-done-regexp nil
4546 "Matches any of the TODO state keywords except the last one.")
4547 (make-variable-buffer-local 'org-not-done-regexp)
4548 (defvar org-not-done-heading-regexp nil
4549 "Matches a TODO headline that is not done.")
4550 (make-variable-buffer-local 'org-not-done-regexp)
4551 (defvar org-todo-line-regexp nil
4552 "Matches a headline and puts TODO state into group 2 if present.")
4553 (make-variable-buffer-local 'org-todo-line-regexp)
4554 (defvar org-complex-heading-regexp nil
4555 "Matches a headline and puts everything into groups:
4556 group 1: the stars
4557 group 2: The todo keyword, maybe
4558 group 3: Priority cookie
4559 group 4: True headline
4560 group 5: Tags")
4561 (make-variable-buffer-local 'org-complex-heading-regexp)
4562 (defvar org-complex-heading-regexp-format nil
4563 "Printf format to make regexp to match an exact headline.
4564 This regexp will match the headline of any node which has the
4565 exact headline text that is put into the format, but may have any
4566 TODO state, priority and tags.")
4567 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4568 (defvar org-todo-line-tags-regexp nil
4569 "Matches a headline and puts TODO state into group 2 if present.
4570 Also put tags into group 4 if tags are present.")
4571 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4572 (defvar org-ds-keyword-length 12
4573 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4574 (make-variable-buffer-local 'org-ds-keyword-length)
4575 (defvar org-deadline-regexp nil
4576 "Matches the DEADLINE keyword.")
4577 (make-variable-buffer-local 'org-deadline-regexp)
4578 (defvar org-deadline-time-regexp nil
4579 "Matches the DEADLINE keyword together with a time stamp.")
4580 (make-variable-buffer-local 'org-deadline-time-regexp)
4581 (defvar org-deadline-time-hour-regexp nil
4582 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4583 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4584 (defvar org-deadline-line-regexp nil
4585 "Matches the DEADLINE keyword and the rest of the line.")
4586 (make-variable-buffer-local 'org-deadline-line-regexp)
4587 (defvar org-scheduled-regexp nil
4588 "Matches the SCHEDULED keyword.")
4589 (make-variable-buffer-local 'org-scheduled-regexp)
4590 (defvar org-scheduled-time-regexp nil
4591 "Matches the SCHEDULED keyword together with a time stamp.")
4592 (make-variable-buffer-local 'org-scheduled-time-regexp)
4593 (defvar org-scheduled-time-hour-regexp nil
4594 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4595 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4596 (defvar org-closed-time-regexp nil
4597 "Matches the CLOSED keyword together with a time stamp.")
4598 (make-variable-buffer-local 'org-closed-time-regexp)
4600 (defvar org-keyword-time-regexp nil
4601 "Matches any of the 4 keywords, together with the time stamp.")
4602 (make-variable-buffer-local 'org-keyword-time-regexp)
4603 (defvar org-keyword-time-not-clock-regexp nil
4604 "Matches any of the 3 keywords, together with the time stamp.")
4605 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4606 (defvar org-maybe-keyword-time-regexp nil
4607 "Matches a timestamp, possibly preceded by a keyword.")
4608 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4609 (defvar org-all-time-keywords nil
4610 "List of time keywords.")
4611 (make-variable-buffer-local 'org-all-time-keywords)
4613 (defconst org-plain-time-of-day-regexp
4614 (concat
4615 "\\(\\<[012]?[0-9]"
4616 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4617 "\\(--?"
4618 "\\(\\<[012]?[0-9]"
4619 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4620 "\\)?")
4621 "Regular expression to match a plain time or time range.
4622 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4623 groups carry important information:
4624 0 the full match
4625 1 the first time, range or not
4626 8 the second time, if it is a range.")
4628 (defconst org-plain-time-extension-regexp
4629 (concat
4630 "\\(\\<[012]?[0-9]"
4631 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4632 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4633 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4634 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4635 groups carry important information:
4636 0 the full match
4637 7 hours of duration
4638 9 minutes of duration")
4640 (defconst org-stamp-time-of-day-regexp
4641 (concat
4642 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4643 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4644 "\\(--?"
4645 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4646 "Regular expression to match a timestamp time or time range.
4647 After a match, the following groups carry important information:
4648 0 the full match
4649 1 date plus weekday, for back referencing to make sure both times are on the same day
4650 2 the first time, range or not
4651 4 the second time, if it is a range.")
4653 (defconst org-startup-options
4654 '(("fold" org-startup-folded t)
4655 ("overview" org-startup-folded t)
4656 ("nofold" org-startup-folded nil)
4657 ("showall" org-startup-folded nil)
4658 ("showeverything" org-startup-folded showeverything)
4659 ("content" org-startup-folded content)
4660 ("indent" org-startup-indented t)
4661 ("noindent" org-startup-indented nil)
4662 ("hidestars" org-hide-leading-stars t)
4663 ("showstars" org-hide-leading-stars nil)
4664 ("odd" org-odd-levels-only t)
4665 ("oddeven" org-odd-levels-only nil)
4666 ("align" org-startup-align-all-tables t)
4667 ("noalign" org-startup-align-all-tables nil)
4668 ("inlineimages" org-startup-with-inline-images t)
4669 ("noinlineimages" org-startup-with-inline-images nil)
4670 ("latexpreview" org-startup-with-latex-preview t)
4671 ("nolatexpreview" org-startup-with-latex-preview nil)
4672 ("customtime" org-display-custom-times t)
4673 ("logdone" org-log-done time)
4674 ("lognotedone" org-log-done note)
4675 ("nologdone" org-log-done nil)
4676 ("lognoteclock-out" org-log-note-clock-out t)
4677 ("nolognoteclock-out" org-log-note-clock-out nil)
4678 ("logrepeat" org-log-repeat state)
4679 ("lognoterepeat" org-log-repeat note)
4680 ("logdrawer" org-log-into-drawer t)
4681 ("nologdrawer" org-log-into-drawer nil)
4682 ("logstatesreversed" org-log-states-order-reversed t)
4683 ("nologstatesreversed" org-log-states-order-reversed nil)
4684 ("nologrepeat" org-log-repeat nil)
4685 ("logreschedule" org-log-reschedule time)
4686 ("lognotereschedule" org-log-reschedule note)
4687 ("nologreschedule" org-log-reschedule nil)
4688 ("logredeadline" org-log-redeadline time)
4689 ("lognoteredeadline" org-log-redeadline note)
4690 ("nologredeadline" org-log-redeadline nil)
4691 ("logrefile" org-log-refile time)
4692 ("lognoterefile" org-log-refile note)
4693 ("nologrefile" org-log-refile nil)
4694 ("fninline" org-footnote-define-inline t)
4695 ("nofninline" org-footnote-define-inline nil)
4696 ("fnlocal" org-footnote-section nil)
4697 ("fnauto" org-footnote-auto-label t)
4698 ("fnprompt" org-footnote-auto-label nil)
4699 ("fnconfirm" org-footnote-auto-label confirm)
4700 ("fnplain" org-footnote-auto-label plain)
4701 ("fnadjust" org-footnote-auto-adjust t)
4702 ("nofnadjust" org-footnote-auto-adjust nil)
4703 ("constcgs" constants-unit-system cgs)
4704 ("constSI" constants-unit-system SI)
4705 ("noptag" org-tag-persistent-alist nil)
4706 ("hideblocks" org-hide-block-startup t)
4707 ("nohideblocks" org-hide-block-startup nil)
4708 ("beamer" org-startup-with-beamer-mode t)
4709 ("entitiespretty" org-pretty-entities t)
4710 ("entitiesplain" org-pretty-entities nil))
4711 "Variable associated with STARTUP options for org-mode.
4712 Each element is a list of three items: the startup options (as written
4713 in the #+STARTUP line), the corresponding variable, and the value to set
4714 this variable to if the option is found. An optional forth element PUSH
4715 means to push this value onto the list in the variable.")
4717 (defun org-update-property-plist (key val props)
4718 "Update PROPS with KEY and VAL."
4719 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4720 (key (if appending (substring key 0 (- (length key) 1)) key))
4721 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4722 (previous (cdr (assoc key props))))
4723 (if appending
4724 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4725 (cons (cons key val) remainder))))
4727 (defconst org-block-regexp
4728 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4729 "Regular expression for hiding blocks.")
4730 (defconst org-heading-keyword-regexp-format
4731 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4732 "Printf format for a regexp matching a headline with some keyword.
4733 This regexp will match the headline of any node which has the
4734 exact keyword that is put into the format. The keyword isn't in
4735 any group by default, but the stars and the body are.")
4736 (defconst org-heading-keyword-maybe-regexp-format
4737 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4738 "Printf format for a regexp matching a headline, possibly with some keyword.
4739 This regexp can match any headline with the specified keyword, or
4740 without a keyword. The keyword isn't in any group by default,
4741 but the stars and the body are.")
4743 (defcustom org-group-tags t
4744 "When non-nil (the default), use group tags.
4745 This can be turned on/off through `org-toggle-tags-groups'."
4746 :group 'org-tags
4747 :group 'org-startup
4748 :type 'boolean)
4750 (defun org-toggle-tags-groups ()
4751 "Toggle support for group tags.
4752 Support for group tags is controlled by the option
4753 `org-group-tags', which is non-nil by default."
4754 (interactive)
4755 (setq org-group-tags (not org-group-tags))
4756 (cond ((and (derived-mode-p 'org-agenda-mode)
4757 org-group-tags)
4758 (org-agenda-redo))
4759 ((derived-mode-p 'org-mode)
4760 (let ((org-inhibit-startup t)) (org-mode))))
4761 (message "Groups tags support has been turned %s"
4762 (if org-group-tags "on" "off")))
4764 (defun org-set-regexps-and-options-for-tags ()
4765 "Precompute regular expressions used for tags in the current buffer."
4766 (when (derived-mode-p 'org-mode)
4767 (org-set-local 'org-file-tags nil)
4768 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4769 (splitre "[ \t]+")
4770 tags ftags key value
4771 (start 0))
4772 (save-excursion
4773 (save-restriction
4774 (widen)
4775 (goto-char (point-min))
4776 (while (re-search-forward re nil t)
4777 (setq key (upcase (org-match-string-no-properties 1))
4778 value (org-match-string-no-properties 2))
4779 (if (stringp value) (setq value (org-trim value)))
4780 (cond
4781 ((equal key "TAGS")
4782 (setq tags (append tags (if tags '("\\n") nil)
4783 (org-split-string value splitre))))
4784 ((equal key "FILETAGS")
4785 (when (string-match "\\S-" value)
4786 (setq ftags
4787 (append
4788 ftags
4789 (apply 'append
4790 (mapcar (lambda (x) (org-split-string x ":"))
4791 (org-split-string value)))))))))))
4792 ;; Process the file tags.
4793 (and ftags (org-set-local 'org-file-tags
4794 (mapcar 'org-add-prop-inherited ftags)))
4795 (org-set-local 'org-tag-groups-alist nil)
4796 ;; Process the tags.
4797 ;; FIXME
4798 (when tags
4799 (let (e tgs g)
4800 (while (setq e (pop tags))
4801 (cond
4802 ((equal e "{")
4803 (progn (push '(:startgroup) tgs)
4804 (when (equal (nth 1 tags) ":")
4805 (push (list (replace-regexp-in-string
4806 "(.+)$" "" (nth 0 tags)))
4807 org-tag-groups-alist)
4808 (setq g 0))))
4809 ((equal e ":") (push '(:grouptags) tgs))
4810 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4811 ((equal e "\\n") (push '(:newline) tgs))
4812 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4813 (push (cons (match-string 1 e)
4814 (string-to-char (match-string 2 e))) tgs)
4815 (if (and g (> g 0))
4816 (setcar org-tag-groups-alist
4817 (append (car org-tag-groups-alist)
4818 (list (match-string 1 e)))))
4819 (if g (setq g (1+ g))))
4820 (t (push (list e) tgs)
4821 (if (and g (> g 0))
4822 (setcar org-tag-groups-alist
4823 (append (car org-tag-groups-alist) (list e))))
4824 (if g (setq g (1+ g))))))
4825 (org-set-local 'org-tag-alist nil)
4826 (while (setq e (pop tgs))
4827 (or (and (stringp (car e))
4828 (assoc (car e) org-tag-alist))
4829 (push e org-tag-alist))))))))
4831 (defun org-set-regexps-and-options ()
4832 "Precompute regular expressions used in the current buffer."
4833 (when (derived-mode-p 'org-mode)
4834 (org-set-local 'org-todo-kwd-alist nil)
4835 (org-set-local 'org-todo-key-alist nil)
4836 (org-set-local 'org-todo-key-trigger nil)
4837 (org-set-local 'org-todo-keywords-1 nil)
4838 (org-set-local 'org-done-keywords nil)
4839 (org-set-local 'org-todo-heads nil)
4840 (org-set-local 'org-todo-sets nil)
4841 (org-set-local 'org-todo-log-states nil)
4842 (org-set-local 'org-file-properties nil)
4843 (let ((re (org-make-options-regexp
4844 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4845 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4846 "SETUPFILE" "OPTIONS")
4847 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4848 (splitre "[ \t]+")
4849 (scripts org-use-sub-superscripts)
4850 kwds kws0 kwsa key log value cat arch const links hw dws
4851 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4852 (start 0))
4853 (save-excursion
4854 (save-restriction
4855 (widen)
4856 (goto-char (point-min))
4857 (while (or (and ext-setup-or-nil
4858 (string-match re ext-setup-or-nil start)
4859 (setq start (match-end 0)))
4860 (and (setq ext-setup-or-nil nil start 0)
4861 (re-search-forward re nil t)))
4862 (setq key (upcase (match-string 1 ext-setup-or-nil))
4863 value (org-match-string-no-properties 2 ext-setup-or-nil))
4864 (if (stringp value) (setq value (org-trim value)))
4865 (cond
4866 ((equal key "CATEGORY")
4867 (setq cat value))
4868 ((member key '("SEQ_TODO" "TODO"))
4869 (push (cons 'sequence (org-split-string value splitre)) kwds))
4870 ((equal key "TYP_TODO")
4871 (push (cons 'type (org-split-string value splitre)) kwds))
4872 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4873 ;; general TODO-like setup
4874 (push (cons (intern (downcase (match-string 1 key)))
4875 (org-split-string value splitre)) kwds))
4876 ((equal key "COLUMNS")
4877 (org-set-local 'org-columns-default-format value))
4878 ((equal key "LINK")
4879 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4880 (push (cons (match-string 1 value)
4881 (org-trim (match-string 2 value)))
4882 links)))
4883 ((equal key "PRIORITIES")
4884 (setq prio (org-split-string value " +")))
4885 ((equal key "PROPERTY")
4886 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4887 (setq props (org-update-property-plist (match-string 1 value)
4888 (match-string 2 value)
4889 props))))
4890 ((equal key "DRAWERS")
4891 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4892 ((equal key "CONSTANTS")
4893 (org-table-set-constants))
4894 ((equal key "STARTUP")
4895 (let ((opts (org-split-string value splitre))
4896 l var val)
4897 (while (setq l (pop opts))
4898 (when (setq l (assoc l org-startup-options))
4899 (setq var (nth 1 l) val (nth 2 l))
4900 (if (not (nth 3 l))
4901 (set (make-local-variable var) val)
4902 (if (not (listp (symbol-value var)))
4903 (set (make-local-variable var) nil))
4904 (set (make-local-variable var) (symbol-value var))
4905 (add-to-list var val))))))
4906 ((equal key "ARCHIVE")
4907 (setq arch value)
4908 (remove-text-properties 0 (length arch)
4909 '(face t fontified t) arch))
4910 ((equal key "OPTIONS")
4911 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4912 (setq scripts (read (match-string 2 value)))))
4913 ((and (equal key "SETUPFILE")
4914 ;; Prevent checking in Gnus messages
4915 (not buffer-read-only))
4916 (setq setup-contents (org-file-contents
4917 (expand-file-name
4918 (org-remove-double-quotes value))
4919 'noerror))
4920 (if (not ext-setup-or-nil)
4921 (setq ext-setup-or-nil setup-contents start 0)
4922 (setq ext-setup-or-nil
4923 (concat (substring ext-setup-or-nil 0 start)
4924 "\n" setup-contents "\n"
4925 (substring ext-setup-or-nil start)))))))
4926 ;; search for property blocks
4927 (goto-char (point-min))
4928 (while (re-search-forward org-block-regexp nil t)
4929 (when (equal "PROPERTY" (upcase (match-string 1)))
4930 (setq value (replace-regexp-in-string
4931 "[\n\r]" " " (match-string 4)))
4932 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4933 (setq props (org-update-property-plist (match-string 1 value)
4934 (match-string 2 value)
4935 props)))))))
4936 (org-set-local 'org-use-sub-superscripts scripts)
4937 (when cat
4938 (org-set-local 'org-category (intern cat))
4939 (push (cons "CATEGORY" cat) props))
4940 (when prio
4941 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4942 (setq prio (mapcar 'string-to-char prio))
4943 (org-set-local 'org-highest-priority (nth 0 prio))
4944 (org-set-local 'org-lowest-priority (nth 1 prio))
4945 (org-set-local 'org-default-priority (nth 2 prio)))
4946 (and props (org-set-local 'org-file-properties (nreverse props)))
4947 (and drawers (org-set-local 'org-drawers drawers))
4948 (and arch (org-set-local 'org-archive-location arch))
4949 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4950 ;; Process the TODO keywords
4951 (unless kwds
4952 ;; Use the global values as if they had been given locally.
4953 (setq kwds (default-value 'org-todo-keywords))
4954 (if (stringp (car kwds))
4955 (setq kwds (list (cons org-todo-interpretation
4956 (default-value 'org-todo-keywords)))))
4957 (setq kwds (reverse kwds)))
4958 (setq kwds (nreverse kwds))
4959 (let (inter kws kw)
4960 (while (setq kws (pop kwds))
4961 (let ((kws (or
4962 (run-hook-with-args-until-success
4963 'org-todo-setup-filter-hook kws)
4964 kws)))
4965 (setq inter (pop kws) sep (member "|" kws)
4966 kws0 (delete "|" (copy-sequence kws))
4967 kwsa nil
4968 kws1 (mapcar
4969 (lambda (x)
4970 ;; 1 2
4971 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4972 (progn
4973 (setq kw (match-string 1 x)
4974 key (and (match-end 2) (match-string 2 x))
4975 log (org-extract-log-state-settings x))
4976 (push (cons kw (and key (string-to-char key))) kwsa)
4977 (and log (push log org-todo-log-states))
4979 (error "Invalid TODO keyword %s" x)))
4980 kws0)
4981 kwsa (if kwsa (append '((:startgroup))
4982 (nreverse kwsa)
4983 '((:endgroup))))
4984 hw (car kws1)
4985 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4986 tail (list inter hw (car dws) (org-last dws))))
4987 (add-to-list 'org-todo-heads hw 'append)
4988 (push kws1 org-todo-sets)
4989 (setq org-done-keywords (append org-done-keywords dws nil))
4990 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4991 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4992 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4993 (setq org-todo-sets (nreverse org-todo-sets)
4994 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4995 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4996 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4997 ;; Compute the regular expressions and other local variables.
4998 ;; Using `org-outline-regexp-bol' would complicate them much,
4999 ;; because of the fixed white space at the end of that string.
5000 (if (not org-done-keywords)
5001 (setq org-done-keywords (and org-todo-keywords-1
5002 (list (org-last org-todo-keywords-1)))))
5003 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5004 (length org-scheduled-string)
5005 (length org-clock-string)
5006 (length org-closed-string)))
5007 org-drawer-regexp
5008 (concat "^[ \t]*:\\("
5009 (mapconcat 'regexp-quote org-drawers "\\|")
5010 "\\):[ \t]*$")
5011 org-not-done-keywords
5012 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5013 org-todo-regexp
5014 (concat "\\("
5015 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5016 "\\)")
5017 org-not-done-regexp
5018 (concat "\\("
5019 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5020 "\\)")
5021 org-not-done-heading-regexp
5022 (format org-heading-keyword-regexp-format org-not-done-regexp)
5023 org-todo-line-regexp
5024 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5025 org-complex-heading-regexp
5026 (concat "^\\(\\*+\\)"
5027 "\\(?: +" org-todo-regexp "\\)?"
5028 "\\(?: +\\(\\[#.\\]\\)\\)?"
5029 "\\(?: +\\(.*?\\)\\)??"
5030 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5031 "[ \t]*$")
5032 org-complex-heading-regexp-format
5033 (concat "^\\(\\*+\\)"
5034 "\\(?: +" org-todo-regexp "\\)?"
5035 "\\(?: +\\(\\[#.\\]\\)\\)?"
5036 "\\(?: +"
5037 ;; Stats cookies can be stuck to body.
5038 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5039 "\\(%s\\)"
5040 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5041 "\\)"
5042 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5043 "[ \t]*$")
5044 org-todo-line-tags-regexp
5045 (concat "^\\(\\*+\\)"
5046 "\\(?: +" org-todo-regexp "\\)?"
5047 "\\(?: +\\(.*?\\)\\)??"
5048 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5049 "[ \t]*$")
5050 org-deadline-regexp (concat "\\<" org-deadline-string)
5051 org-deadline-time-regexp
5052 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5053 org-deadline-time-hour-regexp
5054 (concat "\\<" org-deadline-string
5055 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5056 org-deadline-line-regexp
5057 (concat "\\<\\(" org-deadline-string "\\).*")
5058 org-scheduled-regexp
5059 (concat "\\<" org-scheduled-string)
5060 org-scheduled-time-regexp
5061 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5062 org-scheduled-time-hour-regexp
5063 (concat "\\<" org-scheduled-string
5064 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5065 org-closed-time-regexp
5066 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5067 org-keyword-time-regexp
5068 (concat "\\<\\(" org-scheduled-string
5069 "\\|" org-deadline-string
5070 "\\|" org-closed-string
5071 "\\|" org-clock-string "\\)"
5072 " *[[<]\\([^]>]+\\)[]>]")
5073 org-keyword-time-not-clock-regexp
5074 (concat "\\<\\(" org-scheduled-string
5075 "\\|" org-deadline-string
5076 "\\|" org-closed-string
5077 "\\)"
5078 " *[[<]\\([^]>]+\\)[]>]")
5079 org-maybe-keyword-time-regexp
5080 (concat "\\(\\<\\(" org-scheduled-string
5081 "\\|" org-deadline-string
5082 "\\|" org-closed-string
5083 "\\|" org-clock-string "\\)\\)?"
5084 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5085 org-all-time-keywords
5086 (mapcar (lambda (w) (substring w 0 -1))
5087 (list org-scheduled-string org-deadline-string
5088 org-clock-string org-closed-string)))
5089 (org-compute-latex-and-related-regexp)
5090 (org-set-font-lock-defaults))))
5092 (defun org-file-contents (file &optional noerror)
5093 "Return the contents of FILE, as a string."
5094 (if (or (not file)
5095 (not (file-readable-p file)))
5096 (if noerror
5097 (message "Cannot read file \"%s\"" file)
5098 (error "Cannot read file \"%s\"" file))
5099 (with-temp-buffer
5100 (insert-file-contents file)
5101 (buffer-string))))
5103 (defun org-extract-log-state-settings (x)
5104 "Extract the log state setting from a TODO keyword string.
5105 This will extract info from a string like \"WAIT(w@/!)\"."
5106 (let (kw key log1 log2)
5107 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5108 (setq kw (match-string 1 x)
5109 key (and (match-end 2) (match-string 2 x))
5110 log1 (and (match-end 3) (match-string 3 x))
5111 log2 (and (match-end 4) (match-string 4 x)))
5112 (and (or log1 log2)
5113 (list kw
5114 (and log1 (if (equal log1 "!") 'time 'note))
5115 (and log2 (if (equal log2 "!") 'time 'note)))))))
5117 (defun org-remove-keyword-keys (list)
5118 "Remove a pair of parenthesis at the end of each string in LIST."
5119 (mapcar (lambda (x)
5120 (if (string-match "(.*)$" x)
5121 (substring x 0 (match-beginning 0))
5123 list))
5125 (defun org-assign-fast-keys (alist)
5126 "Assign fast keys to a keyword-key alist.
5127 Respect keys that are already there."
5128 (let (new e (alt ?0))
5129 (while (setq e (pop alist))
5130 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5131 (cdr e)) ;; Key already assigned.
5132 (push e new)
5133 (let ((clist (string-to-list (downcase (car e))))
5134 (used (append new alist)))
5135 (when (= (car clist) ?@)
5136 (pop clist))
5137 (while (and clist (rassoc (car clist) used))
5138 (pop clist))
5139 (unless clist
5140 (while (rassoc alt used)
5141 (incf alt)))
5142 (push (cons (car e) (or (car clist) alt)) new))))
5143 (nreverse new)))
5145 ;;; Some variables used in various places
5147 (defvar org-window-configuration nil
5148 "Used in various places to store a window configuration.")
5149 (defvar org-selected-window nil
5150 "Used in various places to store a window configuration.")
5151 (defvar org-finish-function nil
5152 "Function to be called when `C-c C-c' is used.
5153 This is for getting out of special buffers like capture.")
5156 ;; FIXME: Occasionally check by commenting these, to make sure
5157 ;; no other functions uses these, forgetting to let-bind them.
5158 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5159 (defvar org-last-state)
5160 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5162 ;; Defined somewhere in this file, but used before definition.
5163 (defvar org-entities) ;; defined in org-entities.el
5164 (defvar org-struct-menu)
5165 (defvar org-org-menu)
5166 (defvar org-tbl-menu)
5168 ;;;; Define the Org-mode
5170 ;; We use a before-change function to check if a table might need
5171 ;; an update.
5172 (defvar org-table-may-need-update t
5173 "Indicates that a table might need an update.
5174 This variable is set by `org-before-change-function'.
5175 `org-table-align' sets it back to nil.")
5176 (defun org-before-change-function (beg end)
5177 "Every change indicates that a table might need an update."
5178 (setq org-table-may-need-update t))
5179 (defvar org-mode-map)
5180 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5181 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5182 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5183 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5184 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5185 (defvar org-table-buffer-is-an nil)
5187 (defvar bidi-paragraph-direction)
5188 (defvar buffer-face-mode-face)
5190 (require 'outline)
5191 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5192 (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"))
5193 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5195 ;; Other stuff we need.
5196 (require 'time-date)
5197 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5198 (require 'easymenu)
5199 (require 'overlay)
5201 ;; (require 'org-macs) moved higher up in the file before it is first used
5202 (require 'org-entities)
5203 ;; (require 'org-compat) moved higher up in the file before it is first used
5204 (require 'org-faces)
5205 (require 'org-list)
5206 (require 'org-pcomplete)
5207 (require 'org-src)
5208 (require 'org-footnote)
5209 (require 'org-macro)
5211 ;; babel
5212 (require 'ob)
5214 ;;;###autoload
5215 (define-derived-mode org-mode outline-mode "Org"
5216 "Outline-based notes management and organizer, alias
5217 \"Carsten's outline-mode for keeping track of everything.\"
5219 Org-mode develops organizational tasks around a NOTES file which
5220 contains information about projects as plain text. Org-mode is
5221 implemented on top of outline-mode, which is ideal to keep the content
5222 of large files well structured. It supports ToDo items, deadlines and
5223 time stamps, which magically appear in the diary listing of the Emacs
5224 calendar. Tables are easily created with a built-in table editor.
5225 Plain text URL-like links connect to websites, emails (VM), Usenet
5226 messages (Gnus), BBDB entries, and any files related to the project.
5227 For printing and sharing of notes, an Org-mode file (or a part of it)
5228 can be exported as a structured ASCII or HTML file.
5230 The following commands are available:
5232 \\{org-mode-map}"
5234 ;; Get rid of Outline menus, they are not needed
5235 ;; Need to do this here because define-derived-mode sets up
5236 ;; the keymap so late. Still, it is a waste to call this each time
5237 ;; we switch another buffer into org-mode.
5238 (if (featurep 'xemacs)
5239 (when (boundp 'outline-mode-menu-heading)
5240 ;; Assume this is Greg's port, it uses easymenu
5241 (easy-menu-remove outline-mode-menu-heading)
5242 (easy-menu-remove outline-mode-menu-show)
5243 (easy-menu-remove outline-mode-menu-hide))
5244 (define-key org-mode-map [menu-bar headings] 'undefined)
5245 (define-key org-mode-map [menu-bar hide] 'undefined)
5246 (define-key org-mode-map [menu-bar show] 'undefined))
5248 (org-load-modules-maybe)
5249 (easy-menu-add org-org-menu)
5250 (easy-menu-add org-tbl-menu)
5251 (org-install-agenda-files-menu)
5252 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5253 (add-to-invisibility-spec '(org-cwidth))
5254 (add-to-invisibility-spec '(org-hide-block . t))
5255 (when (featurep 'xemacs)
5256 (org-set-local 'line-move-ignore-invisible t))
5257 (org-set-local 'outline-regexp org-outline-regexp)
5258 (org-set-local 'outline-level 'org-outline-level)
5259 (setq bidi-paragraph-direction 'left-to-right)
5260 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5261 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5262 (when (and org-ellipsis
5263 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5264 (fboundp 'make-glyph-code))
5265 (unless org-display-table
5266 (setq org-display-table (make-display-table)))
5267 (set-display-table-slot
5268 org-display-table 4
5269 (vconcat (mapcar
5270 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5271 org-ellipsis)))
5272 (if (stringp org-ellipsis) org-ellipsis "..."))))
5273 (setq buffer-display-table org-display-table))
5274 (org-set-regexps-and-options-for-tags)
5275 (org-set-regexps-and-options)
5276 (when (and org-tag-faces (not org-tags-special-faces-re))
5277 ;; tag faces set outside customize.... force initialization.
5278 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5279 ;; Calc embedded
5280 (org-set-local 'calc-embedded-open-mode "# ")
5281 ;; Modify a few syntax entries
5282 (modify-syntax-entry ?@ "w")
5283 (modify-syntax-entry ?\" "\"")
5284 (if org-startup-truncated (setq truncate-lines t))
5285 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5286 (org-set-local 'font-lock-unfontify-region-function
5287 'org-unfontify-region)
5288 ;; Activate before-change-function
5289 (org-set-local 'org-table-may-need-update t)
5290 (org-add-hook 'before-change-functions 'org-before-change-function nil
5291 'local)
5292 ;; Check for running clock before killing a buffer
5293 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5294 ;; Initialize macros templates.
5295 (org-macro-initialize-templates)
5296 ;; Initialize radio targets.
5297 (org-update-radio-target-regexp)
5298 ;; Indentation.
5299 (org-set-local 'indent-line-function 'org-indent-line)
5300 (org-set-local 'indent-region-function 'org-indent-region)
5301 ;; Filling and auto-filling.
5302 (org-setup-filling)
5303 ;; Comments.
5304 (org-setup-comments-handling)
5305 ;; Beginning/end of defun
5306 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5307 (org-set-local 'end-of-defun-function 'org-forward-element)
5308 ;; Next error for sparse trees
5309 (org-set-local 'next-error-function 'org-occur-next-match)
5310 ;; Make sure dependence stuff works reliably, even for users who set it
5311 ;; too late :-(
5312 (if org-enforce-todo-dependencies
5313 (add-hook 'org-blocker-hook
5314 'org-block-todo-from-children-or-siblings-or-parent)
5315 (remove-hook 'org-blocker-hook
5316 'org-block-todo-from-children-or-siblings-or-parent))
5317 (if org-enforce-todo-checkbox-dependencies
5318 (add-hook 'org-blocker-hook
5319 'org-block-todo-from-checkboxes)
5320 (remove-hook 'org-blocker-hook
5321 'org-block-todo-from-checkboxes))
5323 ;; Align options lines
5324 (org-set-local
5325 'align-mode-rules-list
5326 '((org-in-buffer-settings
5327 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5328 (modes . '(org-mode)))))
5330 ;; Imenu
5331 (org-set-local 'imenu-create-index-function
5332 'org-imenu-get-tree)
5334 ;; Make isearch reveal context
5335 (if (or (featurep 'xemacs)
5336 (not (boundp 'outline-isearch-open-invisible-function)))
5337 ;; Emacs 21 and XEmacs make use of the hook
5338 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5339 ;; Emacs 22 deals with this through a special variable
5340 (org-set-local 'outline-isearch-open-invisible-function
5341 (lambda (&rest ignore) (org-show-context 'isearch)))
5342 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5344 ;; Setup the pcomplete hooks
5345 (set (make-local-variable 'pcomplete-command-completion-function)
5346 'org-pcomplete-initial)
5347 (set (make-local-variable 'pcomplete-command-name-function)
5348 'org-command-at-point)
5349 (set (make-local-variable 'pcomplete-default-completion-function)
5350 'ignore)
5351 (set (make-local-variable 'pcomplete-parse-arguments-function)
5352 'org-parse-arguments)
5353 (set (make-local-variable 'pcomplete-termination-string) "")
5354 (when (>= emacs-major-version 23)
5355 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5357 ;; If empty file that did not turn on org-mode automatically, make it to.
5358 (if (and org-insert-mode-line-in-empty-file
5359 (org-called-interactively-p 'any)
5360 (= (point-min) (point-max)))
5361 (insert "# -*- mode: org -*-\n\n"))
5362 (unless org-inhibit-startup
5363 (org-unmodified
5364 (and org-startup-with-beamer-mode (org-beamer-mode))
5365 (when org-startup-align-all-tables
5366 (org-table-map-tables 'org-table-align 'quietly))
5367 (when org-startup-with-inline-images
5368 (org-display-inline-images))
5369 (when org-startup-with-latex-preview
5370 (org-preview-latex-fragment))
5371 (unless org-inhibit-startup-visibility-stuff
5372 (org-set-startup-visibility))))
5373 ;; Try to set org-hide correctly
5374 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5376 ;; Update `customize-package-emacs-version-alist'
5377 (add-to-list 'customize-package-emacs-version-alist
5378 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5379 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5380 ("8.0" . "24.4")))
5382 (defvar org-mode-transpose-word-syntax-table
5383 (let ((st (make-syntax-table)))
5384 (mapc (lambda(c) (modify-syntax-entry
5385 (string-to-char (car c)) "w p" st))
5386 org-emphasis-alist)
5387 st))
5389 (when (fboundp 'abbrev-table-put)
5390 (abbrev-table-put org-mode-abbrev-table
5391 :parents (list text-mode-abbrev-table)))
5393 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5395 (defsubst org-fix-ellipsis-at-bol ()
5396 (save-excursion (goto-char (window-start)) (recenter 0)))
5398 (defun org-find-invisible-foreground ()
5399 (let ((candidates (remove
5400 "unspecified-bg"
5401 (nconc
5402 (list (face-background 'default)
5403 (face-background 'org-default))
5404 (mapcar
5405 (lambda (alist)
5406 (when (boundp alist)
5407 (cdr (assoc 'background-color (symbol-value alist)))))
5408 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5409 (list (face-foreground 'org-hide))))))
5410 (car (remove nil candidates))))
5412 (defun org-current-time (&optional rounding-minutes past)
5413 "Current time, possibly rounded to ROUNDING-MINUTES.
5414 When ROUNDING-MINUTES is not an integer, fall back on the car of
5415 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5416 the rounding returns a past time."
5417 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5418 (car org-time-stamp-rounding-minutes)))
5419 (time (decode-time)) res)
5420 (if (< r 1)
5421 (current-time)
5422 (setq res
5423 (apply 'encode-time
5424 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5425 (nthcdr 2 time))))
5426 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5427 (seconds-to-time (- (org-float-time res) (* r 60)))
5428 res))))
5430 (defun org-today ()
5431 "Return today date, considering `org-extend-today-until'."
5432 (time-to-days
5433 (time-subtract (current-time)
5434 (list 0 (* 3600 org-extend-today-until) 0))))
5436 ;;;; Font-Lock stuff, including the activators
5438 (defvar org-mouse-map (make-sparse-keymap))
5439 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5440 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5441 (when org-mouse-1-follows-link
5442 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5443 (when org-tab-follows-link
5444 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5445 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5447 (require 'font-lock)
5449 (defconst org-non-link-chars "]\t\n\r<>")
5450 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5451 "shell" "elisp" "doi" "message"))
5452 (defvar org-link-types-re nil
5453 "Matches a link that has a url-like prefix like \"http:\"")
5454 (defvar org-link-re-with-space nil
5455 "Matches a link with spaces, optional angular brackets around it.")
5456 (defvar org-link-re-with-space2 nil
5457 "Matches a link with spaces, optional angular brackets around it.")
5458 (defvar org-link-re-with-space3 nil
5459 "Matches a link with spaces, only for internal part in bracket links.")
5460 (defvar org-angle-link-re nil
5461 "Matches link with angular brackets, spaces are allowed.")
5462 (defvar org-plain-link-re nil
5463 "Matches plain link, without spaces.")
5464 (defvar org-bracket-link-regexp nil
5465 "Matches a link in double brackets.")
5466 (defvar org-bracket-link-analytic-regexp nil
5467 "Regular expression used to analyze links.
5468 Here is what the match groups contain after a match:
5469 1: http:
5470 2: http
5471 3: path
5472 4: [desc]
5473 5: desc")
5474 (defvar org-bracket-link-analytic-regexp++ nil
5475 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5476 (defvar org-any-link-re nil
5477 "Regular expression matching any link.")
5479 (defconst org-match-sexp-depth 3
5480 "Number of stacked braces for sub/superscript matching.")
5482 (defun org-create-multibrace-regexp (left right n)
5483 "Create a regular expression which will match a balanced sexp.
5484 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5485 as single character strings.
5486 The regexp returned will match the entire expression including the
5487 delimiters. It will also define a single group which contains the
5488 match except for the outermost delimiters. The maximum depth of
5489 stacked delimiters is N. Escaping delimiters is not possible."
5490 (let* ((nothing (concat "[^" left right "]*?"))
5491 (or "\\|")
5492 (re nothing)
5493 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5494 (while (> n 1)
5495 (setq n (1- n)
5496 re (concat re or next)
5497 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5498 (concat left "\\(" re "\\)" right)))
5500 (defvar org-match-substring-regexp
5501 (concat
5502 "\\(\\S-\\)\\([_^]\\)\\("
5503 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5504 "\\|"
5505 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5506 "\\|"
5507 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5508 "The regular expression matching a sub- or superscript.")
5510 (defvar org-match-substring-with-braces-regexp
5511 (concat
5512 "\\(\\S-\\)\\([_^]\\)\\("
5513 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5514 "\\)")
5515 "The regular expression matching a sub- or superscript, forcing braces.")
5517 (defun org-make-link-regexps ()
5518 "Update the link regular expressions.
5519 This should be called after the variable `org-link-types' has changed."
5520 (setq org-link-types-re
5521 (concat
5522 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5523 org-link-re-with-space
5524 (concat
5525 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5526 "\\([^" org-non-link-chars " ]"
5527 "[^" org-non-link-chars "]*"
5528 "[^" org-non-link-chars " ]\\)>?")
5529 org-link-re-with-space2
5530 (concat
5531 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5532 "\\([^" org-non-link-chars " ]"
5533 "[^\t\n\r]*"
5534 "[^" org-non-link-chars " ]\\)>?")
5535 org-link-re-with-space3
5536 (concat
5537 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5538 "\\([^" org-non-link-chars " ]"
5539 "[^\t\n\r]*\\)")
5540 org-angle-link-re
5541 (concat
5542 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5543 "\\([^" org-non-link-chars " ]"
5544 "[^" org-non-link-chars "]*"
5545 "\\)>")
5546 org-plain-link-re
5547 (concat
5548 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5549 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5550 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5551 org-bracket-link-regexp
5552 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5553 org-bracket-link-analytic-regexp
5554 (concat
5555 "\\[\\["
5556 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5557 "\\([^]]+\\)"
5558 "\\]"
5559 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5560 "\\]")
5561 org-bracket-link-analytic-regexp++
5562 (concat
5563 "\\[\\["
5564 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5565 "\\([^]]+\\)"
5566 "\\]"
5567 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5568 "\\]")
5569 org-any-link-re
5570 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5571 org-angle-link-re "\\)\\|\\("
5572 org-plain-link-re "\\)")))
5574 (org-make-link-regexps)
5576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5577 "Regular expression for fast time stamp matching.")
5578 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5579 "Regular expression for fast time stamp matching.")
5580 (defconst org-ts-regexp0
5581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5582 "Regular expression matching time strings for analysis.
5583 This one does not require the space after the date, so it can be used
5584 on a string that terminates immediately after the date.")
5585 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5586 "Regular expression matching time strings for analysis.")
5587 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5588 "Regular expression matching time stamps, with groups.")
5589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5590 "Regular expression matching time stamps (also [..]), with groups.")
5591 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5592 "Regular expression matching a time stamp range.")
5593 (defconst org-tr-regexp-both
5594 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5595 "Regular expression matching a time stamp range.")
5596 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5597 org-ts-regexp "\\)?")
5598 "Regular expression matching a time stamp or time stamp range.")
5599 (defconst org-tsr-regexp-both
5600 (concat org-ts-regexp-both "\\(--?-?"
5601 org-ts-regexp-both "\\)?")
5602 "Regular expression matching a time stamp or time stamp range.
5603 The time stamps may be either active or inactive.")
5605 (defvar org-emph-face nil)
5607 (defun org-do-emphasis-faces (limit)
5608 "Run through the buffer and add overlays to emphasized strings."
5609 (let (rtn a)
5610 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5611 (if (not (= (char-after (match-beginning 3))
5612 (char-after (match-beginning 4))))
5613 (progn
5614 (setq rtn t)
5615 (setq a (assoc (match-string 3) org-emphasis-alist))
5616 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5617 'face
5618 (nth 1 a))
5619 (and (nth 4 a)
5620 (org-remove-flyspell-overlays-in
5621 (match-beginning 0) (match-end 0)))
5622 (add-text-properties (match-beginning 2) (match-end 2)
5623 '(font-lock-multiline t org-emphasis t))
5624 (when org-hide-emphasis-markers
5625 (add-text-properties (match-end 4) (match-beginning 5)
5626 '(invisible org-link))
5627 (add-text-properties (match-beginning 3) (match-end 3)
5628 '(invisible org-link)))))
5629 (backward-char 1))
5630 rtn))
5632 (defun org-emphasize (&optional char)
5633 "Insert or change an emphasis, i.e. a font like bold or italic.
5634 If there is an active region, change that region to a new emphasis.
5635 If there is no region, just insert the marker characters and position
5636 the cursor between them.
5637 CHAR should be either the marker character, or the first character of the
5638 HTML tag associated with that emphasis. If CHAR is a space, the means
5639 to remove the emphasis of the selected region.
5640 If char is not given (for example in an interactive call) it
5641 will be prompted for."
5642 (interactive)
5643 (let ((eal org-emphasis-alist) e det
5644 (erc org-emphasis-regexp-components)
5645 (prompt "")
5646 (string "") beg end move tag c s)
5647 (if (org-region-active-p)
5648 (setq beg (region-beginning) end (region-end)
5649 string (buffer-substring beg end))
5650 (setq move t))
5652 (while (setq e (pop eal))
5653 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5654 c (aref tag 0))
5655 (push (cons c (string-to-char (car e))) det)
5656 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5657 (substring tag 1)))))
5658 (setq det (nreverse det))
5659 (unless char
5660 (message "%s" (concat "Emphasis marker or tag:" prompt))
5661 (setq char (read-char-exclusive)))
5662 (setq char (or (cdr (assoc char det)) char))
5663 (if (equal char ?\ )
5664 (setq s "" move nil)
5665 (unless (assoc (char-to-string char) org-emphasis-alist)
5666 (error "No such emphasis marker: \"%c\"" char))
5667 (setq s (char-to-string char)))
5668 (while (and (> (length string) 1)
5669 (equal (substring string 0 1) (substring string -1))
5670 (assoc (substring string 0 1) org-emphasis-alist))
5671 (setq string (substring string 1 -1)))
5672 (setq string (concat s string s))
5673 (if beg (delete-region beg end))
5674 (unless (or (bolp)
5675 (string-match (concat "[" (nth 0 erc) "\n]")
5676 (char-to-string (char-before (point)))))
5677 (insert " "))
5678 (unless (or (eobp)
5679 (string-match (concat "[" (nth 1 erc) "\n]")
5680 (char-to-string (char-after (point)))))
5681 (insert " ") (backward-char 1))
5682 (insert string)
5683 (and move (backward-char 1))))
5685 (defconst org-nonsticky-props
5686 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5688 (defsubst org-rear-nonsticky-at (pos)
5689 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5691 (defun org-activate-plain-links (limit)
5692 "Run through the buffer and add overlays to links."
5693 (let (f hl)
5694 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5695 (not (org-in-src-block-p)))
5696 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5697 (setq f (get-text-property (match-beginning 0) 'face))
5698 (setq hl (org-match-string-no-properties 0))
5699 (if (or (eq f 'org-tag)
5700 (and (listp f) (memq 'org-tag f)))
5702 (add-text-properties (match-beginning 0) (match-end 0)
5703 (list 'mouse-face 'highlight
5704 'face 'org-link
5705 'htmlize-link `(:uri ,hl)
5706 'keymap org-mouse-map))
5707 (org-rear-nonsticky-at (match-end 0)))
5708 t)))
5710 (defun org-activate-code (limit)
5711 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5712 (progn
5713 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5714 (remove-text-properties (match-beginning 0) (match-end 0)
5715 '(display t invisible t intangible t))
5716 t)))
5718 (defcustom org-src-fontify-natively nil
5719 "When non-nil, fontify code in code blocks."
5720 :type 'boolean
5721 :version "24.1"
5722 :group 'org-appearance
5723 :group 'org-babel)
5725 (defcustom org-allow-promoting-top-level-subtree nil
5726 "When non-nil, allow promoting a top level subtree.
5727 The leading star of the top level headline will be replaced
5728 by a #."
5729 :type 'boolean
5730 :version "24.1"
5731 :group 'org-appearance)
5733 (defun org-fontify-meta-lines-and-blocks (limit)
5734 (condition-case nil
5735 (org-fontify-meta-lines-and-blocks-1 limit)
5736 (error (message "org-mode fontification error"))))
5738 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5739 "Fontify #+ lines and blocks."
5740 (let ((case-fold-search t))
5741 (if (re-search-forward
5742 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5743 limit t)
5744 (let ((beg (match-beginning 0))
5745 (block-start (match-end 0))
5746 (block-end nil)
5747 (lang (match-string 7))
5748 (beg1 (line-beginning-position 2))
5749 (dc1 (downcase (match-string 2)))
5750 (dc3 (downcase (match-string 3)))
5751 end end1 quoting block-type ovl)
5752 (cond
5753 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5754 ;; a single line of backend-specific content
5755 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5756 (remove-text-properties (match-beginning 0) (match-end 0)
5757 '(display t invisible t intangible t))
5758 (add-text-properties (match-beginning 1) (match-end 3)
5759 '(font-lock-fontified t face org-meta-line))
5760 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5761 '(font-lock-fontified t face org-block))
5762 ; for backend-specific code
5764 ((and (match-end 4) (equal dc3 "+begin"))
5765 ;; Truly a block
5766 (setq block-type (downcase (match-string 5))
5767 quoting (member block-type org-protecting-blocks))
5768 (when (re-search-forward
5769 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5770 nil t) ;; on purpose, we look further than LIMIT
5771 (setq end (min (point-max) (match-end 0))
5772 end1 (min (point-max) (1- (match-beginning 0))))
5773 (setq block-end (match-beginning 0))
5774 (when quoting
5775 (remove-text-properties beg end
5776 '(display t invisible t intangible t)))
5777 (add-text-properties
5778 beg end
5779 '(font-lock-fontified t font-lock-multiline t))
5780 (add-text-properties beg beg1 '(face org-meta-line))
5781 (add-text-properties end1 (min (point-max) (1+ end))
5782 '(face org-meta-line)) ; for end_src
5783 (cond
5784 ((and lang (not (string= lang "")) org-src-fontify-natively)
5785 (org-src-font-lock-fontify-block lang block-start block-end)
5786 ;; remove old background overlays
5787 (mapc (lambda (ov)
5788 (if (eq (overlay-get ov 'face) 'org-block-background)
5789 (delete-overlay ov)))
5790 (overlays-at (/ (+ beg1 block-end) 2)))
5791 ;; add a background overlay
5792 (setq ovl (make-overlay beg1 block-end))
5793 (overlay-put ovl 'face 'org-block-background)
5794 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5795 (quoting
5796 (add-text-properties beg1 (min (point-max) (1+ end1))
5797 '(face org-block))) ; end of source block
5798 ((not org-fontify-quote-and-verse-blocks))
5799 ((string= block-type "quote")
5800 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5801 ((string= block-type "verse")
5802 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5803 (add-text-properties beg beg1 '(face org-block-begin-line))
5804 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5805 '(face org-block-end-line))
5807 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5808 (add-text-properties
5809 beg (match-end 3)
5810 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5811 '(font-lock-fontified t invisible t)
5812 '(font-lock-fontified t face org-document-info-keyword)))
5813 (add-text-properties
5814 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5815 (if (string-equal dc1 "+title:")
5816 '(font-lock-fontified t face org-document-title)
5817 '(font-lock-fontified t face org-document-info))))
5818 ((or (equal dc1 "+results")
5819 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5820 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5821 "+call:" "+header:" "+headers:" "+name:"))
5822 (and (match-end 4) (equal dc3 "+attr")))
5823 (add-text-properties
5824 beg (match-end 0)
5825 '(font-lock-fontified t face org-meta-line))
5827 ((member dc3 '(" " ""))
5828 (add-text-properties
5829 beg (match-end 0)
5830 '(font-lock-fontified t face font-lock-comment-face)))
5831 ((not (member (char-after beg) '(?\ ?\t)))
5832 ;; just any other in-buffer setting, but not indented
5833 (add-text-properties
5834 beg (match-end 0)
5835 '(font-lock-fontified t face org-meta-line))
5837 (t nil))))))
5839 (defun org-activate-angle-links (limit)
5840 "Run through the buffer and add overlays to links."
5841 (if (and (re-search-forward org-angle-link-re limit t)
5842 (not (org-in-src-block-p)))
5843 (progn
5844 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5845 (add-text-properties (match-beginning 0) (match-end 0)
5846 (list 'mouse-face 'highlight
5847 'keymap org-mouse-map))
5848 (org-rear-nonsticky-at (match-end 0))
5849 t)))
5851 (defun org-activate-footnote-links (limit)
5852 "Run through the buffer and add overlays to footnotes."
5853 (let ((fn (org-footnote-next-reference-or-definition limit)))
5854 (when fn
5855 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5856 (org-remove-flyspell-overlays-in beg end)
5857 (add-text-properties beg end
5858 (list 'mouse-face 'highlight
5859 'keymap org-mouse-map
5860 'help-echo
5861 (if (= (point-at-bol) beg)
5862 "Footnote definition"
5863 "Footnote reference")
5864 'font-lock-fontified t
5865 'font-lock-multiline t
5866 'face 'org-footnote))))))
5868 (defun org-activate-bracket-links (limit)
5869 "Run through the buffer and add overlays to bracketed links."
5870 (if (and (re-search-forward org-bracket-link-regexp limit t)
5871 (not (org-in-src-block-p)))
5872 (let* ((hl (org-match-string-no-properties 1))
5873 (help (concat "LINK: " hl))
5874 ;; FIXME: Above we should remove the escapes. But that
5875 ;; requires another match, protecting match data, a lot
5876 ;; of overhead for font-lock.
5877 (ip (org-maybe-intangible
5878 (list 'invisible 'org-link
5879 'keymap org-mouse-map 'mouse-face 'highlight
5880 'font-lock-multiline t 'help-echo help
5881 'htmlize-link `(:uri ,hl))))
5882 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5883 'font-lock-multiline t 'help-echo help
5884 'htmlize-link `(:uri ,hl))))
5885 ;; We need to remove the invisible property here. Table narrowing
5886 ;; may have made some of this invisible.
5887 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5888 (remove-text-properties (match-beginning 0) (match-end 0)
5889 '(invisible nil))
5890 (if (match-end 3)
5891 (progn
5892 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5893 (org-rear-nonsticky-at (match-beginning 3))
5894 (add-text-properties (match-beginning 3) (match-end 3) vp)
5895 (org-rear-nonsticky-at (match-end 3))
5896 (add-text-properties (match-end 3) (match-end 0) ip)
5897 (org-rear-nonsticky-at (match-end 0)))
5898 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5899 (org-rear-nonsticky-at (match-beginning 1))
5900 (add-text-properties (match-beginning 1) (match-end 1) vp)
5901 (org-rear-nonsticky-at (match-end 1))
5902 (add-text-properties (match-end 1) (match-end 0) ip)
5903 (org-rear-nonsticky-at (match-end 0)))
5904 t)))
5906 (defun org-activate-dates (limit)
5907 "Run through the buffer and add overlays to dates."
5908 (if (and (re-search-forward org-tsr-regexp-both limit t)
5909 (not (equal (char-before (match-beginning 0)) 91)))
5910 (progn
5911 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5912 (add-text-properties (match-beginning 0) (match-end 0)
5913 (list 'mouse-face 'highlight
5914 'keymap org-mouse-map))
5915 (org-rear-nonsticky-at (match-end 0))
5916 (when org-display-custom-times
5917 (if (match-end 3)
5918 (org-display-custom-time (match-beginning 3) (match-end 3)))
5919 (org-display-custom-time (match-beginning 1) (match-end 1)))
5920 t)))
5922 (defvar org-target-link-regexp nil
5923 "Regular expression matching radio targets in plain text.")
5924 (make-variable-buffer-local 'org-target-link-regexp)
5925 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5926 "Regular expression matching a link target.")
5927 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5928 "Regular expression matching a radio target.")
5929 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5930 "Regular expression matching any target.")
5932 (defun org-activate-target-links (limit)
5933 "Run through the buffer and add overlays to target matches."
5934 (when org-target-link-regexp
5935 (let ((case-fold-search t))
5936 (if (re-search-forward org-target-link-regexp limit t)
5937 (progn
5938 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5939 (add-text-properties (match-beginning 0) (match-end 0)
5940 (list 'mouse-face 'highlight
5941 'keymap org-mouse-map
5942 'help-echo "Radio target link"
5943 'org-linked-text t))
5944 (org-rear-nonsticky-at (match-end 0))
5945 t)))))
5947 (defun org-update-radio-target-regexp ()
5948 "Find all radio targets in this file and update the regular expression."
5949 (interactive)
5950 (when (memq 'radio org-activate-links)
5951 (setq org-target-link-regexp
5952 (org-make-target-link-regexp (org-all-targets 'radio)))
5953 (org-restart-font-lock)))
5955 (defun org-hide-wide-columns (limit)
5956 (let (s e)
5957 (setq s (text-property-any (point) (or limit (point-max))
5958 'org-cwidth t))
5959 (when s
5960 (setq e (next-single-property-change s 'org-cwidth))
5961 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5962 (goto-char e)
5963 t)))
5965 (defvar org-latex-and-related-regexp nil
5966 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5967 (defvar org-match-substring-regexp)
5968 (defvar org-match-substring-with-braces-regexp)
5970 (defun org-compute-latex-and-related-regexp ()
5971 "Compute regular expression for LaTeX, entities and sub/superscript.
5972 Result depends on variable `org-highlight-latex-and-related'."
5973 (org-set-local
5974 'org-latex-and-related-regexp
5975 (let* ((re-sub
5976 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5977 ((eq org-use-sub-superscripts '{})
5978 (list org-match-substring-with-braces-regexp))
5979 (org-use-sub-superscripts (list org-match-substring-regexp))))
5980 (re-latex
5981 (when (memq 'latex org-highlight-latex-and-related)
5982 (let ((matchers (plist-get org-format-latex-options :matchers)))
5983 (delq nil
5984 (mapcar (lambda (x)
5985 (and (member (car x) matchers) (nth 1 x)))
5986 org-latex-regexps)))))
5987 (re-entities
5988 (when (memq 'entities org-highlight-latex-and-related)
5989 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5990 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5992 (defun org-do-latex-and-related (limit)
5993 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5994 LIMIT bounds the search for syntax to highlight. Stop at first
5995 highlighted object, if any. Return t if some highlighting was
5996 done, nil otherwise."
5997 (when (org-string-nw-p org-latex-and-related-regexp)
5998 (catch 'found
5999 (while (re-search-forward org-latex-and-related-regexp limit t)
6000 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6001 'face))
6002 '(org-code org-verbatim underline))
6003 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6004 '(?_ ?^))
6006 0)))
6007 (font-lock-prepend-text-property
6008 (+ offset (match-beginning 0)) (match-end 0)
6009 'face 'org-latex-and-related)
6010 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6011 '(font-lock-multiline t)))
6012 (throw 'found t)))
6013 nil)))
6015 (defun org-restart-font-lock ()
6016 "Restart `font-lock-mode', to force refontification."
6017 (when (and (boundp 'font-lock-mode) font-lock-mode)
6018 (font-lock-mode -1)
6019 (font-lock-mode 1)))
6021 (defun org-all-targets (&optional radio)
6022 "Return a list of all targets in this file.
6023 When optional argument RADIO is non-nil, only find radio
6024 targets."
6025 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6026 (save-excursion
6027 (goto-char (point-min))
6028 (while (re-search-forward re nil t)
6029 ;; Make sure point is really within the object.
6030 (backward-char)
6031 (let ((obj (org-element-context)))
6032 (when (memq (org-element-type obj) '(radio-target target))
6033 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6034 rtn)))
6036 (defun org-make-target-link-regexp (targets)
6037 "Make regular expression matching all strings in TARGETS.
6038 The regular expression finds the targets also if there is a line break
6039 between words."
6040 (and targets
6041 (concat
6042 "\\<\\("
6043 (mapconcat
6044 (lambda (x)
6045 (setq x (regexp-quote x))
6046 (while (string-match " +" x)
6047 (setq x (replace-match "\\s-+" t t x)))
6049 targets
6050 "\\|")
6051 "\\)\\>")))
6053 (defun org-activate-tags (limit)
6054 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6055 (progn
6056 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6057 (add-text-properties (match-beginning 1) (match-end 1)
6058 (list 'mouse-face 'highlight
6059 'keymap org-mouse-map))
6060 (org-rear-nonsticky-at (match-end 1))
6061 t)))
6063 (defun org-outline-level ()
6064 "Compute the outline level of the heading at point.
6065 If this is called at a normal headline, the level is the number of stars.
6066 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6067 (save-excursion
6068 (if (not (condition-case nil
6069 (org-back-to-heading t)
6070 (error nil)))
6072 (looking-at org-outline-regexp)
6073 (1- (- (match-end 0) (match-beginning 0))))))
6075 (defvar org-font-lock-keywords nil)
6077 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6078 "Regular expression matching a property line.")
6080 (defvar org-font-lock-hook nil
6081 "Functions to be called for special font lock stuff.")
6083 (defvar org-font-lock-set-keywords-hook nil
6084 "Functions that can manipulate `org-font-lock-extra-keywords'.
6085 This is called after `org-font-lock-extra-keywords' is defined, but before
6086 it is installed to be used by font lock. This can be useful if something
6087 needs to be inserted at a specific position in the font-lock sequence.")
6089 (defun org-font-lock-hook (limit)
6090 "Run `org-font-lock-hook' within LIMIT."
6091 (run-hook-with-args 'org-font-lock-hook limit))
6093 (defun org-set-font-lock-defaults ()
6094 "Set font lock defaults for the current buffer."
6095 (let* ((em org-fontify-emphasized-text)
6096 (lk org-activate-links)
6097 (org-font-lock-extra-keywords
6098 (list
6099 ;; Call the hook
6100 '(org-font-lock-hook)
6101 ;; Headlines
6102 `(,(if org-fontify-whole-heading-line
6103 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6104 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6105 (1 (org-get-level-face 1))
6106 (2 (org-get-level-face 2))
6107 (3 (org-get-level-face 3)))
6108 ;; Table lines
6109 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6110 (1 'org-table t))
6111 ;; Table internals
6112 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6113 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6114 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6115 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6116 ;; Drawers
6117 (list org-drawer-regexp '(0 'org-special-keyword t))
6118 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6119 ;; Properties
6120 (list org-property-re
6121 '(1 'org-special-keyword t)
6122 '(3 'org-property-value t))
6123 ;; Links
6124 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6125 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6126 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6127 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6128 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6129 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6130 (if (memq 'footnote lk) '(org-activate-footnote-links))
6131 ;; Targets.
6132 (list org-any-target-regexp '(0 'org-target t))
6133 ;; Diary sexps.
6134 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6135 ;; Macro
6136 '("{{{.+}}}" (0 'org-macro t))
6137 '(org-hide-wide-columns (0 nil append))
6138 ;; TODO keyword
6139 (list (format org-heading-keyword-regexp-format
6140 org-todo-regexp)
6141 '(2 (org-get-todo-face 2) t))
6142 ;; DONE
6143 (if org-fontify-done-headline
6144 (list (format org-heading-keyword-regexp-format
6145 (concat
6146 "\\(?:"
6147 (mapconcat 'regexp-quote org-done-keywords "\\|")
6148 "\\)"))
6149 '(2 'org-headline-done t))
6150 nil)
6151 ;; Priorities
6152 '(org-font-lock-add-priority-faces)
6153 ;; Tags
6154 '(org-font-lock-add-tag-faces)
6155 ;; Tags groups
6156 (if (and org-group-tags org-tag-groups-alist)
6157 (list (concat org-outline-regexp-bol ".+\\(:"
6158 (regexp-opt (mapcar 'car org-tag-groups-alist))
6159 ":\\).*$")
6160 '(1 'org-tag-group prepend)))
6161 ;; Special keywords
6162 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6163 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6164 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6165 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6166 ;; Emphasis
6167 (if em
6168 (if (featurep 'xemacs)
6169 '(org-do-emphasis-faces (0 nil append))
6170 '(org-do-emphasis-faces)))
6171 ;; Checkboxes
6172 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6173 1 'org-checkbox prepend)
6174 (if (cdr (assq 'checkbox org-list-automatic-rules))
6175 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6176 (0 (org-get-checkbox-statistics-face) t)))
6177 ;; Description list items
6178 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6179 1 'org-list-dt prepend)
6180 ;; ARCHIVEd headings
6181 (list (concat
6182 org-outline-regexp-bol
6183 "\\(.*:" org-archive-tag ":.*\\)")
6184 '(1 'org-archived prepend))
6185 ;; Specials
6186 '(org-do-latex-and-related)
6187 '(org-fontify-entities)
6188 '(org-raise-scripts)
6189 ;; Code
6190 '(org-activate-code (1 'org-code t))
6191 ;; COMMENT
6192 (list (format org-heading-keyword-regexp-format
6193 (concat "\\("
6194 org-comment-string "\\|" org-quote-string
6195 "\\)"))
6196 '(2 'org-special-keyword t))
6197 ;; Blocks and meta lines
6198 '(org-fontify-meta-lines-and-blocks)
6200 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6201 (run-hooks 'org-font-lock-set-keywords-hook)
6202 ;; Now set the full font-lock-keywords
6203 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6204 (org-set-local 'font-lock-defaults
6205 '(org-font-lock-keywords t nil nil backward-paragraph))
6206 (kill-local-variable 'font-lock-keywords) nil))
6208 (defun org-toggle-pretty-entities ()
6209 "Toggle the composition display of entities as UTF8 characters."
6210 (interactive)
6211 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6212 (org-restart-font-lock)
6213 (if org-pretty-entities
6214 (message "Entities are displayed as UTF8 characters")
6215 (save-restriction
6216 (widen)
6217 (org-decompose-region (point-min) (point-max))
6218 (message "Entities are displayed plain"))))
6220 (defvar org-custom-properties-overlays nil
6221 "List of overlays used for custom properties.")
6222 (make-variable-buffer-local 'org-custom-properties-overlays)
6224 (defun org-toggle-custom-properties-visibility ()
6225 "Display or hide properties in `org-custom-properties'."
6226 (interactive)
6227 (if org-custom-properties-overlays
6228 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6229 (setq org-custom-properties-overlays nil))
6230 (unless (not org-custom-properties)
6231 (save-excursion
6232 (save-restriction
6233 (widen)
6234 (goto-char (point-min))
6235 (while (re-search-forward org-property-re nil t)
6236 (mapc (lambda(p)
6237 (when (equal p (substring (match-string 1) 1 -1))
6238 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6239 (overlay-put o 'invisible t)
6240 (overlay-put o 'org-custom-property t)
6241 (push o org-custom-properties-overlays))))
6242 org-custom-properties)))))))
6244 (defun org-fontify-entities (limit)
6245 "Find an entity to fontify."
6246 (let (ee)
6247 (when org-pretty-entities
6248 (catch 'match
6249 (while (re-search-forward
6250 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6251 limit t)
6252 (if (and (not (org-in-indented-comment-line))
6253 (setq ee (org-entity-get (match-string 1)))
6254 (= (length (nth 6 ee)) 1))
6255 (let*
6256 ((end (if (equal (match-string 2) "{}")
6257 (match-end 2)
6258 (match-end 1))))
6259 (add-text-properties
6260 (match-beginning 0) end
6261 (list 'font-lock-fontified t))
6262 (compose-region (match-beginning 0) end
6263 (nth 6 ee) nil)
6264 (backward-char 1)
6265 (throw 'match t))))
6266 nil))))
6268 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6269 "Fontify string S like in Org-mode."
6270 (with-temp-buffer
6271 (insert s)
6272 (let ((org-odd-levels-only odd-levels))
6273 (org-mode)
6274 (font-lock-fontify-buffer)
6275 (buffer-string))))
6277 (defvar org-m nil)
6278 (defvar org-l nil)
6279 (defvar org-f nil)
6280 (defun org-get-level-face (n)
6281 "Get the right face for match N in font-lock matching of headlines."
6282 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6283 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6284 (if org-cycle-level-faces
6285 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6286 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6287 (cond
6288 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6289 ((eq n 2) org-f)
6290 (t (if org-level-color-stars-only nil org-f))))
6293 (defun org-get-todo-face (kwd)
6294 "Get the right face for a TODO keyword KWD.
6295 If KWD is a number, get the corresponding match group."
6296 (if (numberp kwd) (setq kwd (match-string kwd)))
6297 (or (org-face-from-face-or-color
6298 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6299 (and (member kwd org-done-keywords) 'org-done)
6300 'org-todo))
6302 (defun org-face-from-face-or-color (context inherit face-or-color)
6303 "Create a face list that inherits INHERIT, but sets the foreground color.
6304 When FACE-OR-COLOR is not a string, just return it."
6305 (if (stringp face-or-color)
6306 (list :inherit inherit
6307 (cdr (assoc context org-faces-easy-properties))
6308 face-or-color)
6309 face-or-color))
6311 (defun org-font-lock-add-tag-faces (limit)
6312 "Add the special tag faces."
6313 (when (and org-tag-faces org-tags-special-faces-re)
6314 (while (re-search-forward org-tags-special-faces-re limit t)
6315 (add-text-properties (match-beginning 1) (match-end 1)
6316 (list 'face (org-get-tag-face 1)
6317 'font-lock-fontified t))
6318 (backward-char 1))))
6320 (defun org-font-lock-add-priority-faces (limit)
6321 "Add the special priority faces."
6322 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6323 (when (save-match-data (org-at-heading-p))
6324 (add-text-properties
6325 (match-beginning 0) (match-end 0)
6326 (list 'face (or (org-face-from-face-or-color
6327 'priority 'org-priority
6328 (cdr (assoc (char-after (match-beginning 1))
6329 org-priority-faces)))
6330 'org-priority)
6331 'font-lock-fontified t)))))
6333 (defun org-get-tag-face (kwd)
6334 "Get the right face for a TODO keyword KWD.
6335 If KWD is a number, get the corresponding match group."
6336 (if (numberp kwd) (setq kwd (match-string kwd)))
6337 (or (org-face-from-face-or-color
6338 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6339 'org-tag))
6341 (defun org-unfontify-region (beg end &optional maybe_loudly)
6342 "Remove fontification and activation overlays from links."
6343 (font-lock-default-unfontify-region beg end)
6344 (let* ((buffer-undo-list t)
6345 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6346 (inhibit-modification-hooks t)
6347 deactivate-mark buffer-file-name buffer-file-truename)
6348 (org-decompose-region beg end)
6349 (remove-text-properties beg end
6350 '(mouse-face t keymap t org-linked-text t
6351 invisible t intangible t
6352 org-no-flyspell t org-emphasis t))
6353 (org-remove-font-lock-display-properties beg end)))
6355 (defconst org-script-display '(((raise -0.3) (height 0.7))
6356 ((raise 0.3) (height 0.7))
6357 ((raise -0.5))
6358 ((raise 0.5)))
6359 "Display properties for showing superscripts and subscripts.")
6361 (defun org-remove-font-lock-display-properties (beg end)
6362 "Remove specific display properties that have been added by font lock.
6363 The will remove the raise properties that are used to show superscripts
6364 and subscripts."
6365 (let (next prop)
6366 (while (< beg end)
6367 (setq next (next-single-property-change beg 'display nil end)
6368 prop (get-text-property beg 'display))
6369 (if (member prop org-script-display)
6370 (put-text-property beg next 'display nil))
6371 (setq beg next))))
6373 (defun org-raise-scripts (limit)
6374 "Add raise properties to sub/superscripts."
6375 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6376 (if (re-search-forward
6377 (if (eq org-use-sub-superscripts t)
6378 org-match-substring-regexp
6379 org-match-substring-with-braces-regexp)
6380 limit t)
6381 (let* ((pos (point)) table-p comment-p
6382 (mpos (match-beginning 3))
6383 (emph-p (get-text-property mpos 'org-emphasis))
6384 (link-p (get-text-property mpos 'mouse-face))
6385 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6386 (goto-char (point-at-bol))
6387 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6388 comment-p (org-looking-at-p "[ \t]*#"))
6389 (goto-char pos)
6390 ;; FIXME: Should we go back one character here, for a_b^c
6391 ;; (goto-char (1- pos)) ;????????????????????
6392 (if (or comment-p emph-p link-p keyw-p)
6394 (put-text-property (match-beginning 3) (match-end 0)
6395 'display
6396 (if (equal (char-after (match-beginning 2)) ?^)
6397 (nth (if table-p 3 1) org-script-display)
6398 (nth (if table-p 2 0) org-script-display)))
6399 (add-text-properties (match-beginning 2) (match-end 2)
6400 (list 'invisible t
6401 'org-dwidth t 'org-dwidth-n 1))
6402 (if (and (eq (char-after (match-beginning 3)) ?{)
6403 (eq (char-before (match-end 3)) ?}))
6404 (progn
6405 (add-text-properties
6406 (match-beginning 3) (1+ (match-beginning 3))
6407 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6408 (add-text-properties
6409 (1- (match-end 3)) (match-end 3)
6410 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6411 t)))))
6413 ;;;; Visibility cycling, including org-goto and indirect buffer
6415 ;;; Cycling
6417 (defvar org-cycle-global-status nil)
6418 (make-variable-buffer-local 'org-cycle-global-status)
6419 (put 'org-cycle-global-status 'org-state t)
6420 (defvar org-cycle-subtree-status nil)
6421 (make-variable-buffer-local 'org-cycle-subtree-status)
6422 (put 'org-cycle-subtree-status 'org-state t)
6424 (defvar org-inlinetask-min-level)
6426 ;;;###autoload
6427 (defun org-cycle (&optional arg)
6428 "TAB-action and visibility cycling for Org-mode.
6430 This is the command invoked in Org-mode by the TAB key. Its main purpose
6431 is outline visibility cycling, but it also invokes other actions
6432 in special contexts.
6434 - When this function is called with a prefix argument, rotate the entire
6435 buffer through 3 states (global cycling)
6436 1. OVERVIEW: Show only top-level headlines.
6437 2. CONTENTS: Show all headlines of all levels, but no body text.
6438 3. SHOW ALL: Show everything.
6439 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6440 determined by the variable `org-startup-folded', and by any VISIBILITY
6441 properties in the buffer.
6442 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6443 including any drawers.
6445 - When inside a table, re-align the table and move to the next field.
6447 - When point is at the beginning of a headline, rotate the subtree started
6448 by this line through 3 different states (local cycling)
6449 1. FOLDED: Only the main headline is shown.
6450 2. CHILDREN: The main headline and the direct children are shown.
6451 From this state, you can move to one of the children
6452 and zoom in further.
6453 3. SUBTREE: Show the entire subtree, including body text.
6454 If there is no subtree, switch directly from CHILDREN to FOLDED.
6456 - When point is at the beginning of an empty headline and the variable
6457 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6458 of the headline by demoting and promoting it to likely levels. This
6459 speeds up creation document structure by pressing TAB once or several
6460 times right after creating a new headline.
6462 - When there is a numeric prefix, go up to a heading with level ARG, do
6463 a `show-subtree' and return to the previous cursor position. If ARG
6464 is negative, go up that many levels.
6466 - When point is not at the beginning of a headline, execute the global
6467 binding for TAB, which is re-indenting the line. See the option
6468 `org-cycle-emulate-tab' for details.
6470 - Special case: if point is at the beginning of the buffer and there is
6471 no headline in line 1, this function will act as if called with prefix arg
6472 (C-u TAB, same as S-TAB) also when called without prefix arg.
6473 But only if also the variable `org-cycle-global-at-bob' is t."
6474 (interactive "P")
6475 (org-load-modules-maybe)
6476 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6477 (and org-cycle-level-after-item/entry-creation
6478 (or (org-cycle-level)
6479 (org-cycle-item-indentation))))
6480 (let* (message-log-max ; Don't populate the *Messages* buffer
6481 (limit-level
6482 (or org-cycle-max-level
6483 (and (boundp 'org-inlinetask-min-level)
6484 org-inlinetask-min-level
6485 (1- org-inlinetask-min-level))))
6486 (nstars (and limit-level
6487 (if org-odd-levels-only
6488 (and limit-level (1- (* limit-level 2)))
6489 limit-level)))
6490 (org-outline-regexp
6491 (if (not (derived-mode-p 'org-mode))
6492 outline-regexp
6493 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6494 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6495 (not (looking-at org-outline-regexp))))
6496 (org-cycle-hook
6497 (if bob-special
6498 (delq 'org-optimize-window-after-visibility-change
6499 (copy-sequence org-cycle-hook))
6500 org-cycle-hook))
6501 (pos (point)))
6503 (if (or bob-special (equal arg '(4)))
6504 ;; special case: use global cycling
6505 (setq arg t))
6507 (cond
6509 ((equal arg '(16))
6510 (setq last-command 'dummy)
6511 (org-set-startup-visibility)
6512 (message "Startup visibility, plus VISIBILITY properties"))
6514 ((equal arg '(64))
6515 (show-all)
6516 (message "Entire buffer visible, including drawers"))
6518 ;; Table: enter it or move to the next field.
6519 ((org-at-table-p 'any)
6520 (if (org-at-table.el-p)
6521 (message "Use C-c ' to edit table.el tables")
6522 (if arg (org-table-edit-field t)
6523 (org-table-justify-field-maybe)
6524 (call-interactively 'org-table-next-field))))
6526 ((run-hook-with-args-until-success
6527 'org-tab-after-check-for-table-hook))
6529 ;; Global cycling: delegate to `org-cycle-internal-global'.
6530 ((eq arg t) (org-cycle-internal-global))
6532 ;; Drawers: delegate to `org-flag-drawer'.
6533 ((and org-drawers org-drawer-regexp
6534 (save-excursion
6535 (beginning-of-line 1)
6536 (looking-at org-drawer-regexp)))
6537 (org-flag-drawer ; toggle block visibility
6538 (not (get-char-property (match-end 0) 'invisible))))
6540 ;; Show-subtree, ARG levels up from here.
6541 ((integerp arg)
6542 (save-excursion
6543 (org-back-to-heading)
6544 (outline-up-heading (if (< arg 0) (- arg)
6545 (- (funcall outline-level) arg)))
6546 (org-show-subtree)))
6548 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6549 ((and (featurep 'org-inlinetask)
6550 (org-inlinetask-at-task-p)
6551 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6552 (org-inlinetask-toggle-visibility))
6554 ((org-try-cdlatex-tab))
6556 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6557 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6558 (save-excursion (beginning-of-line 1)
6559 (looking-at org-outline-regexp)))
6560 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6561 (org-cycle-internal-local))
6563 ;; From there: TAB emulation and template completion.
6564 (buffer-read-only (org-back-to-heading))
6566 ((run-hook-with-args-until-success
6567 'org-tab-after-check-for-cycling-hook))
6569 ((org-try-structure-completion))
6571 ((run-hook-with-args-until-success
6572 'org-tab-before-tab-emulation-hook))
6574 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6575 (or (not (bolp))
6576 (not (looking-at org-outline-regexp))))
6577 (call-interactively (global-key-binding "\t")))
6579 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6580 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6581 (or (and (eq org-cycle-emulate-tab 'white)
6582 (= (match-end 0) (point-at-eol)))
6583 (and (eq org-cycle-emulate-tab 'whitestart)
6584 (>= (match-end 0) pos))))
6586 (eq org-cycle-emulate-tab t))
6587 (call-interactively (global-key-binding "\t")))
6589 (t (save-excursion
6590 (org-back-to-heading)
6591 (org-cycle)))))))
6593 (defun org-cycle-internal-global ()
6594 "Do the global cycling action."
6595 ;; Hack to avoid display of messages for .org attachments in Gnus
6596 (let (message-log-max ; Don't populate the *Messages* buffer
6597 (ga (string-match "\\*fontification" (buffer-name))))
6598 (cond
6599 ((and (eq last-command this-command)
6600 (eq org-cycle-global-status 'overview))
6601 ;; We just created the overview - now do table of contents
6602 ;; This can be slow in very large buffers, so indicate action
6603 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6604 (unless ga (message "CONTENTS..."))
6605 (org-content)
6606 (unless ga (message "CONTENTS...done"))
6607 (setq org-cycle-global-status 'contents)
6608 (run-hook-with-args 'org-cycle-hook 'contents))
6610 ((and (eq last-command this-command)
6611 (eq org-cycle-global-status 'contents))
6612 ;; We just showed the table of contents - now show everything
6613 (run-hook-with-args 'org-pre-cycle-hook 'all)
6614 (show-all)
6615 (unless ga (message "SHOW ALL"))
6616 (setq org-cycle-global-status 'all)
6617 (run-hook-with-args 'org-cycle-hook 'all))
6620 ;; Default action: go to overview
6621 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6622 (org-overview)
6623 (unless ga (message "OVERVIEW"))
6624 (setq org-cycle-global-status 'overview)
6625 (run-hook-with-args 'org-cycle-hook 'overview)))))
6627 (defun org-cycle-internal-local ()
6628 "Do the local cycling action."
6629 (let (message-log-max ; Don't populate the *Messages* buffer
6630 (goal-column 0) eoh eol eos has-children children-skipped struct)
6631 ;; First, determine end of headline (EOH), end of subtree or item
6632 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6633 (save-excursion
6634 (if (org-at-item-p)
6635 (progn
6636 (beginning-of-line)
6637 (setq struct (org-list-struct))
6638 (setq eoh (point-at-eol))
6639 (setq eos (org-list-get-item-end-before-blank (point) struct))
6640 (setq has-children (org-list-has-child-p (point) struct)))
6641 (org-back-to-heading)
6642 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6643 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6644 (setq has-children
6645 (or (save-excursion
6646 (let ((level (funcall outline-level)))
6647 (outline-next-heading)
6648 (and (org-at-heading-p t)
6649 (> (funcall outline-level) level))))
6650 (save-excursion
6651 (org-list-search-forward (org-item-beginning-re) eos t)))))
6652 ;; Determine end invisible part of buffer (EOL)
6653 (beginning-of-line 2)
6654 ;; XEmacs doesn't have `next-single-char-property-change'
6655 (if (featurep 'xemacs)
6656 (while (and (not (eobp)) ;; this is like `next-line'
6657 (get-char-property (1- (point)) 'invisible))
6658 (beginning-of-line 2))
6659 (while (and (not (eobp)) ;; this is like `next-line'
6660 (get-char-property (1- (point)) 'invisible))
6661 (goto-char (next-single-char-property-change (point) 'invisible))
6662 (and (eolp) (beginning-of-line 2))))
6663 (setq eol (point)))
6664 ;; Find out what to do next and set `this-command'
6665 (cond
6666 ((= eos eoh)
6667 ;; Nothing is hidden behind this heading
6668 (unless (org-before-first-heading-p)
6669 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6670 (message "EMPTY ENTRY")
6671 (setq org-cycle-subtree-status nil)
6672 (save-excursion
6673 (goto-char eos)
6674 (outline-next-heading)
6675 (if (outline-invisible-p) (org-flag-heading nil))))
6676 ((and (or (>= eol eos)
6677 (not (string-match "\\S-" (buffer-substring eol eos))))
6678 (or has-children
6679 (not (setq children-skipped
6680 org-cycle-skip-children-state-if-no-children))))
6681 ;; Entire subtree is hidden in one line: children view
6682 (unless (org-before-first-heading-p)
6683 (run-hook-with-args 'org-pre-cycle-hook 'children))
6684 (if (org-at-item-p)
6685 (org-list-set-item-visibility (point-at-bol) struct 'children)
6686 (org-show-entry)
6687 (org-with-limited-levels (show-children))
6688 ;; FIXME: This slows down the func way too much.
6689 ;; How keep drawers hidden in subtree anyway?
6690 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6691 ;; (org-cycle-hide-drawers 'subtree))
6693 ;; Fold every list in subtree to top-level items.
6694 (when (eq org-cycle-include-plain-lists 'integrate)
6695 (save-excursion
6696 (org-back-to-heading)
6697 (while (org-list-search-forward (org-item-beginning-re) eos t)
6698 (beginning-of-line 1)
6699 (let* ((struct (org-list-struct))
6700 (prevs (org-list-prevs-alist struct))
6701 (end (org-list-get-bottom-point struct)))
6702 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6703 (org-list-get-all-items (point) struct prevs))
6704 (goto-char end))))))
6705 (message "CHILDREN")
6706 (save-excursion
6707 (goto-char eos)
6708 (outline-next-heading)
6709 (if (outline-invisible-p) (org-flag-heading nil)))
6710 (setq org-cycle-subtree-status 'children)
6711 (unless (org-before-first-heading-p)
6712 (run-hook-with-args 'org-cycle-hook 'children)))
6713 ((or children-skipped
6714 (and (eq last-command this-command)
6715 (eq org-cycle-subtree-status 'children)))
6716 ;; We just showed the children, or no children are there,
6717 ;; now show everything.
6718 (unless (org-before-first-heading-p)
6719 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6720 (outline-flag-region eoh eos nil)
6721 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6722 (setq org-cycle-subtree-status 'subtree)
6723 (unless (org-before-first-heading-p)
6724 (run-hook-with-args 'org-cycle-hook 'subtree)))
6726 ;; Default action: hide the subtree.
6727 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6728 (outline-flag-region eoh eos t)
6729 (message "FOLDED")
6730 (setq org-cycle-subtree-status 'folded)
6731 (unless (org-before-first-heading-p)
6732 (run-hook-with-args 'org-cycle-hook 'folded))))))
6734 ;;;###autoload
6735 (defun org-global-cycle (&optional arg)
6736 "Cycle the global visibility. For details see `org-cycle'.
6737 With \\[universal-argument] prefix arg, switch to startup visibility.
6738 With a numeric prefix, show all headlines up to that level."
6739 (interactive "P")
6740 (let ((org-cycle-include-plain-lists
6741 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6742 (cond
6743 ((integerp arg)
6744 (show-all)
6745 (hide-sublevels arg)
6746 (setq org-cycle-global-status 'contents))
6747 ((equal arg '(4))
6748 (org-set-startup-visibility)
6749 (message "Startup visibility, plus VISIBILITY properties."))
6751 (org-cycle '(4))))))
6753 (defun org-set-startup-visibility ()
6754 "Set the visibility required by startup options and properties."
6755 (cond
6756 ((eq org-startup-folded t)
6757 (org-cycle '(4)))
6758 ((eq org-startup-folded 'content)
6759 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6760 (org-cycle '(4)) (org-cycle '(4)))))
6761 (unless (eq org-startup-folded 'showeverything)
6762 (if org-hide-block-startup (org-hide-block-all))
6763 (org-set-visibility-according-to-property 'no-cleanup)
6764 (org-cycle-hide-archived-subtrees 'all)
6765 (org-cycle-hide-drawers 'all)
6766 (org-cycle-show-empty-lines t)))
6768 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6769 "Switch subtree visibilities according to :VISIBILITY: property."
6770 (interactive)
6771 (let (org-show-entry-below state)
6772 (save-excursion
6773 (goto-char (point-min))
6774 (while (re-search-forward
6775 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6776 nil t)
6777 (setq state (match-string 1))
6778 (save-excursion
6779 (org-back-to-heading t)
6780 (hide-subtree)
6781 (org-reveal)
6782 (cond
6783 ((equal state '("fold" "folded"))
6784 (hide-subtree))
6785 ((equal state "children")
6786 (org-show-hidden-entry)
6787 (show-children))
6788 ((equal state "content")
6789 (save-excursion
6790 (save-restriction
6791 (org-narrow-to-subtree)
6792 (org-content))))
6793 ((member state '("all" "showall"))
6794 (show-subtree)))))
6795 (unless no-cleanup
6796 (org-cycle-hide-archived-subtrees 'all)
6797 (org-cycle-hide-drawers 'all)
6798 (org-cycle-show-empty-lines 'all)))))
6800 ;; This function uses outline-regexp instead of the more fundamental
6801 ;; org-outline-regexp so that org-cycle-global works outside of Org
6802 ;; buffers, where outline-regexp is needed.
6803 (defun org-overview ()
6804 "Switch to overview mode, showing only top-level headlines.
6805 Really, this shows all headlines with level equal or greater than the level
6806 of the first headline in the buffer. This is important, because if the
6807 first headline is not level one, then (hide-sublevels 1) gives confusing
6808 results."
6809 (interactive)
6810 (let ((l (org-current-line))
6811 (level (save-excursion
6812 (goto-char (point-min))
6813 (if (re-search-forward (concat "^" outline-regexp) nil t)
6814 (progn
6815 (goto-char (match-beginning 0))
6816 (funcall outline-level))))))
6817 (and level (hide-sublevels level))
6818 (recenter '(4))
6819 (org-goto-line l)))
6821 (defun org-content (&optional arg)
6822 "Show all headlines in the buffer, like a table of contents.
6823 With numerical argument N, show content up to level N."
6824 (interactive "P")
6825 (save-excursion
6826 ;; Visit all headings and show their offspring
6827 (and (integerp arg) (org-overview))
6828 (goto-char (point-max))
6829 (catch 'exit
6830 (while (and (progn (condition-case nil
6831 (outline-previous-visible-heading 1)
6832 (error (goto-char (point-min))))
6834 (looking-at org-outline-regexp))
6835 (if (integerp arg)
6836 (show-children (1- arg))
6837 (show-branches))
6838 (if (bobp) (throw 'exit nil))))))
6841 (defun org-optimize-window-after-visibility-change (state)
6842 "Adjust the window after a change in outline visibility.
6843 This function is the default value of the hook `org-cycle-hook'."
6844 (when (get-buffer-window (current-buffer))
6845 (cond
6846 ((eq state 'content) nil)
6847 ((eq state 'all) nil)
6848 ((eq state 'folded) nil)
6849 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6850 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6852 (defun org-remove-empty-overlays-at (pos)
6853 "Remove outline overlays that do not contain non-white stuff."
6854 (mapc
6855 (lambda (o)
6856 (and (eq 'outline (overlay-get o 'invisible))
6857 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6858 (overlay-end o))))
6859 (delete-overlay o)))
6860 (overlays-at pos)))
6862 (defun org-clean-visibility-after-subtree-move ()
6863 "Fix visibility issues after moving a subtree."
6864 ;; First, find a reasonable region to look at:
6865 ;; Start two siblings above, end three below
6866 (let* ((beg (save-excursion
6867 (and (org-get-last-sibling)
6868 (org-get-last-sibling))
6869 (point)))
6870 (end (save-excursion
6871 (and (org-get-next-sibling)
6872 (org-get-next-sibling)
6873 (org-get-next-sibling))
6874 (if (org-at-heading-p)
6875 (point-at-eol)
6876 (point))))
6877 (level (looking-at "\\*+"))
6878 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6879 (save-excursion
6880 (save-restriction
6881 (narrow-to-region beg end)
6882 (when re
6883 ;; Properly fold already folded siblings
6884 (goto-char (point-min))
6885 (while (re-search-forward re nil t)
6886 (if (and (not (outline-invisible-p))
6887 (save-excursion
6888 (goto-char (point-at-eol)) (outline-invisible-p)))
6889 (hide-entry))))
6890 (org-cycle-show-empty-lines 'overview)
6891 (org-cycle-hide-drawers 'overview)))))
6893 (defun org-cycle-show-empty-lines (state)
6894 "Show empty lines above all visible headlines.
6895 The region to be covered depends on STATE when called through
6896 `org-cycle-hook'. Lisp program can use t for STATE to get the
6897 entire buffer covered. Note that an empty line is only shown if there
6898 are at least `org-cycle-separator-lines' empty lines before the headline."
6899 (when (not (= org-cycle-separator-lines 0))
6900 (save-excursion
6901 (let* ((n (abs org-cycle-separator-lines))
6902 (re (cond
6903 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6904 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6905 (t (let ((ns (number-to-string (- n 2))))
6906 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6907 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6908 beg end b e)
6909 (cond
6910 ((memq state '(overview contents t))
6911 (setq beg (point-min) end (point-max)))
6912 ((memq state '(children folded))
6913 (setq beg (point) end (progn (org-end-of-subtree t t)
6914 (beginning-of-line 2)
6915 (point)))))
6916 (when beg
6917 (goto-char beg)
6918 (while (re-search-forward re end t)
6919 (unless (get-char-property (match-end 1) 'invisible)
6920 (setq e (match-end 1))
6921 (if (< org-cycle-separator-lines 0)
6922 (setq b (save-excursion
6923 (goto-char (match-beginning 0))
6924 (org-back-over-empty-lines)
6925 (if (save-excursion
6926 (goto-char (max (point-min) (1- (point))))
6927 (org-at-heading-p))
6928 (1- (point))
6929 (point))))
6930 (setq b (match-beginning 1)))
6931 (outline-flag-region b e nil)))))))
6932 ;; Never hide empty lines at the end of the file.
6933 (save-excursion
6934 (goto-char (point-max))
6935 (outline-previous-heading)
6936 (outline-end-of-heading)
6937 (if (and (looking-at "[ \t\n]+")
6938 (= (match-end 0) (point-max)))
6939 (outline-flag-region (point) (match-end 0) nil))))
6941 (defun org-show-empty-lines-in-parent ()
6942 "Move to the parent and re-show empty lines before visible headlines."
6943 (save-excursion
6944 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6945 (org-cycle-show-empty-lines context))))
6947 (defun org-files-list ()
6948 "Return `org-agenda-files' list, plus all open org-mode files.
6949 This is useful for operations that need to scan all of a user's
6950 open and agenda-wise Org files."
6951 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6952 (dolist (buf (buffer-list))
6953 (with-current-buffer buf
6954 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6955 (let ((file (expand-file-name (buffer-file-name))))
6956 (unless (member file files)
6957 (push file files))))))
6958 files))
6960 (defsubst org-entry-beginning-position ()
6961 "Return the beginning position of the current entry."
6962 (save-excursion (outline-back-to-heading t) (point)))
6964 (defsubst org-entry-end-position ()
6965 "Return the end position of the current entry."
6966 (save-excursion (outline-next-heading) (point)))
6968 (defun org-cycle-hide-drawers (state)
6969 "Re-hide all drawers after a visibility state change."
6970 (when (and (derived-mode-p 'org-mode)
6971 (not (memq state '(overview folded contents))))
6972 (save-excursion
6973 (let* ((globalp (memq state '(contents all)))
6974 (beg (if globalp (point-min) (point)))
6975 (end (if globalp (point-max)
6976 (if (eq state 'children)
6977 (save-excursion (outline-next-heading) (point))
6978 (org-end-of-subtree t)))))
6979 (goto-char beg)
6980 (while (re-search-forward org-drawer-regexp end t)
6981 (org-flag-drawer t))))))
6983 (defun org-cycle-hide-inline-tasks (state)
6984 "Re-hide inline task when switching to 'contents visibility state."
6985 (when (and (eq state 'contents)
6986 (boundp 'org-inlinetask-min-level)
6987 org-inlinetask-min-level)
6988 (hide-sublevels (1- org-inlinetask-min-level))))
6990 (defun org-flag-drawer (flag)
6991 "When FLAG is non-nil, hide the drawer we are within.
6992 Otherwise make it visible."
6993 (save-excursion
6994 (beginning-of-line 1)
6995 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6996 (let ((b (match-end 0)))
6997 (if (re-search-forward
6998 "^[ \t]*:END:"
6999 (save-excursion (outline-next-heading) (point)) t)
7000 (outline-flag-region b (point-at-eol) flag)
7001 (error ":END: line missing at position %s" b))))))
7003 (defun org-subtree-end-visible-p ()
7004 "Is the end of the current subtree visible?"
7005 (pos-visible-in-window-p
7006 (save-excursion (org-end-of-subtree t) (point))))
7008 (defun org-first-headline-recenter (&optional N)
7009 "Move cursor to the first headline and recenter the headline.
7010 Optional argument N means put the headline into the Nth line of the window."
7011 (goto-char (point-min))
7012 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7013 (beginning-of-line)
7014 (recenter (prefix-numeric-value N))))
7016 ;;; Saving and restoring visibility
7018 (defun org-outline-overlay-data (&optional use-markers)
7019 "Return a list of the locations of all outline overlays.
7020 These are overlays with the `invisible' property value `outline'.
7021 The return value is a list of cons cells, with start and stop
7022 positions for each overlay.
7023 If USE-MARKERS is set, return the positions as markers."
7024 (let (beg end)
7025 (save-excursion
7026 (save-restriction
7027 (widen)
7028 (delq nil
7029 (mapcar (lambda (o)
7030 (when (eq (overlay-get o 'invisible) 'outline)
7031 (setq beg (overlay-start o)
7032 end (overlay-end o))
7033 (and beg end (> end beg)
7034 (if use-markers
7035 (cons (move-marker (make-marker) beg)
7036 (move-marker (make-marker) end))
7037 (cons beg end)))))
7038 (overlays-in (point-min) (point-max))))))))
7040 (defun org-set-outline-overlay-data (data)
7041 "Create visibility overlays for all positions in DATA.
7042 DATA should have been made by `org-outline-overlay-data'."
7043 (let (o)
7044 (save-excursion
7045 (save-restriction
7046 (widen)
7047 (show-all)
7048 (mapc (lambda (c)
7049 (outline-flag-region (car c) (cdr c) t))
7050 data)))))
7052 ;;; Folding of blocks
7054 (defvar org-hide-block-overlays nil
7055 "Overlays hiding blocks.")
7056 (make-variable-buffer-local 'org-hide-block-overlays)
7058 (defun org-block-map (function &optional start end)
7059 "Call FUNCTION at the head of all source blocks in the current buffer.
7060 Optional arguments START and END can be used to limit the range."
7061 (let ((start (or start (point-min)))
7062 (end (or end (point-max))))
7063 (save-excursion
7064 (goto-char start)
7065 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7066 (save-excursion
7067 (save-match-data
7068 (goto-char (match-beginning 0))
7069 (funcall function)))))))
7071 (defun org-hide-block-toggle-all ()
7072 "Toggle the visibility of all blocks in the current buffer."
7073 (org-block-map #'org-hide-block-toggle))
7075 (defun org-hide-block-all ()
7076 "Fold all blocks in the current buffer."
7077 (interactive)
7078 (org-show-block-all)
7079 (org-block-map #'org-hide-block-toggle-maybe))
7081 (defun org-show-block-all ()
7082 "Unfold all blocks in the current buffer."
7083 (interactive)
7084 (mapc 'delete-overlay org-hide-block-overlays)
7085 (setq org-hide-block-overlays nil))
7087 (defun org-hide-block-toggle-maybe ()
7088 "Toggle visibility of block at point."
7089 (interactive)
7090 (let ((case-fold-search t))
7091 (if (save-excursion
7092 (beginning-of-line 1)
7093 (looking-at org-block-regexp))
7094 (progn (org-hide-block-toggle)
7095 t) ;; to signal that we took action
7096 nil))) ;; to signal that we did not
7098 (defun org-hide-block-toggle (&optional force)
7099 "Toggle the visibility of the current block."
7100 (interactive)
7101 (save-excursion
7102 (beginning-of-line)
7103 (if (re-search-forward org-block-regexp nil t)
7104 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7105 (end (match-end 0)) ;; end of entire body
7107 (if (memq t (mapcar (lambda (overlay)
7108 (eq (overlay-get overlay 'invisible)
7109 'org-hide-block))
7110 (overlays-at start)))
7111 (if (or (not force) (eq force 'off))
7112 (mapc (lambda (ov)
7113 (when (member ov org-hide-block-overlays)
7114 (setq org-hide-block-overlays
7115 (delq ov org-hide-block-overlays)))
7116 (when (eq (overlay-get ov 'invisible)
7117 'org-hide-block)
7118 (delete-overlay ov)))
7119 (overlays-at start)))
7120 (setq ov (make-overlay start end))
7121 (overlay-put ov 'invisible 'org-hide-block)
7122 ;; make the block accessible to isearch
7123 (overlay-put
7124 ov 'isearch-open-invisible
7125 (lambda (ov)
7126 (when (member ov org-hide-block-overlays)
7127 (setq org-hide-block-overlays
7128 (delq ov org-hide-block-overlays)))
7129 (when (eq (overlay-get ov 'invisible)
7130 'org-hide-block)
7131 (delete-overlay ov))))
7132 (push ov org-hide-block-overlays)))
7133 (error "Not looking at a source block"))))
7135 ;; org-tab-after-check-for-cycling-hook
7136 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7137 ;; Remove overlays when changing major mode
7138 (add-hook 'org-mode-hook
7139 (lambda () (org-add-hook 'change-major-mode-hook
7140 'org-show-block-all 'append 'local)))
7142 ;;; Org-goto
7144 (defvar org-goto-window-configuration nil)
7145 (defvar org-goto-marker nil)
7146 (defvar org-goto-map)
7147 (defun org-goto-map ()
7148 "Set the keymap `org-goto'."
7149 (setq org-goto-map
7150 (let ((map (make-sparse-keymap)))
7151 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7152 mouse-drag-region universal-argument org-occur))
7153 cmd)
7154 (while (setq cmd (pop cmds))
7155 (substitute-key-definition cmd cmd map global-map)))
7156 (suppress-keymap map)
7157 (org-defkey map "\C-m" 'org-goto-ret)
7158 (org-defkey map [(return)] 'org-goto-ret)
7159 (org-defkey map [(left)] 'org-goto-left)
7160 (org-defkey map [(right)] 'org-goto-right)
7161 (org-defkey map [(control ?g)] 'org-goto-quit)
7162 (org-defkey map "\C-i" 'org-cycle)
7163 (org-defkey map [(tab)] 'org-cycle)
7164 (org-defkey map [(down)] 'outline-next-visible-heading)
7165 (org-defkey map [(up)] 'outline-previous-visible-heading)
7166 (if org-goto-auto-isearch
7167 (if (fboundp 'define-key-after)
7168 (define-key-after map [t] 'org-goto-local-auto-isearch)
7169 nil)
7170 (org-defkey map "q" 'org-goto-quit)
7171 (org-defkey map "n" 'outline-next-visible-heading)
7172 (org-defkey map "p" 'outline-previous-visible-heading)
7173 (org-defkey map "f" 'outline-forward-same-level)
7174 (org-defkey map "b" 'outline-backward-same-level)
7175 (org-defkey map "u" 'outline-up-heading))
7176 (org-defkey map "/" 'org-occur)
7177 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7178 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7179 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7180 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7181 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7182 map)))
7184 (defconst org-goto-help
7185 "Browse buffer copy, to find location or copy text.%s
7186 RET=jump to location C-g=quit and return to previous location
7187 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7189 (defvar org-goto-start-pos) ; dynamically scoped parameter
7191 (defun org-goto (&optional alternative-interface)
7192 "Look up a different location in the current file, keeping current visibility.
7194 When you want look-up or go to a different location in a
7195 document, the fastest way is often to fold the entire buffer and
7196 then dive into the tree. This method has the disadvantage, that
7197 the previous location will be folded, which may not be what you
7198 want.
7200 This command works around this by showing a copy of the current
7201 buffer in an indirect buffer, in overview mode. You can dive
7202 into the tree in that copy, use org-occur and incremental search
7203 to find a location. When pressing RET or `Q', the command
7204 returns to the original buffer in which the visibility is still
7205 unchanged. After RET it will also jump to the location selected
7206 in the indirect buffer and expose the headline hierarchy above.
7208 With a prefix argument, use the alternative interface: e.g. if
7209 `org-goto-interface' is 'outline use 'outline-path-completion."
7210 (interactive "P")
7211 (org-goto-map)
7212 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7213 (org-refile-use-outline-path t)
7214 (org-refile-target-verify-function nil)
7215 (interface
7216 (if (not alternative-interface)
7217 org-goto-interface
7218 (if (eq org-goto-interface 'outline)
7219 'outline-path-completion
7220 'outline)))
7221 (org-goto-start-pos (point))
7222 (selected-point
7223 (if (eq interface 'outline)
7224 (car (org-get-location (current-buffer) org-goto-help))
7225 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7226 (org-refile-check-position pa)
7227 (nth 3 pa)))))
7228 (if selected-point
7229 (progn
7230 (org-mark-ring-push org-goto-start-pos)
7231 (goto-char selected-point)
7232 (if (or (outline-invisible-p) (org-invisible-p2))
7233 (org-show-context 'org-goto)))
7234 (message "Quit"))))
7236 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7237 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7238 (defvar org-goto-local-auto-isearch-map) ; defined below
7240 (defun org-get-location (buf help)
7241 "Let the user select a location in the Org-mode buffer BUF.
7242 This function uses a recursive edit. It returns the selected position
7243 or nil."
7244 (org-no-popups
7245 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7246 (isearch-hide-immediately nil)
7247 (isearch-search-fun-function
7248 (lambda () 'org-goto-local-search-headings))
7249 (org-goto-selected-point org-goto-exit-command))
7250 (save-excursion
7251 (save-window-excursion
7252 (delete-other-windows)
7253 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7254 (org-pop-to-buffer-same-window
7255 (condition-case nil
7256 (make-indirect-buffer (current-buffer) "*org-goto*")
7257 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7258 (with-output-to-temp-buffer "*Org Help*"
7259 (princ (format help (if org-goto-auto-isearch
7260 " Just type for auto-isearch."
7261 " n/p/f/b/u to navigate, q to quit."))))
7262 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7263 (setq buffer-read-only nil)
7264 (let ((org-startup-truncated t)
7265 (org-startup-folded nil)
7266 (org-startup-align-all-tables nil))
7267 (org-mode)
7268 (org-overview))
7269 (setq buffer-read-only t)
7270 (if (and (boundp 'org-goto-start-pos)
7271 (integer-or-marker-p org-goto-start-pos))
7272 (let ((org-show-hierarchy-above t)
7273 (org-show-siblings t)
7274 (org-show-following-heading t))
7275 (goto-char org-goto-start-pos)
7276 (and (outline-invisible-p) (org-show-context)))
7277 (goto-char (point-min)))
7278 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7279 (message "Select location and press RET")
7280 (use-local-map org-goto-map)
7281 (recursive-edit)))
7282 (kill-buffer "*org-goto*")
7283 (cons org-goto-selected-point org-goto-exit-command))))
7285 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7286 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7287 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7288 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7290 (defun org-goto-local-search-headings (string bound noerror)
7291 "Search and make sure that any matches are in headlines."
7292 (catch 'return
7293 (while (if isearch-forward
7294 (search-forward string bound noerror)
7295 (search-backward string bound noerror))
7296 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7297 (and (member :headline context)
7298 (not (member :tags context))))
7299 (throw 'return (point))))))
7301 (defun org-goto-local-auto-isearch ()
7302 "Start isearch."
7303 (interactive)
7304 (goto-char (point-min))
7305 (let ((keys (this-command-keys)))
7306 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7307 (isearch-mode t)
7308 (isearch-process-search-char (string-to-char keys)))))
7310 (defun org-goto-ret (&optional arg)
7311 "Finish `org-goto' by going to the new location."
7312 (interactive "P")
7313 (setq org-goto-selected-point (point)
7314 org-goto-exit-command 'return)
7315 (throw 'exit nil))
7317 (defun org-goto-left ()
7318 "Finish `org-goto' by going to the new location."
7319 (interactive)
7320 (if (org-at-heading-p)
7321 (progn
7322 (beginning-of-line 1)
7323 (setq org-goto-selected-point (point)
7324 org-goto-exit-command 'left)
7325 (throw 'exit nil))
7326 (error "Not on a heading")))
7328 (defun org-goto-right ()
7329 "Finish `org-goto' by going to the new location."
7330 (interactive)
7331 (if (org-at-heading-p)
7332 (progn
7333 (setq org-goto-selected-point (point)
7334 org-goto-exit-command 'right)
7335 (throw 'exit nil))
7336 (error "Not on a heading")))
7338 (defun org-goto-quit ()
7339 "Finish `org-goto' without cursor motion."
7340 (interactive)
7341 (setq org-goto-selected-point nil)
7342 (setq org-goto-exit-command 'quit)
7343 (throw 'exit nil))
7345 ;;; Indirect buffer display of subtrees
7347 (defvar org-indirect-dedicated-frame nil
7348 "This is the frame being used for indirect tree display.")
7349 (defvar org-last-indirect-buffer nil)
7351 (defun org-tree-to-indirect-buffer (&optional arg)
7352 "Create indirect buffer and narrow it to current subtree.
7353 With a numerical prefix ARG, go up to this level and then take that tree.
7354 If ARG is negative, go up that many levels.
7356 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7357 indirect buffer previously made with this command, to avoid proliferation of
7358 indirect buffers. However, when you call the command with a \
7359 \\[universal-argument] prefix, or
7360 when `org-indirect-buffer-display' is `new-frame', the last buffer
7361 is kept so that you can work with several indirect buffers at the same time.
7362 If `org-indirect-buffer-display' is `dedicated-frame', the \
7363 \\[universal-argument] prefix also
7364 requests that a new frame be made for the new buffer, so that the dedicated
7365 frame is not changed."
7366 (interactive "P")
7367 (let ((cbuf (current-buffer))
7368 (cwin (selected-window))
7369 (pos (point))
7370 beg end level heading ibuf)
7371 (save-excursion
7372 (org-back-to-heading t)
7373 (when (numberp arg)
7374 (setq level (org-outline-level))
7375 (if (< arg 0) (setq arg (+ level arg)))
7376 (while (> (setq level (org-outline-level)) arg)
7377 (org-up-heading-safe)))
7378 (setq beg (point)
7379 heading (org-get-heading))
7380 (org-end-of-subtree t t)
7381 (if (org-at-heading-p) (backward-char 1))
7382 (setq end (point)))
7383 (if (and (buffer-live-p org-last-indirect-buffer)
7384 (not (eq org-indirect-buffer-display 'new-frame))
7385 (not arg))
7386 (kill-buffer org-last-indirect-buffer))
7387 (setq ibuf (org-get-indirect-buffer cbuf)
7388 org-last-indirect-buffer ibuf)
7389 (cond
7390 ((or (eq org-indirect-buffer-display 'new-frame)
7391 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7392 (select-frame (make-frame))
7393 (delete-other-windows)
7394 (org-pop-to-buffer-same-window ibuf)
7395 (org-set-frame-title heading))
7396 ((eq org-indirect-buffer-display 'dedicated-frame)
7397 (raise-frame
7398 (select-frame (or (and org-indirect-dedicated-frame
7399 (frame-live-p org-indirect-dedicated-frame)
7400 org-indirect-dedicated-frame)
7401 (setq org-indirect-dedicated-frame (make-frame)))))
7402 (delete-other-windows)
7403 (org-pop-to-buffer-same-window ibuf)
7404 (org-set-frame-title (concat "Indirect: " heading)))
7405 ((eq org-indirect-buffer-display 'current-window)
7406 (org-pop-to-buffer-same-window ibuf))
7407 ((eq org-indirect-buffer-display 'other-window)
7408 (pop-to-buffer ibuf))
7409 (t (error "Invalid value")))
7410 (if (featurep 'xemacs)
7411 (save-excursion (org-mode) (turn-on-font-lock)))
7412 (narrow-to-region beg end)
7413 (show-all)
7414 (goto-char pos)
7415 (run-hook-with-args 'org-cycle-hook 'all)
7416 (and (window-live-p cwin) (select-window cwin))))
7418 (defun org-get-indirect-buffer (&optional buffer)
7419 (setq buffer (or buffer (current-buffer)))
7420 (let ((n 1) (base (buffer-name buffer)) bname)
7421 (while (buffer-live-p
7422 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7423 (setq n (1+ n)))
7424 (condition-case nil
7425 (make-indirect-buffer buffer bname 'clone)
7426 (error (make-indirect-buffer buffer bname)))))
7428 (defun org-set-frame-title (title)
7429 "Set the title of the current frame to the string TITLE."
7430 ;; FIXME: how to name a single frame in XEmacs???
7431 (unless (featurep 'xemacs)
7432 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7434 ;;;; Structure editing
7436 ;;; Inserting headlines
7438 (defun org-previous-line-empty-p (&optional next)
7439 "Is the previous line a blank line?
7440 When NEXT is non-nil, check the next line instead."
7441 (save-excursion
7442 (and (not (bobp))
7443 (or (beginning-of-line (if next 2 0)) t)
7444 (save-match-data
7445 (looking-at "[ \t]*$")))))
7447 (defun org-insert-heading (&optional arg invisible-ok)
7448 "Insert a new heading or item with same depth at point.
7449 If point is in a plain list and ARG is nil, create a new list item.
7450 With one universal prefix argument, insert a heading even in lists.
7451 With two universal prefix arguments, insert the heading at the end
7452 of the parent subtree.
7454 If point is at the beginning of a headline, insert a sibling before
7455 the current headline. If point is not at the beginning, split the line
7456 and create a new headline with the text in the current line after point
7457 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7459 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7460 This is important for non-interactive uses of the command."
7461 (interactive "P")
7462 (cond
7463 ((or (= (buffer-size) 0)
7464 (and (not (save-excursion
7465 (and (ignore-errors (org-back-to-heading invisible-ok))
7466 (org-at-heading-p))))
7467 (or arg (not (org-in-item-p)))))
7468 (insert
7469 (if (org-previous-line-empty-p) "" "\n")
7470 (if (org-in-src-block-p) ",* " "* "))
7471 (run-hooks 'org-insert-heading-hook))
7472 ((or arg (not (org-insert-item
7473 (save-excursion
7474 (beginning-of-line)
7475 (looking-at org-list-full-item-re)
7476 (match-string 3)))))
7477 (let (begn endn)
7478 (when (org-buffer-narrowed-p)
7479 (setq begn (point-min) endn (point-max))
7480 (widen))
7481 (let* ((empty-line-p nil)
7482 (eops (equal arg '(16))) ; insert at end of parent subtree
7483 (org-insert-heading-respect-content
7484 (or (not (null arg)) org-insert-heading-respect-content))
7485 (level nil)
7486 (on-heading (org-at-heading-p))
7487 (head (save-excursion
7488 (condition-case nil
7489 (progn
7490 (org-back-to-heading invisible-ok)
7491 (when (and (not on-heading)
7492 (featurep 'org-inlinetask)
7493 (integerp org-inlinetask-min-level)
7494 (>= (length (match-string 0))
7495 org-inlinetask-min-level))
7496 ;; Find a heading level before the inline task
7497 (while (and (setq level (org-up-heading-safe))
7498 (>= level org-inlinetask-min-level)))
7499 (if (org-at-heading-p)
7500 (org-back-to-heading invisible-ok)
7501 (error "This should not happen")))
7502 (unless (and (save-excursion
7503 (save-match-data
7504 (org-backward-heading-same-level 1 invisible-ok))
7505 (= (point) (match-beginning 0)))
7506 (not (org-previous-line-empty-p t)))
7507 (setq empty-line-p (org-previous-line-empty-p)))
7508 (match-string 0))
7509 (error "* "))))
7510 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7511 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7512 pos hide-previous previous-pos)
7513 (if ;; At the beginning of a heading, open a new line for insertiong
7514 (and (bolp) (org-at-heading-p)
7515 (not eops)
7516 (or (bobp)
7517 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7518 (open-line (if blank 2 1))
7519 (save-excursion
7520 (setq previous-pos (point-at-bol))
7521 (end-of-line)
7522 (setq hide-previous (outline-invisible-p)))
7523 (and org-insert-heading-respect-content
7524 (save-excursion
7525 (while (outline-invisible-p)
7526 (org-show-subtree)
7527 (org-up-heading-safe))))
7528 (let ((split
7529 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7530 (save-excursion
7531 (let ((p (point)))
7532 (goto-char (point-at-bol))
7533 (and (looking-at org-complex-heading-regexp)
7534 (match-beginning 4)
7535 (> p (match-beginning 4)))))))
7536 tags pos)
7537 (cond
7538 ;; Insert a new line, possibly at end of parent subtree
7539 (org-insert-heading-respect-content
7540 (if (not eops)
7541 (progn
7542 (org-end-of-subtree nil t)
7543 (and (looking-at "^\\*") (backward-char 1))
7544 (while (and (not (bobp))
7545 ;; Don't delete spaces in empty headlines
7546 (not (looking-back org-outline-regexp))
7547 (member (char-before) '(?\ ?\t ?\n)))
7548 (backward-delete-char 1)))
7549 (let ((p (point)))
7550 (org-up-heading-safe)
7551 (if (= p (point))
7552 (goto-char (point-max))
7553 (org-end-of-subtree nil t))))
7554 (when (featurep 'org-inlinetask)
7555 (while (and (not (eobp))
7556 (looking-at "\\(\\*+\\)[ \t]+")
7557 (>= (length (match-string 1))
7558 org-inlinetask-min-level))
7559 (org-end-of-subtree nil t)))
7560 (or (bolp) (newline))
7561 (or (org-previous-line-empty-p)
7562 (and blank (newline)))
7563 (if (or empty-line-p eops) (open-line 1)))
7564 ;; Insert a headling containing text after point
7565 ((org-at-heading-p)
7566 (when hide-previous
7567 (show-children)
7568 (org-show-entry))
7569 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7570 (setq tags (and (match-end 2) (match-string 2)))
7571 (and (match-end 1)
7572 (delete-region (match-beginning 1) (match-end 1)))
7573 (setq pos (point-at-bol))
7574 (or split (end-of-line 1))
7575 (delete-horizontal-space)
7576 (if (string-match "\\`\\*+\\'"
7577 (buffer-substring (point-at-bol) (point)))
7578 (insert " "))
7579 (newline (if blank 2 1))
7580 (when tags
7581 (save-excursion
7582 (goto-char pos)
7583 (end-of-line 1)
7584 (insert " " tags)
7585 (org-set-tags nil 'align))))
7587 (or split (end-of-line 1))
7588 (newline (if blank 2 1))))))
7589 (insert head) (just-one-space)
7590 (setq pos (point))
7591 (end-of-line 1)
7592 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7593 (when (and org-insert-heading-respect-content hide-previous)
7594 (save-excursion
7595 (goto-char previous-pos)
7596 (hide-subtree)))
7597 (when (and begn endn)
7598 (narrow-to-region (min (point) begn) (max (point) endn)))
7599 (run-hooks 'org-insert-heading-hook))))))
7601 (defun org-get-heading (&optional no-tags no-todo)
7602 "Return the heading of the current entry, without the stars.
7603 When NO-TAGS is non-nil, don't include tags.
7604 When NO-TODO is non-nil, don't include TODO keywords."
7605 (save-excursion
7606 (org-back-to-heading t)
7607 (cond
7608 ((and no-tags no-todo)
7609 (looking-at org-complex-heading-regexp)
7610 (match-string 4))
7611 (no-tags
7612 (looking-at (concat org-outline-regexp
7613 "\\(.*?\\)"
7614 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7615 (match-string 1))
7616 (no-todo
7617 (looking-at org-todo-line-regexp)
7618 (match-string 3))
7619 (t (looking-at org-heading-regexp)
7620 (match-string 2)))))
7622 (defvar orgstruct-mode) ; defined below
7624 (defun org-heading-components ()
7625 "Return the components of the current heading.
7626 This is a list with the following elements:
7627 - the level as an integer
7628 - the reduced level, different if `org-odd-levels-only' is set.
7629 - the TODO keyword, or nil
7630 - the priority character, like ?A, or nil if no priority is given
7631 - the headline text itself, or the tags string if no headline text
7632 - the tags string, or nil."
7633 (save-excursion
7634 (org-back-to-heading t)
7635 (if (let (case-fold-search)
7636 (looking-at
7637 (if orgstruct-mode
7638 org-heading-regexp
7639 org-complex-heading-regexp)))
7640 (if orgstruct-mode
7641 (list (length (match-string 1))
7642 (org-reduced-level (length (match-string 1)))
7645 (match-string 2)
7646 nil)
7647 (list (length (match-string 1))
7648 (org-reduced-level (length (match-string 1)))
7649 (org-match-string-no-properties 2)
7650 (and (match-end 3) (aref (match-string 3) 2))
7651 (org-match-string-no-properties 4)
7652 (org-match-string-no-properties 5))))))
7654 (defun org-get-entry ()
7655 "Get the entry text, after heading, entire subtree."
7656 (save-excursion
7657 (org-back-to-heading t)
7658 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7660 (defun org-insert-heading-after-current ()
7661 "Insert a new heading with same level as current, after current subtree."
7662 (interactive)
7663 (org-back-to-heading)
7664 (org-insert-heading)
7665 (org-move-subtree-down)
7666 (end-of-line 1))
7668 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7669 "Insert heading with `org-insert-heading-respect-content' set to t."
7670 (interactive "P")
7671 (let ((org-insert-heading-respect-content t))
7672 (org-insert-heading arg invisible-ok)))
7674 (defun org-insert-todo-heading-respect-content (&optional force-state)
7675 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7676 (interactive "P")
7677 (let ((org-insert-heading-respect-content t))
7678 (org-insert-todo-heading force-state t)))
7680 (defun org-insert-todo-heading (arg &optional force-heading)
7681 "Insert a new heading with the same level and TODO state as current heading.
7682 If the heading has no TODO state, or if the state is DONE, use the first
7683 state (TODO by default). Also one prefix arg, force first state. With two
7684 prefix args, force inserting at the end of the parent subtree."
7685 (interactive "P")
7686 (when (or force-heading (not (org-insert-item 'checkbox)))
7687 (org-insert-heading (or (and (equal arg '(16)) '(16))
7688 force-heading))
7689 (save-excursion
7690 (org-back-to-heading)
7691 (outline-previous-heading)
7692 (looking-at org-todo-line-regexp))
7693 (let*
7694 ((new-mark-x
7695 (if (or arg
7696 (not (match-beginning 2))
7697 (member (match-string 2) org-done-keywords))
7698 (car org-todo-keywords-1)
7699 (match-string 2)))
7700 (new-mark
7702 (run-hook-with-args-until-success
7703 'org-todo-get-default-hook new-mark-x nil)
7704 new-mark-x)))
7705 (beginning-of-line 1)
7706 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7707 (if org-treat-insert-todo-heading-as-state-change
7708 (org-todo new-mark)
7709 (insert new-mark " "))))
7710 (when org-provide-todo-statistics
7711 (org-update-parent-todo-statistics))))
7713 (defun org-insert-subheading (arg)
7714 "Insert a new subheading and demote it.
7715 Works for outline headings and for plain lists alike."
7716 (interactive "P")
7717 (org-insert-heading arg)
7718 (cond
7719 ((org-at-heading-p) (org-do-demote))
7720 ((org-at-item-p) (org-indent-item))))
7722 (defun org-insert-todo-subheading (arg)
7723 "Insert a new subheading with TODO keyword or checkbox and demote it.
7724 Works for outline headings and for plain lists alike."
7725 (interactive "P")
7726 (org-insert-todo-heading arg)
7727 (cond
7728 ((org-at-heading-p) (org-do-demote))
7729 ((org-at-item-p) (org-indent-item))))
7731 ;;; Promotion and Demotion
7733 (defvar org-after-demote-entry-hook nil
7734 "Hook run after an entry has been demoted.
7735 The cursor will be at the beginning of the entry.
7736 When a subtree is being demoted, the hook will be called for each node.")
7738 (defvar org-after-promote-entry-hook nil
7739 "Hook run after an entry has been promoted.
7740 The cursor will be at the beginning of the entry.
7741 When a subtree is being promoted, the hook will be called for each node.")
7743 (defun org-promote-subtree ()
7744 "Promote the entire subtree.
7745 See also `org-promote'."
7746 (interactive)
7747 (save-excursion
7748 (org-with-limited-levels (org-map-tree 'org-promote)))
7749 (org-fix-position-after-promote))
7751 (defun org-demote-subtree ()
7752 "Demote the entire subtree. See `org-demote'.
7753 See also `org-promote'."
7754 (interactive)
7755 (save-excursion
7756 (org-with-limited-levels (org-map-tree 'org-demote)))
7757 (org-fix-position-after-promote))
7760 (defun org-do-promote ()
7761 "Promote the current heading higher up the tree.
7762 If the region is active in `transient-mark-mode', promote all headings
7763 in the region."
7764 (interactive)
7765 (save-excursion
7766 (if (org-region-active-p)
7767 (org-map-region 'org-promote (region-beginning) (region-end))
7768 (org-promote)))
7769 (org-fix-position-after-promote))
7771 (defun org-do-demote ()
7772 "Demote the current heading lower down the tree.
7773 If the region is active in `transient-mark-mode', demote all headings
7774 in the region."
7775 (interactive)
7776 (save-excursion
7777 (if (org-region-active-p)
7778 (org-map-region 'org-demote (region-beginning) (region-end))
7779 (org-demote)))
7780 (org-fix-position-after-promote))
7782 (defun org-fix-position-after-promote ()
7783 "Make sure that after pro/demotion cursor position is right."
7784 (let ((pos (point)))
7785 (when (save-excursion
7786 (beginning-of-line 1)
7787 (looking-at org-todo-line-regexp)
7788 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7789 (cond ((eobp) (insert " "))
7790 ((eolp) (insert " "))
7791 ((equal (char-after) ?\ ) (forward-char 1))))))
7793 (defun org-current-level ()
7794 "Return the level of the current entry, or nil if before the first headline.
7795 The level is the number of stars at the beginning of the headline."
7796 (save-excursion
7797 (org-with-limited-levels
7798 (if (ignore-errors (org-back-to-heading t))
7799 (funcall outline-level)))))
7801 (defun org-get-previous-line-level ()
7802 "Return the outline depth of the last headline before the current line.
7803 Returns 0 for the first headline in the buffer, and nil if before the
7804 first headline."
7805 (let ((current-level (org-current-level))
7806 (prev-level (when (> (line-number-at-pos) 1)
7807 (save-excursion
7808 (beginning-of-line 0)
7809 (org-current-level)))))
7810 (cond ((null current-level) nil) ; Before first headline
7811 ((null prev-level) 0) ; At first headline
7812 (prev-level))))
7814 (defun org-reduced-level (l)
7815 "Compute the effective level of a heading.
7816 This takes into account the setting of `org-odd-levels-only'."
7817 (cond
7818 ((zerop l) 0)
7819 (org-odd-levels-only (1+ (floor (/ l 2))))
7820 (t l)))
7822 (defun org-level-increment ()
7823 "Return the number of stars that will be added or removed at a
7824 time to headlines when structure editing, based on the value of
7825 `org-odd-levels-only'."
7826 (if org-odd-levels-only 2 1))
7828 (defun org-get-valid-level (level &optional change)
7829 "Rectify a level change under the influence of `org-odd-levels-only'
7830 LEVEL is a current level, CHANGE is by how much the level should be
7831 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7832 even level numbers will become the next higher odd number."
7833 (if org-odd-levels-only
7834 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7835 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7836 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7837 (max 1 (+ level (or change 0)))))
7839 (if (boundp 'define-obsolete-function-alias)
7840 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7841 (define-obsolete-function-alias 'org-get-legal-level
7842 'org-get-valid-level)
7843 (define-obsolete-function-alias 'org-get-legal-level
7844 'org-get-valid-level "23.1")))
7846 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7847 ;; ̀org-with-limited-levels'
7848 (defun org-promote ()
7849 "Promote the current heading higher up the tree.
7850 If the region is active in `transient-mark-mode', promote all headings
7851 in the region."
7852 (org-back-to-heading t)
7853 (let* ((level (save-match-data (funcall outline-level)))
7854 (after-change-functions (remove 'flyspell-after-change-function
7855 after-change-functions))
7856 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7857 (diff (abs (- level (length up-head) -1))))
7858 (cond ((and (= level 1) org-called-with-limited-levels
7859 org-allow-promoting-top-level-subtree)
7860 (replace-match "# " nil t))
7861 ((= level 1)
7862 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7863 (t (replace-match up-head nil t)))
7864 ;; Fixup tag positioning
7865 (unless (= level 1)
7866 (and org-auto-align-tags (org-set-tags nil t))
7867 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7868 (run-hooks 'org-after-promote-entry-hook)))
7870 (defun org-demote ()
7871 "Demote the current heading lower down the tree.
7872 If the region is active in `transient-mark-mode', demote all headings
7873 in the region."
7874 (org-back-to-heading t)
7875 (let* ((level (save-match-data (funcall outline-level)))
7876 (after-change-functions (remove 'flyspell-after-change-function
7877 after-change-functions))
7878 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7879 (diff (abs (- level (length down-head) -1))))
7880 (replace-match down-head nil t)
7881 ;; Fixup tag positioning
7882 (and org-auto-align-tags (org-set-tags nil t))
7883 (if org-adapt-indentation (org-fixup-indentation diff))
7884 (run-hooks 'org-after-demote-entry-hook)))
7886 (defun org-cycle-level ()
7887 "Cycle the level of an empty headline through possible states.
7888 This goes first to child, then to parent, level, then up the hierarchy.
7889 After top level, it switches back to sibling level."
7890 (interactive)
7891 (let ((org-adapt-indentation nil))
7892 (when (org-point-at-end-of-empty-headline)
7893 (setq this-command 'org-cycle-level) ; Only needed for caching
7894 (let ((cur-level (org-current-level))
7895 (prev-level (org-get-previous-line-level)))
7896 (cond
7897 ;; If first headline in file, promote to top-level.
7898 ((= prev-level 0)
7899 (loop repeat (/ (- cur-level 1) (org-level-increment))
7900 do (org-do-promote)))
7901 ;; If same level as prev, demote one.
7902 ((= prev-level cur-level)
7903 (org-do-demote))
7904 ;; If parent is top-level, promote to top level if not already.
7905 ((= prev-level 1)
7906 (loop repeat (/ (- cur-level 1) (org-level-increment))
7907 do (org-do-promote)))
7908 ;; If top-level, return to prev-level.
7909 ((= cur-level 1)
7910 (loop repeat (/ (- prev-level 1) (org-level-increment))
7911 do (org-do-demote)))
7912 ;; If less than prev-level, promote one.
7913 ((< cur-level prev-level)
7914 (org-do-promote))
7915 ;; If deeper than prev-level, promote until higher than
7916 ;; prev-level.
7917 ((> cur-level prev-level)
7918 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7919 do (org-do-promote))))
7920 t))))
7922 (defun org-map-tree (fun)
7923 "Call FUN for every heading underneath the current one."
7924 (org-back-to-heading)
7925 (let ((level (funcall outline-level)))
7926 (save-excursion
7927 (funcall fun)
7928 (while (and (progn
7929 (outline-next-heading)
7930 (> (funcall outline-level) level))
7931 (not (eobp)))
7932 (funcall fun)))))
7934 (defun org-map-region (fun beg end)
7935 "Call FUN for every heading between BEG and END."
7936 (let ((org-ignore-region t))
7937 (save-excursion
7938 (setq end (copy-marker end))
7939 (goto-char beg)
7940 (if (and (re-search-forward org-outline-regexp-bol nil t)
7941 (< (point) end))
7942 (funcall fun))
7943 (while (and (progn
7944 (outline-next-heading)
7945 (< (point) end))
7946 (not (eobp)))
7947 (funcall fun)))))
7949 (defvar org-property-end-re) ; silence byte-compiler
7950 (defun org-fixup-indentation (diff)
7951 "Change the indentation in the current entry by DIFF.
7952 However, if any line in the current entry has no indentation, or if it
7953 would end up with no indentation after the change, nothing at all is done."
7954 (save-excursion
7955 (let ((end (save-excursion (outline-next-heading)
7956 (point-marker)))
7957 (prohibit (if (> diff 0)
7958 "^\\S-"
7959 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7960 col)
7961 (unless (save-excursion (end-of-line 1)
7962 (re-search-forward prohibit end t))
7963 (while (and (< (point) end)
7964 (re-search-forward "^[ \t]+" end t))
7965 (goto-char (match-end 0))
7966 (setq col (current-column))
7967 (if (< diff 0) (replace-match ""))
7968 (org-indent-to-column (+ diff col))))
7969 (move-marker end nil))))
7971 (defun org-convert-to-odd-levels ()
7972 "Convert an org-mode file with all levels allowed to one with odd levels.
7973 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7974 level 5 etc."
7975 (interactive)
7976 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7977 (let ((outline-level 'org-outline-level)
7978 (org-odd-levels-only nil) n)
7979 (save-excursion
7980 (goto-char (point-min))
7981 (while (re-search-forward "^\\*\\*+ " nil t)
7982 (setq n (- (length (match-string 0)) 2))
7983 (while (>= (setq n (1- n)) 0)
7984 (org-demote))
7985 (end-of-line 1))))))
7987 (defun org-convert-to-oddeven-levels ()
7988 "Convert an org-mode file with only odd levels to one with odd/even levels.
7989 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7990 file contains a section with an even level, conversion would
7991 destroy the structure of the file. An error is signaled in this
7992 case."
7993 (interactive)
7994 (goto-char (point-min))
7995 ;; First check if there are no even levels
7996 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7997 (org-show-context t)
7998 (error "Not all levels are odd in this file. Conversion not possible"))
7999 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8000 (let ((outline-regexp org-outline-regexp)
8001 (outline-level 'org-outline-level)
8002 (org-odd-levels-only nil) n)
8003 (save-excursion
8004 (goto-char (point-min))
8005 (while (re-search-forward "^\\*\\*+ " nil t)
8006 (setq n (/ (1- (length (match-string 0))) 2))
8007 (while (>= (setq n (1- n)) 0)
8008 (org-promote))
8009 (end-of-line 1))))))
8011 (defun org-tr-level (n)
8012 "Make N odd if required."
8013 (if org-odd-levels-only (1+ (/ n 2)) n))
8015 ;;; Vertical tree motion, cutting and pasting of subtrees
8017 (defun org-move-subtree-up (&optional arg)
8018 "Move the current subtree up past ARG headlines of the same level."
8019 (interactive "p")
8020 (org-move-subtree-down (- (prefix-numeric-value arg))))
8022 (defun org-move-subtree-down (&optional arg)
8023 "Move the current subtree down past ARG headlines of the same level."
8024 (interactive "p")
8025 (setq arg (prefix-numeric-value arg))
8026 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8027 'org-get-last-sibling))
8028 (ins-point (make-marker))
8029 (cnt (abs arg))
8030 (col (current-column))
8031 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8032 ;; Select the tree
8033 (org-back-to-heading)
8034 (setq beg0 (point))
8035 (save-excursion
8036 (setq ne-beg (org-back-over-empty-lines))
8037 (setq beg (point)))
8038 (save-match-data
8039 (save-excursion (outline-end-of-heading)
8040 (setq folded (outline-invisible-p)))
8041 (outline-end-of-subtree))
8042 (outline-next-heading)
8043 (setq ne-end (org-back-over-empty-lines))
8044 (setq end (point))
8045 (goto-char beg0)
8046 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8047 ;; include less whitespace
8048 (save-excursion
8049 (goto-char beg)
8050 (forward-line (- ne-beg ne-end))
8051 (setq beg (point))))
8052 ;; Find insertion point, with error handling
8053 (while (> cnt 0)
8054 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8055 (progn (goto-char beg0)
8056 (user-error "Cannot move past superior level or buffer limit")))
8057 (setq cnt (1- cnt)))
8058 (if (> arg 0)
8059 ;; Moving forward - still need to move over subtree
8060 (progn (org-end-of-subtree t t)
8061 (save-excursion
8062 (org-back-over-empty-lines)
8063 (or (bolp) (newline)))))
8064 (setq ne-ins (org-back-over-empty-lines))
8065 (move-marker ins-point (point))
8066 (setq txt (buffer-substring beg end))
8067 (org-save-markers-in-region beg end)
8068 (delete-region beg end)
8069 (org-remove-empty-overlays-at beg)
8070 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8071 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8072 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8073 (let ((bbb (point)))
8074 (insert-before-markers txt)
8075 (org-reinstall-markers-in-region bbb)
8076 (move-marker ins-point bbb))
8077 (or (bolp) (insert "\n"))
8078 (setq ins-end (point))
8079 (goto-char ins-point)
8080 (org-skip-whitespace)
8081 (when (and (< arg 0)
8082 (org-first-sibling-p)
8083 (> ne-ins ne-beg))
8084 ;; Move whitespace back to beginning
8085 (save-excursion
8086 (goto-char ins-end)
8087 (let ((kill-whole-line t))
8088 (kill-line (- ne-ins ne-beg)) (point)))
8089 (insert (make-string (- ne-ins ne-beg) ?\n)))
8090 (move-marker ins-point nil)
8091 (if folded
8092 (hide-subtree)
8093 (org-show-entry)
8094 (show-children)
8095 (org-cycle-hide-drawers 'children))
8096 (org-clean-visibility-after-subtree-move)
8097 ;; move back to the initial column we were at
8098 (move-to-column col)))
8100 (defvar org-subtree-clip ""
8101 "Clipboard for cut and paste of subtrees.
8102 This is actually only a copy of the kill, because we use the normal kill
8103 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8105 (defvar org-subtree-clip-folded nil
8106 "Was the last copied subtree folded?
8107 This is used to fold the tree back after pasting.")
8109 (defun org-cut-subtree (&optional n)
8110 "Cut the current subtree into the clipboard.
8111 With prefix arg N, cut this many sequential subtrees.
8112 This is a short-hand for marking the subtree and then cutting it."
8113 (interactive "p")
8114 (org-copy-subtree n 'cut))
8116 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8117 "Cut the current subtree into the clipboard.
8118 With prefix arg N, cut this many sequential subtrees.
8119 This is a short-hand for marking the subtree and then copying it.
8120 If CUT is non-nil, actually cut the subtree.
8121 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8122 of some markers in the region, even if CUT is non-nil. This is
8123 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8124 (interactive "p")
8125 (let (beg end folded (beg0 (point)))
8126 (if (org-called-interactively-p 'any)
8127 (org-back-to-heading nil) ; take what looks like a subtree
8128 (org-back-to-heading t)) ; take what is really there
8129 (setq beg (point))
8130 (skip-chars-forward " \t\r\n")
8131 (save-match-data
8132 (if nosubtrees
8133 (outline-next-heading)
8134 (save-excursion (outline-end-of-heading)
8135 (setq folded (outline-invisible-p)))
8136 (condition-case nil
8137 (org-forward-heading-same-level (1- n) t)
8138 (error nil))
8139 (org-end-of-subtree t t)))
8140 (setq end (point))
8141 (goto-char beg0)
8142 (when (> end beg)
8143 (setq org-subtree-clip-folded folded)
8144 (when (or cut force-store-markers)
8145 (org-save-markers-in-region beg end))
8146 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8147 (setq org-subtree-clip (current-kill 0))
8148 (message "%s: Subtree(s) with %d characters"
8149 (if cut "Cut" "Copied")
8150 (length org-subtree-clip)))))
8152 (defun org-paste-subtree (&optional level tree for-yank)
8153 "Paste the clipboard as a subtree, with modification of headline level.
8154 The entire subtree is promoted or demoted in order to match a new headline
8155 level.
8157 If the cursor is at the beginning of a headline, the same level as
8158 that headline is used to paste the tree.
8160 If not, the new level is derived from the *visible* headings
8161 before and after the insertion point, and taken to be the inferior headline
8162 level of the two. So if the previous visible heading is level 3 and the
8163 next is level 4 (or vice versa), level 4 will be used for insertion.
8164 This makes sure that the subtree remains an independent subtree and does
8165 not swallow low level entries.
8167 You can also force a different level, either by using a numeric prefix
8168 argument, or by inserting the heading marker by hand. For example, if the
8169 cursor is after \"*****\", then the tree will be shifted to level 5.
8171 If optional TREE is given, use this text instead of the kill ring.
8173 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8174 move back over whitespace before inserting, and move point to the end of
8175 the inserted text when done."
8176 (interactive "P")
8177 (setq tree (or tree (and kill-ring (current-kill 0))))
8178 (unless (org-kill-is-subtree-p tree)
8179 (error "%s"
8180 (substitute-command-keys
8181 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8182 (org-with-limited-levels
8183 (let* ((visp (not (outline-invisible-p)))
8184 (txt tree)
8185 (^re_ "\\(\\*+\\)[ \t]*")
8186 (old-level (if (string-match org-outline-regexp-bol txt)
8187 (- (match-end 0) (match-beginning 0) 1)
8188 -1))
8189 (force-level (cond (level (prefix-numeric-value level))
8190 ((and (looking-at "[ \t]*$")
8191 (string-match
8192 "^\\*+$" (buffer-substring
8193 (point-at-bol) (point))))
8194 (- (match-end 1) (match-beginning 1)))
8195 ((and (bolp)
8196 (looking-at org-outline-regexp))
8197 (- (match-end 0) (point) 1))))
8198 (previous-level (save-excursion
8199 (condition-case nil
8200 (progn
8201 (outline-previous-visible-heading 1)
8202 (if (looking-at ^re_)
8203 (- (match-end 0) (match-beginning 0) 1)
8205 (error 1))))
8206 (next-level (save-excursion
8207 (condition-case nil
8208 (progn
8209 (or (looking-at org-outline-regexp)
8210 (outline-next-visible-heading 1))
8211 (if (looking-at ^re_)
8212 (- (match-end 0) (match-beginning 0) 1)
8214 (error 1))))
8215 (new-level (or force-level (max previous-level next-level)))
8216 (shift (if (or (= old-level -1)
8217 (= new-level -1)
8218 (= old-level new-level))
8220 (- new-level old-level)))
8221 (delta (if (> shift 0) -1 1))
8222 (func (if (> shift 0) 'org-demote 'org-promote))
8223 (org-odd-levels-only nil)
8224 beg end newend)
8225 ;; Remove the forced level indicator
8226 (if force-level
8227 (delete-region (point-at-bol) (point)))
8228 ;; Paste
8229 (beginning-of-line (if (bolp) 1 2))
8230 (setq beg (point))
8231 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8232 (insert-before-markers txt)
8233 (unless (string-match "\n\\'" txt) (insert "\n"))
8234 (setq newend (point))
8235 (org-reinstall-markers-in-region beg)
8236 (setq end (point))
8237 (goto-char beg)
8238 (skip-chars-forward " \t\n\r")
8239 (setq beg (point))
8240 (if (and (outline-invisible-p) visp)
8241 (save-excursion (outline-show-heading)))
8242 ;; Shift if necessary
8243 (unless (= shift 0)
8244 (save-restriction
8245 (narrow-to-region beg end)
8246 (while (not (= shift 0))
8247 (org-map-region func (point-min) (point-max))
8248 (setq shift (+ delta shift)))
8249 (goto-char (point-min))
8250 (setq newend (point-max))))
8251 (when (or (org-called-interactively-p 'interactive) for-yank)
8252 (message "Clipboard pasted as level %d subtree" new-level))
8253 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8254 kill-ring
8255 (eq org-subtree-clip (current-kill 0))
8256 org-subtree-clip-folded)
8257 ;; The tree was folded before it was killed/copied
8258 (hide-subtree))
8259 (and for-yank (goto-char newend)))))
8261 (defun org-kill-is-subtree-p (&optional txt)
8262 "Check if the current kill is an outline subtree, or a set of trees.
8263 Returns nil if kill does not start with a headline, or if the first
8264 headline level is not the largest headline level in the tree.
8265 So this will actually accept several entries of equal levels as well,
8266 which is OK for `org-paste-subtree'.
8267 If optional TXT is given, check this string instead of the current kill."
8268 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8269 (re (org-get-limited-outline-regexp))
8270 (^re (concat "^" re))
8271 (start-level (and kill
8272 (string-match
8273 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8274 kill)
8275 (- (match-end 2) (match-beginning 2) 1)))
8276 (start (1+ (or (match-beginning 2) -1))))
8277 (if (not start-level)
8278 (progn
8279 nil) ;; does not even start with a heading
8280 (catch 'exit
8281 (while (setq start (string-match ^re kill (1+ start)))
8282 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8283 (throw 'exit nil)))
8284 t))))
8286 (defvar org-markers-to-move nil
8287 "Markers that should be moved with a cut-and-paste operation.
8288 Those markers are stored together with their positions relative to
8289 the start of the region.")
8291 (defun org-save-markers-in-region (beg end)
8292 "Check markers in region.
8293 If these markers are between BEG and END, record their position relative
8294 to BEG, so that after moving the block of text, we can put the markers back
8295 into place.
8296 This function gets called just before an entry or tree gets cut from the
8297 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8298 called immediately, to move the markers with the entries."
8299 (setq org-markers-to-move nil)
8300 (when (featurep 'org-clock)
8301 (org-clock-save-markers-for-cut-and-paste beg end))
8302 (when (featurep 'org-agenda)
8303 (org-agenda-save-markers-for-cut-and-paste beg end)))
8305 (defun org-check-and-save-marker (marker beg end)
8306 "Check if MARKER is between BEG and END.
8307 If yes, remember the marker and the distance to BEG."
8308 (when (and (marker-buffer marker)
8309 (equal (marker-buffer marker) (current-buffer)))
8310 (if (and (>= marker beg) (< marker end))
8311 (push (cons marker (- marker beg)) org-markers-to-move))))
8313 (defun org-reinstall-markers-in-region (beg)
8314 "Move all remembered markers to their position relative to BEG."
8315 (mapc (lambda (x)
8316 (move-marker (car x) (+ beg (cdr x))))
8317 org-markers-to-move)
8318 (setq org-markers-to-move nil))
8320 (defun org-narrow-to-subtree ()
8321 "Narrow buffer to the current subtree."
8322 (interactive)
8323 (save-excursion
8324 (save-match-data
8325 (org-with-limited-levels
8326 (narrow-to-region
8327 (progn (org-back-to-heading t) (point))
8328 (progn (org-end-of-subtree t t)
8329 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8330 (point)))))))
8332 (defun org-narrow-to-block ()
8333 "Narrow buffer to the current block."
8334 (interactive)
8335 (let* ((case-fold-search t)
8336 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8337 "^[ \t]*#\\+end_.*")))
8338 (if blockp
8339 (narrow-to-region (car blockp) (cdr blockp))
8340 (error "Not in a block"))))
8342 (eval-when-compile
8343 (defvar org-property-drawer-re))
8345 (defvar org-property-start-re) ;; defined below
8346 (defun org-clone-subtree-with-time-shift (n &optional shift)
8347 "Clone the task (subtree) at point N times.
8348 The clones will be inserted as siblings.
8350 In interactive use, the user will be prompted for the number of
8351 clones to be produced. When called with a universal prefix argument
8352 and if the entry has a timestamp, the user will also be prompted for
8353 a time shift, which may be a repeater as used in time stamps, for
8354 example `+3d'.
8356 When a valid repeater is given and the entry contains any time
8357 stamps, the clones will become a sequence in time, with time
8358 stamps in the subtree shifted for each clone produced. If SHIFT
8359 is nil or the empty string, time stamps will be left alone. The
8360 ID property of the original subtree is removed.
8362 If the original subtree did contain time stamps with a repeater,
8363 the following will happen:
8364 - the repeater will be removed in each clone
8365 - an additional clone will be produced, with the current, unshifted
8366 date(s) in the entry.
8367 - the original entry will be placed *after* all the clones, with
8368 repeater intact.
8369 - the start days in the repeater in the original entry will be shifted
8370 to past the last clone.
8371 In this way you can spell out a number of instances of a repeating task,
8372 and still retain the repeater to cover future instances of the task."
8373 (interactive "nNumber of clones to produce: ")
8374 (let ((shift
8375 (or shift
8376 (if (and (equal current-prefix-arg '(4))
8377 (save-excursion
8378 (re-search-forward org-ts-regexp-both
8379 (save-excursion
8380 (org-end-of-subtree t)
8381 (point)) t)))
8382 (read-from-minibuffer
8383 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8384 ""))) ;; No time shift
8385 (n-no-remove -1)
8386 (drawer-re org-drawer-regexp)
8387 beg end template task idprop
8388 shift-n shift-what doshift nmin nmax)
8389 (if (not (and (integerp n) (> n 0)))
8390 (error "Invalid number of replications %s" n))
8391 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8392 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8393 shift)))
8394 (error "Invalid shift specification %s" shift))
8395 (when doshift
8396 (setq shift-n (string-to-number (match-string 1 shift))
8397 shift-what (cdr (assoc (match-string 2 shift)
8398 '(("d" . day) ("w" . week)
8399 ("m" . month) ("y" . year))))))
8400 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8401 (setq nmin 1 nmax n)
8402 (org-back-to-heading t)
8403 (setq beg (point))
8404 (setq idprop (org-entry-get nil "ID"))
8405 (org-end-of-subtree t t)
8406 (or (bolp) (insert "\n"))
8407 (setq end (point))
8408 (setq template (buffer-substring beg end))
8409 (when (and doshift
8410 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8411 (delete-region beg end)
8412 (setq end beg)
8413 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8414 (goto-char end)
8415 (loop for n from nmin to nmax do
8416 ;; prepare clone
8417 (with-temp-buffer
8418 (insert template)
8419 (org-mode)
8420 (goto-char (point-min))
8421 (org-show-subtree)
8422 (and idprop (if org-clone-delete-id
8423 (org-entry-delete nil "ID")
8424 (org-id-get-create t)))
8425 (unless (= n 0)
8426 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8427 (kill-whole-line))
8428 (goto-char (point-min))
8429 (while (re-search-forward drawer-re nil t)
8430 (mapc (lambda (d)
8431 (org-remove-empty-drawer-at d (point))) org-drawers)))
8432 (goto-char (point-min))
8433 (when doshift
8434 (while (re-search-forward org-ts-regexp-both nil t)
8435 (org-timestamp-change (* n shift-n) shift-what))
8436 (unless (= n n-no-remove)
8437 (goto-char (point-min))
8438 (while (re-search-forward org-ts-regexp nil t)
8439 (save-excursion
8440 (goto-char (match-beginning 0))
8441 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8442 (delete-region (match-beginning 1) (match-end 1)))))))
8443 (setq task (buffer-string)))
8444 (insert task))
8445 (goto-char beg)))
8447 ;;; Outline Sorting
8449 (defun org-sort (with-case)
8450 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8451 Optional argument WITH-CASE means sort case-sensitively."
8452 (interactive "P")
8453 (cond
8454 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8455 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8457 (org-call-with-arg 'org-sort-entries with-case))))
8459 (defun org-sort-remove-invisible (s)
8460 "Remove invisible links from string S."
8461 (remove-text-properties 0 (length s) org-rm-props s)
8462 (while (string-match org-bracket-link-regexp s)
8463 (setq s (replace-match (if (match-end 2)
8464 (match-string 3 s)
8465 (match-string 1 s)) t t s)))
8466 (let ((st (format " %s " s)))
8467 (while (string-match org-emph-re st)
8468 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8469 (setq s (substring st 1 -1)))
8472 (defvar org-priority-regexp) ; defined later in the file
8474 (defvar org-after-sorting-entries-or-items-hook nil
8475 "Hook that is run after a bunch of entries or items have been sorted.
8476 When children are sorted, the cursor is in the parent line when this
8477 hook gets called. When a region or a plain list is sorted, the cursor
8478 will be in the first entry of the sorted region/list.")
8480 (defun org-sort-entries
8481 (&optional with-case sorting-type getkey-func compare-func property)
8482 "Sort entries on a certain level of an outline tree.
8483 If there is an active region, the entries in the region are sorted.
8484 Else, if the cursor is before the first entry, sort the top-level items.
8485 Else, the children of the entry at point are sorted.
8487 Sorting can be alphabetically, numerically, by date/time as given by
8488 a time stamp, by a property, by priority order, or by a custom function.
8490 The command prompts for the sorting type unless it has been given to the
8491 function through the SORTING-TYPE argument, which needs to be a character,
8492 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8493 precise meaning of each character:
8495 n Numerically, by converting the beginning of the entry/item to a number.
8496 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8497 o By order of TODO keywords.
8498 t By date/time, either the first active time stamp in the entry, or, if
8499 none exist, by the first inactive one.
8500 s By the scheduled date/time.
8501 d By deadline date/time.
8502 c By creation time, which is assumed to be the first inactive time stamp
8503 at the beginning of a line.
8504 p By priority according to the cookie.
8505 r By the value of a property.
8507 Capital letters will reverse the sort order.
8509 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8510 called with point at the beginning of the record. It must return either
8511 a string or a number that should serve as the sorting key for that record.
8513 Comparing entries ignores case by default. However, with an optional argument
8514 WITH-CASE, the sorting considers case as well.
8516 Sorting is done against the visible part of the headlines, it ignores hidden
8517 links."
8518 (interactive "P")
8519 (let ((case-func (if with-case 'identity 'downcase))
8520 (cmstr
8521 ;; The clock marker is lost when using `sort-subr', let's
8522 ;; store the clocking string.
8523 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8524 (save-excursion
8525 (goto-char org-clock-marker)
8526 (looking-back "^.*") (match-string-no-properties 0))))
8527 start beg end stars re re2
8528 txt what tmp)
8529 ;; Find beginning and end of region to sort
8530 (cond
8531 ((org-region-active-p)
8532 ;; we will sort the region
8533 (setq end (region-end)
8534 what "region")
8535 (goto-char (region-beginning))
8536 (if (not (org-at-heading-p)) (outline-next-heading))
8537 (setq start (point)))
8538 ((or (org-at-heading-p)
8539 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8540 ;; we will sort the children of the current headline
8541 (org-back-to-heading)
8542 (setq start (point)
8543 end (progn (org-end-of-subtree t t)
8544 (or (bolp) (insert "\n"))
8545 (org-back-over-empty-lines)
8546 (point))
8547 what "children")
8548 (goto-char start)
8549 (show-subtree)
8550 (outline-next-heading))
8552 ;; we will sort the top-level entries in this file
8553 (goto-char (point-min))
8554 (or (org-at-heading-p) (outline-next-heading))
8555 (setq start (point))
8556 (goto-char (point-max))
8557 (beginning-of-line 1)
8558 (when (looking-at ".*?\\S-")
8559 ;; File ends in a non-white line
8560 (end-of-line 1)
8561 (insert "\n"))
8562 (setq end (point-max))
8563 (setq what "top-level")
8564 (goto-char start)
8565 (show-all)))
8567 (setq beg (point))
8568 (if (>= beg end) (error "Nothing to sort"))
8570 (looking-at "\\(\\*+\\)")
8571 (setq stars (match-string 1)
8572 re (concat "^" (regexp-quote stars) " +")
8573 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8574 txt (buffer-substring beg end))
8575 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8576 (if (and (not (equal stars "*")) (string-match re2 txt))
8577 (error "Region to sort contains a level above the first entry"))
8579 (unless sorting-type
8580 (message
8581 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8582 [t]ime [s]cheduled [d]eadline [c]reated
8583 A/N/P/R/O/F/T/S/D/C means reversed:"
8584 what)
8585 (setq sorting-type (read-char-exclusive))
8587 (unless getkey-func
8588 (and (= (downcase sorting-type) ?f)
8589 (setq getkey-func
8590 (org-icompleting-read "Sort using function: "
8591 obarray 'fboundp t nil nil))
8592 (setq getkey-func (intern getkey-func))))
8594 (and (= (downcase sorting-type) ?r)
8595 (not property)
8596 (setq property
8597 (org-icompleting-read "Property: "
8598 (mapcar 'list (org-buffer-property-keys t))
8599 nil t))))
8601 (message "Sorting entries...")
8603 (save-restriction
8604 (narrow-to-region start end)
8605 (let ((dcst (downcase sorting-type))
8606 (case-fold-search nil)
8607 (now (current-time)))
8608 (sort-subr
8609 (/= dcst sorting-type)
8610 ;; This function moves to the beginning character of the "record" to
8611 ;; be sorted.
8612 (lambda nil
8613 (if (re-search-forward re nil t)
8614 (goto-char (match-beginning 0))
8615 (goto-char (point-max))))
8616 ;; This function moves to the last character of the "record" being
8617 ;; sorted.
8618 (lambda nil
8619 (save-match-data
8620 (condition-case nil
8621 (outline-forward-same-level 1)
8622 (error
8623 (goto-char (point-max))))))
8624 ;; This function returns the value that gets sorted against.
8625 (lambda nil
8626 (cond
8627 ((= dcst ?n)
8628 (if (looking-at org-complex-heading-regexp)
8629 (string-to-number (org-sort-remove-invisible (match-string 4)))
8630 nil))
8631 ((= dcst ?a)
8632 (if (looking-at org-complex-heading-regexp)
8633 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8634 nil))
8635 ((= dcst ?t)
8636 (let ((end (save-excursion (outline-next-heading) (point))))
8637 (if (or (re-search-forward org-ts-regexp end t)
8638 (re-search-forward org-ts-regexp-both end t))
8639 (org-time-string-to-seconds (match-string 0))
8640 (org-float-time now))))
8641 ((= dcst ?c)
8642 (let ((end (save-excursion (outline-next-heading) (point))))
8643 (if (re-search-forward
8644 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8645 end t)
8646 (org-time-string-to-seconds (match-string 0))
8647 (org-float-time now))))
8648 ((= dcst ?s)
8649 (let ((end (save-excursion (outline-next-heading) (point))))
8650 (if (re-search-forward org-scheduled-time-regexp end t)
8651 (org-time-string-to-seconds (match-string 1))
8652 (org-float-time now))))
8653 ((= dcst ?d)
8654 (let ((end (save-excursion (outline-next-heading) (point))))
8655 (if (re-search-forward org-deadline-time-regexp end t)
8656 (org-time-string-to-seconds (match-string 1))
8657 (org-float-time now))))
8658 ((= dcst ?p)
8659 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8660 (string-to-char (match-string 2))
8661 org-default-priority))
8662 ((= dcst ?r)
8663 (or (org-entry-get nil property) ""))
8664 ((= dcst ?o)
8665 (if (looking-at org-complex-heading-regexp)
8666 (- 9999 (length (member (match-string 2)
8667 org-todo-keywords-1)))))
8668 ((= dcst ?f)
8669 (if getkey-func
8670 (progn
8671 (setq tmp (funcall getkey-func))
8672 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8673 tmp)
8674 (error "Invalid key function `%s'" getkey-func)))
8675 (t (error "Invalid sorting type `%c'" sorting-type))))
8677 (cond
8678 ((= dcst ?a) 'string<)
8679 ((= dcst ?f) compare-func)
8680 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8681 (run-hooks 'org-after-sorting-entries-or-items-hook)
8682 ;; Reset the clock marker if needed
8683 (when cmstr
8684 (save-excursion
8685 (goto-char start)
8686 (search-forward cmstr nil t)
8687 (move-marker org-clock-marker (point))))
8688 (message "Sorting entries...done")))
8690 (defun org-do-sort (table what &optional with-case sorting-type)
8691 "Sort TABLE of WHAT according to SORTING-TYPE.
8692 The user will be prompted for the SORTING-TYPE if the call to this
8693 function does not specify it. WHAT is only for the prompt, to indicate
8694 what is being sorted. The sorting key will be extracted from
8695 the car of the elements of the table.
8696 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8697 (unless sorting-type
8698 (message
8699 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8700 what)
8701 (setq sorting-type (read-char-exclusive)))
8702 (let ((dcst (downcase sorting-type))
8703 extractfun comparefun)
8704 ;; Define the appropriate functions
8705 (cond
8706 ((= dcst ?n)
8707 (setq extractfun 'string-to-number
8708 comparefun (if (= dcst sorting-type) '< '>)))
8709 ((= dcst ?a)
8710 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8711 (lambda(x) (downcase (org-sort-remove-invisible x))))
8712 comparefun (if (= dcst sorting-type)
8713 'string<
8714 (lambda (a b) (and (not (string< a b))
8715 (not (string= a b)))))))
8716 ((= dcst ?t)
8717 (setq extractfun
8718 (lambda (x)
8719 (if (or (string-match org-ts-regexp x)
8720 (string-match org-ts-regexp-both x))
8721 (org-float-time
8722 (org-time-string-to-time (match-string 0 x)))
8724 comparefun (if (= dcst sorting-type) '< '>)))
8725 (t (error "Invalid sorting type `%c'" sorting-type)))
8727 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8728 table)
8729 (lambda (a b) (funcall comparefun (car a) (car b))))))
8732 ;;; The orgstruct minor mode
8734 ;; Define a minor mode which can be used in other modes in order to
8735 ;; integrate the org-mode structure editing commands.
8737 ;; This is really a hack, because the org-mode structure commands use
8738 ;; keys which normally belong to the major mode. Here is how it
8739 ;; works: The minor mode defines all the keys necessary to operate the
8740 ;; structure commands, but wraps the commands into a function which
8741 ;; tests if the cursor is currently at a headline or a plain list
8742 ;; item. If that is the case, the structure command is used,
8743 ;; temporarily setting many Org-mode variables like regular
8744 ;; expressions for filling etc. However, when any of those keys is
8745 ;; used at a different location, function uses `key-binding' to look
8746 ;; up if the key has an associated command in another currently active
8747 ;; keymap (minor modes, major mode, global), and executes that
8748 ;; command. There might be problems if any of the keys is otherwise
8749 ;; used as a prefix key.
8751 (defcustom orgstruct-heading-prefix-regexp nil
8752 "Regexp that matches the custom prefix of Org headlines in
8753 orgstruct(++)-mode."
8754 :group 'org
8755 :version "24.4"
8756 :package-version '(Org . "8.0")
8757 :type 'string)
8758 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8760 (defcustom orgstruct-setup-hook nil
8761 "Hook run after orgstruct-mode-map is filled."
8762 :group 'org
8763 :version "24.4"
8764 :package-version '(Org . "8.0")
8765 :type 'hook)
8767 (defvar orgstruct-initialized nil)
8769 (defvar org-local-vars nil
8770 "List of local variables, for use by `orgstruct-mode'.")
8772 ;;;###autoload
8773 (define-minor-mode orgstruct-mode
8774 "Toggle the minor mode `orgstruct-mode'.
8775 This mode is for using Org-mode structure commands in other
8776 modes. The following keys behave as if Org-mode were active, if
8777 the cursor is on a headline, or on a plain list item (both as
8778 defined by Org-mode)."
8779 nil " OrgStruct" (make-sparse-keymap)
8780 (funcall (if orgstruct-mode
8781 'add-to-invisibility-spec
8782 'remove-from-invisibility-spec)
8783 '(outline . t))
8784 (when orgstruct-mode
8785 (org-load-modules-maybe)
8786 (unless orgstruct-initialized
8787 (orgstruct-setup)
8788 (setq orgstruct-initialized t))))
8790 ;;;###autoload
8791 (defun turn-on-orgstruct ()
8792 "Unconditionally turn on `orgstruct-mode'."
8793 (orgstruct-mode 1))
8795 (defvar org-fb-vars nil)
8796 (make-variable-buffer-local 'org-fb-vars)
8797 (defun orgstruct++-mode (&optional arg)
8798 "Toggle `orgstruct-mode', the enhanced version of it.
8799 In addition to setting orgstruct-mode, this also exports all
8800 indentation and autofilling variables from org-mode into the
8801 buffer. It will also recognize item context in multiline items."
8802 (interactive "P")
8803 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8804 (if (< arg 1)
8805 (progn (orgstruct-mode -1)
8806 (mapc (lambda(v)
8807 (org-set-local (car v)
8808 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8809 org-fb-vars))
8810 (orgstruct-mode 1)
8811 (setq org-fb-vars nil)
8812 (let (var val)
8813 (mapc
8814 (lambda (x)
8815 (when (string-match
8816 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8817 (symbol-name (car x)))
8818 (setq var (car x) val (nth 1 x))
8819 (push (list var `(quote ,(eval var))) org-fb-vars)
8820 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8821 org-local-vars)
8822 (org-set-local 'orgstruct-is-++ t))))
8824 (defvar orgstruct-is-++ nil
8825 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8826 (make-variable-buffer-local 'orgstruct-is-++)
8828 ;;;###autoload
8829 (defun turn-on-orgstruct++ ()
8830 "Unconditionally turn on `orgstruct++-mode'."
8831 (orgstruct++-mode 1))
8833 (defun orgstruct-error ()
8834 "Error when there is no default binding for a structure key."
8835 (interactive)
8836 (funcall (if (fboundp 'user-error)
8837 'user-error
8838 'error)
8839 "This key has no function outside structure elements"))
8841 (defun orgstruct-setup ()
8842 "Setup orgstruct keymap."
8843 (dolist (cell '((org-demote . t)
8844 (org-metaleft . t)
8845 (org-metaright . t)
8846 (org-promote . t)
8847 (org-shiftmetaleft . t)
8848 (org-shiftmetaright . t)
8849 org-backward-element
8850 org-backward-heading-same-level
8851 org-ctrl-c-ret
8852 org-ctrl-c-minus
8853 org-ctrl-c-star
8854 org-cycle
8855 org-forward-heading-same-level
8856 org-insert-heading
8857 org-insert-heading-respect-content
8858 org-kill-note-or-show-branches
8859 org-mark-subtree
8860 org-meta-return
8861 org-metadown
8862 org-metaup
8863 org-narrow-to-subtree
8864 org-promote-subtree
8865 org-reveal
8866 org-shiftdown
8867 org-shiftleft
8868 org-shiftmetadown
8869 org-shiftmetaup
8870 org-shiftright
8871 org-shifttab
8872 org-shifttab
8873 org-shiftup
8874 org-show-subtree
8875 org-sort
8876 org-up-element
8877 outline-demote
8878 outline-next-visible-heading
8879 outline-previous-visible-heading
8880 outline-promote
8881 outline-up-heading
8882 show-children))
8883 (let ((f (or (car-safe cell) cell))
8884 (disable-when-heading-prefix (cdr-safe cell)))
8885 (when (fboundp f)
8886 (dolist (binding (nconc (where-is-internal f org-mode-map)
8887 (where-is-internal f outline-mode-map)))
8888 ;; TODO use local-function-key-map
8889 (dolist (rep '(("<tab>" . "TAB")
8890 ("<return>" . "RET")
8891 ("<escape>" . "ESC")
8892 ("<delete>" . "DEL")))
8893 (setq binding (read-kbd-macro
8894 (let ((case-fold-search))
8895 (replace-regexp-in-string
8896 (regexp-quote (cdr rep))
8897 (car rep)
8898 (key-description binding))))))
8899 (let ((key (lookup-key orgstruct-mode-map binding)))
8900 (when (or (not key) (numberp key))
8901 (condition-case nil
8902 (org-defkey orgstruct-mode-map
8903 binding
8904 (orgstruct-make-binding f binding disable-when-heading-prefix))
8905 (error nil))))))))
8906 (run-hooks 'orgstruct-setup-hook))
8908 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8909 "Create a function for binding in the structure minor mode.
8910 FUN is the command to call inside a table. KEY is the key that
8911 should be checked in for a command to execute outside of tables.
8912 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8913 if `orgstruct-heading-prefix-regexp' is non-nil."
8914 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8915 (let ((nname name)
8916 (i 0))
8917 (while (fboundp (intern nname))
8918 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8919 (setq name (intern nname)))
8920 (eval
8921 (let ((bindings '((org-heading-regexp
8922 (concat "^"
8923 orgstruct-heading-prefix-regexp
8924 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8925 (org-outline-regexp
8926 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8927 (org-outline-regexp-bol
8928 (concat "^" org-outline-regexp))
8929 (outline-regexp org-outline-regexp)
8930 (outline-heading-end-regexp "\n")
8931 (outline-level 'org-outline-level)
8932 (outline-heading-alist))))
8933 `(defun ,name (arg)
8934 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8935 "Outside of structure, run the binding of `"
8936 (key-description key) "'."
8937 (when disable-when-heading-prefix
8938 (concat
8939 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8940 "back to the default binding due to limitations of Org's implementation of\n"
8941 "`" (symbol-name fun) "'.")))
8942 (interactive "p")
8943 (let* ((disable
8944 ,(when disable-when-heading-prefix
8945 '(and orgstruct-heading-prefix-regexp
8946 (not (string= orgstruct-heading-prefix-regexp "")))))
8947 (fallback
8948 (or disable
8949 (not
8950 (let* ,bindings
8951 (org-context-p 'headline 'item
8952 ,(when (memq fun '(org-insert-heading))
8953 '(when orgstruct-is-++
8954 'item-body))))))))
8955 (if fallback
8956 (let* ((orgstruct-mode)
8957 (binding
8958 (loop with key = ,key
8959 for rep in '(nil
8960 ("<tab>" . "TAB")
8961 ("<return>" . "RET")
8962 ("<escape>" . "ESC")
8963 ("<delete>" . "DEL"))
8965 (when rep
8966 (setq key (read-kbd-macro
8967 (let ((case-fold-search))
8968 (replace-regexp-in-string
8969 (regexp-quote (car rep))
8970 (cdr rep)
8971 (key-description key))))))
8972 thereis (key-binding key))))
8973 (if (keymapp binding)
8974 (set-temporary-overlay-map binding)
8975 (let ((func (or binding
8976 (unless disable
8977 'orgstruct-error))))
8978 (when func
8979 (call-interactively func)))))
8980 (org-run-like-in-org-mode
8981 (lambda ()
8982 (interactive)
8983 (let* ,bindings
8984 (call-interactively ',fun)))))))))
8985 name))
8987 (defun org-contextualize-keys (alist contexts)
8988 "Return valid elements in ALIST depending on CONTEXTS.
8990 `org-agenda-custom-commands' or `org-capture-templates' are the
8991 values used for ALIST, and `org-agenda-custom-commands-contexts'
8992 or `org-capture-templates-contexts' are the associated contexts
8993 definitions."
8994 (let ((contexts
8995 ;; normalize contexts
8996 (mapcar
8997 (lambda(c) (cond ((listp (cadr c))
8998 (list (car c) (car c) (cadr c)))
8999 ((string= "" (cadr c))
9000 (list (car c) (car c) (caddr c)))
9001 (t c))) contexts))
9002 (a alist) c r s)
9003 ;; loop over all commands or templates
9004 (while (setq c (pop a))
9005 (let (vrules repl)
9006 (cond
9007 ((not (assoc (car c) contexts))
9008 (push c r))
9009 ((and (assoc (car c) contexts)
9010 (setq vrules (org-contextualize-validate-key
9011 (car c) contexts)))
9012 (mapc (lambda (vr)
9013 (when (not (equal (car vr) (cadr vr)))
9014 (setq repl vr))) vrules)
9015 (if (not repl) (push c r)
9016 (push (cadr repl) s)
9017 (push
9018 (cons (car c)
9019 (cdr (or (assoc (cadr repl) alist)
9020 (error "Undefined key `%s' as contextual replacement for `%s'"
9021 (cadr repl) (car c)))))
9022 r))))))
9023 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9024 (delq
9026 (delete-dups
9027 (mapcar (lambda (x)
9028 (let ((tpl (car x)))
9029 (when (not (delq
9031 (mapcar (lambda(y)
9032 (equal y tpl)) s))) x)))
9033 (reverse r))))))
9035 (defun org-contextualize-validate-key (key contexts)
9036 "Check CONTEXTS for agenda or capture KEY."
9037 (let (r rr res)
9038 (while (setq r (pop contexts))
9039 (mapc
9040 (lambda (rr)
9041 (when
9042 (and (equal key (car r))
9043 (if (functionp rr) (funcall rr)
9044 (or (and (eq (car rr) 'in-file)
9045 (buffer-file-name)
9046 (string-match (cdr rr) (buffer-file-name)))
9047 (and (eq (car rr) 'in-mode)
9048 (string-match (cdr rr) (symbol-name major-mode)))
9049 (and (eq (car rr) 'in-buffer)
9050 (string-match (cdr rr) (buffer-name)))
9051 (when (and (eq (car rr) 'not-in-file)
9052 (buffer-file-name))
9053 (not (string-match (cdr rr) (buffer-file-name))))
9054 (when (eq (car rr) 'not-in-mode)
9055 (not (string-match (cdr rr) (symbol-name major-mode))))
9056 (when (eq (car rr) 'not-in-buffer)
9057 (not (string-match (cdr rr) (buffer-name)))))))
9058 (push r res)))
9059 (car (last r))))
9060 (delete-dups (delq nil res))))
9062 (defun org-context-p (&rest contexts)
9063 "Check if local context is any of CONTEXTS.
9064 Possible values in the list of contexts are `table', `headline', and `item'."
9065 (let ((pos (point)))
9066 (goto-char (point-at-bol))
9067 (prog1 (or (and (memq 'table contexts)
9068 (looking-at "[ \t]*|"))
9069 (and (memq 'headline contexts)
9070 (looking-at org-outline-regexp))
9071 (and (memq 'item contexts)
9072 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9073 (and (memq 'item-body contexts)
9074 (org-in-item-p)))
9075 (goto-char pos))))
9077 (defun org-get-local-variables ()
9078 "Return a list of all local variables in an Org mode buffer."
9079 (let (varlist)
9080 (with-current-buffer (get-buffer-create "*Org tmp*")
9081 (erase-buffer)
9082 (org-mode)
9083 (setq varlist (buffer-local-variables)))
9084 (kill-buffer "*Org tmp*")
9085 (delq nil
9086 (mapcar
9087 (lambda (x)
9088 (setq x
9089 (if (symbolp x)
9090 (list x)
9091 (list (car x) (cdr x))))
9092 (if (and (not (get (car x) 'org-state))
9093 (string-match
9094 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9095 (symbol-name (car x))))
9096 x nil))
9097 varlist))))
9099 (defun org-clone-local-variables (from-buffer &optional regexp)
9100 "Clone local variables from FROM-BUFFER.
9101 Optional argument REGEXP selects variables to clone."
9102 (mapc
9103 (lambda (pair)
9104 (and (symbolp (car pair))
9105 (or (null regexp)
9106 (string-match regexp (symbol-name (car pair))))
9107 (set (make-local-variable (car pair))
9108 (cdr pair))))
9109 (buffer-local-variables from-buffer)))
9111 ;;;###autoload
9112 (defun org-run-like-in-org-mode (cmd)
9113 "Run a command, pretending that the current buffer is in Org-mode.
9114 This will temporarily bind local variables that are typically bound in
9115 Org-mode to the values they have in Org-mode, and then interactively
9116 call CMD."
9117 (org-load-modules-maybe)
9118 (unless org-local-vars
9119 (setq org-local-vars (org-get-local-variables)))
9120 (let (binds)
9121 (dolist (var org-local-vars)
9122 (when (or (not (boundp (car var)))
9123 (eq (symbol-value (car var))
9124 (default-value (car var))))
9125 (push (list (car var) `(quote ,(cadr var))) binds)))
9126 (eval `(let ,binds
9127 (call-interactively (quote ,cmd))))))
9129 ;;;; Archiving
9131 (defun org-get-category (&optional pos force-refresh)
9132 "Get the category applying to position POS."
9133 (save-match-data
9134 (if force-refresh (org-refresh-category-properties))
9135 (let ((pos (or pos (point))))
9136 (or (get-text-property pos 'org-category)
9137 (progn (org-refresh-category-properties)
9138 (get-text-property pos 'org-category))))))
9140 (defun org-refresh-category-properties ()
9141 "Refresh category text properties in the buffer."
9142 (let ((case-fold-search t)
9143 (inhibit-read-only t)
9144 (def-cat (cond
9145 ((null org-category)
9146 (if buffer-file-name
9147 (file-name-sans-extension
9148 (file-name-nondirectory buffer-file-name))
9149 "???"))
9150 ((symbolp org-category) (symbol-name org-category))
9151 (t org-category)))
9152 beg end cat pos optionp)
9153 (org-with-silent-modifications
9154 (save-excursion
9155 (save-restriction
9156 (widen)
9157 (goto-char (point-min))
9158 (put-text-property (point) (point-max) 'org-category def-cat)
9159 (while (re-search-forward
9160 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9161 (setq pos (match-end 0)
9162 optionp (equal (char-after (match-beginning 0)) ?#)
9163 cat (org-trim (match-string 2)))
9164 (if optionp
9165 (setq beg (point-at-bol) end (point-max))
9166 (org-back-to-heading t)
9167 (setq beg (point) end (org-end-of-subtree t t)))
9168 (put-text-property beg end 'org-category cat)
9169 (put-text-property beg end 'org-category-position beg)
9170 (goto-char pos)))))))
9172 (defun org-refresh-properties (dprop tprop)
9173 "Refresh buffer text properties.
9174 DPROP is the drawer property and TPROP is the corresponding text
9175 property to set."
9176 (let ((case-fold-search t)
9177 (inhibit-read-only t) p)
9178 (org-with-silent-modifications
9179 (save-excursion
9180 (save-restriction
9181 (widen)
9182 (goto-char (point-min))
9183 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9184 (setq p (org-match-string-no-properties 1))
9185 (save-excursion
9186 (org-back-to-heading t)
9187 (put-text-property
9188 (point-at-bol) (point-at-eol) tprop p))))))))
9191 ;;;; Link Stuff
9193 ;;; Link abbreviations
9195 (defun org-link-expand-abbrev (link)
9196 "Apply replacements as defined in `org-link-abbrev-alist'."
9197 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9198 (let* ((key (match-string 1 link))
9199 (as (or (assoc key org-link-abbrev-alist-local)
9200 (assoc key org-link-abbrev-alist)))
9201 (tag (and (match-end 2) (match-string 3 link)))
9202 rpl)
9203 (if (not as)
9204 link
9205 (setq rpl (cdr as))
9206 (cond
9207 ((symbolp rpl) (funcall rpl tag))
9208 ((string-match "%(\\([^)]+\\))" rpl)
9209 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9210 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9211 ((string-match "%h" rpl)
9212 (replace-match (url-hexify-string (or tag "")) t t rpl))
9213 (t (concat rpl tag)))))
9214 link))
9216 ;;; Storing and inserting links
9218 (defvar org-insert-link-history nil
9219 "Minibuffer history for links inserted with `org-insert-link'.")
9221 (defvar org-stored-links nil
9222 "Contains the links stored with `org-store-link'.")
9224 (defvar org-store-link-plist nil
9225 "Plist with info about the most recently link created with `org-store-link'.")
9227 (defvar org-link-protocols nil
9228 "Link protocols added to Org-mode using `org-add-link-type'.")
9230 (defvar org-store-link-functions nil
9231 "List of functions that are called to create and store a link.
9232 Each function will be called in turn until one returns a non-nil
9233 value. Each function should check if it is responsible for creating
9234 this link (for example by looking at the major mode).
9235 If not, it must exit and return nil.
9236 If yes, it should return a non-nil value after a calling
9237 `org-store-link-props' with a list of properties and values.
9238 Special properties are:
9240 :type The link prefix, like \"http\". This must be given.
9241 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9242 This is obligatory as well.
9243 :description Optional default description for the second pair
9244 of brackets in an Org-mode link. The user can still change
9245 this when inserting this link into an Org-mode buffer.
9247 In addition to these, any additional properties can be specified
9248 and then used in capture templates.")
9250 (defun org-add-link-type (type &optional follow export)
9251 "Add TYPE to the list of `org-link-types'.
9252 Re-compute all regular expressions depending on `org-link-types'
9254 FOLLOW and EXPORT are two functions.
9256 FOLLOW should take the link path as the single argument and do whatever
9257 is necessary to follow the link, for example find a file or display
9258 a mail message.
9260 EXPORT should format the link path for export to one of the export formats.
9261 It should be a function accepting three arguments:
9263 path the path of the link, the text after the prefix (like \"http:\")
9264 desc the description of the link, if any, or a description added by
9265 org-export-normalize-links if there is none
9266 format the export format, a symbol like `html' or `latex' or `ascii'..
9268 The function may use the FORMAT information to return different values
9269 depending on the format. The return value will be put literally into
9270 the exported file. If the return value is nil, this means Org should
9271 do what it normally does with links which do not have EXPORT defined.
9273 Org-mode has a built-in default for exporting links. If you are happy with
9274 this default, there is no need to define an export function for the link
9275 type. For a simple example of an export function, see `org-bbdb.el'."
9276 (add-to-list 'org-link-types type t)
9277 (org-make-link-regexps)
9278 (if (assoc type org-link-protocols)
9279 (setcdr (assoc type org-link-protocols) (list follow export))
9280 (push (list type follow export) org-link-protocols)))
9282 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9283 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9285 ;;;###autoload
9286 (defun org-store-link (arg &optional ignore-region)
9287 "\\<org-mode-map>Store an org-link to the current location.
9288 This link is added to `org-stored-links' and can later be inserted
9289 into an org-buffer with \\[org-insert-link].
9291 For some link types, a prefix arg is interpreted.
9292 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9293 For file links, arg negates `org-context-in-file-links'.
9295 A double prefix arg force skipping storing functions that are not
9296 part of Org's core.
9298 When the region is active and IGNORE-REGION is nil, store each line
9299 in the region as a separate link."
9300 (interactive "P")
9301 (org-load-modules-maybe)
9302 (setq org-store-link-plist nil) ; reset
9303 (if (and (org-region-active-p) (not ignore-region))
9304 (save-excursion
9305 (let ((beg (region-beginning)) (end (region-end)))
9306 (goto-char beg)
9307 (while (< (point-at-eol) end)
9308 (funcall 'org-store-link arg t)
9309 (move-beginning-of-line 2))))
9310 (org-with-limited-levels
9311 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9312 (cond
9313 ((and (not (equal arg '(16)))
9314 (setq sfuns
9315 (delq
9316 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9317 org-store-link-functions))
9318 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9319 (or (and (cdr sfuns)
9320 (funcall (intern
9321 (completing-read "Which function for creating the link? "
9322 sfunsn t (car sfunsn)))))
9323 (funcall (caar sfuns)))
9324 (setq link (plist-get org-store-link-plist :link)
9325 desc (or (plist-get org-store-link-plist :description) link))))
9326 ((org-src-edit-buffer-p)
9327 (let (label gc)
9328 (while (or (not label)
9329 (save-excursion
9330 (save-restriction
9331 (widen)
9332 (goto-char (point-min))
9333 (re-search-forward
9334 (regexp-quote (format org-coderef-label-format label))
9335 nil t))))
9336 (when label (message "Label exists already") (sit-for 2))
9337 (setq label (read-string "Code line label: " label)))
9338 (end-of-line 1)
9339 (setq link (format org-coderef-label-format label))
9340 (setq gc (- 79 (length link)))
9341 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9342 (insert link)
9343 (setq link (concat "(" label ")") desc nil)))
9345 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9346 ;; We are in the agenda, link to referenced location
9347 (let ((m (or (get-text-property (point) 'org-hd-marker)
9348 (get-text-property (point) 'org-marker))))
9349 (when m
9350 (org-with-point-at m
9351 (setq agenda-link
9352 (if (org-called-interactively-p 'any)
9353 (call-interactively 'org-store-link)
9354 (org-store-link nil)))))))
9356 ((eq major-mode 'calendar-mode)
9357 (let ((cd (calendar-cursor-to-date)))
9358 (setq link
9359 (format-time-string
9360 (car org-time-stamp-formats)
9361 (apply 'encode-time
9362 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9363 nil nil nil))))
9364 (org-store-link-props :type "calendar" :date cd)))
9366 ((eq major-mode 'help-mode)
9367 (setq link (concat "help:" (save-excursion
9368 (goto-char (point-min))
9369 (looking-at "^[^ ]+")
9370 (match-string 0))))
9371 (org-store-link-props :type "help"))
9373 ((eq major-mode 'w3-mode)
9374 (setq cpltxt (if (and (buffer-name)
9375 (not (string-match "Untitled" (buffer-name))))
9376 (buffer-name)
9377 (url-view-url t))
9378 link (url-view-url t))
9379 (org-store-link-props :type "w3" :url (url-view-url t)))
9381 ((setq search (run-hook-with-args-until-success
9382 'org-create-file-search-functions))
9383 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9384 "::" search))
9385 (setq cpltxt (or description link)))
9387 ((eq major-mode 'image-mode)
9388 (setq cpltxt (concat "file:"
9389 (abbreviate-file-name buffer-file-name))
9390 link cpltxt)
9391 (org-store-link-props :type "image" :file buffer-file-name))
9393 ((eq major-mode 'dired-mode)
9394 ;; link to the file in the current line
9395 (let ((file (dired-get-filename nil t)))
9396 (setq file (if file
9397 (abbreviate-file-name
9398 (expand-file-name (dired-get-filename nil t)))
9399 ;; otherwise, no file so use current directory.
9400 default-directory))
9401 (setq cpltxt (concat "file:" file)
9402 link cpltxt)))
9404 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9405 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9406 (cond
9407 ((org-in-regexp "<<\\(.*?\\)>>")
9408 (setq cpltxt
9409 (concat "file:"
9410 (abbreviate-file-name
9411 (buffer-file-name (buffer-base-buffer)))
9412 "::" (match-string 1))
9413 link cpltxt))
9414 ((and (featurep 'org-id)
9415 (or (eq org-id-link-to-org-use-id t)
9416 (and (org-called-interactively-p 'any)
9417 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9418 (and (eq org-id-link-to-org-use-id
9419 'create-if-interactive-and-no-custom-id)
9420 (not custom-id))))
9421 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9422 ;; We can make a link using the ID.
9423 (setq link (condition-case nil
9424 (prog1 (org-id-store-link)
9425 (setq desc (plist-get org-store-link-plist :description)))
9426 (error
9427 ;; probably before first headline, link to file only
9428 (concat "file:"
9429 (abbreviate-file-name
9430 (buffer-file-name (buffer-base-buffer))))))))
9432 ;; Just link to current headline
9433 (setq cpltxt (concat "file:"
9434 (abbreviate-file-name
9435 (buffer-file-name (buffer-base-buffer)))))
9436 ;; Add a context search string
9437 (when (org-xor org-context-in-file-links arg)
9438 (let* ((ee (org-element-at-point))
9439 (et (org-element-type ee))
9440 (ev (plist-get (cadr ee) :value))
9441 (ek (plist-get (cadr ee) :key))
9442 (eok (and (stringp ek) (string-match "name\\|target" ek))))
9443 (setq txt (cond
9444 ((org-at-heading-p) nil)
9445 ((and (eq et 'keyword) eok) ev)
9446 ((org-region-active-p)
9447 (buffer-substring (region-beginning) (region-end)))))
9448 (when (or (null txt) (string-match "\\S-" txt))
9449 (setq cpltxt
9450 (concat cpltxt "::"
9451 (condition-case nil
9452 (org-make-org-heading-search-string txt)
9453 (error "")))
9454 desc (or (and (eq et 'keyword) eok ev)
9455 (nth 4 (ignore-errors (org-heading-components)))
9456 "NONE")))))
9457 (if (string-match "::\\'" cpltxt)
9458 (setq cpltxt (substring cpltxt 0 -2)))
9459 (setq link cpltxt))))
9461 ((buffer-file-name (buffer-base-buffer))
9462 ;; Just link to this file here.
9463 (setq cpltxt (concat "file:"
9464 (abbreviate-file-name
9465 (buffer-file-name (buffer-base-buffer)))))
9466 ;; Add a context string
9467 (when (org-xor org-context-in-file-links arg)
9468 (setq txt (if (org-region-active-p)
9469 (buffer-substring (region-beginning) (region-end))
9470 (buffer-substring (point-at-bol) (point-at-eol))))
9471 ;; Only use search option if there is some text.
9472 (when (string-match "\\S-" txt)
9473 (setq cpltxt
9474 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9475 desc "NONE")))
9476 (setq link cpltxt))
9478 ((org-called-interactively-p 'interactive)
9479 (user-error "No method for storing a link from this buffer"))
9481 (t (setq link nil)))
9483 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9484 (setq link (or link cpltxt)
9485 desc (or desc cpltxt))
9486 (cond ((equal desc "NONE") (setq desc nil))
9487 ((string-match org-bracket-link-regexp desc)
9488 (setq desc (replace-regexp-in-string
9489 org-bracket-link-regexp
9490 (concat "\\3" (if (equal (length (match-string 0 desc))
9491 (length desc)) "*" "")) desc))))
9493 (if (and (or (org-called-interactively-p 'any)
9494 executing-kbd-macro ignore-region) link)
9495 (progn
9496 (setq org-stored-links
9497 (cons (list link desc) org-stored-links))
9498 (message "Stored: %s" (or desc link))
9499 (when custom-id
9500 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9501 "::#" custom-id))
9502 (setq org-stored-links
9503 (cons (list link desc) org-stored-links))))
9504 (or agenda-link (and link (org-make-link-string link desc))))))))
9506 (defun org-store-link-props (&rest plist)
9507 "Store link properties, extract names and addresses."
9508 (let (x adr)
9509 (when (setq x (plist-get plist :from))
9510 (setq adr (mail-extract-address-components x))
9511 (setq plist (plist-put plist :fromname (car adr)))
9512 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9513 (when (setq x (plist-get plist :to))
9514 (setq adr (mail-extract-address-components x))
9515 (setq plist (plist-put plist :toname (car adr)))
9516 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9517 (let ((from (plist-get plist :from))
9518 (to (plist-get plist :to)))
9519 (when (and from to org-from-is-user-regexp)
9520 (setq plist
9521 (plist-put plist :fromto
9522 (if (string-match org-from-is-user-regexp from)
9523 (concat "to %t")
9524 (concat "from %f"))))))
9525 (setq org-store-link-plist plist))
9527 (defun org-add-link-props (&rest plist)
9528 "Add these properties to the link property list."
9529 (let (key value)
9530 (while plist
9531 (setq key (pop plist) value (pop plist))
9532 (setq org-store-link-plist
9533 (plist-put org-store-link-plist key value)))))
9535 (defun org-email-link-description (&optional fmt)
9536 "Return the description part of an email link.
9537 This takes information from `org-store-link-plist' and formats it
9538 according to FMT (default from `org-email-link-description-format')."
9539 (setq fmt (or fmt org-email-link-description-format))
9540 (let* ((p org-store-link-plist)
9541 (to (plist-get p :toaddress))
9542 (from (plist-get p :fromaddress))
9543 (table
9544 (list
9545 (cons "%c" (plist-get p :fromto))
9546 (cons "%F" (plist-get p :from))
9547 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9548 (cons "%T" (plist-get p :to))
9549 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9550 (cons "%s" (plist-get p :subject))
9551 (cons "%d" (plist-get p :date))
9552 (cons "%m" (plist-get p :message-id)))))
9553 (when (string-match "%c" fmt)
9554 ;; Check if the user wrote this message
9555 (if (and org-from-is-user-regexp from to
9556 (save-match-data (string-match org-from-is-user-regexp from)))
9557 (setq fmt (replace-match "to %t" t t fmt))
9558 (setq fmt (replace-match "from %f" t t fmt))))
9559 (org-replace-escapes fmt table)))
9561 (defun org-make-org-heading-search-string (&optional string)
9562 "Make search string for the current headline or STRING."
9563 (let ((s (or string
9564 (and (derived-mode-p 'org-mode)
9565 (save-excursion
9566 (org-back-to-heading t)
9567 (org-element-property :raw-value (org-element-at-point))))))
9568 (lines org-context-in-file-links))
9569 (or string (setq s (concat "*" s))) ; Add * for headlines
9570 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9571 (when (and string (integerp lines) (> lines 0))
9572 (let ((slines (org-split-string s "\n")))
9573 (when (< lines (length slines))
9574 (setq s (mapconcat
9575 'identity
9576 (reverse (nthcdr (- (length slines) lines)
9577 (reverse slines))) "\n")))))
9578 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9580 (defun org-make-link-string (link &optional description)
9581 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9582 (unless (string-match "\\S-" link)
9583 (error "Empty link"))
9584 (when (and description
9585 (stringp description)
9586 (not (string-match "\\S-" description)))
9587 (setq description nil))
9588 (when (stringp description)
9589 ;; Remove brackets from the description, they are fatal.
9590 (while (string-match "\\[" description)
9591 (setq description (replace-match "{" t t description)))
9592 (while (string-match "\\]" description)
9593 (setq description (replace-match "}" t t description))))
9594 (when (equal link description)
9595 ;; No description needed, it is identical
9596 (setq description nil))
9597 (when (and (not description)
9598 (not (string-match (org-image-file-name-regexp) link))
9599 (not (equal link (org-link-escape link))))
9600 (setq description (org-extract-attributes link)))
9601 (setq link
9602 (cond ((string-match (org-image-file-name-regexp) link) link)
9603 ((string-match org-link-types-re link)
9604 (concat (match-string 1 link)
9605 (org-link-escape (substring link (match-end 1)))))
9606 (t (org-link-escape link))))
9607 (concat "[[" link "]"
9608 (if description (concat "[" description "]") "")
9609 "]"))
9611 (defconst org-link-escape-chars
9612 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9613 "List of characters that should be escaped in link.
9614 This is the list that is used for internal purposes.")
9616 (defconst org-link-escape-chars-browser
9617 '(?\ )
9618 "List of escapes for characters that are problematic in links.
9619 This is the list that is used before handing over to the browser.")
9621 (defun org-link-escape (text &optional table merge)
9622 "Return percent escaped representation of TEXT.
9623 TEXT is a string with the text to escape.
9624 Optional argument TABLE is a list with characters that should be
9625 escaped. When nil, `org-link-escape-chars' is used.
9626 If optional argument MERGE is set, merge TABLE into
9627 `org-link-escape-chars'."
9628 (cond
9629 ((and table merge)
9630 (mapc (lambda (defchr)
9631 (unless (member defchr table)
9632 (setq table (cons defchr table)))) org-link-escape-chars))
9633 ((null table)
9634 (setq table org-link-escape-chars)))
9635 (mapconcat
9636 (lambda (char)
9637 (if (or (member char table)
9638 (and (or (< char 32) (= char 37) (> char 126))
9639 org-url-hexify-p))
9640 (mapconcat (lambda (sequence-element)
9641 (format "%%%.2X" sequence-element))
9642 (or (encode-coding-char char 'utf-8)
9643 (error "Unable to percent escape character: %s"
9644 (char-to-string char))) "")
9645 (char-to-string char))) text ""))
9647 (defun org-link-unescape (str)
9648 "Unhex hexified Unicode strings as returned from the JavaScript function
9649 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9650 (unless (and (null str) (string= "" str))
9651 (let ((pos 0) (case-fold-search t) unhexed)
9652 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9653 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9654 (setq str (replace-match unhexed t t str))
9655 (setq pos (+ pos (length unhexed))))))
9656 str)
9658 (defun org-link-unescape-compound (hex)
9659 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9660 Note: this function also decodes single byte encodings like
9661 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9662 (save-match-data
9663 (let* ((bytes (cdr (split-string hex "%")))
9664 (ret "")
9665 (eat 0)
9666 (sum 0))
9667 (while bytes
9668 (let* ((val (string-to-number (pop bytes) 16))
9669 (shift-xor
9670 (if (= 0 eat)
9671 (cond
9672 ((>= val 252) (cons 6 252))
9673 ((>= val 248) (cons 5 248))
9674 ((>= val 240) (cons 4 240))
9675 ((>= val 224) (cons 3 224))
9676 ((>= val 192) (cons 2 192))
9677 (t (cons 0 0)))
9678 (cons 6 128))))
9679 (if (>= val 192) (setq eat (car shift-xor)))
9680 (setq val (logxor val (cdr shift-xor)))
9681 (setq sum (+ (lsh sum (car shift-xor)) val))
9682 (if (> eat 0) (setq eat (- eat 1)))
9683 (cond
9684 ((= 0 eat) ;multi byte
9685 (setq ret (concat ret (org-char-to-string sum)))
9686 (setq sum 0))
9687 ((not bytes) ; single byte(s)
9688 (setq ret (org-link-unescape-single-byte-sequence hex))))
9689 )) ;; end (while bytes
9690 ret )))
9692 (defun org-link-unescape-single-byte-sequence (hex)
9693 "Unhexify hex-encoded single byte character sequences."
9694 (mapconcat (lambda (byte)
9695 (char-to-string (string-to-number byte 16)))
9696 (cdr (split-string hex "%")) ""))
9698 (defun org-xor (a b)
9699 "Exclusive or."
9700 (if a (not b) b))
9702 (defun org-fixup-message-id-for-http (s)
9703 "Replace special characters in a message id, so it can be used in an http query."
9704 (when (string-match "%" s)
9705 (setq s (mapconcat (lambda (c)
9706 (if (eq c ?%)
9707 "%25"
9708 (char-to-string c)))
9709 s "")))
9710 (while (string-match "<" s)
9711 (setq s (replace-match "%3C" t t s)))
9712 (while (string-match ">" s)
9713 (setq s (replace-match "%3E" t t s)))
9714 (while (string-match "@" s)
9715 (setq s (replace-match "%40" t t s)))
9718 (defun org-link-prettify (link)
9719 "Return a human-readable representation of LINK.
9720 The car of LINK must be a raw link the cdr of LINK must be either
9721 a link description or nil."
9722 (let ((desc (or (cadr link) "<no description>")))
9723 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9724 "<" (car link) ">")))
9726 ;;;###autoload
9727 (defun org-insert-link-global ()
9728 "Insert a link like Org-mode does.
9729 This command can be called in any mode to insert a link in Org-mode syntax."
9730 (interactive)
9731 (org-load-modules-maybe)
9732 (org-run-like-in-org-mode 'org-insert-link))
9734 (defun org-insert-all-links (&optional keep)
9735 "Insert all links in `org-stored-links'."
9736 (interactive "P")
9737 (let ((links (copy-sequence org-stored-links)) l)
9738 (while (setq l (if keep (pop links) (pop org-stored-links)))
9739 (insert "- ")
9740 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9741 (insert "\n"))))
9743 (defun org-link-fontify-links-to-this-file ()
9744 "Fontify links to the current file in `org-stored-links'."
9745 (let ((f (buffer-file-name)) a b)
9746 (setq a (mapcar (lambda(l)
9747 (let ((ll (car l)))
9748 (when (and (string-match "^file:\\(.+\\)::" ll)
9749 (equal f (expand-file-name (match-string 1 ll))))
9750 ll)))
9751 org-stored-links))
9752 (when (featurep 'org-id)
9753 (setq b (mapcar (lambda(l)
9754 (let ((ll (car l)))
9755 (when (and (string-match "^id:\\(.+\\)$" ll)
9756 (equal f (expand-file-name
9757 (or (org-id-find-id-file
9758 (match-string 1 ll)) ""))))
9759 ll)))
9760 org-stored-links)))
9761 (mapcar (lambda(l)
9762 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9763 (delq nil (append a b)))))
9765 (defvar org-link-links-in-this-file nil)
9766 (defun org-insert-link (&optional complete-file link-location default-description)
9767 "Insert a link. At the prompt, enter the link.
9769 Completion can be used to insert any of the link protocol prefixes like
9770 http or ftp in use.
9772 The history can be used to select a link previously stored with
9773 `org-store-link'. When the empty string is entered (i.e. if you just
9774 press RET at the prompt), the link defaults to the most recently
9775 stored link. As SPC triggers completion in the minibuffer, you need to
9776 use M-SPC or C-q SPC to force the insertion of a space character.
9778 You will also be prompted for a description, and if one is given, it will
9779 be displayed in the buffer instead of the link.
9781 If there is already a link at point, this command will allow you to edit link
9782 and description parts.
9784 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9785 be selected using completion. The path to the file will be relative to the
9786 current directory if the file is in the current directory or a subdirectory.
9787 Otherwise, the link will be the absolute path as completed in the minibuffer
9788 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9789 option `org-link-file-path-type'.
9791 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9792 the current directory or below.
9794 With three \\[universal-argument] prefixes, negate the meaning of
9795 `org-keep-stored-link-after-insertion'.
9797 If `org-make-link-description-function' is non-nil, this function will be
9798 called with the link target, and the result will be the default
9799 link description.
9801 If the LINK-LOCATION parameter is non-nil, this value will be
9802 used as the link location instead of reading one interactively.
9804 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9805 be used as the default description."
9806 (interactive "P")
9807 (let* ((wcf (current-window-configuration))
9808 (origbuf (current-buffer))
9809 (region (if (org-region-active-p)
9810 (buffer-substring (region-beginning) (region-end))))
9811 (remove (and region (list (region-beginning) (region-end))))
9812 (desc region)
9813 tmphist ; byte-compile incorrectly complains about this
9814 (link link-location)
9815 (abbrevs org-link-abbrev-alist-local)
9816 entry file all-prefixes auto-desc)
9817 (cond
9818 (link-location) ; specified by arg, just use it.
9819 ((org-in-regexp org-bracket-link-regexp 1)
9820 ;; We do have a link at point, and we are going to edit it.
9821 (setq remove (list (match-beginning 0) (match-end 0)))
9822 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9823 (setq link (read-string "Link: "
9824 (org-link-unescape
9825 (org-match-string-no-properties 1)))))
9826 ((or (org-in-regexp org-angle-link-re)
9827 (org-in-regexp org-plain-link-re))
9828 ;; Convert to bracket link
9829 (setq remove (list (match-beginning 0) (match-end 0))
9830 link (read-string "Link: "
9831 (org-remove-angle-brackets (match-string 0)))))
9832 ((member complete-file '((4) (16)))
9833 ;; Completing read for file names.
9834 (setq link (org-file-complete-link complete-file)))
9836 ;; Read link, with completion for stored links.
9837 (org-link-fontify-links-to-this-file)
9838 (org-switch-to-buffer-other-window "*Org Links*")
9839 (with-current-buffer "*Org Links*"
9840 (erase-buffer)
9841 (insert "Insert a link.
9842 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9843 (when org-stored-links
9844 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9845 (insert (mapconcat 'org-link-prettify
9846 (reverse org-stored-links) "\n")))
9847 (goto-char (point-min)))
9848 (let ((cw (selected-window)))
9849 (select-window (get-buffer-window "*Org Links*" 'visible))
9850 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9851 (unless (pos-visible-in-window-p (point-max))
9852 (org-fit-window-to-buffer))
9853 (and (window-live-p cw) (select-window cw)))
9854 ;; Fake a link history, containing the stored links.
9855 (setq tmphist (append (mapcar 'car org-stored-links)
9856 org-insert-link-history))
9857 (setq all-prefixes (append (mapcar 'car abbrevs)
9858 (mapcar 'car org-link-abbrev-alist)
9859 org-link-types))
9860 (unwind-protect
9861 (progn
9862 (setq link
9863 (org-completing-read
9864 "Link: "
9865 (append
9866 (mapcar (lambda (x) (concat x ":"))
9867 all-prefixes)
9868 (mapcar 'car org-stored-links))
9869 nil nil nil
9870 'tmphist
9871 (caar org-stored-links)))
9872 (if (not (string-match "\\S-" link))
9873 (error "No link selected"))
9874 (mapc (lambda(l)
9875 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9876 org-stored-links)
9877 (if (or (member link all-prefixes)
9878 (and (equal ":" (substring link -1))
9879 (member (substring link 0 -1) all-prefixes)
9880 (setq link (substring link 0 -1))))
9881 (setq link (with-current-buffer origbuf
9882 (org-link-try-special-completion link)))))
9883 (set-window-configuration wcf)
9884 (kill-buffer "*Org Links*"))
9885 (setq entry (assoc link org-stored-links))
9886 (or entry (push link org-insert-link-history))
9887 (setq desc (or desc (nth 1 entry)))))
9889 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9890 (not org-keep-stored-link-after-insertion))
9891 (setq org-stored-links (delq (assoc link org-stored-links)
9892 org-stored-links)))
9894 (if (string-match org-plain-link-re link)
9895 ;; URL-like link, normalize the use of angular brackets.
9896 (setq link (org-remove-angle-brackets link)))
9898 ;; Check if we are linking to the current file with a search
9899 ;; option If yes, simplify the link by using only the search
9900 ;; option.
9901 (when (and buffer-file-name
9902 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9903 (let* ((path (match-string 1 link))
9904 (case-fold-search nil)
9905 (search (match-string 2 link)))
9906 (save-match-data
9907 (if (equal (file-truename buffer-file-name) (file-truename path))
9908 ;; We are linking to this same file, with a search option
9909 (setq link search)))))
9911 ;; Check if we can/should use a relative path. If yes, simplify the link
9912 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9913 (let* ((type (match-string 1 link))
9914 (path (match-string 2 link))
9915 (origpath path)
9916 (case-fold-search nil))
9917 (cond
9918 ((or (eq org-link-file-path-type 'absolute)
9919 (equal complete-file '(16)))
9920 (setq path (abbreviate-file-name (expand-file-name path))))
9921 ((eq org-link-file-path-type 'noabbrev)
9922 (setq path (expand-file-name path)))
9923 ((eq org-link-file-path-type 'relative)
9924 (setq path (file-relative-name path)))
9926 (save-match-data
9927 (if (string-match (concat "^" (regexp-quote
9928 (expand-file-name
9929 (file-name-as-directory
9930 default-directory))))
9931 (expand-file-name path))
9932 ;; We are linking a file with relative path name.
9933 (setq path (substring (expand-file-name path)
9934 (match-end 0)))
9935 (setq path (abbreviate-file-name (expand-file-name path)))))))
9936 (setq link (concat type path))
9937 (if (equal desc origpath)
9938 (setq desc path))))
9940 (if org-make-link-description-function
9941 (setq desc
9942 (or (condition-case nil
9943 (funcall org-make-link-description-function link desc)
9944 (error (progn (message "Can't get link description from `%s'"
9945 (symbol-name org-make-link-description-function))
9946 (sit-for 2) nil)))
9947 (read-string "Description: " default-description)))
9948 (if default-description (setq desc default-description)
9949 (setq desc (or (and auto-desc desc)
9950 (read-string "Description: " desc)))))
9952 (unless (string-match "\\S-" desc) (setq desc nil))
9953 (if remove (apply 'delete-region remove))
9954 (insert (org-make-link-string link desc))))
9956 (defun org-link-try-special-completion (type)
9957 "If there is completion support for link type TYPE, offer it."
9958 (let ((fun (intern (concat "org-" type "-complete-link"))))
9959 (if (functionp fun)
9960 (funcall fun)
9961 (read-string "Link (no completion support): " (concat type ":")))))
9963 (defun org-file-complete-link (&optional arg)
9964 "Create a file link using completion."
9965 (let (file link)
9966 (setq file (org-iread-file-name "File: "))
9967 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9968 (pwd1 (file-name-as-directory (abbreviate-file-name
9969 (expand-file-name ".")))))
9970 (cond
9971 ((equal arg '(16))
9972 (setq link (concat
9973 "file:"
9974 (abbreviate-file-name (expand-file-name file)))))
9975 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9976 (setq link (concat "file:" (match-string 1 file))))
9977 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9978 (expand-file-name file))
9979 (setq link (concat
9980 "file:" (match-string 1 (expand-file-name file)))))
9981 (t (setq link (concat "file:" file)))))
9982 link))
9984 (defun org-iread-file-name (&rest args)
9985 "Read-file-name using `ido-mode' speedup if available.
9986 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9987 See `read-file-name' for a description of parameters."
9988 (org-without-partial-completion
9989 (if (and org-completion-use-ido
9990 (fboundp 'ido-read-file-name)
9991 (boundp 'ido-mode) ido-mode
9992 (listp (second args)))
9993 (let ((ido-enter-matching-directory nil))
9994 (apply 'ido-read-file-name args))
9995 (apply 'read-file-name args))))
9997 (defun org-completing-read (&rest args)
9998 "Completing-read with SPACE being a normal character."
9999 (let ((enable-recursive-minibuffers t)
10000 (minibuffer-local-completion-map
10001 (copy-keymap minibuffer-local-completion-map)))
10002 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10003 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10004 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10005 (apply 'org-icompleting-read args)))
10007 (defun org-completing-read-no-i (&rest args)
10008 (let (org-completion-use-ido org-completion-use-iswitchb)
10009 (apply 'org-completing-read args)))
10011 (defun org-iswitchb-completing-read (prompt choices &rest args)
10012 "Use iswitch as a completing-read replacement to choose from choices.
10013 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10014 from."
10015 (let* ((iswitchb-use-virtual-buffers nil)
10016 (iswitchb-make-buflist-hook
10017 (lambda ()
10018 (setq iswitchb-temp-buflist choices))))
10019 (iswitchb-read-buffer prompt)))
10021 (defun org-icompleting-read (&rest args)
10022 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10023 (org-without-partial-completion
10024 (if (and org-completion-use-ido
10025 (fboundp 'ido-completing-read)
10026 (boundp 'ido-mode) ido-mode
10027 (listp (second args)))
10028 (let ((ido-enter-matching-directory nil))
10029 (apply 'ido-completing-read (concat (car args))
10030 (if (consp (car (nth 1 args)))
10031 (mapcar 'car (nth 1 args))
10032 (nth 1 args))
10033 (cddr args)))
10034 (if (and org-completion-use-iswitchb
10035 (boundp 'iswitchb-mode) iswitchb-mode
10036 (listp (second args)))
10037 (apply 'org-iswitchb-completing-read (concat (car args))
10038 (if (consp (car (nth 1 args)))
10039 (mapcar 'car (nth 1 args))
10040 (nth 1 args))
10041 (cddr args))
10042 (apply 'completing-read args)))))
10044 (defun org-extract-attributes (s)
10045 "Extract the attributes cookie from a string and set as text property."
10046 (let (a attr (start 0) key value)
10047 (save-match-data
10048 (when (string-match "{{\\([^}]+\\)}}$" s)
10049 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10050 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10051 (setq key (match-string 1 a) value (match-string 2 a)
10052 start (match-end 0)
10053 attr (plist-put attr (intern key) value))))
10054 (org-add-props s nil 'org-attr attr))
10057 (defun org-extract-attributes-from-string (tag)
10058 (let (key value attr)
10059 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10060 (setq key (match-string 1 tag) value (match-string 2 tag)
10061 tag (replace-match "" t t tag)
10062 attr (plist-put attr (intern key) value)))
10063 (cons tag attr)))
10065 (defun org-attributes-to-string (plist)
10066 "Format a property list into an HTML attribute list."
10067 (let ((s "") key value)
10068 (while plist
10069 (setq key (pop plist) value (pop plist))
10070 (and value
10071 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10074 ;;; Opening/following a link
10076 (defvar org-link-search-failed nil)
10078 (defvar org-open-link-functions nil
10079 "Hook for functions finding a plain text link.
10080 These functions must take a single argument, the link content.
10081 They will be called for links that look like [[link text][description]]
10082 when LINK TEXT does not have a protocol like \"http:\" and does not look
10083 like a filename (e.g. \"./blue.png\").
10085 These functions will be called *before* Org attempts to resolve the
10086 link by doing text searches in the current buffer - so if you want a
10087 link \"[[target]]\" to still find \"<<target>>\", your function should
10088 handle this as a special case.
10090 When the function does handle the link, it must return a non-nil value.
10091 If it decides that it is not responsible for this link, it must return
10092 nil to indicate that that Org-mode can continue with other options
10093 like exact and fuzzy text search.")
10095 (defun org-next-link (&optional search-backward)
10096 "Move forward to the next link.
10097 If the link is in hidden text, expose it."
10098 (interactive "P")
10099 (when (and org-link-search-failed (eq this-command last-command))
10100 (goto-char (point-min))
10101 (message "Link search wrapped back to beginning of buffer"))
10102 (setq org-link-search-failed nil)
10103 (let* ((pos (point))
10104 (ct (org-context))
10105 (a (assoc :link ct))
10106 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10107 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10108 ((looking-at org-any-link-re)
10109 ;; Don't stay stuck at link without an org-link face
10110 (forward-char (if search-backward -1 1))))
10111 (if (funcall srch-fun org-any-link-re nil t)
10112 (progn
10113 (goto-char (match-beginning 0))
10114 (if (outline-invisible-p) (org-show-context)))
10115 (goto-char pos)
10116 (setq org-link-search-failed t)
10117 (message "No further link found"))))
10119 (defun org-previous-link ()
10120 "Move backward to the previous link.
10121 If the link is in hidden text, expose it."
10122 (interactive)
10123 (funcall 'org-next-link t))
10125 (defun org-translate-link (s)
10126 "Translate a link string if a translation function has been defined."
10127 (if (and org-link-translation-function
10128 (fboundp org-link-translation-function)
10129 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10130 (progn
10131 (setq s (funcall org-link-translation-function
10132 (match-string 1 s) (match-string 2 s)))
10133 (concat (car s) ":" (cdr s)))
10136 (defun org-translate-link-from-planner (type path)
10137 "Translate a link from Emacs Planner syntax so that Org can follow it.
10138 This is still an experimental function, your mileage may vary."
10139 (cond
10140 ((member type '("http" "https" "news" "ftp"))
10141 ;; standard Internet links are the same.
10142 nil)
10143 ((and (equal type "irc") (string-match "^//" path))
10144 ;; Planner has two / at the beginning of an irc link, we have 1.
10145 ;; We should have zero, actually....
10146 (setq path (substring path 1)))
10147 ((and (equal type "lisp") (string-match "^/" path))
10148 ;; Planner has a slash, we do not.
10149 (setq type "elisp" path (substring path 1)))
10150 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10151 ;; A typical message link. Planner has the id after the final slash,
10152 ;; we separate it with a hash mark
10153 (setq path (concat (match-string 1 path) "#"
10154 (org-remove-angle-brackets (match-string 2 path)))))
10156 (cons type path))
10158 (defun org-find-file-at-mouse (ev)
10159 "Open file link or URL at mouse."
10160 (interactive "e")
10161 (mouse-set-point ev)
10162 (org-open-at-point 'in-emacs))
10164 (defun org-open-at-mouse (ev)
10165 "Open file link or URL at mouse.
10166 See the docstring of `org-open-file' for details."
10167 (interactive "e")
10168 (mouse-set-point ev)
10169 (if (eq major-mode 'org-agenda-mode)
10170 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10171 (org-open-at-point))
10173 (defvar org-window-config-before-follow-link nil
10174 "The window configuration before following a link.
10175 This is saved in case the need arises to restore it.")
10177 (defvar org-open-link-marker (make-marker)
10178 "Marker pointing to the location where `org-open-at-point; was called.")
10180 ;;;###autoload
10181 (defun org-open-at-point-global ()
10182 "Follow a link like Org-mode does.
10183 This command can be called in any mode to follow a link that has
10184 Org-mode syntax."
10185 (interactive)
10186 (org-run-like-in-org-mode 'org-open-at-point))
10188 ;;;###autoload
10189 (defun org-open-link-from-string (s &optional arg reference-buffer)
10190 "Open a link in the string S, as if it was in Org-mode."
10191 (interactive "sLink: \nP")
10192 (let ((reference-buffer (or reference-buffer (current-buffer))))
10193 (with-temp-buffer
10194 (let ((org-inhibit-startup (not reference-buffer)))
10195 (org-mode)
10196 (insert s)
10197 (goto-char (point-min))
10198 (when reference-buffer
10199 (setq org-link-abbrev-alist-local
10200 (with-current-buffer reference-buffer
10201 org-link-abbrev-alist-local)))
10202 (org-open-at-point arg reference-buffer)))))
10204 (defvar org-open-at-point-functions nil
10205 "Hook that is run when following a link at point.
10207 Functions in this hook must return t if they identify and follow
10208 a link at point. If they don't find anything interesting at point,
10209 they must return nil.")
10211 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10212 (defun org-open-at-point (&optional arg reference-buffer)
10213 "Open link at or after point.
10214 If there is no link at point, this function will search forward up to
10215 the end of the current line.
10216 Normally, files will be opened by an appropriate application. If the
10217 optional prefix argument ARG is non-nil, Emacs will visit the file.
10218 With a double prefix argument, try to open outside of Emacs, in the
10219 application the system uses for this file type."
10220 (interactive "P")
10221 ;; if in a code block, then open the block's results
10222 (unless (call-interactively #'org-babel-open-src-block-result)
10223 (org-load-modules-maybe)
10224 (move-marker org-open-link-marker (point))
10225 (setq org-window-config-before-follow-link (current-window-configuration))
10226 (org-remove-occur-highlights nil nil t)
10227 (cond
10228 ((and (org-at-heading-p)
10229 (not (org-at-timestamp-p t))
10230 (not (org-in-regexp
10231 (concat org-plain-link-re "\\|"
10232 org-bracket-link-regexp "\\|"
10233 org-angle-link-re "\\|"
10234 "[ \t]:[^ \t\n]+:[ \t]*$")))
10235 (not (get-text-property (point) 'org-linked-text)))
10236 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10237 (lk0 (car lkall))
10238 (lk (if (stringp lk0) (list lk0) lk0))
10239 (lkend (cdr lkall)))
10240 (mapcar (lambda(l)
10241 (search-forward l nil lkend)
10242 (goto-char (match-beginning 0))
10243 (org-open-at-point))
10244 lk))
10245 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10246 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10247 ((and (org-at-timestamp-p t)
10248 (not (org-in-regexp org-bracket-link-regexp)))
10249 (org-follow-timestamp-link))
10250 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10251 (not (org-in-regexp org-any-link-re)))
10252 (org-footnote-action))
10254 (let (type path link line search (pos (point)))
10255 (catch 'match
10256 (save-excursion
10257 (skip-chars-forward "^]\n\r")
10258 (when (org-in-regexp org-bracket-link-regexp 1)
10259 (setq link (org-extract-attributes
10260 (org-link-unescape (org-match-string-no-properties 1))))
10261 (while (string-match " *\n *" link)
10262 (setq link (replace-match " " t t link)))
10263 (setq link (org-link-expand-abbrev link))
10264 (cond
10265 ((or (file-name-absolute-p link)
10266 (string-match "^\\.\\.?/" link))
10267 (setq type "file" path link))
10268 ((string-match org-link-re-with-space3 link)
10269 (setq type (match-string 1 link) path (match-string 2 link)))
10270 ((string-match "^help:+\\(.+\\)" link)
10271 (setq type "help" path (match-string 1 link)))
10272 (t (setq type "thisfile" path link)))
10273 (throw 'match t)))
10275 (when (get-text-property (point) 'org-linked-text)
10276 (setq type "thisfile"
10277 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10278 (1+ (point)) (point))
10279 path (buffer-substring
10280 (or (previous-single-property-change pos 'org-linked-text)
10281 (point-min))
10282 (or (next-single-property-change pos 'org-linked-text)
10283 (point-max))))
10284 (throw 'match t))
10286 (save-excursion
10287 (when (or (org-in-regexp org-angle-link-re)
10288 (let ((match (org-in-regexp org-plain-link-re)))
10289 ;; Check a plain link is not within a bracket link
10290 (and match
10291 (save-excursion
10292 (progn
10293 (goto-char (car match))
10294 (not (org-in-regexp org-bracket-link-regexp))))))
10295 (let ((line_ending (save-excursion (end-of-line) (point))))
10296 ;; We are in a line before a plain or bracket link
10297 (or (re-search-forward org-plain-link-re line_ending t)
10298 (re-search-forward org-bracket-link-regexp line_ending t))))
10299 (setq type (match-string 1)
10300 path (org-link-unescape (match-string 2)))
10301 (throw 'match t)))
10302 (save-excursion
10303 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10304 (setq type "tags"
10305 path (match-string 1))
10306 (while (string-match ":" path)
10307 (setq path (replace-match "+" t t path)))
10308 (throw 'match t)))
10309 (when (org-in-regexp "<\\([^><\n]+\\)>")
10310 (setq type "tree-match"
10311 path (match-string 1))
10312 (throw 'match t)))
10313 (unless path
10314 (user-error "No link found"))
10316 ;; switch back to reference buffer
10317 ;; needed when if called in a temporary buffer through
10318 ;; org-open-link-from-string
10319 (with-current-buffer (or reference-buffer (current-buffer))
10321 ;; Remove any trailing spaces in path
10322 (if (string-match " +\\'" path)
10323 (setq path (replace-match "" t t path)))
10324 (if (and org-link-translation-function
10325 (fboundp org-link-translation-function))
10326 ;; Check if we need to translate the link
10327 (let ((tmp (funcall org-link-translation-function type path)))
10328 (setq type (car tmp) path (cdr tmp))))
10330 (cond
10332 ((assoc type org-link-protocols)
10333 (funcall (nth 1 (assoc type org-link-protocols)) path))
10335 ((equal type "help")
10336 (let ((f-or-v (intern path)))
10337 (cond ((fboundp f-or-v)
10338 (describe-function f-or-v))
10339 ((boundp f-or-v)
10340 (describe-variable f-or-v))
10341 (t (error "Not a known function or variable")))))
10343 ((equal type "mailto")
10344 (let ((cmd (car org-link-mailto-program))
10345 (args (cdr org-link-mailto-program)) args1
10346 (address path) (subject "") a)
10347 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10348 (setq address (match-string 1 path)
10349 subject (org-link-escape (match-string 2 path))))
10350 (while args
10351 (cond
10352 ((not (stringp (car args))) (push (pop args) args1))
10353 (t (setq a (pop args))
10354 (if (string-match "%a" a)
10355 (setq a (replace-match address t t a)))
10356 (if (string-match "%s" a)
10357 (setq a (replace-match subject t t a)))
10358 (push a args1))))
10359 (apply cmd (nreverse args1))))
10361 ((member type '("http" "https" "ftp" "news"))
10362 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10363 (org-link-escape
10364 path org-link-escape-chars-browser)
10365 path))))
10367 ((string= type "doi")
10368 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10369 (org-link-escape
10370 path org-link-escape-chars-browser)
10371 path))))
10373 ((member type '("message"))
10374 (browse-url (concat type ":" path)))
10376 ((string= type "tags")
10377 (org-tags-view arg path))
10379 ((string= type "tree-match")
10380 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10382 ((string= type "file")
10383 (if (string-match "::\\([0-9]+\\)\\'" path)
10384 (setq line (string-to-number (match-string 1 path))
10385 path (substring path 0 (match-beginning 0)))
10386 (if (string-match "::\\(.+\\)\\'" path)
10387 (setq search (match-string 1 path)
10388 path (substring path 0 (match-beginning 0)))))
10389 (if (string-match "[*?{]" (file-name-nondirectory path))
10390 (dired path)
10391 (org-open-file path arg line search)))
10393 ((string= type "shell")
10394 (let ((buf (generate-new-buffer "*Org Shell Output"))
10395 (cmd path))
10396 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10397 (string-match org-confirm-shell-link-not-regexp cmd))
10398 (not org-confirm-shell-link-function)
10399 (funcall org-confirm-shell-link-function
10400 (format "Execute \"%s\" in shell? "
10401 (org-add-props cmd nil
10402 'face 'org-warning))))
10403 (progn
10404 (message "Executing %s" cmd)
10405 (shell-command cmd buf)
10406 (if (featurep 'midnight)
10407 (setq clean-buffer-list-kill-buffer-names
10408 (cons buf clean-buffer-list-kill-buffer-names))))
10409 (error "Abort"))))
10411 ((string= type "elisp")
10412 (let ((cmd path))
10413 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10414 (string-match org-confirm-elisp-link-not-regexp cmd))
10415 (not org-confirm-elisp-link-function)
10416 (funcall org-confirm-elisp-link-function
10417 (format "Execute \"%s\" as elisp? "
10418 (org-add-props cmd nil
10419 'face 'org-warning))))
10420 (message "%s => %s" cmd
10421 (if (equal (string-to-char cmd) ?\()
10422 (eval (read cmd))
10423 (call-interactively (read cmd))))
10424 (error "Abort"))))
10426 ((and (string= type "thisfile")
10427 (run-hook-with-args-until-success
10428 'org-open-link-functions path)))
10430 ((string= type "thisfile")
10431 (if arg
10432 (switch-to-buffer-other-window
10433 (org-get-buffer-for-internal-link (current-buffer)))
10434 (org-mark-ring-push))
10435 (let ((cmd `(org-link-search
10436 ,path
10437 ,(cond ((equal arg '(4)) ''occur)
10438 ((equal arg '(16)) ''org-occur))
10439 ,pos)))
10440 (condition-case nil (let ((org-link-search-inhibit-query t))
10441 (eval cmd))
10442 (error (progn (widen) (eval cmd))))))
10444 (t (browse-url-at-point)))))))
10445 (move-marker org-open-link-marker nil)
10446 (run-hook-with-args 'org-follow-link-hook)))
10448 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10449 "Offer links in the current entry and return the selected link.
10450 If there is only one link, return it.
10451 If NTH is an integer, return the NTH link found.
10452 If ZERO is a string, check also this string for a link, and if
10453 there is one, return it."
10454 (with-current-buffer buffer
10455 (save-excursion
10456 (save-restriction
10457 (widen)
10458 (goto-char marker)
10459 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10460 "\\(" org-angle-link-re "\\)\\|"
10461 "\\(" org-plain-link-re "\\)"))
10462 (cnt ?0)
10463 (in-emacs (if (integerp nth) nil nth))
10464 have-zero end links link c)
10465 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10466 (push (match-string 0 zero) links)
10467 (setq cnt (1- cnt) have-zero t))
10468 (save-excursion
10469 (org-back-to-heading t)
10470 (setq end (save-excursion (outline-next-heading) (point)))
10471 (while (re-search-forward re end t)
10472 (push (match-string 0) links))
10473 (setq links (org-uniquify (reverse links))))
10474 (cond
10475 ((null links)
10476 (message "No links"))
10477 ((equal (length links) 1)
10478 (setq link (car links)))
10479 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10480 (setq link (nth (if have-zero nth (1- nth)) links)))
10481 (t ; we have to select a link
10482 (save-excursion
10483 (save-window-excursion
10484 (delete-other-windows)
10485 (with-output-to-temp-buffer "*Select Link*"
10486 (mapc (lambda (l)
10487 (if (not (string-match org-bracket-link-regexp l))
10488 (princ (format "[%c] %s\n" (incf cnt)
10489 (org-remove-angle-brackets l)))
10490 (if (match-end 3)
10491 (princ (format "[%c] %s (%s)\n" (incf cnt)
10492 (match-string 3 l) (match-string 1 l)))
10493 (princ (format "[%c] %s\n" (incf cnt)
10494 (match-string 1 l))))))
10495 links))
10496 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10497 (message "Select link to open, RET to open all:")
10498 (setq c (read-char-exclusive))
10499 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10500 (when (equal c ?q) (error "Abort"))
10501 (if (equal c ?\C-m)
10502 (setq link links)
10503 (setq nth (- c ?0))
10504 (if have-zero (setq nth (1+ nth)))
10505 (unless (and (integerp nth) (>= (length links) nth))
10506 (error "Invalid link selection"))
10507 (setq link (nth (1- nth) links)))))
10508 (cons link end))))))
10510 ;; Add special file links that specify the way of opening
10512 (org-add-link-type "file+sys" 'org-open-file-with-system)
10513 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10514 (defun org-open-file-with-system (path)
10515 "Open file at PATH using the system way of opening it."
10516 (org-open-file path 'system))
10517 (defun org-open-file-with-emacs (path)
10518 "Open file at PATH in Emacs."
10519 (org-open-file path 'emacs))
10522 ;;; File search
10524 (defvar org-create-file-search-functions nil
10525 "List of functions to construct the right search string for a file link.
10526 These functions are called in turn with point at the location to
10527 which the link should point.
10529 A function in the hook should first test if it would like to
10530 handle this file type, for example by checking the `major-mode'
10531 or the file extension. If it decides not to handle this file, it
10532 should just return nil to give other functions a chance. If it
10533 does handle the file, it must return the search string to be used
10534 when following the link. The search string will be part of the
10535 file link, given after a double colon, and `org-open-at-point'
10536 will automatically search for it. If special measures must be
10537 taken to make the search successful, another function should be
10538 added to the companion hook `org-execute-file-search-functions',
10539 which see.
10541 A function in this hook may also use `setq' to set the variable
10542 `description' to provide a suggestion for the descriptive text to
10543 be used for this link when it gets inserted into an Org-mode
10544 buffer with \\[org-insert-link].")
10546 (defvar org-execute-file-search-functions nil
10547 "List of functions to execute a file search triggered by a link.
10549 Functions added to this hook must accept a single argument, the
10550 search string that was part of the file link, the part after the
10551 double colon. The function must first check if it would like to
10552 handle this search, for example by checking the `major-mode' or
10553 the file extension. If it decides not to handle this search, it
10554 should just return nil to give other functions a chance. If it
10555 does handle the search, it must return a non-nil value to keep
10556 other functions from trying.
10558 Each function can access the current prefix argument through the
10559 variable `current-prefix-arg'. Note that a single prefix is used
10560 to force opening a link in Emacs, so it may be good to only use a
10561 numeric or double prefix to guide the search function.
10563 In case this is needed, a function in this hook can also restore
10564 the window configuration before `org-open-at-point' was called using:
10566 (set-window-configuration org-window-config-before-follow-link)")
10568 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10569 (defun org-link-search (s &optional type avoid-pos stealth)
10570 "Search for a link search option.
10571 If S is surrounded by forward slashes, it is interpreted as a
10572 regular expression. In org-mode files, this will create an `org-occur'
10573 sparse tree. In ordinary files, `occur' will be used to list matches.
10574 If the current buffer is in `dired-mode', grep will be used to search
10575 in all files. If AVOID-POS is given, ignore matches near that position.
10577 When optional argument STEALTH is non-nil, do not modify
10578 visibility around point, thus ignoring
10579 `org-show-hierarchy-above', `org-show-following-heading' and
10580 `org-show-siblings' variables."
10581 (let ((case-fold-search t)
10582 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10583 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10584 (append '(("") (" ") ("\t") ("\n"))
10585 org-emphasis-alist)
10586 "\\|") "\\)"))
10587 (pos (point))
10588 (pre nil) (post nil)
10589 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10590 (cond
10591 ;; First check if there are any special search functions
10592 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10593 ;; Now try the builtin stuff
10594 ((and (equal (string-to-char s0) ?#)
10595 (> (length s0) 1)
10596 (save-excursion
10597 (goto-char (point-min))
10598 (and
10599 (re-search-forward
10600 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10601 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10602 (setq type 'dedicated
10603 pos (match-beginning 0))))
10604 ;; There is an exact target for this
10605 (goto-char pos)
10606 (org-back-to-heading t)))
10607 ((save-excursion
10608 (goto-char (point-min))
10609 (and
10610 (re-search-forward
10611 (concat "<<" (regexp-quote s0) ">>") nil t)
10612 (setq type 'dedicated
10613 pos (match-beginning 0))))
10614 ;; There is an exact target for this
10615 (goto-char pos))
10616 ((save-excursion
10617 (goto-char (point-min))
10618 (and
10619 (re-search-forward
10620 (format "^[ \t]*#\\+\\(?:TARGET\\|NAME\\): %s"
10621 (regexp-quote s0)) nil t)
10622 (setq type 'dedicated pos (match-beginning 0))))
10623 ;; Found an invisible target.
10624 (goto-char pos))
10625 ((and (string-match "^(\\(.*\\))$" s0)
10626 (save-excursion
10627 (goto-char (point-min))
10628 (and
10629 (re-search-forward
10630 (concat "[^[]" (regexp-quote
10631 (format org-coderef-label-format
10632 (match-string 1 s0))))
10633 nil t)
10634 (setq type 'dedicated
10635 pos (1+ (match-beginning 0))))))
10636 ;; There is a coderef target for this
10637 (goto-char pos))
10638 ((string-match "^/\\(.*\\)/$" s)
10639 ;; A regular expression
10640 (cond
10641 ((derived-mode-p 'org-mode)
10642 (org-occur (match-string 1 s)))
10643 (t (org-do-occur (match-string 1 s)))))
10644 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10645 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10646 (goto-char (point-min))
10647 (cond
10648 ((let (case-fold-search)
10649 (re-search-forward (format org-complex-heading-regexp-format
10650 (regexp-quote s))
10651 nil t))
10652 ;; OK, found a match
10653 (setq type 'dedicated)
10654 (goto-char (match-beginning 0)))
10655 ((and (not org-link-search-inhibit-query)
10656 (eq org-link-search-must-match-exact-headline 'query-to-create)
10657 (y-or-n-p "No match - create this as a new heading? "))
10658 (goto-char (point-max))
10659 (or (bolp) (newline))
10660 (insert "* " s "\n")
10661 (beginning-of-line 0))
10663 (goto-char pos)
10664 (error "No match"))))
10666 ;; A normal search string
10667 (when (equal (string-to-char s) ?*)
10668 ;; Anchor on headlines, post may include tags.
10669 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10670 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10671 s (substring s 1)))
10672 (remove-text-properties
10673 0 (length s)
10674 '(face nil mouse-face nil keymap nil fontified nil) s)
10675 ;; Make a series of regular expressions to find a match
10676 (setq words (org-split-string s "[ \n\r\t]+")
10678 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10679 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10680 "\\)" markers)
10681 re2a_ (concat "\\(" (mapconcat 'downcase words
10682 "[ \t\r\n]+") "\\)[ \t\r\n]")
10683 re2a (concat "[ \t\r\n]" re2a_)
10684 re4_ (concat "\\(" (mapconcat 'downcase words
10685 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10686 re4 (concat "[^a-zA-Z_]" re4_)
10688 re1 (concat pre re2 post)
10689 re3 (concat pre (if pre re4_ re4) post)
10690 re5 (concat pre ".*" re4)
10691 re2 (concat pre re2)
10692 re2a (concat pre (if pre re2a_ re2a))
10693 re4 (concat pre (if pre re4_ re4))
10694 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10695 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10696 re5 "\\)"
10698 (cond
10699 ((eq type 'org-occur) (org-occur reall))
10700 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10701 (t (goto-char (point-min))
10702 (setq type 'fuzzy)
10703 (if (or (and (org-search-not-self 1 re0 nil t)
10704 (setq type 'dedicated))
10705 (org-search-not-self 1 re1 nil t)
10706 (org-search-not-self 1 re2 nil t)
10707 (org-search-not-self 1 re2a nil t)
10708 (org-search-not-self 1 re3 nil t)
10709 (org-search-not-self 1 re4 nil t)
10710 (org-search-not-self 1 re5 nil t))
10711 (goto-char (match-beginning 1))
10712 (goto-char pos)
10713 (error "No match"))))))
10714 (and (derived-mode-p 'org-mode)
10715 (not stealth)
10716 (org-show-context 'link-search))
10717 type))
10719 (defun org-search-not-self (group &rest args)
10720 "Execute `re-search-forward', but only accept matches that do not
10721 enclose the position of `org-open-link-marker'."
10722 (let ((m org-open-link-marker))
10723 (catch 'exit
10724 (while (apply 're-search-forward args)
10725 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10726 (goto-char (match-end group))
10727 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10728 (> (match-beginning 0) (marker-position m))
10729 (< (match-end 0) (marker-position m)))
10730 (save-match-data
10731 (or (not (org-in-regexp
10732 org-bracket-link-analytic-regexp 1))
10733 (not (match-end 4)) ; no description
10734 (and (<= (match-beginning 4) (point))
10735 (>= (match-end 4) (point))))))
10736 (throw 'exit (point))))))))
10738 (defun org-get-buffer-for-internal-link (buffer)
10739 "Return a buffer to be used for displaying the link target of internal links."
10740 (cond
10741 ((not org-display-internal-link-with-indirect-buffer)
10742 buffer)
10743 ((string-match "(Clone)$" (buffer-name buffer))
10744 (message "Buffer is already a clone, not making another one")
10745 ;; we also do not modify visibility in this case
10746 buffer)
10747 (t ; make a new indirect buffer for displaying the link
10748 (let* ((bn (buffer-name buffer))
10749 (ibn (concat bn "(Clone)"))
10750 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10751 (with-current-buffer ib (org-overview))
10752 ib))))
10754 (defun org-do-occur (regexp &optional cleanup)
10755 "Call the Emacs command `occur'.
10756 If CLEANUP is non-nil, remove the printout of the regular expression
10757 in the *Occur* buffer. This is useful if the regex is long and not useful
10758 to read."
10759 (occur regexp)
10760 (when cleanup
10761 (let ((cwin (selected-window)) win beg end)
10762 (when (setq win (get-buffer-window "*Occur*"))
10763 (select-window win))
10764 (goto-char (point-min))
10765 (when (re-search-forward "match[a-z]+" nil t)
10766 (setq beg (match-end 0))
10767 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10768 (setq end (1- (match-beginning 0)))))
10769 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10770 (goto-char (point-min))
10771 (select-window cwin))))
10773 ;;; The mark ring for links jumps
10775 (defvar org-mark-ring nil
10776 "Mark ring for positions before jumps in Org-mode.")
10777 (defvar org-mark-ring-last-goto nil
10778 "Last position in the mark ring used to go back.")
10779 ;; Fill and close the ring
10780 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10781 (loop for i from 1 to org-mark-ring-length do
10782 (push (make-marker) org-mark-ring))
10783 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10784 org-mark-ring)
10786 (defun org-mark-ring-push (&optional pos buffer)
10787 "Put the current position or POS into the mark ring and rotate it."
10788 (interactive)
10789 (setq pos (or pos (point)))
10790 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10791 (move-marker (car org-mark-ring)
10792 (or pos (point))
10793 (or buffer (current-buffer)))
10794 (message "%s"
10795 (substitute-command-keys
10796 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10798 (defun org-mark-ring-goto (&optional n)
10799 "Jump to the previous position in the mark ring.
10800 With prefix arg N, jump back that many stored positions. When
10801 called several times in succession, walk through the entire ring.
10802 Org-mode commands jumping to a different position in the current file,
10803 or to another Org-mode file, automatically push the old position
10804 onto the ring."
10805 (interactive "p")
10806 (let (p m)
10807 (if (eq last-command this-command)
10808 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10809 (setq p org-mark-ring))
10810 (setq org-mark-ring-last-goto p)
10811 (setq m (car p))
10812 (org-pop-to-buffer-same-window (marker-buffer m))
10813 (goto-char m)
10814 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10816 (defun org-remove-angle-brackets (s)
10817 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10818 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10820 (defun org-add-angle-brackets (s)
10821 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10822 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10824 (defun org-remove-double-quotes (s)
10825 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10826 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10829 ;;; Following specific links
10831 (defun org-follow-timestamp-link ()
10832 "Open an agenda view for the time-stamp date/range at point."
10833 (cond
10834 ((org-at-date-range-p t)
10835 (let ((org-agenda-start-on-weekday)
10836 (t1 (match-string 1))
10837 (t2 (match-string 2)) tt1 tt2)
10838 (setq tt1 (time-to-days (org-time-string-to-time t1))
10839 tt2 (time-to-days (org-time-string-to-time t2)))
10840 (let ((org-agenda-buffer-tmp-name
10841 (format "*Org Agenda(a:%s)"
10842 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10843 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10844 ((org-at-timestamp-p t)
10845 (let ((org-agenda-buffer-tmp-name
10846 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10847 (org-agenda-list nil (time-to-days (org-time-string-to-time
10848 (substring (match-string 1) 0 10)))
10849 1)))
10850 (t (error "This should not happen"))))
10853 ;;; Following file links
10854 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10855 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10856 (declare-function mailcap-mime-info
10857 "mailcap" (string &optional request no-decode))
10858 (defvar org-wait nil)
10859 (defun org-open-file (path &optional in-emacs line search)
10860 "Open the file at PATH.
10861 First, this expands any special file name abbreviations. Then the
10862 configuration variable `org-file-apps' is checked if it contains an
10863 entry for this file type, and if yes, the corresponding command is launched.
10865 If no application is found, Emacs simply visits the file.
10867 With optional prefix argument IN-EMACS, Emacs will visit the file.
10868 With a double \\[universal-argument] \\[universal-argument] \
10869 prefix arg, Org tries to avoid opening in Emacs
10870 and to use an external application to visit the file.
10872 Optional LINE specifies a line to go to, optional SEARCH a string
10873 to search for. If LINE or SEARCH is given, the file will be
10874 opened in Emacs, unless an entry from org-file-apps that makes
10875 use of groups in a regexp matches.
10877 If you want to change the way frames are used when following a
10878 link, please customize `org-link-frame-setup'.
10880 If the file does not exist, an error is thrown."
10881 (let* ((file (if (equal path "")
10882 buffer-file-name
10883 (substitute-in-file-name (expand-file-name path))))
10884 (file-apps (append org-file-apps (org-default-apps)))
10885 (apps (org-remove-if
10886 'org-file-apps-entry-match-against-dlink-p file-apps))
10887 (apps-dlink (org-remove-if-not
10888 'org-file-apps-entry-match-against-dlink-p file-apps))
10889 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10890 (dirp (if remp nil (file-directory-p file)))
10891 (file (if (and dirp org-open-directory-means-index-dot-org)
10892 (concat (file-name-as-directory file) "index.org")
10893 file))
10894 (a-m-a-p (assq 'auto-mode apps))
10895 (dfile (downcase file))
10896 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10897 (link (cond ((and (eq line nil)
10898 (eq search nil))
10899 file)
10900 (line
10901 (concat file "::" (number-to-string line)))
10902 (search
10903 (concat file "::" search))))
10904 (dlink (downcase link))
10905 (old-buffer (current-buffer))
10906 (old-pos (point))
10907 (old-mode major-mode)
10908 ext cmd link-match-data)
10909 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10910 (setq ext (match-string 1 dfile))
10911 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10912 (setq ext (match-string 1 dfile))))
10913 (cond
10914 ((member in-emacs '((16) system))
10915 (setq cmd (cdr (assoc 'system apps))))
10916 (in-emacs (setq cmd 'emacs))
10918 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10919 (and dirp (cdr (assoc 'directory apps)))
10920 ; first, try matching against apps-dlink
10921 ; if we get a match here, store the match data for later
10922 (let ((match (assoc-default dlink apps-dlink
10923 'string-match)))
10924 (if match
10925 (progn (setq link-match-data (match-data))
10926 match)
10927 (progn (setq in-emacs (or in-emacs line search))
10928 nil))) ; if we have no match in apps-dlink,
10929 ; always open the file in emacs if line or search
10930 ; is given (for backwards compatibility)
10931 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10932 'string-match)
10933 (cdr (assoc ext apps))
10934 (cdr (assoc t apps))))))
10935 (when (eq cmd 'system)
10936 (setq cmd (cdr (assoc 'system apps))))
10937 (when (eq cmd 'default)
10938 (setq cmd (cdr (assoc t apps))))
10939 (when (eq cmd 'mailcap)
10940 (require 'mailcap)
10941 (mailcap-parse-mailcaps)
10942 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10943 (command (mailcap-mime-info mime-type)))
10944 (if (stringp command)
10945 (setq cmd command)
10946 (setq cmd 'emacs))))
10947 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10948 (not (file-exists-p file))
10949 (not org-open-non-existing-files))
10950 (error "No such file: %s" file))
10951 (cond
10952 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10953 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10954 (while (string-match "['\"]%s['\"]" cmd)
10955 (setq cmd (replace-match "%s" t t cmd)))
10956 (while (string-match "%s" cmd)
10957 (setq cmd (replace-match
10958 (save-match-data
10959 (shell-quote-argument
10960 (convert-standard-filename file)))
10961 t t cmd)))
10963 ;; Replace "%1", "%2" etc. in command with group matches from regex
10964 (save-match-data
10965 (let ((match-index 1)
10966 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10967 (set-match-data link-match-data)
10968 (while (<= match-index number-of-groups)
10969 (let ((regex (concat "%" (number-to-string match-index)))
10970 (replace-with (match-string match-index dlink)))
10971 (while (string-match regex cmd)
10972 (setq cmd (replace-match replace-with t t cmd))))
10973 (setq match-index (+ match-index 1)))))
10975 (save-window-excursion
10976 (message "Running %s...done" cmd)
10977 (start-process-shell-command cmd nil cmd)
10978 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10979 ((or (stringp cmd)
10980 (eq cmd 'emacs))
10981 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10982 (widen)
10983 (if line (org-goto-line line)
10984 (if search (org-link-search search))))
10985 ((consp cmd)
10986 (let ((file (convert-standard-filename file)))
10987 (save-match-data
10988 (set-match-data link-match-data)
10989 (eval cmd))))
10990 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10991 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10992 (or (not (equal old-buffer (current-buffer)))
10993 (not (equal old-pos (point))))
10994 (org-mark-ring-push old-pos old-buffer))))
10996 (defun org-file-apps-entry-match-against-dlink-p (entry)
10997 "This function returns non-nil if `entry' uses a regular
10998 expression which should be matched against the whole link by
10999 org-open-file.
11001 It assumes that is the case when the entry uses a regular
11002 expression which has at least one grouping construct and the
11003 action is either a lisp form or a command string containing
11004 '%1', i.e. using at least one subexpression match as a
11005 parameter."
11006 (let ((selector (car entry))
11007 (action (cdr entry)))
11008 (if (stringp selector)
11009 (and (> (regexp-opt-depth selector) 0)
11010 (or (and (stringp action)
11011 (string-match "%[0-9]" action))
11012 (consp action)))
11013 nil)))
11015 (defun org-default-apps ()
11016 "Return the default applications for this operating system."
11017 (cond
11018 ((eq system-type 'darwin)
11019 org-file-apps-defaults-macosx)
11020 ((eq system-type 'windows-nt)
11021 org-file-apps-defaults-windowsnt)
11022 (t org-file-apps-defaults-gnu)))
11024 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11025 "Convert extensions to regular expressions in the cars of LIST.
11026 Also, weed out any non-string entries, because the return value is used
11027 only for regexp matching.
11028 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11029 point to the symbol `emacs', indicating that the file should
11030 be opened in Emacs."
11031 (append
11032 (delq nil
11033 (mapcar (lambda (x)
11034 (if (not (stringp (car x)))
11036 (if (string-match "\\W" (car x))
11038 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11039 list))
11040 (if add-auto-mode
11041 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11043 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11044 (defun org-file-remote-p (file)
11045 "Test whether FILE specifies a location on a remote system.
11046 Return non-nil if the location is indeed remote.
11048 For example, the filename \"/user@host:/foo\" specifies a location
11049 on the system \"/user@host:\"."
11050 (cond ((fboundp 'file-remote-p)
11051 (file-remote-p file))
11052 ((fboundp 'tramp-handle-file-remote-p)
11053 (tramp-handle-file-remote-p file))
11054 ((and (boundp 'ange-ftp-name-format)
11055 (string-match (car ange-ftp-name-format) file))
11056 t)))
11059 ;;;; Refiling
11061 (defun org-get-org-file ()
11062 "Read a filename, with default directory `org-directory'."
11063 (let ((default (or org-default-notes-file remember-data-file)))
11064 (read-file-name (format "File name [%s]: " default)
11065 (file-name-as-directory org-directory)
11066 default)))
11068 (defun org-notes-order-reversed-p ()
11069 "Check if the current file should receive notes in reversed order."
11070 (cond
11071 ((not org-reverse-note-order) nil)
11072 ((eq t org-reverse-note-order) t)
11073 ((not (listp org-reverse-note-order)) nil)
11074 (t (catch 'exit
11075 (let ((all org-reverse-note-order)
11076 entry)
11077 (while (setq entry (pop all))
11078 (if (string-match (car entry) buffer-file-name)
11079 (throw 'exit (cdr entry))))
11080 nil)))))
11082 (defvar org-refile-target-table nil
11083 "The list of refile targets, created by `org-refile'.")
11085 (defvar org-agenda-new-buffers nil
11086 "Buffers created to visit agenda files.")
11088 (defvar org-refile-cache nil
11089 "Cache for refile targets.")
11091 (defvar org-refile-markers nil
11092 "All the markers used for caching refile locations.")
11094 (defun org-refile-marker (pos)
11095 "Get a new refile marker, but only if caching is in use."
11096 (if (not org-refile-use-cache)
11098 (let ((m (make-marker)))
11099 (move-marker m pos)
11100 (push m org-refile-markers)
11101 m)))
11103 (defun org-refile-cache-clear ()
11104 "Clear the refile cache and disable all the markers."
11105 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11106 (setq org-refile-markers nil)
11107 (setq org-refile-cache nil)
11108 (message "Refile cache has been cleared"))
11110 (defun org-refile-cache-check-set (set)
11111 "Check if all the markers in the cache still have live buffers."
11112 (let (marker)
11113 (catch 'exit
11114 (while (and set (setq marker (nth 3 (pop set))))
11115 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11116 (when (and marker (null (marker-buffer marker)))
11117 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11118 (sit-for 3)
11119 (throw 'exit nil)))
11120 t)))
11122 (defun org-refile-cache-put (set &rest identifiers)
11123 "Push the refile targets SET into the cache, under IDENTIFIERS."
11124 (let* ((key (sha1 (prin1-to-string identifiers)))
11125 (entry (assoc key org-refile-cache)))
11126 (if entry
11127 (setcdr entry set)
11128 (push (cons key set) org-refile-cache))))
11130 (defun org-refile-cache-get (&rest identifiers)
11131 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11132 (cond
11133 ((not org-refile-cache) nil)
11134 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11136 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11137 org-refile-cache))))
11138 (and set (org-refile-cache-check-set set) set)))))
11140 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11141 "Produce a table with refile targets."
11142 (let ((case-fold-search nil)
11143 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11144 (entries (or org-refile-targets '((nil . (:level . 1)))))
11145 targets tgs txt re files f desc descre fast-path-p level pos0)
11146 (message "Getting targets...")
11147 (with-current-buffer (or default-buffer (current-buffer))
11148 (while (setq entry (pop entries))
11149 (setq files (car entry) desc (cdr entry))
11150 (setq fast-path-p nil)
11151 (cond
11152 ((null files) (setq files (list (current-buffer))))
11153 ((eq files 'org-agenda-files)
11154 (setq files (org-agenda-files 'unrestricted)))
11155 ((and (symbolp files) (fboundp files))
11156 (setq files (funcall files)))
11157 ((and (symbolp files) (boundp files))
11158 (setq files (symbol-value files))))
11159 (if (stringp files) (setq files (list files)))
11160 (cond
11161 ((eq (car desc) :tag)
11162 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11163 ((eq (car desc) :todo)
11164 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11165 ((eq (car desc) :regexp)
11166 (setq descre (cdr desc)))
11167 ((eq (car desc) :level)
11168 (setq descre (concat "^\\*\\{" (number-to-string
11169 (if org-odd-levels-only
11170 (1- (* 2 (cdr desc)))
11171 (cdr desc)))
11172 "\\}[ \t]")))
11173 ((eq (car desc) :maxlevel)
11174 (setq fast-path-p t)
11175 (setq descre (concat "^\\*\\{1," (number-to-string
11176 (if org-odd-levels-only
11177 (1- (* 2 (cdr desc)))
11178 (cdr desc)))
11179 "\\}[ \t]")))
11180 (t (error "Bad refiling target description %s" desc)))
11181 (while (setq f (pop files))
11182 (with-current-buffer
11183 (if (bufferp f) f (org-get-agenda-file-buffer f))
11185 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11186 (progn
11187 (if (bufferp f) (setq f (buffer-file-name
11188 (buffer-base-buffer f))))
11189 (setq f (and f (expand-file-name f)))
11190 (if (eq org-refile-use-outline-path 'file)
11191 (push (list (file-name-nondirectory f) f nil nil) tgs))
11192 (save-excursion
11193 (save-restriction
11194 (widen)
11195 (goto-char (point-min))
11196 (while (re-search-forward descre nil t)
11197 (goto-char (setq pos0 (point-at-bol)))
11198 (catch 'next
11199 (when org-refile-target-verify-function
11200 (save-match-data
11201 (or (funcall org-refile-target-verify-function)
11202 (throw 'next t))))
11203 (when (and (looking-at org-complex-heading-regexp)
11204 (not (member (match-string 4) excluded-entries))
11205 (match-string 4))
11206 (setq level (org-reduced-level
11207 (- (match-end 1) (match-beginning 1)))
11208 txt (org-link-display-format (match-string 4))
11209 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11210 re (format org-complex-heading-regexp-format
11211 (regexp-quote (match-string 4))))
11212 (when org-refile-use-outline-path
11213 (setq txt (mapconcat
11214 'org-protect-slash
11215 (append
11216 (if (eq org-refile-use-outline-path
11217 'file)
11218 (list (file-name-nondirectory
11219 (buffer-file-name
11220 (buffer-base-buffer))))
11221 (if (eq org-refile-use-outline-path
11222 'full-file-path)
11223 (list (buffer-file-name
11224 (buffer-base-buffer)))))
11225 (org-get-outline-path fast-path-p
11226 level txt)
11227 (list txt))
11228 "/")))
11229 (push (list txt f re (org-refile-marker (point)))
11230 tgs)))
11231 (when (= (point) pos0)
11232 ;; verification function has not moved point
11233 (goto-char (point-at-eol))))))))
11234 (when org-refile-use-cache
11235 (org-refile-cache-put tgs (buffer-file-name) descre))
11236 (setq targets (append tgs targets))
11237 ))))
11238 (message "Getting targets...done")
11239 (nreverse targets)))
11241 (defun org-protect-slash (s)
11242 (while (string-match "/" s)
11243 (setq s (replace-match "\\" t t s)))
11246 (defvar org-olpa (make-vector 20 nil))
11248 (defun org-get-outline-path (&optional fastp level heading)
11249 "Return the outline path to the current entry, as a list.
11251 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11252 routine which makes outline path derivations for an entire file,
11253 avoiding backtracing. Refile target collection makes use of that."
11254 (if fastp
11255 (progn
11256 (if (> level 19)
11257 (error "Outline path failure, more than 19 levels"))
11258 (loop for i from level upto 19 do
11259 (aset org-olpa i nil))
11260 (prog1
11261 (delq nil (append org-olpa nil))
11262 (aset org-olpa level heading)))
11263 (let (rtn case-fold-search)
11264 (save-excursion
11265 (save-restriction
11266 (widen)
11267 (while (org-up-heading-safe)
11268 (when (looking-at org-complex-heading-regexp)
11269 (push (org-match-string-no-properties 4) rtn)))
11270 rtn)))))
11272 (defun org-format-outline-path (path &optional width prefix separator)
11273 "Format the outline path PATH for display.
11274 WIDTH is the maximum number of characters that is available.
11275 PREFIX is a prefix to be included in the returned string,
11276 such as the file name.
11277 SEPARATOR is inserted between the different parts of the path,
11278 the default is \"/\"."
11279 (setq width (or width 79))
11280 (if prefix (setq width (- width (length prefix))))
11281 (if (not path)
11282 (or prefix "")
11283 (let* ((nsteps (length path))
11284 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11285 (maxwidth (if (<= total-width width)
11286 10000 ;; everything fits
11287 ;; we need to shorten the level headings
11288 (/ (- width nsteps) nsteps)))
11289 (org-odd-levels-only nil)
11290 (n 0)
11291 (total (1+ (length prefix))))
11292 (setq maxwidth (max maxwidth 10))
11293 (concat prefix
11294 (if prefix (or separator "/"))
11295 (mapconcat
11296 (lambda (h)
11297 (setq n (1+ n))
11298 (if (and (= n nsteps) (< maxwidth 10000))
11299 (setq maxwidth (- total-width total)))
11300 (if (< (length h) maxwidth)
11301 (progn (setq total (+ total (length h) 1)) h)
11302 (setq h (substring h 0 (- maxwidth 2))
11303 total (+ total maxwidth 1))
11304 (if (string-match "[ \t]+\\'" h)
11305 (setq h (substring h 0 (match-beginning 0))))
11306 (setq h (concat h "..")))
11307 (org-add-props h nil 'face
11308 (nth (% (1- n) org-n-level-faces)
11309 org-level-faces))
11311 path (or separator "/"))))))
11313 (defun org-display-outline-path (&optional file current separator just-return-string)
11314 "Display the current outline path in the echo area.
11316 If FILE is non-nil, prepend the output with the file name.
11317 If CURRENT is non-nil, append the current heading to the output.
11318 SEPARATOR is passed through to `org-format-outline-path'. It separates
11319 the different parts of the path and defaults to \"/\".
11320 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11321 (interactive "P")
11322 (let* (case-fold-search
11323 message-log-max ; Don't populate the *Messages* buffer
11324 (bfn (buffer-file-name (buffer-base-buffer)))
11325 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11326 res)
11327 (if current (setq path (append path
11328 (save-excursion
11329 (org-back-to-heading t)
11330 (if (looking-at org-complex-heading-regexp)
11331 (list (match-string 4)))))))
11332 (setq res
11333 (org-format-outline-path
11334 path
11335 (1- (frame-width))
11336 (and file bfn (concat (file-name-nondirectory bfn) separator))
11337 separator))
11338 (if just-return-string
11339 (org-no-properties res)
11340 (message "%s" res))))
11342 (defvar org-refile-history nil
11343 "History for refiling operations.")
11345 (defvar org-after-refile-insert-hook nil
11346 "Hook run after `org-refile' has inserted its stuff at the new location.
11347 Note that this is still *before* the stuff will be removed from
11348 the *old* location.")
11350 (defvar org-capture-last-stored-marker)
11351 (defvar org-refile-keep nil
11352 "Non-nil means `org-refile' will copy instead of refile.")
11354 (defun org-copy ()
11355 "Like `org-refile', but copy."
11356 (interactive)
11357 (let ((org-refile-keep t))
11358 (funcall 'org-refile nil nil nil "Copy")))
11360 (defun org-refile (&optional goto default-buffer rfloc msg)
11361 "Move the entry or entries at point to another heading.
11362 The list of target headings is compiled using the information in
11363 `org-refile-targets', which see.
11365 At the target location, the entry is filed as a subitem of the target
11366 heading. Depending on `org-reverse-note-order', the new subitem will
11367 either be the first or the last subitem.
11369 If there is an active region, all entries in that region will be moved.
11370 However, the region must fulfill the requirement that the first heading
11371 is the first one sets the top-level of the moved text - at most siblings
11372 below it are allowed.
11374 With prefix arg GOTO, the command will only visit the target location
11375 and not actually move anything.
11377 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11378 go to the location where the last refiling operation has put the subtree.
11379 With a prefix argument of `2', refile to the running clock.
11381 RFLOC can be a refile location obtained in a different way.
11383 MSG is a string to replace \"Refile\" in the default prompt with
11384 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11386 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11388 If you are using target caching (see `org-refile-use-cache'),
11389 you have to clear the target cache in order to find new targets.
11390 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11391 prefix argument (`C-u C-u C-u C-c C-w')."
11393 (interactive "P")
11394 (if (member goto '(0 (64)))
11395 (org-refile-cache-clear)
11396 (let* ((actionmsg (or msg "Refile"))
11397 (cbuf (current-buffer))
11398 (regionp (org-region-active-p))
11399 (region-start (and regionp (region-beginning)))
11400 (region-end (and regionp (region-end)))
11401 (region-length (and regionp (- region-end region-start)))
11402 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11403 pos it nbuf file re level reversed)
11404 (setq last-command nil)
11405 (when regionp
11406 (goto-char region-start)
11407 (or (bolp) (goto-char (point-at-bol)))
11408 (setq region-start (point))
11409 (unless (or (org-kill-is-subtree-p
11410 (buffer-substring region-start region-end))
11411 (prog1 org-refile-active-region-within-subtree
11412 (org-toggle-heading)))
11413 (error "The region is not a (sequence of) subtree(s)")))
11414 (if (equal goto '(16))
11415 (org-refile-goto-last-stored)
11416 (when (or
11417 (and (equal goto 2)
11418 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11419 (prog1
11420 (setq it (list (or org-clock-heading "running clock")
11421 (buffer-file-name
11422 (marker-buffer org-clock-hd-marker))
11424 (marker-position org-clock-hd-marker)))
11425 (setq goto nil)))
11426 (setq it (or rfloc
11427 (let (heading-text)
11428 (save-excursion
11429 (unless goto
11430 (org-back-to-heading t)
11431 (setq heading-text
11432 (nth 4 (org-heading-components))))
11434 (org-refile-get-location
11435 (cond (goto "Goto")
11436 (regionp (concat actionmsg " region to"))
11437 (t (concat actionmsg " subtree \""
11438 heading-text "\" to")))
11439 default-buffer
11440 (and (not (equal '(4) goto))
11441 org-refile-allow-creating-parent-nodes)
11442 goto))))))
11443 (setq file (nth 1 it)
11444 re (nth 2 it)
11445 pos (nth 3 it))
11446 (if (and (not goto)
11448 (equal (buffer-file-name) file)
11449 (if regionp
11450 (and (>= pos region-start)
11451 (<= pos region-end))
11452 (and (>= pos (point))
11453 (< pos (save-excursion
11454 (org-end-of-subtree t t))))))
11455 (error "Cannot refile to position inside the tree or region"))
11457 (setq nbuf (or (find-buffer-visiting file)
11458 (find-file-noselect file)))
11459 (if goto
11460 (progn
11461 (org-pop-to-buffer-same-window nbuf)
11462 (goto-char pos)
11463 (org-show-context 'org-goto))
11464 (if regionp
11465 (progn
11466 (org-kill-new (buffer-substring region-start region-end))
11467 (org-save-markers-in-region region-start region-end))
11468 (org-copy-subtree 1 nil t))
11469 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11470 (find-file-noselect file)))
11471 (setq reversed (org-notes-order-reversed-p))
11472 (save-excursion
11473 (save-restriction
11474 (widen)
11475 (if pos
11476 (progn
11477 (goto-char pos)
11478 (looking-at org-outline-regexp)
11479 (setq level (org-get-valid-level (funcall outline-level) 1))
11480 (goto-char
11481 (if reversed
11482 (or (outline-next-heading) (point-max))
11483 (or (save-excursion (org-get-next-sibling))
11484 (org-end-of-subtree t t)
11485 (point-max)))))
11486 (setq level 1)
11487 (if (not reversed)
11488 (goto-char (point-max))
11489 (goto-char (point-min))
11490 (or (outline-next-heading) (goto-char (point-max)))))
11491 (if (not (bolp)) (newline))
11492 (org-paste-subtree level)
11493 (when org-log-refile
11494 (org-add-log-setup 'refile nil nil 'findpos
11495 org-log-refile)
11496 (unless (eq org-log-refile 'note)
11497 (save-excursion (org-add-log-note))))
11498 (and org-auto-align-tags
11499 (let ((org-loop-over-headlines-in-active-region nil))
11500 (org-set-tags nil t)))
11501 (with-demoted-errors
11502 (bookmark-set "org-refile-last-stored"))
11503 ;; If we are refiling for capture, make sure that the
11504 ;; last-capture pointers point here
11505 (when (org-bound-and-true-p org-refile-for-capture)
11506 (with-demoted-errors
11507 (bookmark-set "org-capture-last-stored-marker"))
11508 (move-marker org-capture-last-stored-marker (point)))
11509 (if (fboundp 'deactivate-mark) (deactivate-mark))
11510 (run-hooks 'org-after-refile-insert-hook))))
11511 (unless org-refile-keep
11512 (if regionp
11513 (delete-region (point) (+ (point) region-length))
11514 (org-cut-subtree)))
11515 (when (featurep 'org-inlinetask)
11516 (org-inlinetask-remove-END-maybe))
11517 (setq org-markers-to-move nil)
11518 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11520 (defun org-refile-goto-last-stored ()
11521 "Go to the location where the last refile was stored."
11522 (interactive)
11523 (bookmark-jump "org-refile-last-stored")
11524 (message "This is the location of the last refile"))
11526 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11527 no-exclude)
11528 "Prompt the user for a refile location, using PROMPT.
11529 PROMPT should not be suffixed with a colon and a space, because
11530 this function appends the default value from
11531 `org-refile-history' automatically, if that is not empty.
11532 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11533 this is used for the GOTO interface."
11534 (let ((org-refile-targets org-refile-targets)
11535 (org-refile-use-outline-path org-refile-use-outline-path)
11536 excluded-entries)
11537 (when (and (derived-mode-p 'org-mode)
11538 (not org-refile-use-cache)
11539 (not no-exclude))
11540 (org-map-tree
11541 (lambda()
11542 (setq excluded-entries
11543 (append excluded-entries (list (org-get-heading t t)))))))
11544 (setq org-refile-target-table
11545 (org-refile-get-targets default-buffer excluded-entries)))
11546 (unless org-refile-target-table
11547 (error "No refile targets"))
11548 (let* ((cbuf (current-buffer))
11549 (partial-completion-mode nil)
11550 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11551 (cfunc (if (and org-refile-use-outline-path
11552 org-outline-path-complete-in-steps)
11553 'org-olpath-completing-read
11554 'org-icompleting-read))
11555 (extra (if org-refile-use-outline-path "/" ""))
11556 (cbnex (concat (buffer-name) extra))
11557 (filename (and cfn (expand-file-name cfn)))
11558 (tbl (mapcar
11559 (lambda (x)
11560 (if (and (not (member org-refile-use-outline-path
11561 '(file full-file-path)))
11562 (not (equal filename (nth 1 x))))
11563 (cons (concat (car x) extra " ("
11564 (file-name-nondirectory (nth 1 x)) ")")
11565 (cdr x))
11566 (cons (concat (car x) extra) (cdr x))))
11567 org-refile-target-table))
11568 (completion-ignore-case t)
11569 cdef
11570 (prompt (concat prompt
11571 (or (and (car org-refile-history)
11572 (concat " (default " (car org-refile-history) ")"))
11573 (and (assoc cbnex tbl) (setq cdef cbnex)
11574 (concat " (default " cbnex ")"))) ": "))
11575 pa answ parent-target child parent old-hist)
11576 (setq old-hist org-refile-history)
11577 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11578 nil 'org-refile-history (or cdef (car org-refile-history))))
11579 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11580 (org-refile-check-position pa)
11581 (if pa
11582 (progn
11583 (when (or (not org-refile-history)
11584 (not (eq old-hist org-refile-history))
11585 (not (equal (car pa) (car org-refile-history))))
11586 (setq org-refile-history
11587 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11588 org-refile-history
11589 (cdr org-refile-history))))
11590 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11591 (pop org-refile-history)))
11593 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11594 (progn
11595 (setq parent (match-string 1 answ)
11596 child (match-string 2 answ))
11597 (setq parent-target (or (assoc parent tbl)
11598 (assoc (concat parent "/") tbl)))
11599 (when (and parent-target
11600 (or (eq new-nodes t)
11601 (and (eq new-nodes 'confirm)
11602 (y-or-n-p (format "Create new node \"%s\"? "
11603 child)))))
11604 (org-refile-new-child parent-target child)))
11605 (error "Invalid target location")))))
11607 (declare-function org-string-nw-p "org-macs" (s))
11608 (defun org-refile-check-position (refile-pointer)
11609 "Check if the refile pointer matches the headline to which it points."
11610 (let* ((file (nth 1 refile-pointer))
11611 (re (nth 2 refile-pointer))
11612 (pos (nth 3 refile-pointer))
11613 buffer)
11614 (if (and (not (markerp pos)) (not file))
11615 (error "Please save the buffer to a file before refiling")
11616 (when (org-string-nw-p re)
11617 (setq buffer (if (markerp pos)
11618 (marker-buffer pos)
11619 (or (find-buffer-visiting file)
11620 (find-file-noselect file))))
11621 (with-current-buffer buffer
11622 (save-excursion
11623 (save-restriction
11624 (widen)
11625 (goto-char pos)
11626 (beginning-of-line 1)
11627 (unless (org-looking-at-p re)
11628 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11630 (defun org-refile-new-child (parent-target child)
11631 "Use refile target PARENT-TARGET to add new CHILD below it."
11632 (unless parent-target
11633 (error "Cannot find parent for new node"))
11634 (let ((file (nth 1 parent-target))
11635 (pos (nth 3 parent-target))
11636 level)
11637 (with-current-buffer (or (find-buffer-visiting file)
11638 (find-file-noselect file))
11639 (save-excursion
11640 (save-restriction
11641 (widen)
11642 (if pos
11643 (goto-char pos)
11644 (goto-char (point-max))
11645 (if (not (bolp)) (newline)))
11646 (when (looking-at org-outline-regexp)
11647 (setq level (funcall outline-level))
11648 (org-end-of-subtree t t))
11649 (org-back-over-empty-lines)
11650 (insert "\n" (make-string
11651 (if pos (org-get-valid-level level 1) 1) ?*)
11652 " " child "\n")
11653 (beginning-of-line 0)
11654 (list (concat (car parent-target) "/" child) file "" (point)))))))
11656 (defun org-olpath-completing-read (prompt collection &rest args)
11657 "Read an outline path like a file name."
11658 (let ((thetable collection)
11659 (org-completion-use-ido nil) ; does not work with ido.
11660 (org-completion-use-iswitchb nil)) ; or iswitchb
11661 (apply
11662 'org-icompleting-read prompt
11663 (lambda (string predicate &optional flag)
11664 (let (rtn r f (l (length string)))
11665 (cond
11666 ((eq flag nil)
11667 ;; try completion
11668 (try-completion string thetable))
11669 ((eq flag t)
11670 ;; all-completions
11671 (setq rtn (all-completions string thetable predicate))
11672 (mapcar
11673 (lambda (x)
11674 (setq r (substring x l))
11675 (if (string-match " ([^)]*)$" x)
11676 (setq f (match-string 0 x))
11677 (setq f ""))
11678 (if (string-match "/" r)
11679 (concat string (substring r 0 (match-end 0)) f)
11681 rtn))
11682 ((eq flag 'lambda)
11683 ;; exact match?
11684 (assoc string thetable)))))
11685 args)))
11687 ;;;; Dynamic blocks
11689 (defun org-find-dblock (name)
11690 "Find the first dynamic block with name NAME in the buffer.
11691 If not found, stay at current position and return nil."
11692 (let ((case-fold-search t) pos)
11693 (save-excursion
11694 (goto-char (point-min))
11695 (setq pos (and (re-search-forward
11696 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11697 (match-beginning 0))))
11698 (if pos (goto-char pos))
11699 pos))
11701 (defconst org-dblock-start-re
11702 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11703 "Matches the start line of a dynamic block, with parameters.")
11705 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11706 "Matches the end of a dynamic block.")
11708 (defun org-create-dblock (plist)
11709 "Create a dynamic block section, with parameters taken from PLIST.
11710 PLIST must contain a :name entry which is used as name of the block."
11711 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11712 (end-of-line 1)
11713 (newline))
11714 (let ((col (current-column))
11715 (name (plist-get plist :name)))
11716 (insert "#+BEGIN: " name)
11717 (while plist
11718 (if (eq (car plist) :name)
11719 (setq plist (cddr plist))
11720 (insert " " (prin1-to-string (pop plist)))))
11721 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11722 (beginning-of-line -2)))
11724 (defun org-prepare-dblock ()
11725 "Prepare dynamic block for refresh.
11726 This empties the block, puts the cursor at the insert position and returns
11727 the property list including an extra property :name with the block name."
11728 (unless (looking-at org-dblock-start-re)
11729 (error "Not at a dynamic block"))
11730 (let* ((begdel (1+ (match-end 0)))
11731 (name (org-no-properties (match-string 1)))
11732 (params (append (list :name name)
11733 (read (concat "(" (match-string 3) ")")))))
11734 (save-excursion
11735 (beginning-of-line 1)
11736 (skip-chars-forward " \t")
11737 (setq params (plist-put params :indentation-column (current-column))))
11738 (unless (re-search-forward org-dblock-end-re nil t)
11739 (error "Dynamic block not terminated"))
11740 (setq params
11741 (append params
11742 (list :content (buffer-substring
11743 begdel (match-beginning 0)))))
11744 (delete-region begdel (match-beginning 0))
11745 (goto-char begdel)
11746 (open-line 1)
11747 params))
11749 (defun org-map-dblocks (&optional command)
11750 "Apply COMMAND to all dynamic blocks in the current buffer.
11751 If COMMAND is not given, use `org-update-dblock'."
11752 (let ((cmd (or command 'org-update-dblock)))
11753 (save-excursion
11754 (goto-char (point-min))
11755 (while (re-search-forward org-dblock-start-re nil t)
11756 (goto-char (match-beginning 0))
11757 (save-excursion
11758 (condition-case nil
11759 (funcall cmd)
11760 (error (message "Error during update of dynamic block"))))
11761 (unless (re-search-forward org-dblock-end-re nil t)
11762 (error "Dynamic block not terminated"))))))
11764 (defun org-dblock-update (&optional arg)
11765 "User command for updating dynamic blocks.
11766 Update the dynamic block at point. With prefix ARG, update all dynamic
11767 blocks in the buffer."
11768 (interactive "P")
11769 (if arg
11770 (org-update-all-dblocks)
11771 (or (looking-at org-dblock-start-re)
11772 (org-beginning-of-dblock))
11773 (org-update-dblock)))
11775 (defun org-update-dblock ()
11776 "Update the dynamic block at point.
11777 This means to empty the block, parse for parameters and then call
11778 the correct writing function."
11779 (interactive)
11780 (save-window-excursion
11781 (let* ((pos (point))
11782 (line (org-current-line))
11783 (params (org-prepare-dblock))
11784 (name (plist-get params :name))
11785 (indent (plist-get params :indentation-column))
11786 (cmd (intern (concat "org-dblock-write:" name))))
11787 (message "Updating dynamic block `%s' at line %d..." name line)
11788 (funcall cmd params)
11789 (message "Updating dynamic block `%s' at line %d...done" name line)
11790 (goto-char pos)
11791 (when (and indent (> indent 0))
11792 (setq indent (make-string indent ?\ ))
11793 (save-excursion
11794 (org-beginning-of-dblock)
11795 (forward-line 1)
11796 (while (not (looking-at org-dblock-end-re))
11797 (insert indent)
11798 (beginning-of-line 2))
11799 (when (looking-at org-dblock-end-re)
11800 (and (looking-at "[ \t]+")
11801 (replace-match ""))
11802 (insert indent)))))))
11804 (defun org-beginning-of-dblock ()
11805 "Find the beginning of the dynamic block at point.
11806 Error if there is no such block at point."
11807 (let ((pos (point))
11808 beg)
11809 (end-of-line 1)
11810 (if (and (re-search-backward org-dblock-start-re nil t)
11811 (setq beg (match-beginning 0))
11812 (re-search-forward org-dblock-end-re nil t)
11813 (> (match-end 0) pos))
11814 (goto-char beg)
11815 (goto-char pos)
11816 (error "Not in a dynamic block"))))
11818 (defun org-update-all-dblocks ()
11819 "Update all dynamic blocks in the buffer.
11820 This function can be used in a hook."
11821 (interactive)
11822 (when (derived-mode-p 'org-mode)
11823 (org-map-dblocks 'org-update-dblock)))
11826 ;;;; Completion
11828 (defun org-get-export-keywords ()
11829 "Return a list of all currently understood export keywords.
11830 Export keywords include options, block names, attributes and
11831 keywords relative to each registered export back-end."
11832 (delq nil
11833 (let (keywords)
11834 (mapc
11835 (lambda (back-end)
11836 (let ((props (cdr back-end)))
11837 ;; Back-end name (for keywords, like #+LATEX:)
11838 (push (upcase (symbol-name (car back-end))) keywords)
11839 ;; Back-end options.
11840 (mapc (lambda (option) (push (cadr option) keywords))
11841 (plist-get (cdr back-end) :options-alist))))
11842 (org-bound-and-true-p org-export-registered-backends))
11843 keywords)))
11845 (defconst org-options-keywords
11846 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11847 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11848 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11849 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11850 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11852 (defcustom org-structure-template-alist
11853 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11854 "<src lang=\"?\">\n\n</src>")
11855 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11856 "<example>\n?\n</example>")
11857 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11858 "<quote>\n?\n</quote>")
11859 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11860 "<verse>\n?\n</verse>")
11861 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11862 "<verbatim>\n?\n</verbatim>")
11863 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11864 "<center>\n?\n</center>")
11865 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11866 "<literal style=\"latex\">\n?\n</literal>")
11867 ("L" "#+LaTeX: "
11868 "<literal style=\"latex\">?</literal>")
11869 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11870 "<literal style=\"html\">\n?\n</literal>")
11871 ("H" "#+HTML: "
11872 "<literal style=\"html\">?</literal>")
11873 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11874 ("A" "#+ASCII: ")
11875 ("i" "#+INDEX: ?"
11876 "#+INDEX: ?")
11877 ("I" "#+INCLUDE: %file ?"
11878 "<include file=%file markup=\"?\">"))
11879 "Structure completion elements.
11880 This is a list of abbreviation keys and values. The value gets inserted
11881 if you type `<' followed by the key and then press the completion key,
11882 usually `M-TAB'. %file will be replaced by a file name after prompting
11883 for the file using completion. The cursor will be placed at the position
11884 of the `?` in the template.
11885 There are two templates for each key, the first uses the original Org syntax,
11886 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11887 the default when the /org-mtags.el/ module has been loaded. See also the
11888 variable `org-mtags-prefer-muse-templates'."
11889 :group 'org-completion
11890 :type '(repeat
11891 (string :tag "Key")
11892 (string :tag "Template")
11893 (string :tag "Muse Template")))
11895 (defun org-try-structure-completion ()
11896 "Try to complete a structure template before point.
11897 This looks for strings like \"<e\" on an otherwise empty line and
11898 expands them."
11899 (let ((l (buffer-substring (point-at-bol) (point)))
11901 (when (and (looking-at "[ \t]*$")
11902 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11903 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11904 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11905 (match-beginning 1)) a)
11906 t)))
11908 (defun org-complete-expand-structure-template (start cell)
11909 "Expand a structure template."
11910 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11911 (rpl (nth (if musep 2 1) cell))
11912 (ind ""))
11913 (delete-region start (point))
11914 (when (string-match "\\`#\\+" rpl)
11915 (cond
11916 ((bolp))
11917 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11918 (setq ind (buffer-substring (point-at-bol) (point))))
11919 (t (newline))))
11920 (setq start (point))
11921 (if (string-match "%file" rpl)
11922 (setq rpl (replace-match
11923 (concat
11924 "\""
11925 (save-match-data
11926 (abbreviate-file-name (read-file-name "Include file: ")))
11927 "\"")
11928 t t rpl)))
11929 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11930 (concat "\n" ind)))
11931 (insert rpl)
11932 (if (re-search-backward "\\?" start t) (delete-char 1))))
11934 ;;;; TODO, DEADLINE, Comments
11936 (defun org-toggle-comment ()
11937 "Change the COMMENT state of an entry."
11938 (interactive)
11939 (save-excursion
11940 (org-back-to-heading)
11941 (let (case-fold-search)
11942 (cond
11943 ((looking-at (format org-heading-keyword-regexp-format
11944 org-comment-string))
11945 (goto-char (match-end 1))
11946 (looking-at (concat " +" org-comment-string))
11947 (replace-match "" t t)
11948 (when (eolp) (insert " ")))
11949 ((looking-at org-outline-regexp)
11950 (goto-char (match-end 0))
11951 (insert org-comment-string " "))))))
11953 (defvar org-last-todo-state-is-todo nil
11954 "This is non-nil when the last TODO state change led to a TODO state.
11955 If the last change removed the TODO tag or switched to DONE, then
11956 this is nil.")
11958 (defvar org-setting-tags nil) ; dynamically skipped
11960 (defvar org-todo-setup-filter-hook nil
11961 "Hook for functions that pre-filter todo specs.
11962 Each function takes a todo spec and returns either nil or the spec
11963 transformed into canonical form." )
11965 (defvar org-todo-get-default-hook nil
11966 "Hook for functions that get a default item for todo.
11967 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11968 nil or a string to be used for the todo mark." )
11970 (defvar org-agenda-headline-snapshot-before-repeat)
11972 (defun org-current-effective-time ()
11973 "Return current time adjusted for `org-extend-today-until' variable."
11974 (let* ((ct (org-current-time))
11975 (dct (decode-time ct))
11976 (ct1
11977 (cond
11978 (org-use-last-clock-out-time-as-effective-time
11979 (or (org-clock-get-last-clock-out-time) ct))
11980 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11981 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11982 (t ct))))
11983 ct1))
11985 (defun org-todo-yesterday (&optional arg)
11986 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11987 (interactive "P")
11988 (if (eq major-mode 'org-agenda-mode)
11989 (apply 'org-agenda-todo-yesterday arg)
11990 (let* ((hour (third (decode-time
11991 (org-current-time))))
11992 (org-extend-today-until (1+ hour)))
11993 (org-todo arg))))
11995 (defvar org-block-entry-blocking ""
11996 "First entry preventing the TODO state change.")
11998 (defun org-todo (&optional arg)
11999 "Change the TODO state of an item.
12000 The state of an item is given by a keyword at the start of the heading,
12001 like
12002 *** TODO Write paper
12003 *** DONE Call mom
12005 The different keywords are specified in the variable `org-todo-keywords'.
12006 By default the available states are \"TODO\" and \"DONE\".
12007 So for this example: when the item starts with TODO, it is changed to DONE.
12008 When it starts with DONE, the DONE is removed. And when neither TODO nor
12009 DONE are present, add TODO at the beginning of the heading.
12011 With \\[universal-argument] prefix arg, use completion to determine the new \
12012 state.
12013 With numeric prefix arg, switch to that state.
12014 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12015 keywords (nextset).
12016 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12017 With a numeric prefix arg of 0, inhibit note taking for the change.
12019 For calling through lisp, arg is also interpreted in the following way:
12020 'none -> empty state
12021 \"\"(empty string) -> switch to empty state
12022 'done -> switch to DONE
12023 'nextset -> switch to the next set of keywords
12024 'previousset -> switch to the previous set of keywords
12025 \"WAITING\" -> switch to the specified keyword, but only if it
12026 really is a member of `org-todo-keywords'."
12027 (interactive "P")
12028 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12029 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12030 'region-start-level 'region))
12031 org-loop-over-headlines-in-active-region)
12032 (org-map-entries
12033 `(org-todo ,arg)
12034 org-loop-over-headlines-in-active-region
12035 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12036 (if (equal arg '(16)) (setq arg 'nextset))
12037 (let ((org-blocker-hook org-blocker-hook)
12038 commentp
12039 case-fold-search)
12040 (when (equal arg '(64))
12041 (setq arg nil org-blocker-hook nil))
12042 (when (and org-blocker-hook
12043 (or org-inhibit-blocking
12044 (org-entry-get nil "NOBLOCKING")))
12045 (setq org-blocker-hook nil))
12046 (save-excursion
12047 (catch 'exit
12048 (org-back-to-heading t)
12049 (when (looking-at (concat "^\\*+ " org-comment-string))
12050 (org-toggle-comment)
12051 (setq commentp t))
12052 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12053 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12054 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12055 (let* ((match-data (match-data))
12056 (startpos (point-at-bol))
12057 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12058 (org-log-done org-log-done)
12059 (org-log-repeat org-log-repeat)
12060 (org-todo-log-states org-todo-log-states)
12061 (org-inhibit-logging
12062 (if (equal arg 0)
12063 (progn (setq arg nil) 'note) org-inhibit-logging))
12064 (this (match-string 1))
12065 (hl-pos (match-beginning 0))
12066 (head (org-get-todo-sequence-head this))
12067 (ass (assoc head org-todo-kwd-alist))
12068 (interpret (nth 1 ass))
12069 (done-word (nth 3 ass))
12070 (final-done-word (nth 4 ass))
12071 (org-last-state (or this ""))
12072 (completion-ignore-case t)
12073 (member (member this org-todo-keywords-1))
12074 (tail (cdr member))
12075 (org-state (cond
12076 ((and org-todo-key-trigger
12077 (or (and (equal arg '(4))
12078 (eq org-use-fast-todo-selection 'prefix))
12079 (and (not arg) org-use-fast-todo-selection
12080 (not (eq org-use-fast-todo-selection
12081 'prefix)))))
12082 ;; Use fast selection
12083 (org-fast-todo-selection))
12084 ((and (equal arg '(4))
12085 (or (not org-use-fast-todo-selection)
12086 (not org-todo-key-trigger)))
12087 ;; Read a state with completion
12088 (org-icompleting-read
12089 "State: " (mapcar 'list org-todo-keywords-1)
12090 nil t))
12091 ((eq arg 'right)
12092 (if this
12093 (if tail (car tail) nil)
12094 (car org-todo-keywords-1)))
12095 ((eq arg 'left)
12096 (if (equal member org-todo-keywords-1)
12098 (if this
12099 (nth (- (length org-todo-keywords-1)
12100 (length tail) 2)
12101 org-todo-keywords-1)
12102 (org-last org-todo-keywords-1))))
12103 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12104 (setq arg nil))) ; hack to fall back to cycling
12105 (arg
12106 ;; user or caller requests a specific state
12107 (cond
12108 ((equal arg "") nil)
12109 ((eq arg 'none) nil)
12110 ((eq arg 'done) (or done-word (car org-done-keywords)))
12111 ((eq arg 'nextset)
12112 (or (car (cdr (member head org-todo-heads)))
12113 (car org-todo-heads)))
12114 ((eq arg 'previousset)
12115 (let ((org-todo-heads (reverse org-todo-heads)))
12116 (or (car (cdr (member head org-todo-heads)))
12117 (car org-todo-heads))))
12118 ((car (member arg org-todo-keywords-1)))
12119 ((stringp arg)
12120 (error "State `%s' not valid in this file" arg))
12121 ((nth (1- (prefix-numeric-value arg))
12122 org-todo-keywords-1))))
12123 ((null member) (or head (car org-todo-keywords-1)))
12124 ((equal this final-done-word) nil) ;; -> make empty
12125 ((null tail) nil) ;; -> first entry
12126 ((memq interpret '(type priority))
12127 (if (eq this-command last-command)
12128 (car tail)
12129 (if (> (length tail) 0)
12130 (or done-word (car org-done-keywords))
12131 nil)))
12133 (car tail))))
12134 (org-state (or
12135 (run-hook-with-args-until-success
12136 'org-todo-get-default-hook org-state org-last-state)
12137 org-state))
12138 (next (if org-state (concat " " org-state " ") " "))
12139 (change-plist (list :type 'todo-state-change :from this :to org-state
12140 :position startpos))
12141 dolog now-done-p)
12142 (when org-blocker-hook
12143 (setq org-last-todo-state-is-todo
12144 (not (member this org-done-keywords)))
12145 (unless (save-excursion
12146 (save-match-data
12147 (org-with-wide-buffer
12148 (run-hook-with-args-until-failure
12149 'org-blocker-hook change-plist))))
12150 (if (org-called-interactively-p 'interactive)
12151 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12152 this org-state org-block-entry-blocking)
12153 ;; fail silently
12154 (message "TODO state change from %s to %s blocked (by \"%s\")"
12155 this org-state org-block-entry-blocking)
12156 (throw 'exit nil))))
12157 (store-match-data match-data)
12158 (replace-match next t t)
12159 (unless (pos-visible-in-window-p hl-pos)
12160 (message "TODO state changed to %s" (org-trim next)))
12161 (unless head
12162 (setq head (org-get-todo-sequence-head org-state)
12163 ass (assoc head org-todo-kwd-alist)
12164 interpret (nth 1 ass)
12165 done-word (nth 3 ass)
12166 final-done-word (nth 4 ass)))
12167 (when (memq arg '(nextset previousset))
12168 (message "Keyword-Set %d/%d: %s"
12169 (- (length org-todo-sets) -1
12170 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12171 (length org-todo-sets)
12172 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12173 (setq org-last-todo-state-is-todo
12174 (not (member org-state org-done-keywords)))
12175 (setq now-done-p (and (member org-state org-done-keywords)
12176 (not (member this org-done-keywords))))
12177 (and logging (org-local-logging logging))
12178 (when (and (or org-todo-log-states org-log-done)
12179 (not (eq org-inhibit-logging t))
12180 (not (memq arg '(nextset previousset))))
12181 ;; we need to look at recording a time and note
12182 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12183 (nth 2 (assoc this org-todo-log-states))))
12184 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12185 (setq dolog 'time))
12186 (when (and org-state
12187 (member org-state org-not-done-keywords)
12188 (not (member this org-not-done-keywords)))
12189 ;; This is now a todo state and was not one before
12190 ;; If there was a CLOSED time stamp, get rid of it.
12191 (org-add-planning-info nil nil 'closed))
12192 (when (and now-done-p org-log-done)
12193 ;; It is now done, and it was not done before
12194 (org-add-planning-info 'closed (org-current-effective-time))
12195 (if (and (not dolog) (eq 'note org-log-done))
12196 (org-add-log-setup 'done org-state this 'findpos 'note)))
12197 (when (and org-state dolog)
12198 ;; This is a non-nil state, and we need to log it
12199 (org-add-log-setup 'state org-state this 'findpos dolog)))
12200 ;; Fixup tag positioning
12201 (org-todo-trigger-tag-changes org-state)
12202 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12203 (when org-provide-todo-statistics
12204 (org-update-parent-todo-statistics))
12205 (run-hooks 'org-after-todo-state-change-hook)
12206 (if (and arg (not (member org-state org-done-keywords)))
12207 (setq head (org-get-todo-sequence-head org-state)))
12208 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12209 ;; Do we need to trigger a repeat?
12210 (when now-done-p
12211 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12212 ;; This is for the agenda, take a snapshot of the headline.
12213 (save-match-data
12214 (setq org-agenda-headline-snapshot-before-repeat
12215 (org-get-heading))))
12216 (org-auto-repeat-maybe org-state))
12217 ;; Fixup cursor location if close to the keyword
12218 (if (and (outline-on-heading-p)
12219 (not (bolp))
12220 (save-excursion (beginning-of-line 1)
12221 (looking-at org-todo-line-regexp))
12222 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12223 (progn
12224 (goto-char (or (match-end 2) (match-end 1)))
12225 (and (looking-at " ") (just-one-space))))
12226 (when org-trigger-hook
12227 (save-excursion
12228 (run-hook-with-args 'org-trigger-hook change-plist)))
12229 (when commentp (org-toggle-comment))))))))
12231 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12232 "Block turning an entry into a TODO, using the hierarchy.
12233 This checks whether the current task should be blocked from state
12234 changes. Such blocking occurs when:
12236 1. The task has children which are not all in a completed state.
12238 2. A task has a parent with the property :ORDERED:, and there
12239 are siblings prior to the current task with incomplete
12240 status.
12242 3. The parent of the task is blocked because it has siblings that should
12243 be done first, or is child of a block grandparent TODO entry."
12245 (if (not org-enforce-todo-dependencies)
12246 t ; if locally turned off don't block
12247 (catch 'dont-block
12248 ;; If this is not a todo state change, or if this entry is already DONE,
12249 ;; do not block
12250 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12251 (member (plist-get change-plist :from)
12252 (cons 'done org-done-keywords))
12253 (member (plist-get change-plist :to)
12254 (cons 'todo org-not-done-keywords))
12255 (not (plist-get change-plist :to)))
12256 (throw 'dont-block t))
12257 ;; If this task has children, and any are undone, it's blocked
12258 (save-excursion
12259 (org-back-to-heading t)
12260 (let ((this-level (funcall outline-level)))
12261 (outline-next-heading)
12262 (let ((child-level (funcall outline-level)))
12263 (while (and (not (eobp))
12264 (> child-level this-level))
12265 ;; this todo has children, check whether they are all
12266 ;; completed
12267 (if (and (not (org-entry-is-done-p))
12268 (org-entry-is-todo-p))
12269 (progn (setq org-block-entry-blocking (org-get-heading))
12270 (throw 'dont-block nil)))
12271 (outline-next-heading)
12272 (setq child-level (funcall outline-level))))))
12273 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12274 ;; any previous siblings are undone, it's blocked
12275 (save-excursion
12276 (org-back-to-heading t)
12277 (let* ((pos (point))
12278 (parent-pos (and (org-up-heading-safe) (point))))
12279 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12280 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12281 (forward-line 1)
12282 (re-search-forward org-not-done-heading-regexp pos t))
12283 (setq org-block-entry-blocking (match-string 0))
12284 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12285 ;; Search further up the hierarchy, to see if an ancestor is blocked
12286 (while t
12287 (goto-char parent-pos)
12288 (if (not (looking-at org-not-done-heading-regexp))
12289 (throw 'dont-block t)) ; do not block, parent is not a TODO
12290 (setq pos (point))
12291 (setq parent-pos (and (org-up-heading-safe) (point)))
12292 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12293 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12294 (forward-line 1)
12295 (re-search-forward org-not-done-heading-regexp pos t)
12296 (setq org-block-entry-blocking (org-get-heading)))
12297 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12299 (defcustom org-track-ordered-property-with-tag nil
12300 "Should the ORDERED property also be shown as a tag?
12301 The ORDERED property decides if an entry should require subtasks to be
12302 completed in sequence. Since a property is not very visible, setting
12303 this option means that toggling the ORDERED property with the command
12304 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12305 not relevant for the behavior, but it makes things more visible.
12307 Note that toggling the tag with tags commands will not change the property
12308 and therefore not influence behavior!
12310 This can be t, meaning the tag ORDERED should be used, It can also be a
12311 string to select a different tag for this task."
12312 :group 'org-todo
12313 :type '(choice
12314 (const :tag "No tracking" nil)
12315 (const :tag "Track with ORDERED tag" t)
12316 (string :tag "Use other tag")))
12318 (defun org-toggle-ordered-property ()
12319 "Toggle the ORDERED property of the current entry.
12320 For better visibility, you can track the value of this property with a tag.
12321 See variable `org-track-ordered-property-with-tag'."
12322 (interactive)
12323 (let* ((t1 org-track-ordered-property-with-tag)
12324 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12325 (save-excursion
12326 (org-back-to-heading)
12327 (if (org-entry-get nil "ORDERED")
12328 (progn
12329 (org-delete-property "ORDERED" "PROPERTIES")
12330 (and tag (org-toggle-tag tag 'off))
12331 (message "Subtasks can be completed in arbitrary order"))
12332 (org-entry-put nil "ORDERED" "t")
12333 (and tag (org-toggle-tag tag 'on))
12334 (message "Subtasks must be completed in sequence")))))
12336 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12337 (defun org-block-todo-from-checkboxes (change-plist)
12338 "Block turning an entry into a TODO, using checkboxes.
12339 This checks whether the current task should be blocked from state
12340 changes because there are unchecked boxes in this entry."
12341 (if (not org-enforce-todo-checkbox-dependencies)
12342 t ; if locally turned off don't block
12343 (catch 'dont-block
12344 ;; If this is not a todo state change, or if this entry is already DONE,
12345 ;; do not block
12346 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12347 (member (plist-get change-plist :from)
12348 (cons 'done org-done-keywords))
12349 (member (plist-get change-plist :to)
12350 (cons 'todo org-not-done-keywords))
12351 (not (plist-get change-plist :to)))
12352 (throw 'dont-block t))
12353 ;; If this task has checkboxes that are not checked, it's blocked
12354 (save-excursion
12355 (org-back-to-heading t)
12356 (let ((beg (point)) end)
12357 (outline-next-heading)
12358 (setq end (point))
12359 (goto-char beg)
12360 (if (org-list-search-forward
12361 (concat (org-item-beginning-re)
12362 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12363 "\\[[- ]\\]")
12364 end t)
12365 (progn
12366 (if (boundp 'org-blocked-by-checkboxes)
12367 (setq org-blocked-by-checkboxes t))
12368 (throw 'dont-block nil)))))
12369 t))) ; do not block
12371 (defun org-entry-blocked-p ()
12372 "Is the current entry blocked?"
12373 (org-with-silent-modifications
12374 (if (org-entry-get nil "NOBLOCKING")
12375 nil ;; Never block this entry
12376 (not (run-hook-with-args-until-failure
12377 'org-blocker-hook
12378 (list :type 'todo-state-change
12379 :position (point)
12380 :from 'todo
12381 :to 'done))))))
12383 (defun org-update-statistics-cookies (all)
12384 "Update the statistics cookie, either from TODO or from checkboxes.
12385 This should be called with the cursor in a line with a statistics cookie."
12386 (interactive "P")
12387 (if all
12388 (progn
12389 (org-update-checkbox-count 'all)
12390 (org-map-entries 'org-update-parent-todo-statistics))
12391 (if (not (org-at-heading-p))
12392 (org-update-checkbox-count)
12393 (let ((pos (point-marker))
12394 end l1 l2)
12395 (ignore-errors (org-back-to-heading t))
12396 (if (not (org-at-heading-p))
12397 (org-update-checkbox-count)
12398 (setq l1 (org-outline-level))
12399 (setq end (save-excursion
12400 (outline-next-heading)
12401 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12402 (point)))
12403 (if (and (save-excursion
12404 (re-search-forward
12405 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12406 (not (save-excursion (re-search-forward
12407 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12408 (org-update-checkbox-count)
12409 (if (and l2 (> l2 l1))
12410 (progn
12411 (goto-char end)
12412 (org-update-parent-todo-statistics))
12413 (goto-char pos)
12414 (beginning-of-line 1)
12415 (while (re-search-forward
12416 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12417 (point-at-eol) t)
12418 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12419 (goto-char pos)
12420 (move-marker pos nil)))))
12422 (defvar org-entry-property-inherited-from) ;; defined below
12423 (defun org-update-parent-todo-statistics ()
12424 "Update any statistics cookie in the parent of the current headline.
12425 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12426 the entire subtree and this will travel up the hierarchy and update
12427 statistics everywhere."
12428 (let* ((prop (save-excursion (org-up-heading-safe)
12429 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12430 (recursive (or (not org-hierarchical-todo-statistics)
12431 (and prop (string-match "\\<recursive\\>" prop))))
12432 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12434 (first t)
12435 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12436 level ltoggle l1 new ndel
12437 (cnt-all 0) (cnt-done 0) is-percent kwd
12438 checkbox-beg ov ovs ove cookie-present)
12439 (catch 'exit
12440 (save-excursion
12441 (beginning-of-line 1)
12442 (setq ltoggle (funcall outline-level))
12443 ;; Three situations are to consider:
12445 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12446 ;; to the top-level ancestor on the headline;
12448 ;; 2. If parent has "recursive" property, repeat up to the
12449 ;; headline setting that property, taking inheritance into
12450 ;; account;
12452 ;; 3. Else, move up to direct parent and proceed only once.
12453 (while (and (setq level (org-up-heading-safe))
12454 (or recursive first)
12455 (>= (point) lim))
12456 (setq first nil cookie-present nil)
12457 (unless (and level
12458 (not (string-match
12459 "\\<checkbox\\>"
12460 (downcase (or (org-entry-get nil "COOKIE_DATA")
12461 "")))))
12462 (throw 'exit nil))
12463 (while (re-search-forward box-re (point-at-eol) t)
12464 (setq cnt-all 0 cnt-done 0 cookie-present t)
12465 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12466 (save-match-data
12467 (unless (outline-next-heading) (throw 'exit nil))
12468 (while (and (looking-at org-complex-heading-regexp)
12469 (> (setq l1 (length (match-string 1))) level))
12470 (setq kwd (and (or recursive (= l1 ltoggle))
12471 (match-string 2)))
12472 (if (or (eq org-provide-todo-statistics 'all-headlines)
12473 (and (listp org-provide-todo-statistics)
12474 (or (member kwd org-provide-todo-statistics)
12475 (member kwd org-done-keywords))))
12476 (setq cnt-all (1+ cnt-all))
12477 (if (eq org-provide-todo-statistics t)
12478 (and kwd (setq cnt-all (1+ cnt-all)))))
12479 (and (member kwd org-done-keywords)
12480 (setq cnt-done (1+ cnt-done)))
12481 (outline-next-heading)))
12482 (setq new
12483 (if is-percent
12484 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12485 (format "[%d/%d]" cnt-done cnt-all))
12486 ndel (- (match-end 0) checkbox-beg))
12487 ;; handle overlays when updating cookie from column view
12488 (when (setq ov (car (overlays-at checkbox-beg)))
12489 (setq ovs (overlay-start ov) ove (overlay-end ov))
12490 (delete-overlay ov))
12491 (goto-char checkbox-beg)
12492 (insert new)
12493 (delete-region (point) (+ (point) ndel))
12494 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12495 (when ov (move-overlay ov ovs ove)))
12496 (when cookie-present
12497 (run-hook-with-args 'org-after-todo-statistics-hook
12498 cnt-done (- cnt-all cnt-done))))))
12499 (run-hooks 'org-todo-statistics-hook)))
12501 (defvar org-after-todo-statistics-hook nil
12502 "Hook that is called after a TODO statistics cookie has been updated.
12503 Each function is called with two arguments: the number of not-done entries
12504 and the number of done entries.
12506 For example, the following function, when added to this hook, will switch
12507 an entry to DONE when all children are done, and back to TODO when new
12508 entries are set to a TODO status. Note that this hook is only called
12509 when there is a statistics cookie in the headline!
12511 (defun org-summary-todo (n-done n-not-done)
12512 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12513 (let (org-log-done org-log-states) ; turn off logging
12514 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12517 (defvar org-todo-statistics-hook nil
12518 "Hook that is run whenever Org thinks TODO statistics should be updated.
12519 This hook runs even if there is no statistics cookie present, in which case
12520 `org-after-todo-statistics-hook' would not run.")
12522 (defun org-todo-trigger-tag-changes (state)
12523 "Apply the changes defined in `org-todo-state-tags-triggers'."
12524 (let ((l org-todo-state-tags-triggers)
12525 changes)
12526 (when (or (not state) (equal state ""))
12527 (setq changes (append changes (cdr (assoc "" l)))))
12528 (when (and (stringp state) (> (length state) 0))
12529 (setq changes (append changes (cdr (assoc state l)))))
12530 (when (member state org-not-done-keywords)
12531 (setq changes (append changes (cdr (assoc 'todo l)))))
12532 (when (member state org-done-keywords)
12533 (setq changes (append changes (cdr (assoc 'done l)))))
12534 (dolist (c changes)
12535 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12537 (defun org-local-logging (value)
12538 "Get logging settings from a property VALUE."
12539 (let* (words w a)
12540 ;; directly set the variables, they are already local.
12541 (setq org-log-done nil
12542 org-log-repeat nil
12543 org-todo-log-states nil)
12544 (setq words (org-split-string value))
12545 (while (setq w (pop words))
12546 (cond
12547 ((setq a (assoc w org-startup-options))
12548 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12549 (set (nth 1 a) (nth 2 a))))
12550 ((setq a (org-extract-log-state-settings w))
12551 (and (member (car a) org-todo-keywords-1)
12552 (push a org-todo-log-states)))))))
12554 (defun org-get-todo-sequence-head (kwd)
12555 "Return the head of the TODO sequence to which KWD belongs.
12556 If KWD is not set, check if there is a text property remembering the
12557 right sequence."
12558 (let (p)
12559 (cond
12560 ((not kwd)
12561 (or (get-text-property (point-at-bol) 'org-todo-head)
12562 (progn
12563 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12564 nil (point-at-eol)))
12565 (get-text-property p 'org-todo-head))))
12566 ((not (member kwd org-todo-keywords-1))
12567 (car org-todo-keywords-1))
12568 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12570 (defun org-fast-todo-selection ()
12571 "Fast TODO keyword selection with single keys.
12572 Returns the new TODO keyword, or nil if no state change should occur."
12573 (let* ((fulltable org-todo-key-alist)
12574 (done-keywords org-done-keywords) ;; needed for the faces.
12575 (maxlen (apply 'max (mapcar
12576 (lambda (x)
12577 (if (stringp (car x)) (string-width (car x)) 0))
12578 fulltable)))
12579 (expert nil)
12580 (fwidth (+ maxlen 3 1 3))
12581 (ncol (/ (- (window-width) 4) fwidth))
12582 tg cnt e c tbl
12583 groups ingroup)
12584 (save-excursion
12585 (save-window-excursion
12586 (if expert
12587 (set-buffer (get-buffer-create " *Org todo*"))
12588 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12589 (erase-buffer)
12590 (org-set-local 'org-done-keywords done-keywords)
12591 (setq tbl fulltable cnt 0)
12592 (while (setq e (pop tbl))
12593 (cond
12594 ((equal e '(:startgroup))
12595 (push '() groups) (setq ingroup t)
12596 (when (not (= cnt 0))
12597 (setq cnt 0)
12598 (insert "\n"))
12599 (insert "{ "))
12600 ((equal e '(:endgroup))
12601 (setq ingroup nil cnt 0)
12602 (insert "}\n"))
12603 ((equal e '(:newline))
12604 (when (not (= cnt 0))
12605 (setq cnt 0)
12606 (insert "\n")
12607 (setq e (car tbl))
12608 (while (equal (car tbl) '(:newline))
12609 (insert "\n")
12610 (setq tbl (cdr tbl)))))
12612 (setq tg (car e) c (cdr e))
12613 (if ingroup (push tg (car groups)))
12614 (setq tg (org-add-props tg nil 'face
12615 (org-get-todo-face tg)))
12616 (if (and (= cnt 0) (not ingroup)) (insert " "))
12617 (insert "[" c "] " tg (make-string
12618 (- fwidth 4 (length tg)) ?\ ))
12619 (when (= (setq cnt (1+ cnt)) ncol)
12620 (insert "\n")
12621 (if ingroup (insert " "))
12622 (setq cnt 0)))))
12623 (insert "\n")
12624 (goto-char (point-min))
12625 (if (not expert) (org-fit-window-to-buffer))
12626 (message "[a-z..]:Set [SPC]:clear")
12627 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12628 (cond
12629 ((or (= c ?\C-g)
12630 (and (= c ?q) (not (rassoc c fulltable))))
12631 (setq quit-flag t))
12632 ((= c ?\ ) nil)
12633 ((setq e (rassoc c fulltable) tg (car e))
12635 (t (setq quit-flag t)))))))
12637 (defun org-entry-is-todo-p ()
12638 (member (org-get-todo-state) org-not-done-keywords))
12640 (defun org-entry-is-done-p ()
12641 (member (org-get-todo-state) org-done-keywords))
12643 (defun org-get-todo-state ()
12644 (save-excursion
12645 (org-back-to-heading t)
12646 (and (looking-at org-todo-line-regexp)
12647 (match-end 2)
12648 (match-string 2))))
12650 (defun org-at-date-range-p (&optional inactive-ok)
12651 "Is the cursor inside a date range?"
12652 (interactive)
12653 (save-excursion
12654 (catch 'exit
12655 (let ((pos (point)))
12656 (skip-chars-backward "^[<\r\n")
12657 (skip-chars-backward "<[")
12658 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12659 (>= (match-end 0) pos)
12660 (throw 'exit t))
12661 (skip-chars-backward "^<[\r\n")
12662 (skip-chars-backward "<[")
12663 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12664 (>= (match-end 0) pos)
12665 (throw 'exit t)))
12666 nil)))
12668 (defun org-get-repeat (&optional tagline)
12669 "Check if there is a deadline/schedule with repeater in this entry."
12670 (save-match-data
12671 (save-excursion
12672 (org-back-to-heading t)
12673 (and (re-search-forward (if tagline
12674 (concat tagline "\\s-*" org-repeat-re)
12675 org-repeat-re)
12676 (org-entry-end-position) t)
12677 (match-string-no-properties 1)))))
12679 (defvar org-last-changed-timestamp)
12680 (defvar org-last-inserted-timestamp)
12681 (defvar org-log-post-message)
12682 (defvar org-log-note-purpose)
12683 (defvar org-log-note-how)
12684 (defvar org-log-note-extra)
12685 (defun org-auto-repeat-maybe (done-word)
12686 "Check if the current headline contains a repeated deadline/schedule.
12687 If yes, set TODO state back to what it was and change the base date
12688 of repeating deadline/scheduled time stamps to new date.
12689 This function is run automatically after each state change to a DONE state."
12690 ;; last-state is dynamically scoped into this function
12691 (let* ((repeat (org-get-repeat))
12692 (aa (assoc org-last-state org-todo-kwd-alist))
12693 (interpret (nth 1 aa))
12694 (head (nth 2 aa))
12695 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12696 (msg "Entry repeats: ")
12697 (org-log-done nil)
12698 (org-todo-log-states nil)
12699 re type n what ts time to-state)
12700 (when repeat
12701 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12702 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12703 org-todo-repeat-to-state))
12704 (unless (and to-state (member to-state org-todo-keywords-1))
12705 (setq to-state (if (eq interpret 'type) org-last-state head)))
12706 (org-todo to-state)
12707 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12708 (org-entry-put nil "LAST_REPEAT" (format-time-string
12709 (org-time-stamp-format t t))))
12710 (when org-log-repeat
12711 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12712 (memq 'org-add-log-note post-command-hook))
12713 ;; OK, we are already setup for some record
12714 (if (eq org-log-repeat 'note)
12715 ;; make sure we take a note, not only a time stamp
12716 (setq org-log-note-how 'note))
12717 ;; Set up for taking a record
12718 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12719 org-last-state
12720 'findpos org-log-repeat)))
12721 (org-back-to-heading t)
12722 (org-add-planning-info nil nil 'closed)
12723 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12724 org-deadline-time-regexp "\\)\\|\\("
12725 org-ts-regexp "\\)"))
12726 (while (re-search-forward
12727 re (save-excursion (outline-next-heading) (point)) t)
12728 (setq type (if (match-end 1) org-scheduled-string
12729 (if (match-end 3) org-deadline-string "Plain:"))
12730 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12731 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12732 (setq n (string-to-number (match-string 2 ts))
12733 what (match-string 3 ts))
12734 (if (equal what "w") (setq n (* n 7) what "d"))
12735 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12736 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12737 ;; Preparation, see if we need to modify the start date for the change
12738 (when (match-end 1)
12739 (setq time (save-match-data (org-time-string-to-time ts)))
12740 (cond
12741 ((equal (match-string 1 ts) ".")
12742 ;; Shift starting date to today
12743 (org-timestamp-change
12744 (- (org-today) (time-to-days time))
12745 'day))
12746 ((equal (match-string 1 ts) "+")
12747 (let ((nshiftmax 10) (nshift 0))
12748 (while (or (= nshift 0)
12749 (<= (time-to-days time)
12750 (time-to-days (current-time))))
12751 (when (= (incf nshift) nshiftmax)
12752 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12753 (error "Abort")))
12754 (org-timestamp-change n (cdr (assoc what whata)))
12755 (org-at-timestamp-p t)
12756 (setq ts (match-string 1))
12757 (setq time (save-match-data (org-time-string-to-time ts)))))
12758 (org-timestamp-change (- n) (cdr (assoc what whata)))
12759 ;; rematch, so that we have everything in place for the real shift
12760 (org-at-timestamp-p t)
12761 (setq ts (match-string 1))
12762 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12763 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12764 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12765 (setq org-log-post-message msg)
12766 (message "%s" msg))))
12768 (defun org-show-todo-tree (arg)
12769 "Make a compact tree which shows all headlines marked with TODO.
12770 The tree will show the lines where the regexp matches, and all higher
12771 headlines above the match.
12772 With a \\[universal-argument] prefix, prompt for a regexp to match.
12773 With a numeric prefix N, construct a sparse tree for the Nth element
12774 of `org-todo-keywords-1'."
12775 (interactive "P")
12776 (let ((case-fold-search nil)
12777 (kwd-re
12778 (cond ((null arg) org-not-done-regexp)
12779 ((equal arg '(4))
12780 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12781 (mapcar 'list org-todo-keywords-1))))
12782 (concat "\\("
12783 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12784 "\\)\\>")))
12785 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12786 (regexp-quote (nth (1- (prefix-numeric-value arg))
12787 org-todo-keywords-1)))
12788 (t (error "Invalid prefix argument: %s" arg)))))
12789 (message "%d TODO entries found"
12790 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12792 (defun org-deadline (arg &optional time)
12793 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12794 With one universal prefix argument, remove any deadline from the item.
12795 With two universal prefix arguments, prompt for a warning delay.
12796 With argument TIME, set the deadline at the corresponding date. TIME
12797 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12798 (interactive "P")
12799 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12800 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12801 'region-start-level 'region))
12802 org-loop-over-headlines-in-active-region)
12803 (org-map-entries
12804 `(org-deadline ',arg ,time)
12805 org-loop-over-headlines-in-active-region
12806 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12807 (let* ((old-date (org-entry-get nil "DEADLINE"))
12808 (old-date-time (if old-date (org-time-string-to-time old-date)))
12809 (repeater (and old-date
12810 (string-match
12811 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12812 old-date)
12813 (match-string 1 old-date))))
12814 (cond
12815 ((equal arg '(4))
12816 (when (and old-date org-log-redeadline)
12817 (org-add-log-setup 'deldeadline nil old-date 'findpos
12818 org-log-redeadline))
12819 (org-remove-timestamp-with-keyword org-deadline-string)
12820 (message "Item no longer has a deadline."))
12821 ((equal arg '(16))
12822 (save-excursion
12823 (if (re-search-forward
12824 org-deadline-time-regexp
12825 (save-excursion (outline-next-heading) (point)) t)
12826 (let* ((rpl0 (match-string 1))
12827 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12828 (replace-match
12829 (concat org-deadline-string
12830 " <" rpl
12831 (format " -%dd"
12832 (abs
12833 (- (time-to-days
12834 (save-match-data
12835 (org-read-date nil t nil "Warn starting from" old-date-time)))
12836 (time-to-days old-date-time))))
12837 ">") t t))
12838 (user-error "No deadline information to update"))))
12840 (org-add-planning-info 'deadline time 'closed)
12841 (when (and old-date org-log-redeadline
12842 (not (equal old-date
12843 (substring org-last-inserted-timestamp 1 -1))))
12844 (org-add-log-setup 'redeadline nil old-date 'findpos
12845 org-log-redeadline))
12846 (when repeater
12847 (save-excursion
12848 (org-back-to-heading t)
12849 (when (re-search-forward (concat org-deadline-string " "
12850 org-last-inserted-timestamp)
12851 (save-excursion
12852 (outline-next-heading) (point)) t)
12853 (goto-char (1- (match-end 0)))
12854 (insert " " repeater)
12855 (setq org-last-inserted-timestamp
12856 (concat (substring org-last-inserted-timestamp 0 -1)
12857 " " repeater
12858 (substring org-last-inserted-timestamp -1))))))
12859 (message "Deadline on %s" org-last-inserted-timestamp))))))
12861 (defun org-schedule (arg &optional time)
12862 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12863 With one universal prefix argument, remove any scheduling date from the item.
12864 With two universal prefix arguments, prompt for a delay cookie.
12865 With argument TIME, scheduled at the corresponding date. TIME can
12866 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12867 (interactive "P")
12868 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12869 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12870 'region-start-level 'region))
12871 org-loop-over-headlines-in-active-region)
12872 (org-map-entries
12873 `(org-schedule ',arg ,time)
12874 org-loop-over-headlines-in-active-region
12875 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12876 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12877 (old-date-time (if old-date (org-time-string-to-time old-date)))
12878 (repeater (and old-date
12879 (string-match
12880 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12881 old-date)
12882 (match-string 1 old-date))))
12883 (cond
12884 ((equal arg '(4))
12885 (progn
12886 (when (and old-date org-log-reschedule)
12887 (org-add-log-setup 'delschedule nil old-date 'findpos
12888 org-log-reschedule))
12889 (org-remove-timestamp-with-keyword org-scheduled-string)
12890 (message "Item is no longer scheduled.")))
12891 ((equal arg '(16))
12892 (save-excursion
12893 (if (re-search-forward
12894 org-scheduled-time-regexp
12895 (save-excursion (outline-next-heading) (point)) t)
12896 (let* ((rpl0 (match-string 1))
12897 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12898 (replace-match
12899 (concat org-scheduled-string
12900 " <" rpl
12901 (format " -%dd"
12902 (abs
12903 (- (time-to-days
12904 (save-match-data
12905 (org-read-date nil t nil "Delay until" old-date-time)))
12906 (time-to-days old-date-time))))
12907 ">") t t))
12908 (user-error "No scheduled information to update"))))
12910 (org-add-planning-info 'scheduled time 'closed)
12911 (when (and old-date org-log-reschedule
12912 (not (equal old-date
12913 (substring org-last-inserted-timestamp 1 -1))))
12914 (org-add-log-setup 'reschedule nil old-date 'findpos
12915 org-log-reschedule))
12916 (when repeater
12917 (save-excursion
12918 (org-back-to-heading t)
12919 (when (re-search-forward (concat org-scheduled-string " "
12920 org-last-inserted-timestamp)
12921 (save-excursion
12922 (outline-next-heading) (point)) t)
12923 (goto-char (1- (match-end 0)))
12924 (insert " " repeater)
12925 (setq org-last-inserted-timestamp
12926 (concat (substring org-last-inserted-timestamp 0 -1)
12927 " " repeater
12928 (substring org-last-inserted-timestamp -1))))))
12929 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12931 (defun org-get-scheduled-time (pom &optional inherit)
12932 "Get the scheduled time as a time tuple, of a format suitable
12933 for calling org-schedule with, or if there is no scheduling,
12934 returns nil."
12935 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12936 (when time
12937 (apply 'encode-time (org-parse-time-string time)))))
12939 (defun org-get-deadline-time (pom &optional inherit)
12940 "Get the deadline as a time tuple, of a format suitable for
12941 calling org-deadline with, or if there is no scheduling, returns
12942 nil."
12943 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12944 (when time
12945 (apply 'encode-time (org-parse-time-string time)))))
12947 (defun org-remove-timestamp-with-keyword (keyword)
12948 "Remove all time stamps with KEYWORD in the current entry."
12949 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12950 beg)
12951 (save-excursion
12952 (org-back-to-heading t)
12953 (setq beg (point))
12954 (outline-next-heading)
12955 (while (re-search-backward re beg t)
12956 (replace-match "")
12957 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12958 (equal (char-before) ?\ ))
12959 (backward-delete-char 1)
12960 (if (string-match "^[ \t]*$" (buffer-substring
12961 (point-at-bol) (point-at-eol)))
12962 (delete-region (point-at-bol)
12963 (min (point-max) (1+ (point-at-eol))))))))))
12965 (defun org-add-planning-info (what &optional time &rest remove)
12966 "Insert new timestamp with keyword in the line directly after the headline.
12967 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12968 If non is given, the user is prompted for a date.
12969 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12970 be removed."
12971 (interactive)
12972 (let (org-time-was-given org-end-time-was-given ts
12973 end default-time default-input)
12975 (catch 'exit
12976 (when (and (memq what '(scheduled deadline))
12977 (or (not time)
12978 (and (stringp time)
12979 (string-match "^[-+]+[0-9]" time))))
12980 ;; Try to get a default date/time from existing timestamp
12981 (save-excursion
12982 (org-back-to-heading t)
12983 (setq end (save-excursion (outline-next-heading) (point)))
12984 (when (re-search-forward (if (eq what 'scheduled)
12985 org-scheduled-time-regexp
12986 org-deadline-time-regexp)
12987 end t)
12988 (setq ts (match-string 1)
12989 default-time
12990 (apply 'encode-time (org-parse-time-string ts))
12991 default-input (and ts (org-get-compact-tod ts))))))
12992 (when what
12993 (setq time
12994 (if (stringp time)
12995 ;; This is a string (relative or absolute), set proper date
12996 (apply 'encode-time
12997 (org-read-date-analyze
12998 time default-time (decode-time default-time)))
12999 ;; If necessary, get the time from the user
13000 (or time (org-read-date nil 'to-time nil nil
13001 default-time default-input)))))
13003 (when (and org-insert-labeled-timestamps-at-point
13004 (member what '(scheduled deadline)))
13005 (insert
13006 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13007 (org-insert-time-stamp time org-time-was-given
13008 nil nil nil (list org-end-time-was-given))
13009 (setq what nil))
13010 (save-excursion
13011 (save-restriction
13012 (let (col list elt ts buffer-invisibility-spec)
13013 (org-back-to-heading t)
13014 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13015 (goto-char (match-end 1))
13016 (setq col (current-column))
13017 (goto-char (match-end 0))
13018 (if (eobp) (insert "\n") (forward-char 1))
13019 (when (and (not what)
13020 (not (looking-at
13021 (concat "[ \t]*"
13022 org-keyword-time-not-clock-regexp))))
13023 ;; Nothing to add, nothing to remove...... :-)
13024 (throw 'exit nil))
13025 (if (and (not (looking-at org-outline-regexp))
13026 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13027 "[^\r\n]*"))
13028 (not (equal (match-string 1) org-clock-string)))
13029 (narrow-to-region (match-beginning 0) (match-end 0))
13030 (insert-before-markers "\n")
13031 (backward-char 1)
13032 (narrow-to-region (point) (point))
13033 (and org-adapt-indentation (org-indent-to-column col)))
13034 ;; Check if we have to remove something.
13035 (setq list (cons what remove))
13036 (while list
13037 (setq elt (pop list))
13038 (when (or (and (eq elt 'scheduled)
13039 (re-search-forward org-scheduled-time-regexp nil t))
13040 (and (eq elt 'deadline)
13041 (re-search-forward org-deadline-time-regexp nil t))
13042 (and (eq elt 'closed)
13043 (re-search-forward org-closed-time-regexp nil t)))
13044 (replace-match "")
13045 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13046 (and (looking-at "[ \t]+") (replace-match ""))
13047 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13048 (when what
13049 (insert
13050 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13051 (cond ((eq what 'scheduled) org-scheduled-string)
13052 ((eq what 'deadline) org-deadline-string)
13053 ((eq what 'closed) org-closed-string))
13054 " ")
13055 (setq ts (org-insert-time-stamp
13056 time
13057 (or org-time-was-given
13058 (and (eq what 'closed) org-log-done-with-time))
13059 (eq what 'closed)
13060 nil nil (list org-end-time-was-given)))
13061 (insert
13062 (if (not (or (bolp) (eq (char-before) ?\ )
13063 (memq (char-after) '(32 10))
13064 (eobp))) " " ""))
13065 (end-of-line 1))
13066 (goto-char (point-min))
13067 (widen)
13068 (if (and (looking-at "[ \t]*\n")
13069 (equal (char-before) ?\n))
13070 (delete-region (1- (point)) (point-at-eol)))
13071 ts))))))
13073 (defvar org-log-note-marker (make-marker))
13074 (defvar org-log-note-purpose nil)
13075 (defvar org-log-note-state nil)
13076 (defvar org-log-note-previous-state nil)
13077 (defvar org-log-note-how nil)
13078 (defvar org-log-note-extra nil)
13079 (defvar org-log-note-window-configuration nil)
13080 (defvar org-log-note-return-to (make-marker))
13081 (defvar org-log-note-effective-time nil
13082 "Remembered current time so that dynamically scoped
13083 `org-extend-today-until' affects tha timestamps in state change
13084 log")
13086 (defvar org-log-post-message nil
13087 "Message to be displayed after a log note has been stored.
13088 The auto-repeater uses this.")
13090 (defun org-add-note ()
13091 "Add a note to the current entry.
13092 This is done in the same way as adding a state change note."
13093 (interactive)
13094 (org-add-log-setup 'note nil nil 'findpos nil))
13096 (defvar org-property-end-re)
13097 (defun org-add-log-setup (&optional purpose state prev-state
13098 findpos how extra)
13099 "Set up the post command hook to take a note.
13100 If this is about to TODO state change, the new state is expected in STATE.
13101 When FINDPOS is non-nil, find the correct position for the note in
13102 the current entry. If not, assume that it can be inserted at point.
13103 HOW is an indicator what kind of note should be created.
13104 EXTRA is additional text that will be inserted into the notes buffer."
13105 (let* ((org-log-into-drawer (org-log-into-drawer))
13106 (drawer (cond ((stringp org-log-into-drawer)
13107 org-log-into-drawer)
13108 (org-log-into-drawer "LOGBOOK"))))
13109 (save-restriction
13110 (save-excursion
13111 (when findpos
13112 (org-back-to-heading t)
13113 (narrow-to-region (point) (save-excursion
13114 (outline-next-heading) (point)))
13115 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13116 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13117 "[^\r\n]*\\)?"))
13118 (goto-char (match-end 0))
13119 (cond
13120 (drawer
13121 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13122 nil t)
13123 (progn
13124 (goto-char (match-end 0))
13125 (or org-log-states-order-reversed
13126 (and (re-search-forward org-property-end-re nil t)
13127 (goto-char (1- (match-beginning 0))))))
13128 (insert "\n:" drawer ":\n:END:")
13129 (beginning-of-line 0)
13130 (org-indent-line)
13131 (beginning-of-line 2)
13132 (org-indent-line)
13133 (end-of-line 0)))
13134 ((and org-log-state-notes-insert-after-drawers
13135 (save-excursion
13136 (forward-line) (looking-at org-drawer-regexp)))
13137 (forward-line)
13138 (while (looking-at org-drawer-regexp)
13139 (goto-char (match-end 0))
13140 (re-search-forward org-property-end-re (point-max) t)
13141 (forward-line))
13142 (forward-line -1)))
13143 (unless org-log-states-order-reversed
13144 (and (= (char-after) ?\n) (forward-char 1))
13145 (org-skip-over-state-notes)
13146 (skip-chars-backward " \t\n\r")))
13147 (move-marker org-log-note-marker (point))
13148 (setq org-log-note-purpose purpose
13149 org-log-note-state state
13150 org-log-note-previous-state prev-state
13151 org-log-note-how how
13152 org-log-note-extra extra
13153 org-log-note-effective-time (org-current-effective-time))
13154 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13156 (defun org-skip-over-state-notes ()
13157 "Skip past the list of State notes in an entry."
13158 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13159 (when (ignore-errors (goto-char (org-in-item-p)))
13160 (let* ((struct (org-list-struct))
13161 (prevs (org-list-prevs-alist struct)))
13162 (while (looking-at "[ \t]*- State")
13163 (goto-char (or (org-list-get-next-item (point) struct prevs)
13164 (org-list-get-item-end (point) struct)))))))
13166 (defun org-add-log-note (&optional purpose)
13167 "Pop up a window for taking a note, and add this note later at point."
13168 (remove-hook 'post-command-hook 'org-add-log-note)
13169 (setq org-log-note-window-configuration (current-window-configuration))
13170 (delete-other-windows)
13171 (move-marker org-log-note-return-to (point))
13172 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13173 (goto-char org-log-note-marker)
13174 (org-switch-to-buffer-other-window "*Org Note*")
13175 (erase-buffer)
13176 (if (memq org-log-note-how '(time state))
13177 (let (current-prefix-arg) (org-store-log-note))
13178 (let ((org-inhibit-startup t)) (org-mode))
13179 (insert (format "# Insert note for %s.
13180 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13181 (cond
13182 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13183 ((eq org-log-note-purpose 'done) "closed todo item")
13184 ((eq org-log-note-purpose 'state)
13185 (format "state change from \"%s\" to \"%s\""
13186 (or org-log-note-previous-state "")
13187 (or org-log-note-state "")))
13188 ((eq org-log-note-purpose 'reschedule)
13189 "rescheduling")
13190 ((eq org-log-note-purpose 'delschedule)
13191 "no longer scheduled")
13192 ((eq org-log-note-purpose 'redeadline)
13193 "changing deadline")
13194 ((eq org-log-note-purpose 'deldeadline)
13195 "removing deadline")
13196 ((eq org-log-note-purpose 'refile)
13197 "refiling")
13198 ((eq org-log-note-purpose 'note)
13199 "this entry")
13200 (t (error "This should not happen")))))
13201 (if org-log-note-extra (insert org-log-note-extra))
13202 (org-set-local 'org-finish-function 'org-store-log-note)
13203 (run-hooks 'org-log-buffer-setup-hook)))
13205 (defvar org-note-abort nil) ; dynamically scoped
13206 (defun org-store-log-note ()
13207 "Finish taking a log note, and insert it to where it belongs."
13208 (let ((txt (buffer-string)))
13209 (kill-buffer (current-buffer))
13210 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13211 lines ind bul)
13212 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13213 (setq txt (replace-match "" t t txt)))
13214 (if (string-match "\\s-+\\'" txt)
13215 (setq txt (replace-match "" t t txt)))
13216 (setq lines (org-split-string txt "\n"))
13217 (when (and note (string-match "\\S-" note))
13218 (setq note
13219 (org-replace-escapes
13220 note
13221 (list (cons "%u" (user-login-name))
13222 (cons "%U" user-full-name)
13223 (cons "%t" (format-time-string
13224 (org-time-stamp-format 'long 'inactive)
13225 org-log-note-effective-time))
13226 (cons "%T" (format-time-string
13227 (org-time-stamp-format 'long nil)
13228 org-log-note-effective-time))
13229 (cons "%d" (format-time-string
13230 (org-time-stamp-format nil 'inactive)
13231 org-log-note-effective-time))
13232 (cons "%D" (format-time-string
13233 (org-time-stamp-format nil nil)
13234 org-log-note-effective-time))
13235 (cons "%s" (if org-log-note-state
13236 (concat "\"" org-log-note-state "\"")
13237 ""))
13238 (cons "%S" (if org-log-note-previous-state
13239 (concat "\"" org-log-note-previous-state "\"")
13240 "\"\"")))))
13241 (if lines (setq note (concat note " \\\\")))
13242 (push note lines))
13243 (when (or current-prefix-arg org-note-abort)
13244 (when org-log-into-drawer
13245 (org-remove-empty-drawer-at
13246 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13247 org-log-note-marker))
13248 (setq lines nil))
13249 (when lines
13250 (with-current-buffer (marker-buffer org-log-note-marker)
13251 (save-excursion
13252 (goto-char org-log-note-marker)
13253 (move-marker org-log-note-marker nil)
13254 (end-of-line 1)
13255 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13256 (setq ind (save-excursion
13257 (if (ignore-errors (goto-char (org-in-item-p)))
13258 (let ((struct (org-list-struct)))
13259 (org-list-get-ind
13260 (org-list-get-top-point struct) struct))
13261 (skip-chars-backward " \r\t\n")
13262 (cond
13263 ((and (org-at-heading-p)
13264 org-adapt-indentation)
13265 (1+ (org-current-level)))
13266 ((org-at-heading-p) 0)
13267 (t (org-get-indentation))))))
13268 (setq bul (org-list-bullet-string "-"))
13269 (org-indent-line-to ind)
13270 (insert bul (pop lines))
13271 (let ((ind-body (+ (length bul) ind)))
13272 (while lines
13273 (insert "\n")
13274 (org-indent-line-to ind-body)
13275 (insert (pop lines))))
13276 (message "Note stored")
13277 (org-back-to-heading t)
13278 (org-cycle-hide-drawers 'children))))))
13279 (set-window-configuration org-log-note-window-configuration)
13280 (with-current-buffer (marker-buffer org-log-note-return-to)
13281 (goto-char org-log-note-return-to))
13282 (move-marker org-log-note-return-to nil)
13283 (and org-log-post-message (message "%s" org-log-post-message)))
13285 (defun org-remove-empty-drawer-at (drawer pos)
13286 "Remove an empty drawer DRAWER at position POS.
13287 POS may also be a marker."
13288 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13289 (save-excursion
13290 (save-restriction
13291 (widen)
13292 (goto-char pos)
13293 (if (org-in-regexp
13294 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13295 (replace-match ""))))))
13297 (defvar org-ts-type nil)
13298 (defun org-sparse-tree (&optional arg type)
13299 "Create a sparse tree, prompt for the details.
13300 This command can create sparse trees. You first need to select the type
13301 of match used to create the tree:
13303 t Show all TODO entries.
13304 T Show entries with a specific TODO keyword.
13305 m Show entries selected by a tags/property match.
13306 p Enter a property name and its value (both with completion on existing
13307 names/values) and show entries with that property.
13308 r Show entries matching a regular expression (`/' can be used as well).
13309 b Show deadlines and scheduled items before a date.
13310 a Show deadlines and scheduled items after a date.
13311 d Show deadlines due within `org-deadline-warning-days'.
13312 D Show deadlines and scheduled items between a date range."
13313 (interactive "P")
13314 (let (ans kwd value ts-type)
13315 (setq type (or type org-sparse-tree-default-date-type))
13316 (setq org-ts-type type)
13317 (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"
13318 (cond ((eq type 'all) "all timestamps")
13319 ((eq type 'scheduled) "only scheduled")
13320 ((eq type 'deadline) "only deadline")
13321 ((eq type 'active) "only active timestamps")
13322 ((eq type 'inactive) "only inactive timestamps")
13323 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13324 (t "scheduled/deadline")))
13325 (setq ans (read-char-exclusive))
13326 (cond
13327 ((equal ans ?c)
13328 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13329 ((equal ans ?d)
13330 (call-interactively 'org-check-deadlines))
13331 ((equal ans ?b)
13332 (call-interactively 'org-check-before-date))
13333 ((equal ans ?a)
13334 (call-interactively 'org-check-after-date))
13335 ((equal ans ?D)
13336 (call-interactively 'org-check-dates-range))
13337 ((equal ans ?t)
13338 (call-interactively 'org-show-todo-tree))
13339 ((equal ans ?T)
13340 (org-show-todo-tree '(4)))
13341 ((member ans '(?T ?m))
13342 (call-interactively 'org-match-sparse-tree))
13343 ((member ans '(?p ?P))
13344 (setq kwd (org-icompleting-read "Property: "
13345 (mapcar 'list (org-buffer-property-keys))))
13346 (setq value (org-icompleting-read "Value: "
13347 (mapcar 'list (org-property-values kwd))))
13348 (unless (string-match "\\`{.*}\\'" value)
13349 (setq value (concat "\"" value "\"")))
13350 (org-match-sparse-tree arg (concat kwd "=" value)))
13351 ((member ans '(?r ?R ?/))
13352 (call-interactively 'org-occur))
13353 (t (error "No such sparse tree command \"%c\"" ans)))))
13355 (defvar org-occur-highlights nil
13356 "List of overlays used for occur matches.")
13357 (make-variable-buffer-local 'org-occur-highlights)
13358 (defvar org-occur-parameters nil
13359 "Parameters of the active org-occur calls.
13360 This is a list, each call to org-occur pushes as cons cell,
13361 containing the regular expression and the callback, onto the list.
13362 The list can contain several entries if `org-occur' has been called
13363 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13364 will only contain one set of parameters. When the highlights are
13365 removed (for example with `C-c C-c', or with the next edit (depending
13366 on `org-remove-highlights-with-change'), this variable is emptied
13367 as well.")
13368 (make-variable-buffer-local 'org-occur-parameters)
13370 (defun org-occur (regexp &optional keep-previous callback)
13371 "Make a compact tree which shows all matches of REGEXP.
13372 The tree will show the lines where the regexp matches, and all higher
13373 headlines above the match. It will also show the heading after the match,
13374 to make sure editing the matching entry is easy.
13375 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13376 call to `org-occur' will be kept, to allow stacking of calls to this
13377 command.
13378 If CALLBACK is non-nil, it is a function which is called to confirm
13379 that the match should indeed be shown."
13380 (interactive "sRegexp: \nP")
13381 (when (equal regexp "")
13382 (error "Regexp cannot be empty"))
13383 (unless keep-previous
13384 (org-remove-occur-highlights nil nil t))
13385 (push (cons regexp callback) org-occur-parameters)
13386 (let ((cnt 0))
13387 (save-excursion
13388 (goto-char (point-min))
13389 (if (or (not keep-previous) ; do not want to keep
13390 (not org-occur-highlights)) ; no previous matches
13391 ;; hide everything
13392 (org-overview))
13393 (while (re-search-forward regexp nil t)
13394 (when (or (not callback)
13395 (save-match-data (funcall callback)))
13396 (setq cnt (1+ cnt))
13397 (when org-highlight-sparse-tree-matches
13398 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13399 (org-show-context 'occur-tree))))
13400 (when org-remove-highlights-with-change
13401 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13402 nil 'local))
13403 (unless org-sparse-tree-open-archived-trees
13404 (org-hide-archived-subtrees (point-min) (point-max)))
13405 (run-hooks 'org-occur-hook)
13406 (if (org-called-interactively-p 'interactive)
13407 (message "%d match(es) for regexp %s" cnt regexp))
13408 cnt))
13410 (defun org-occur-next-match (&optional n reset)
13411 "Function for `next-error-function' to find sparse tree matches.
13412 N is the number of matches to move, when negative move backwards.
13413 RESET is entirely ignored - this function always goes back to the
13414 starting point when no match is found."
13415 (let* ((limit (if (< n 0) (point-min) (point-max)))
13416 (search-func (if (< n 0)
13417 'previous-single-char-property-change
13418 'next-single-char-property-change))
13419 (n (abs n))
13420 (pos (point))
13422 (catch 'exit
13423 (while (setq p1 (funcall search-func (point) 'org-type))
13424 (when (equal p1 limit)
13425 (goto-char pos)
13426 (error "No more matches"))
13427 (when (equal (get-char-property p1 'org-type) 'org-occur)
13428 (setq n (1- n))
13429 (when (= n 0)
13430 (goto-char p1)
13431 (throw 'exit (point))))
13432 (goto-char p1))
13433 (goto-char p1)
13434 (error "No more matches"))))
13436 (defun org-show-context (&optional key)
13437 "Make sure point and context are visible.
13438 How much context is shown depends upon the variables
13439 `org-show-hierarchy-above', `org-show-following-heading',
13440 `org-show-entry-below' and `org-show-siblings'."
13441 (let ((heading-p (org-at-heading-p t))
13442 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13443 (following-p (org-get-alist-option org-show-following-heading key))
13444 (entry-p (org-get-alist-option org-show-entry-below key))
13445 (siblings-p (org-get-alist-option org-show-siblings key)))
13446 ;; Show heading or entry text
13447 (if (and heading-p (not entry-p))
13448 (org-flag-heading nil) ; only show the heading
13449 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13450 (org-show-hidden-entry))) ; show entire entry
13451 (when following-p
13452 ;; Show next sibling, or heading below text
13453 (save-excursion
13454 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13455 (org-flag-heading nil))))
13456 (when siblings-p (org-show-siblings))
13457 (when hierarchy-p
13458 ;; show all higher headings, possibly with siblings
13459 (save-excursion
13460 (while (and (condition-case nil
13461 (progn (org-up-heading-all 1) t)
13462 (error nil))
13463 (not (bobp)))
13464 (org-flag-heading nil)
13465 (when siblings-p (org-show-siblings)))))
13466 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13468 (defvar org-reveal-start-hook nil
13469 "Hook run before revealing a location.")
13471 (defun org-reveal (&optional siblings)
13472 "Show current entry, hierarchy above it, and the following headline.
13473 This can be used to show a consistent set of context around locations
13474 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13475 not t for the search context.
13477 With optional argument SIBLINGS, on each level of the hierarchy all
13478 siblings are shown. This repairs the tree structure to what it would
13479 look like when opened with hierarchical calls to `org-cycle'.
13480 With double optional argument \\[universal-argument] \\[universal-argument], \
13481 go to the parent and show the
13482 entire tree."
13483 (interactive "P")
13484 (run-hooks 'org-reveal-start-hook)
13485 (let ((org-show-hierarchy-above t)
13486 (org-show-following-heading t)
13487 (org-show-siblings (if siblings t org-show-siblings)))
13488 (org-show-context nil))
13489 (when (equal siblings '(16))
13490 (save-excursion
13491 (when (org-up-heading-safe)
13492 (org-show-subtree)
13493 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13495 (defun org-highlight-new-match (beg end)
13496 "Highlight from BEG to END and mark the highlight is an occur headline."
13497 (let ((ov (make-overlay beg end)))
13498 (overlay-put ov 'face 'secondary-selection)
13499 (overlay-put ov 'org-type 'org-occur)
13500 (push ov org-occur-highlights)))
13502 (defun org-remove-occur-highlights (&optional beg end noremove)
13503 "Remove the occur highlights from the buffer.
13504 BEG and END are ignored. If NOREMOVE is nil, remove this function
13505 from the `before-change-functions' in the current buffer."
13506 (interactive)
13507 (unless org-inhibit-highlight-removal
13508 (mapc 'delete-overlay org-occur-highlights)
13509 (setq org-occur-highlights nil)
13510 (setq org-occur-parameters nil)
13511 (unless noremove
13512 (remove-hook 'before-change-functions
13513 'org-remove-occur-highlights 'local))))
13515 ;;;; Priorities
13517 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13518 "Regular expression matching the priority indicator.")
13520 (defvar org-remove-priority-next-time nil)
13522 (defun org-priority-up ()
13523 "Increase the priority of the current item."
13524 (interactive)
13525 (org-priority 'up))
13527 (defun org-priority-down ()
13528 "Decrease the priority of the current item."
13529 (interactive)
13530 (org-priority 'down))
13532 (defun org-priority (&optional action show)
13533 "Change the priority of an item.
13534 ACTION can be `set', `up', `down', or a character."
13535 (interactive "P")
13536 (if (equal action '(4))
13537 (org-show-priority)
13538 (unless org-enable-priority-commands
13539 (error "Priority commands are disabled"))
13540 (setq action (or action 'set))
13541 (let (current new news have remove)
13542 (save-excursion
13543 (org-back-to-heading t)
13544 (if (looking-at org-priority-regexp)
13545 (setq current (string-to-char (match-string 2))
13546 have t))
13547 (cond
13548 ((eq action 'remove)
13549 (setq remove t new ?\ ))
13550 ((or (eq action 'set)
13551 (if (featurep 'xemacs) (characterp action) (integerp action)))
13552 (if (not (eq action 'set))
13553 (setq new action)
13554 (message "Priority %c-%c, SPC to remove: "
13555 org-highest-priority org-lowest-priority)
13556 (save-match-data
13557 (setq new (read-char-exclusive))))
13558 (if (and (= (upcase org-highest-priority) org-highest-priority)
13559 (= (upcase org-lowest-priority) org-lowest-priority))
13560 (setq new (upcase new)))
13561 (cond ((equal new ?\ ) (setq remove t))
13562 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13563 (error "Priority must be between `%c' and `%c'"
13564 org-highest-priority org-lowest-priority))))
13565 ((eq action 'up)
13566 (setq new (if have
13567 (1- current) ; normal cycling
13568 ;; last priority was empty
13569 (if (eq last-command this-command)
13570 org-lowest-priority ; wrap around empty to lowest
13571 ;; default
13572 (if org-priority-start-cycle-with-default
13573 org-default-priority
13574 (1- org-default-priority))))))
13575 ((eq action 'down)
13576 (setq new (if have
13577 (1+ current) ; normal cycling
13578 ;; last priority was empty
13579 (if (eq last-command this-command)
13580 org-highest-priority ; wrap around empty to highest
13581 ;; default
13582 (if org-priority-start-cycle-with-default
13583 org-default-priority
13584 (1+ org-default-priority))))))
13585 (t (error "Invalid action")))
13586 (if (or (< (upcase new) org-highest-priority)
13587 (> (upcase new) org-lowest-priority))
13588 (if (and (memq action '(up down))
13589 (not have) (not (eq last-command this-command)))
13590 ;; `new' is from default priority
13591 (error
13592 "The default can not be set, see `org-default-priority' why")
13593 ;; normal cycling: `new' is beyond highest/lowest priority
13594 ;; and is wrapped around to the empty priority
13595 (setq remove t)))
13596 (setq news (format "%c" new))
13597 (if have
13598 (if remove
13599 (replace-match "" t t nil 1)
13600 (replace-match news t t nil 2))
13601 (if remove
13602 (error "No priority cookie found in line")
13603 (let ((case-fold-search nil))
13604 (looking-at org-todo-line-regexp))
13605 (if (match-end 2)
13606 (progn
13607 (goto-char (match-end 2))
13608 (insert " [#" news "]"))
13609 (goto-char (match-beginning 3))
13610 (insert "[#" news "] "))))
13611 (org-preserve-lc (org-set-tags nil 'align)))
13612 (if remove
13613 (message "Priority removed")
13614 (message "Priority of current item set to %s" news)))))
13616 (defun org-show-priority ()
13617 "Show the priority of the current item.
13618 This priority is composed of the main priority given with the [#A] cookies,
13619 and by additional input from the age of a schedules or deadline entry."
13620 (interactive)
13621 (let ((pri (if (eq major-mode 'org-agenda-mode)
13622 (org-get-at-bol 'priority)
13623 (save-excursion
13624 (save-match-data
13625 (beginning-of-line)
13626 (and (looking-at org-heading-regexp)
13627 (org-get-priority (match-string 0))))))))
13628 (message "Priority is %d" (if pri pri -1000))))
13630 (defun org-get-priority (s)
13631 "Find priority cookie and return priority."
13632 (save-match-data
13633 (if (functionp org-get-priority-function)
13634 (funcall org-get-priority-function)
13635 (if (not (string-match org-priority-regexp s))
13636 (* 1000 (- org-lowest-priority org-default-priority))
13637 (* 1000 (- org-lowest-priority
13638 (string-to-char (match-string 2 s))))))))
13640 ;;;; Tags
13642 (defvar org-agenda-archives-mode)
13643 (defvar org-map-continue-from nil
13644 "Position from where mapping should continue.
13645 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13647 (defvar org-scanner-tags nil
13648 "The current tag list while the tags scanner is running.")
13649 (defvar org-trust-scanner-tags nil
13650 "Should `org-get-tags-at' use the tags for the scanner.
13651 This is for internal dynamical scoping only.
13652 When this is non-nil, the function `org-get-tags-at' will return the value
13653 of `org-scanner-tags' instead of building the list by itself. This
13654 can lead to large speed-ups when the tags scanner is used in a file with
13655 many entries, and when the list of tags is retrieved, for example to
13656 obtain a list of properties. Building the tags list for each entry in such
13657 a file becomes an N^2 operation - but with this variable set, it scales
13658 as N.")
13660 (defun org-scan-tags (action matcher todo-only &optional start-level)
13661 "Sca headline tags with inheritance and produce output ACTION.
13663 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13664 or `agenda' to produce an entry list for an agenda view. It can also be
13665 a Lisp form or a function that should be called at each matched headline, in
13666 this case the return value is a list of all return values from these calls.
13668 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13669 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13670 only lines with a not-done TODO keyword are included in the output.
13671 This should be the same variable that was scoped into
13672 and set by `org-make-tags-matcher' when it constructed MATCHER.
13674 START-LEVEL can be a string with asterisks, reducing the scope to
13675 headlines matching this string."
13676 (require 'org-agenda)
13677 (let* ((re (concat "^"
13678 (if start-level
13679 ;; Get the correct level to match
13680 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13681 org-outline-regexp)
13682 " *\\(\\<\\("
13683 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13684 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13685 (props (list 'face 'default
13686 'done-face 'org-agenda-done
13687 'undone-face 'default
13688 'mouse-face 'highlight
13689 'org-not-done-regexp org-not-done-regexp
13690 'org-todo-regexp org-todo-regexp
13691 'org-complex-heading-regexp org-complex-heading-regexp
13692 'help-echo
13693 (format "mouse-2 or RET jump to org file %s"
13694 (abbreviate-file-name
13695 (or (buffer-file-name (buffer-base-buffer))
13696 (buffer-name (buffer-base-buffer)))))))
13697 (case-fold-search nil)
13698 (org-map-continue-from nil)
13699 lspos tags tags-list
13700 (tags-alist (list (cons 0 org-file-tags)))
13701 (llast 0) rtn rtn1 level category i txt
13702 todo marker entry priority)
13703 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13704 (setq action (list 'lambda nil action)))
13705 (save-excursion
13706 (goto-char (point-min))
13707 (when (eq action 'sparse-tree)
13708 (org-overview)
13709 (org-remove-occur-highlights))
13710 (while (re-search-forward re nil t)
13711 (setq org-map-continue-from nil)
13712 (catch :skip
13713 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13714 tags (if (match-end 4) (org-match-string-no-properties 4)))
13715 (goto-char (setq lspos (match-beginning 0)))
13716 (setq level (org-reduced-level (org-outline-level))
13717 category (org-get-category))
13718 (setq i llast llast level)
13719 ;; remove tag lists from same and sublevels
13720 (while (>= i level)
13721 (when (setq entry (assoc i tags-alist))
13722 (setq tags-alist (delete entry tags-alist)))
13723 (setq i (1- i)))
13724 ;; add the next tags
13725 (when tags
13726 (setq tags (org-split-string tags ":")
13727 tags-alist
13728 (cons (cons level tags) tags-alist)))
13729 ;; compile tags for current headline
13730 (setq tags-list
13731 (if org-use-tag-inheritance
13732 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13733 tags)
13734 org-scanner-tags tags-list)
13735 (when org-use-tag-inheritance
13736 (setcdr (car tags-alist)
13737 (mapcar (lambda (x)
13738 (setq x (copy-sequence x))
13739 (org-add-prop-inherited x))
13740 (cdar tags-alist))))
13741 (when (and tags org-use-tag-inheritance
13742 (or (not (eq t org-use-tag-inheritance))
13743 org-tags-exclude-from-inheritance))
13744 ;; selective inheritance, remove uninherited ones
13745 (setcdr (car tags-alist)
13746 (org-remove-uninherited-tags (cdar tags-alist))))
13747 (when (and
13749 ;; eval matcher only when the todo condition is OK
13750 (and (or (not todo-only) (member todo org-not-done-keywords))
13751 (let ((case-fold-search t) (org-trust-scanner-tags t))
13752 (eval matcher)))
13754 ;; Call the skipper, but return t if it does not skip,
13755 ;; so that the `and' form continues evaluating
13756 (progn
13757 (unless (eq action 'sparse-tree) (org-agenda-skip))
13760 ;; Check if timestamps are deselecting this entry
13761 (or (not todo-only)
13762 (and (member todo org-not-done-keywords)
13763 (or (not org-agenda-tags-todo-honor-ignore-options)
13764 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13766 ;; select this headline
13767 (cond
13768 ((eq action 'sparse-tree)
13769 (and org-highlight-sparse-tree-matches
13770 (org-get-heading) (match-end 0)
13771 (org-highlight-new-match
13772 (match-beginning 1) (match-end 1)))
13773 (org-show-context 'tags-tree))
13774 ((eq action 'agenda)
13775 (setq txt (org-agenda-format-item
13777 (concat
13778 (if (eq org-tags-match-list-sublevels 'indented)
13779 (make-string (1- level) ?.) "")
13780 (org-get-heading))
13781 level category
13782 tags-list)
13783 priority (org-get-priority txt))
13784 (goto-char lspos)
13785 (setq marker (org-agenda-new-marker))
13786 (org-add-props txt props
13787 'org-marker marker 'org-hd-marker marker 'org-category category
13788 'todo-state todo
13789 'priority priority 'type "tagsmatch")
13790 (push txt rtn))
13791 ((functionp action)
13792 (setq org-map-continue-from nil)
13793 (save-excursion
13794 (setq rtn1 (funcall action))
13795 (push rtn1 rtn)))
13796 (t (error "Invalid action")))
13798 ;; if we are to skip sublevels, jump to end of subtree
13799 (unless org-tags-match-list-sublevels
13800 (org-end-of-subtree t)
13801 (backward-char 1))))
13802 ;; Get the correct position from where to continue
13803 (if org-map-continue-from
13804 (goto-char org-map-continue-from)
13805 (and (= (point) lspos) (end-of-line 1)))))
13806 (when (and (eq action 'sparse-tree)
13807 (not org-sparse-tree-open-archived-trees))
13808 (org-hide-archived-subtrees (point-min) (point-max)))
13809 (nreverse rtn)))
13811 (defun org-remove-uninherited-tags (tags)
13812 "Remove all tags that are not inherited from the list TAGS."
13813 (cond
13814 ((eq org-use-tag-inheritance t)
13815 (if org-tags-exclude-from-inheritance
13816 (org-delete-all org-tags-exclude-from-inheritance tags)
13817 tags))
13818 ((not org-use-tag-inheritance) nil)
13819 ((stringp org-use-tag-inheritance)
13820 (delq nil (mapcar
13821 (lambda (x)
13822 (if (and (string-match org-use-tag-inheritance x)
13823 (not (member x org-tags-exclude-from-inheritance)))
13824 x nil))
13825 tags)))
13826 ((listp org-use-tag-inheritance)
13827 (delq nil (mapcar
13828 (lambda (x)
13829 (if (member x org-use-tag-inheritance) x nil))
13830 tags)))))
13832 (defun org-match-sparse-tree (&optional todo-only match)
13833 "Create a sparse tree according to tags string MATCH.
13834 MATCH can contain positive and negative selection of tags, like
13835 \"+WORK+URGENT-WITHBOSS\".
13836 If optional argument TODO-ONLY is non-nil, only select lines that are
13837 also TODO lines."
13838 (interactive "P")
13839 (org-agenda-prepare-buffers (list (current-buffer)))
13840 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13842 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13844 (defvar org-cached-props nil)
13845 (defun org-cached-entry-get (pom property)
13846 (if (or (eq t org-use-property-inheritance)
13847 (and (stringp org-use-property-inheritance)
13848 (string-match org-use-property-inheritance property))
13849 (and (listp org-use-property-inheritance)
13850 (member property org-use-property-inheritance)))
13851 ;; Caching is not possible, check it directly
13852 (org-entry-get pom property 'inherit)
13853 ;; Get all properties, so that we can do complicated checks easily
13854 (cdr (assoc property (or org-cached-props
13855 (setq org-cached-props
13856 (org-entry-properties pom)))))))
13858 (defun org-global-tags-completion-table (&optional files)
13859 "Return the list of all tags in all agenda buffer/files.
13860 Optional FILES argument is a list of files which can be used
13861 instead of the agenda files."
13862 (save-excursion
13863 (org-uniquify
13864 (delq nil
13865 (apply 'append
13866 (mapcar
13867 (lambda (file)
13868 (set-buffer (find-file-noselect file))
13869 (append (org-get-buffer-tags)
13870 (mapcar (lambda (x) (if (stringp (car-safe x))
13871 (list (car-safe x)) nil))
13872 org-tag-alist)))
13873 (if (and files (car files))
13874 files
13875 (org-agenda-files))))))))
13877 (defun org-make-tags-matcher (match)
13878 "Create the TAGS/TODO matcher form for the selection string MATCH.
13880 The variable `todo-only' is scoped dynamically into this function.
13881 It will be set to t if the matcher restricts matching to TODO entries,
13882 otherwise will not be touched.
13884 Returns a cons of the selection string MATCH and the constructed
13885 lisp form implementing the matcher. The matcher is to be evaluated
13886 at an Org entry, with point on the headline, and returns t if the
13887 entry matches the selection string MATCH. The returned lisp form
13888 references two variables with information about the entry, which
13889 must be bound around the form's evaluation: todo, the TODO keyword
13890 at the entry (or nil of none); and tags-list, the list of all tags
13891 at the entry including inherited ones. Additionally, the category
13892 of the entry (if any) must be specified as the text property
13893 'org-category on the headline.
13895 See also `org-scan-tags'.
13897 (declare (special todo-only))
13898 (unless (boundp 'todo-only)
13899 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13900 (unless match
13901 ;; Get a new match request, with completion
13902 (let ((org-last-tags-completion-table
13903 (org-global-tags-completion-table)))
13904 (setq match (org-completing-read-no-i
13905 "Match: " 'org-tags-completion-function nil nil nil
13906 'org-tags-history))))
13908 ;; Parse the string and create a lisp form
13909 (let ((match0 match)
13910 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13911 minus tag mm
13912 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13913 orterms term orlist re-p str-p level-p level-op time-p
13914 prop-p pn pv po gv rest)
13915 ;; Expand group tags
13916 (setq match (org-tags-expand match))
13917 (if (string-match "/+" match)
13918 ;; match contains also a todo-matching request
13919 (progn
13920 (setq tagsmatch (substring match 0 (match-beginning 0))
13921 todomatch (substring match (match-end 0)))
13922 (if (string-match "^!" todomatch)
13923 (setq todo-only t todomatch (substring todomatch 1)))
13924 (if (string-match "^\\s-*$" todomatch)
13925 (setq todomatch nil)))
13926 ;; only matching tags
13927 (setq tagsmatch match todomatch nil))
13929 ;; Make the tags matcher
13930 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13931 (setq tagsmatcher t)
13932 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13933 (while (setq term (pop orterms))
13934 (while (and (equal (substring term -1) "\\") orterms)
13935 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13936 (while (string-match re term)
13937 (setq rest (substring term (match-end 0))
13938 minus (and (match-end 1)
13939 (equal (match-string 1 term) "-"))
13940 tag (save-match-data (replace-regexp-in-string
13941 "\\\\-" "-"
13942 (match-string 2 term)))
13943 re-p (equal (string-to-char tag) ?{)
13944 level-p (match-end 4)
13945 prop-p (match-end 5)
13946 mm (cond
13947 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13948 (level-p
13949 (setq level-op (org-op-to-function (match-string 3 term)))
13950 `(,level-op level ,(string-to-number
13951 (match-string 4 term))))
13952 (prop-p
13953 (setq pn (match-string 5 term)
13954 po (match-string 6 term)
13955 pv (match-string 7 term)
13956 re-p (equal (string-to-char pv) ?{)
13957 str-p (equal (string-to-char pv) ?\")
13958 time-p (save-match-data
13959 (string-match "^\"[[<].*[]>]\"$" pv))
13960 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13961 (if time-p (setq pv (org-matcher-time pv)))
13962 (setq po (org-op-to-function po (if time-p 'time str-p)))
13963 (cond
13964 ((equal pn "CATEGORY")
13965 (setq gv '(get-text-property (point) 'org-category)))
13966 ((equal pn "TODO")
13967 (setq gv 'todo))
13969 (setq gv `(org-cached-entry-get nil ,pn))))
13970 (if re-p
13971 (if (eq po 'org<>)
13972 `(not (string-match ,pv (or ,gv "")))
13973 `(string-match ,pv (or ,gv "")))
13974 (if str-p
13975 `(,po (or ,gv "") ,pv)
13976 `(,po (string-to-number (or ,gv ""))
13977 ,(string-to-number pv) ))))
13978 (t `(member ,tag tags-list)))
13979 mm (if minus (list 'not mm) mm)
13980 term rest)
13981 (push mm tagsmatcher))
13982 (push (if (> (length tagsmatcher) 1)
13983 (cons 'and tagsmatcher)
13984 (car tagsmatcher))
13985 orlist)
13986 (setq tagsmatcher nil))
13987 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13988 (setq tagsmatcher
13989 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13990 ;; Make the todo matcher
13991 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13992 (setq todomatcher t)
13993 (setq orterms (org-split-string todomatch "|") orlist nil)
13994 (while (setq term (pop orterms))
13995 (while (string-match re term)
13996 (setq minus (and (match-end 1)
13997 (equal (match-string 1 term) "-"))
13998 kwd (match-string 2 term)
13999 re-p (equal (string-to-char kwd) ?{)
14000 term (substring term (match-end 0))
14001 mm (if re-p
14002 `(string-match ,(substring kwd 1 -1) todo)
14003 (list 'equal 'todo kwd))
14004 mm (if minus (list 'not mm) mm))
14005 (push mm todomatcher))
14006 (push (if (> (length todomatcher) 1)
14007 (cons 'and todomatcher)
14008 (car todomatcher))
14009 orlist)
14010 (setq todomatcher nil))
14011 (setq todomatcher (if (> (length orlist) 1)
14012 (cons 'or orlist) (car orlist))))
14014 ;; Return the string and lisp forms of the matcher
14015 (setq matcher (if todomatcher
14016 (list 'and tagsmatcher todomatcher)
14017 tagsmatcher))
14018 (when todo-only
14019 (setq matcher (list 'and '(member todo org-not-done-keywords)
14020 matcher)))
14021 (cons match0 matcher)))
14023 (defun org-tags-expand (match &optional single-as-list downcased)
14024 "Expand group tags in MATCH.
14026 This replaces every group tag in MATCH with a regexp tag search.
14027 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14028 will be replaced like this:
14030 Work => {\(?:Work\|Lab\|Conf\}
14031 +Work => +{\(?:Work\|Lab\|Conf\}
14032 -Work => -{\(?:Work\|Lab\|Conf\}
14034 Replacing by a regexp preserves the structure of the match.
14035 E.g., this expansion
14037 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14039 will match anything tagged with \"Lab\" and \"Home\", or tagged
14040 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14042 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14043 assumed to be a single group tag, and the function will return
14044 the list of tags in this group.
14046 When DOWNCASE is non-nil, expand downcased TAGS."
14047 (if org-group-tags
14048 (let* ((case-fold-search t)
14049 (stable org-mode-syntax-table)
14050 (tal (or org-tag-groups-alist-for-agenda
14051 org-tag-groups-alist))
14052 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14053 (tml (mapcar 'car tal))
14054 (rtnmatch match) rpl)
14055 ;; @ and _ are allowed as word-components in tags
14056 (modify-syntax-entry ?@ "w" stable)
14057 (modify-syntax-entry ?_ "w" stable)
14058 (while (and tml (string-match
14059 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14060 rtnmatch))
14061 (let* ((dir (match-string 1 rtnmatch))
14062 (tag (match-string 2 rtnmatch))
14063 (tag (if downcased (downcase tag) tag)))
14064 (setq tml (delete tag tml))
14065 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14066 (setq rtnmatch
14067 (replace-match
14068 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14069 (if single-as-list
14070 (or (reverse rpl) (list rtnmatch))
14071 rtnmatch))
14072 (if single-as-list (list (if downcased (downcase match) match))
14073 match)))
14075 (defun org-op-to-function (op &optional stringp)
14076 "Turn an operator into the appropriate function."
14077 (setq op
14078 (cond
14079 ((equal op "<" ) '(< string< org-time<))
14080 ((equal op ">" ) '(> org-string> org-time>))
14081 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14082 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14083 ((member op '("=" "==")) '(= string= org-time=))
14084 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14085 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14087 (defun org<> (a b) (not (= a b)))
14088 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14089 (defun org-string>= (a b) (not (string< a b)))
14090 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14091 (defun org-string<> (a b) (not (string= a b)))
14092 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14093 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14094 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14095 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14096 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14097 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14098 (defun org-2ft (s)
14099 "Convert S to a floating point time.
14100 If S is already a number, just return it. If it is a string, parse
14101 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14102 (cond
14103 ((numberp s) s)
14104 ((stringp s)
14105 (condition-case nil
14106 (float-time (apply 'encode-time (org-parse-time-string s)))
14107 (error 0.)))
14108 (t 0.)))
14110 (defun org-time-today ()
14111 "Time in seconds today at 0:00.
14112 Returns the float number of seconds since the beginning of the
14113 epoch to the beginning of today (00:00)."
14114 (float-time (apply 'encode-time
14115 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14117 (defun org-matcher-time (s)
14118 "Interpret a time comparison value."
14119 (save-match-data
14120 (cond
14121 ((string= s "<now>") (float-time))
14122 ((string= s "<today>") (org-time-today))
14123 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14124 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14125 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14126 (+ (org-time-today)
14127 (* (string-to-number (match-string 1 s))
14128 (cdr (assoc (match-string 2 s)
14129 '(("d" . 86400.0) ("w" . 604800.0)
14130 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14131 (t (org-2ft s)))))
14133 (defun org-match-any-p (re list)
14134 "Does re match any element of list?"
14135 (setq list (mapcar (lambda (x) (string-match re x)) list))
14136 (delq nil list))
14138 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14139 (defvar org-tags-overlay (make-overlay 1 1))
14140 (org-detach-overlay org-tags-overlay)
14142 (defun org-get-local-tags-at (&optional pos)
14143 "Get a list of tags defined in the current headline."
14144 (org-get-tags-at pos 'local))
14146 (defun org-get-local-tags ()
14147 "Get a list of tags defined in the current headline."
14148 (org-get-tags-at nil 'local))
14150 (defun org-get-tags-at (&optional pos local)
14151 "Get a list of all headline tags applicable at POS.
14152 POS defaults to point. If tags are inherited, the list contains
14153 the targets in the same sequence as the headlines appear, i.e.
14154 the tags of the current headline come last.
14155 When LOCAL is non-nil, only return tags from the current headline,
14156 ignore inherited ones."
14157 (interactive)
14158 (if (and org-trust-scanner-tags
14159 (or (not pos) (equal pos (point)))
14160 (not local))
14161 org-scanner-tags
14162 (let (tags ltags lastpos parent)
14163 (save-excursion
14164 (save-restriction
14165 (widen)
14166 (goto-char (or pos (point)))
14167 (save-match-data
14168 (catch 'done
14169 (condition-case nil
14170 (progn
14171 (org-back-to-heading t)
14172 (while (not (equal lastpos (point)))
14173 (setq lastpos (point))
14174 (when (looking-at
14175 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14176 (setq ltags (org-split-string
14177 (org-match-string-no-properties 1) ":"))
14178 (when parent
14179 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14180 (setq tags (append
14181 (if parent
14182 (org-remove-uninherited-tags ltags)
14183 ltags)
14184 tags)))
14185 (or org-use-tag-inheritance (throw 'done t))
14186 (if local (throw 'done t))
14187 (or (org-up-heading-safe) (error nil))
14188 (setq parent t)))
14189 (error nil)))))
14190 (if local
14191 tags
14192 (reverse (delete-dups
14193 (reverse (append
14194 (org-remove-uninherited-tags
14195 org-file-tags) tags)))))))))
14197 (defun org-add-prop-inherited (s)
14198 (add-text-properties 0 (length s) '(inherited t) s)
14201 (defun org-toggle-tag (tag &optional onoff)
14202 "Toggle the tag TAG for the current line.
14203 If ONOFF is `on' or `off', don't toggle but set to this state."
14204 (let (res current)
14205 (save-excursion
14206 (org-back-to-heading t)
14207 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14208 (point-at-eol) t)
14209 (progn
14210 (setq current (match-string 1))
14211 (replace-match ""))
14212 (setq current ""))
14213 (setq current (nreverse (org-split-string current ":")))
14214 (cond
14215 ((eq onoff 'on)
14216 (setq res t)
14217 (or (member tag current) (push tag current)))
14218 ((eq onoff 'off)
14219 (or (not (member tag current)) (setq current (delete tag current))))
14220 (t (if (member tag current)
14221 (setq current (delete tag current))
14222 (setq res t)
14223 (push tag current))))
14224 (end-of-line 1)
14225 (if current
14226 (progn
14227 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14228 (org-set-tags nil t))
14229 (delete-horizontal-space))
14230 (run-hooks 'org-after-tags-change-hook))
14231 res))
14233 (defun org-align-tags-here (to-col)
14234 ;; Assumes that this is a headline
14235 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14236 (beginning-of-line 1)
14237 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14238 (< pos (match-beginning 2)))
14239 (progn
14240 (setq tags-l (- (match-end 2) (match-beginning 2)))
14241 (goto-char (match-beginning 1))
14242 (insert " ")
14243 (delete-region (point) (1+ (match-beginning 2)))
14244 (setq ncol (max (current-column)
14245 (1+ col)
14246 (if (> to-col 0)
14247 to-col
14248 (- (abs to-col) tags-l))))
14249 (setq p (point))
14250 (insert (make-string (- ncol (current-column)) ?\ ))
14251 (setq ncol (current-column))
14252 (when indent-tabs-mode (tabify p (point-at-eol)))
14253 (org-move-to-column (min ncol col) t))
14254 (goto-char pos))))
14256 (defun org-set-tags-command (&optional arg just-align)
14257 "Call the set-tags command for the current entry."
14258 (interactive "P")
14259 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14260 (org-set-tags arg just-align)
14261 (save-excursion
14262 (unless (and (org-region-active-p)
14263 org-loop-over-headlines-in-active-region)
14264 (org-back-to-heading t))
14265 (org-set-tags arg just-align))))
14267 (defun org-set-tags-to (data)
14268 "Set the tags of the current entry to DATA, replacing the current tags.
14269 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14270 If DATA is nil or the empty string, any tags will be removed."
14271 (interactive "sTags: ")
14272 (setq data
14273 (cond
14274 ((eq data nil) "")
14275 ((equal data "") "")
14276 ((stringp data)
14277 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14278 ":"))
14279 ((listp data)
14280 (concat ":" (mapconcat 'identity data ":") ":"))))
14281 (when data
14282 (save-excursion
14283 (org-back-to-heading t)
14284 (when (looking-at org-complex-heading-regexp)
14285 (if (match-end 5)
14286 (progn
14287 (goto-char (match-beginning 5))
14288 (insert data)
14289 (delete-region (point) (point-at-eol))
14290 (org-set-tags nil 'align))
14291 (goto-char (point-at-eol))
14292 (insert " " data)
14293 (org-set-tags nil 'align)))
14294 (beginning-of-line 1)
14295 (if (looking-at ".*?\\([ \t]+\\)$")
14296 (delete-region (match-beginning 1) (match-end 1))))))
14298 (defun org-align-all-tags ()
14299 "Align the tags i all headings."
14300 (interactive)
14301 (save-excursion
14302 (or (ignore-errors (org-back-to-heading t))
14303 (outline-next-heading))
14304 (if (org-at-heading-p)
14305 (org-set-tags t)
14306 (message "No headings"))))
14308 (defvar org-indent-indentation-per-level)
14309 (defun org-set-tags (&optional arg just-align)
14310 "Set the tags for the current headline.
14311 With prefix ARG, realign all tags in headings in the current buffer."
14312 (interactive "P")
14313 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14314 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14315 'region-start-level 'region))
14316 org-loop-over-headlines-in-active-region)
14317 (org-map-entries
14318 ;; We don't use ARG and JUST-ALIGN here these args are not
14319 ;; useful when looping over headlines
14320 `(org-set-tags)
14321 org-loop-over-headlines-in-active-region
14322 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14323 (let* ((re org-outline-regexp-bol)
14324 (current (unless arg (org-get-tags-string)))
14325 (col (current-column))
14326 (org-setting-tags t)
14327 table current-tags inherited-tags ; computed below when needed
14328 tags p0 c0 c1 rpl di tc level)
14329 (if arg
14330 (save-excursion
14331 (goto-char (point-min))
14332 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14333 (while (re-search-forward re nil t)
14334 (org-set-tags nil t)
14335 (end-of-line 1)))
14336 (message "All tags realigned to column %d" org-tags-column))
14337 (if just-align
14338 (setq tags current)
14339 ;; Get a new set of tags from the user
14340 (save-excursion
14341 (setq table (append org-tag-persistent-alist
14342 (or org-tag-alist (org-get-buffer-tags))
14343 (and
14344 org-complete-tags-always-offer-all-agenda-tags
14345 (org-global-tags-completion-table
14346 (org-agenda-files))))
14347 org-last-tags-completion-table table
14348 current-tags (org-split-string current ":")
14349 inherited-tags (nreverse
14350 (nthcdr (length current-tags)
14351 (nreverse (org-get-tags-at))))
14352 tags
14353 (if (or (eq t org-use-fast-tag-selection)
14354 (and org-use-fast-tag-selection
14355 (delq nil (mapcar 'cdr table))))
14356 (org-fast-tag-selection
14357 current-tags inherited-tags table
14358 (if org-fast-tag-selection-include-todo
14359 org-todo-key-alist))
14360 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14361 (org-trim
14362 (org-icompleting-read "Tags: "
14363 'org-tags-completion-function
14364 nil nil current 'org-tags-history))))))
14365 (while (string-match "[-+&]+" tags)
14366 ;; No boolean logic, just a list
14367 (setq tags (replace-match ":" t t tags))))
14369 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14371 (if org-tags-sort-function
14372 (setq tags (mapconcat 'identity
14373 (sort (org-split-string
14374 tags (org-re "[^[:alnum:]_@#%]+"))
14375 org-tags-sort-function) ":")))
14377 (if (string-match "\\`[\t ]*\\'" tags)
14378 (setq tags "")
14379 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14380 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14382 ;; Insert new tags at the correct column
14383 (beginning-of-line 1)
14384 (setq level (or (and (looking-at org-outline-regexp)
14385 (- (match-end 0) (point) 1))
14387 (cond
14388 ((and (equal current "") (equal tags "")))
14389 ((re-search-forward
14390 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14391 (point-at-eol) t)
14392 (if (equal tags "")
14393 (setq rpl "")
14394 (goto-char (match-beginning 0))
14395 (setq c0 (current-column)
14396 ;; compute offset for the case of org-indent-mode active
14397 di (if org-indent-mode
14398 (* (1- org-indent-indentation-per-level) (1- level))
14400 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14401 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14402 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14403 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14404 (replace-match rpl t t)
14405 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14406 tags)
14407 (t (error "Tags alignment failed")))
14408 (org-move-to-column col)
14409 (unless just-align
14410 (run-hooks 'org-after-tags-change-hook))))))
14412 (defun org-change-tag-in-region (beg end tag off)
14413 "Add or remove TAG for each entry in the region.
14414 This works in the agenda, and also in an org-mode buffer."
14415 (interactive
14416 (list (region-beginning) (region-end)
14417 (let ((org-last-tags-completion-table
14418 (if (derived-mode-p 'org-mode)
14419 (org-get-buffer-tags)
14420 (org-global-tags-completion-table))))
14421 (org-icompleting-read
14422 "Tag: " 'org-tags-completion-function nil nil nil
14423 'org-tags-history))
14424 (progn
14425 (message "[s]et or [r]emove? ")
14426 (equal (read-char-exclusive) ?r))))
14427 (if (fboundp 'deactivate-mark) (deactivate-mark))
14428 (let ((agendap (equal major-mode 'org-agenda-mode))
14429 l1 l2 m buf pos newhead (cnt 0))
14430 (goto-char end)
14431 (setq l2 (1- (org-current-line)))
14432 (goto-char beg)
14433 (setq l1 (org-current-line))
14434 (loop for l from l1 to l2 do
14435 (org-goto-line l)
14436 (setq m (get-text-property (point) 'org-hd-marker))
14437 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14438 (and agendap m))
14439 (setq buf (if agendap (marker-buffer m) (current-buffer))
14440 pos (if agendap m (point)))
14441 (with-current-buffer buf
14442 (save-excursion
14443 (save-restriction
14444 (goto-char pos)
14445 (setq cnt (1+ cnt))
14446 (org-toggle-tag tag (if off 'off 'on))
14447 (setq newhead (org-get-heading)))))
14448 (and agendap (org-agenda-change-all-lines newhead m))))
14449 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14451 (defun org-tags-completion-function (string predicate &optional flag)
14452 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14453 (confirm (lambda (x) (stringp (car x)))))
14454 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14455 (setq s1 (match-string 1 string)
14456 s2 (match-string 2 string))
14457 (setq s1 "" s2 string))
14458 (cond
14459 ((eq flag nil)
14460 ;; try completion
14461 (setq rtn (try-completion s2 ctable confirm))
14462 (if (stringp rtn)
14463 (setq rtn
14464 (concat s1 s2 (substring rtn (length s2))
14465 (if (and org-add-colon-after-tag-completion
14466 (assoc rtn ctable))
14467 ":" ""))))
14468 rtn)
14469 ((eq flag t)
14470 ;; all-completions
14471 (all-completions s2 ctable confirm))
14472 ((eq flag 'lambda)
14473 ;; exact match?
14474 (assoc s2 ctable)))))
14476 (defun org-fast-tag-insert (kwd tags face &optional end)
14477 "Insert KDW, and the TAGS, the latter with face FACE.
14478 Also insert END."
14479 (insert (format "%-12s" (concat kwd ":"))
14480 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14481 (or end "")))
14483 (defun org-fast-tag-show-exit (flag)
14484 (save-excursion
14485 (org-goto-line 3)
14486 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14487 (replace-match ""))
14488 (when flag
14489 (end-of-line 1)
14490 (org-move-to-column (- (window-width) 19) t)
14491 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14493 (defun org-set-current-tags-overlay (current prefix)
14494 "Add an overlay to CURRENT tag with PREFIX."
14495 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14496 (if (featurep 'xemacs)
14497 (org-overlay-display org-tags-overlay (concat prefix s)
14498 'secondary-selection)
14499 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14500 (org-overlay-display org-tags-overlay (concat prefix s)))))
14502 (defvar org-last-tag-selection-key nil)
14503 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14504 "Fast tag selection with single keys.
14505 CURRENT is the current list of tags in the headline, INHERITED is the
14506 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14507 possibly with grouping information. TODO-TABLE is a similar table with
14508 TODO keywords, should these have keys assigned to them.
14509 If the keys are nil, a-z are automatically assigned.
14510 Returns the new tags string, or nil to not change the current settings."
14511 (let* ((fulltable (append table todo-table))
14512 (maxlen (apply 'max (mapcar
14513 (lambda (x)
14514 (if (stringp (car x)) (string-width (car x)) 0))
14515 fulltable)))
14516 (buf (current-buffer))
14517 (expert (eq org-fast-tag-selection-single-key 'expert))
14518 (buffer-tags nil)
14519 (fwidth (+ maxlen 3 1 3))
14520 (ncol (/ (- (window-width) 4) fwidth))
14521 (i-face 'org-done)
14522 (c-face 'org-todo)
14523 tg cnt e c char c1 c2 ntable tbl rtn
14524 ov-start ov-end ov-prefix
14525 (exit-after-next org-fast-tag-selection-single-key)
14526 (done-keywords org-done-keywords)
14527 groups ingroup)
14528 (save-excursion
14529 (beginning-of-line 1)
14530 (if (looking-at
14531 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14532 (setq ov-start (match-beginning 1)
14533 ov-end (match-end 1)
14534 ov-prefix "")
14535 (setq ov-start (1- (point-at-eol))
14536 ov-end (1+ ov-start))
14537 (skip-chars-forward "^\n\r")
14538 (setq ov-prefix
14539 (concat
14540 (buffer-substring (1- (point)) (point))
14541 (if (> (current-column) org-tags-column)
14543 (make-string (- org-tags-column (current-column)) ?\ ))))))
14544 (move-overlay org-tags-overlay ov-start ov-end)
14545 (save-window-excursion
14546 (if expert
14547 (set-buffer (get-buffer-create " *Org tags*"))
14548 (delete-other-windows)
14549 (split-window-vertically)
14550 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14551 (erase-buffer)
14552 (org-set-local 'org-done-keywords done-keywords)
14553 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14554 (org-fast-tag-insert "Current" current c-face "\n\n")
14555 (org-fast-tag-show-exit exit-after-next)
14556 (org-set-current-tags-overlay current ov-prefix)
14557 (setq tbl fulltable char ?a cnt 0)
14558 (while (setq e (pop tbl))
14559 (cond
14560 ((equal (car e) :startgroup)
14561 (push '() groups) (setq ingroup t)
14562 (when (not (= cnt 0))
14563 (setq cnt 0)
14564 (insert "\n"))
14565 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14566 ((equal (car e) :endgroup)
14567 (setq ingroup nil cnt 0)
14568 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14569 ((equal e '(:newline))
14570 (when (not (= cnt 0))
14571 (setq cnt 0)
14572 (insert "\n")
14573 (setq e (car tbl))
14574 (while (equal (car tbl) '(:newline))
14575 (insert "\n")
14576 (setq tbl (cdr tbl)))))
14577 ((equal e '(:grouptags)) nil)
14579 (setq tg (copy-sequence (car e)) c2 nil)
14580 (if (cdr e)
14581 (setq c (cdr e))
14582 ;; automatically assign a character.
14583 (setq c1 (string-to-char
14584 (downcase (substring
14585 tg (if (= (string-to-char tg) ?@) 1 0)))))
14586 (if (or (rassoc c1 ntable) (rassoc c1 table))
14587 (while (or (rassoc char ntable) (rassoc char table))
14588 (setq char (1+ char)))
14589 (setq c2 c1))
14590 (setq c (or c2 char)))
14591 (if ingroup (push tg (car groups)))
14592 (setq tg (org-add-props tg nil 'face
14593 (cond
14594 ((not (assoc tg table))
14595 (org-get-todo-face tg))
14596 ((member tg current) c-face)
14597 ((member tg inherited) i-face))))
14598 (if (equal (caar tbl) :grouptags)
14599 (org-add-props tg nil 'face 'org-tag-group))
14600 (if (and (= cnt 0) (not ingroup)) (insert " "))
14601 (insert "[" c "] " tg (make-string
14602 (- fwidth 4 (length tg)) ?\ ))
14603 (push (cons tg c) ntable)
14604 (when (= (setq cnt (1+ cnt)) ncol)
14605 (insert "\n")
14606 (if ingroup (insert " "))
14607 (setq cnt 0)))))
14608 (setq ntable (nreverse ntable))
14609 (insert "\n")
14610 (goto-char (point-min))
14611 (if (not expert) (org-fit-window-to-buffer))
14612 (setq rtn
14613 (catch 'exit
14614 (while t
14615 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14616 (if (not groups) "no " "")
14617 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14618 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14619 (setq org-last-tag-selection-key c)
14620 (cond
14621 ((= c ?\r) (throw 'exit t))
14622 ((= c ?!)
14623 (setq groups (not groups))
14624 (goto-char (point-min))
14625 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14626 ((= c ?\C-c)
14627 (if (not expert)
14628 (org-fast-tag-show-exit
14629 (setq exit-after-next (not exit-after-next)))
14630 (setq expert nil)
14631 (delete-other-windows)
14632 (set-window-buffer (split-window-vertically) " *Org tags*")
14633 (org-switch-to-buffer-other-window " *Org tags*")
14634 (org-fit-window-to-buffer)))
14635 ((or (= c ?\C-g)
14636 (and (= c ?q) (not (rassoc c ntable))))
14637 (org-detach-overlay org-tags-overlay)
14638 (setq quit-flag t))
14639 ((= c ?\ )
14640 (setq current nil)
14641 (if exit-after-next (setq exit-after-next 'now)))
14642 ((= c ?\t)
14643 (condition-case nil
14644 (setq tg (org-icompleting-read
14645 "Tag: "
14646 (or buffer-tags
14647 (with-current-buffer buf
14648 (org-get-buffer-tags)))))
14649 (quit (setq tg "")))
14650 (when (string-match "\\S-" tg)
14651 (add-to-list 'buffer-tags (list tg))
14652 (if (member tg current)
14653 (setq current (delete tg current))
14654 (push tg current)))
14655 (if exit-after-next (setq exit-after-next 'now)))
14656 ((setq e (rassoc c todo-table) tg (car e))
14657 (with-current-buffer buf
14658 (save-excursion (org-todo tg)))
14659 (if exit-after-next (setq exit-after-next 'now)))
14660 ((setq e (rassoc c ntable) tg (car e))
14661 (if (member tg current)
14662 (setq current (delete tg current))
14663 (loop for g in groups do
14664 (if (member tg g)
14665 (mapc (lambda (x)
14666 (setq current (delete x current)))
14667 g)))
14668 (push tg current))
14669 (if exit-after-next (setq exit-after-next 'now))))
14671 ;; Create a sorted list
14672 (setq current
14673 (sort current
14674 (lambda (a b)
14675 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14676 (if (eq exit-after-next 'now) (throw 'exit t))
14677 (goto-char (point-min))
14678 (beginning-of-line 2)
14679 (delete-region (point) (point-at-eol))
14680 (org-fast-tag-insert "Current" current c-face)
14681 (org-set-current-tags-overlay current ov-prefix)
14682 (while (re-search-forward
14683 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14684 (setq tg (match-string 1))
14685 (add-text-properties
14686 (match-beginning 1) (match-end 1)
14687 (list 'face
14688 (cond
14689 ((member tg current) c-face)
14690 ((member tg inherited) i-face)
14691 (t (get-text-property (match-beginning 1) 'face))))))
14692 (goto-char (point-min)))))
14693 (org-detach-overlay org-tags-overlay)
14694 (if rtn
14695 (mapconcat 'identity current ":")
14696 nil))))
14698 (defun org-get-tags-string ()
14699 "Get the TAGS string in the current headline."
14700 (unless (org-at-heading-p t)
14701 (error "Not on a heading"))
14702 (save-excursion
14703 (beginning-of-line 1)
14704 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14705 (org-match-string-no-properties 1)
14706 "")))
14708 (defun org-get-tags ()
14709 "Get the list of tags specified in the current headline."
14710 (org-split-string (org-get-tags-string) ":"))
14712 (defun org-get-buffer-tags ()
14713 "Get a table of all tags used in the buffer, for completion."
14714 (let (tags)
14715 (save-excursion
14716 (goto-char (point-min))
14717 (while (re-search-forward
14718 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14719 (when (equal (char-after (point-at-bol 0)) ?*)
14720 (mapc (lambda (x) (add-to-list 'tags x))
14721 (org-split-string (org-match-string-no-properties 1) ":")))))
14722 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14723 (mapcar 'list tags)))
14725 ;;;; The mapping API
14727 (defun org-map-entries (func &optional match scope &rest skip)
14728 "Call FUNC at each headline selected by MATCH in SCOPE.
14730 FUNC is a function or a lisp form. The function will be called without
14731 arguments, with the cursor positioned at the beginning of the headline.
14732 The return values of all calls to the function will be collected and
14733 returned as a list.
14735 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14736 does not need to preserve point. After evaluation, the cursor will be
14737 moved to the end of the line (presumably of the headline of the
14738 processed entry) and search continues from there. Under some
14739 circumstances, this may not produce the wanted results. For example,
14740 if you have removed (e.g. archived) the current (sub)tree it could
14741 mean that the next entry will be skipped entirely. In such cases, you
14742 can specify the position from where search should continue by making
14743 FUNC set the variable `org-map-continue-from' to the desired buffer
14744 position.
14746 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14747 Only headlines that are matched by this query will be considered during
14748 the iteration. When MATCH is nil or t, all headlines will be
14749 visited by the iteration.
14751 SCOPE determines the scope of this command. It can be any of:
14753 nil The current buffer, respecting the restriction if any
14754 tree The subtree started with the entry at point
14755 region The entries within the active region, if any
14756 region-start-level
14757 The entries within the active region, but only those at
14758 the same level than the first one.
14759 file The current buffer, without restriction
14760 file-with-archives
14761 The current buffer, and any archives associated with it
14762 agenda All agenda files
14763 agenda-with-archives
14764 All agenda files with any archive files associated with them
14765 \(file1 file2 ...)
14766 If this is a list, all files in the list will be scanned
14768 The remaining args are treated as settings for the skipping facilities of
14769 the scanner. The following items can be given here:
14771 archive skip trees with the archive tag
14772 comment skip trees with the COMMENT keyword
14773 function or Emacs Lisp form:
14774 will be used as value for `org-agenda-skip-function', so
14775 whenever the function returns a position, FUNC will not be
14776 called for that entry and search will continue from the
14777 position returned
14779 If your function needs to retrieve the tags including inherited tags
14780 at the *current* entry, you can use the value of the variable
14781 `org-scanner-tags' which will be much faster than getting the value
14782 with `org-get-tags-at'. If your function gets properties with
14783 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14784 to t around the call to `org-entry-properties' to get the same speedup.
14785 Note that if your function moves around to retrieve tags and properties at
14786 a *different* entry, you cannot use these techniques."
14787 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14788 (not (org-region-active-p)))
14789 (let* ((org-agenda-archives-mode nil) ; just to make sure
14790 (org-agenda-skip-archived-trees (memq 'archive skip))
14791 (org-agenda-skip-comment-trees (memq 'comment skip))
14792 (org-agenda-skip-function
14793 (car (org-delete-all '(comment archive) skip)))
14794 (org-tags-match-list-sublevels t)
14795 (start-level (eq scope 'region-start-level))
14796 matcher file res
14797 org-todo-keywords-for-agenda
14798 org-done-keywords-for-agenda
14799 org-todo-keyword-alist-for-agenda
14800 org-drawers-for-agenda
14801 org-tag-alist-for-agenda
14802 todo-only)
14804 (cond
14805 ((eq match t) (setq matcher t))
14806 ((eq match nil) (setq matcher t))
14807 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14809 (save-window-excursion
14810 (save-restriction
14811 (cond ((eq scope 'tree)
14812 (org-back-to-heading t)
14813 (org-narrow-to-subtree)
14814 (setq scope nil))
14815 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14816 (org-region-active-p))
14817 ;; If needed, set start-level to a string like "2"
14818 (when start-level
14819 (save-excursion
14820 (goto-char (region-beginning))
14821 (unless (org-at-heading-p) (outline-next-heading))
14822 (setq start-level (org-current-level))))
14823 (narrow-to-region (region-beginning)
14824 (save-excursion
14825 (goto-char (region-end))
14826 (unless (and (bolp) (org-at-heading-p))
14827 (outline-next-heading))
14828 (point)))
14829 (setq scope nil)))
14831 (if (not scope)
14832 (progn
14833 (org-agenda-prepare-buffers
14834 (list (buffer-file-name (current-buffer))))
14835 (setq res (org-scan-tags func matcher todo-only start-level)))
14836 ;; Get the right scope
14837 (cond
14838 ((and scope (listp scope) (symbolp (car scope)))
14839 (setq scope (eval scope)))
14840 ((eq scope 'agenda)
14841 (setq scope (org-agenda-files t)))
14842 ((eq scope 'agenda-with-archives)
14843 (setq scope (org-agenda-files t))
14844 (setq scope (org-add-archive-files scope)))
14845 ((eq scope 'file)
14846 (setq scope (list (buffer-file-name))))
14847 ((eq scope 'file-with-archives)
14848 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14849 (org-agenda-prepare-buffers scope)
14850 (while (setq file (pop scope))
14851 (with-current-buffer (org-find-base-buffer-visiting file)
14852 (save-excursion
14853 (save-restriction
14854 (widen)
14855 (goto-char (point-min))
14856 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14857 res)))
14859 ;;;; Properties
14861 ;;; Setting and retrieving properties
14863 (defconst org-special-properties
14864 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14865 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14866 "The special properties valid in Org-mode.
14868 These are properties that are not defined in the property drawer,
14869 but in some other way.")
14871 (defconst org-default-properties
14872 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14873 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14874 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14875 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14876 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14877 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14878 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14879 "Some properties that are used by Org-mode for various purposes.
14880 Being in this list makes sure that they are offered for completion.")
14882 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14883 "Regular expression matching the first line of a property drawer.")
14885 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14886 "Regular expression matching the last line of a property drawer.")
14888 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14889 "Regular expression matching the first line of a property drawer.")
14891 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14892 "Regular expression matching the first line of a property drawer.")
14894 (defconst org-property-drawer-re
14895 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14896 org-property-end-re "\\)\n?")
14897 "Matches an entire property drawer.")
14899 (defconst org-clock-drawer-re
14900 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14901 org-property-end-re "\\)\n?")
14902 "Matches an entire clock drawer.")
14904 (defsubst org-re-property (property)
14905 "Return a regexp matching a PROPERTY line.
14906 Match group 1 will be set to the value."
14907 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14909 (defsubst org-re-property-keyword (property)
14910 "Return a regexp matching a PROPERTY line, possibly with no
14911 value for the property."
14912 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14914 (defun org-property-action ()
14915 "Do an action on properties."
14916 (interactive)
14917 (let (c)
14918 (org-at-property-p)
14919 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14920 (setq c (read-char-exclusive))
14921 (cond
14922 ((equal c ?s)
14923 (call-interactively 'org-set-property))
14924 ((equal c ?d)
14925 (call-interactively 'org-delete-property))
14926 ((equal c ?D)
14927 (call-interactively 'org-delete-property-globally))
14928 ((equal c ?c)
14929 (call-interactively 'org-compute-property-at-point))
14930 (t (error "No such property action %c" c)))))
14932 (defun org-inc-effort ()
14933 "Increment the value of the effort property in the current entry."
14934 (interactive)
14935 (org-set-effort nil t))
14937 (defvar org-clock-effort) ;; Defined in org-clock.el
14938 (defvar org-clock-current-task) ;; Defined in org-clock.el
14939 (defun org-set-effort (&optional value increment)
14940 "Set the effort property of the current entry.
14941 With numerical prefix arg, use the nth allowed value, 0 stands for the
14942 10th allowed value.
14944 When INCREMENT is non-nil, set the property to the next allowed value."
14945 (interactive "P")
14946 (if (equal value 0) (setq value 10))
14947 (let* ((completion-ignore-case t)
14948 (prop org-effort-property)
14949 (cur (org-entry-get nil prop))
14950 (allowed (org-property-get-allowed-values nil prop 'table))
14951 (existing (mapcar 'list (org-property-values prop)))
14952 (heading (nth 4 (org-heading-components)))
14954 (val (cond
14955 ((stringp value) value)
14956 ((and allowed (integerp value))
14957 (or (car (nth (1- value) allowed))
14958 (car (org-last allowed))))
14959 ((and allowed increment)
14960 (or (caadr (member (list cur) allowed))
14961 (error "Allowed effort values are not set")))
14962 (allowed
14963 (message "Select 1-9,0, [RET%s]: %s"
14964 (if cur (concat "=" cur) "")
14965 (mapconcat 'car allowed " "))
14966 (setq rpl (read-char-exclusive))
14967 (if (equal rpl ?\r)
14969 (setq rpl (- rpl ?0))
14970 (if (equal rpl 0) (setq rpl 10))
14971 (if (and (> rpl 0) (<= rpl (length allowed)))
14972 (car (nth (1- rpl) allowed))
14973 (org-completing-read "Effort: " allowed nil))))
14975 (let (org-completion-use-ido org-completion-use-iswitchb)
14976 (org-completing-read
14977 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14978 (concat "[" cur "]") "")
14979 ": ")
14980 existing nil nil "" nil cur))))))
14981 (unless (equal (org-entry-get nil prop) val)
14982 (org-entry-put nil prop val))
14983 (save-excursion
14984 (org-back-to-heading t)
14985 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14986 (when (string= heading org-clock-current-task)
14987 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14988 (org-clock-update-mode-line))
14989 (message "%s is now %s" prop val)))
14991 (defun org-at-property-p ()
14992 "Is cursor inside a property drawer?"
14993 (save-excursion
14994 (beginning-of-line 1)
14995 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14996 (save-match-data ;; Used by calling procedures
14997 (let ((p (point))
14998 (range (unless (org-before-first-heading-p)
14999 (org-get-property-block))))
15000 (and range (<= (car range) p) (< p (cdr range))))))))
15002 (defun org-get-property-block (&optional beg end force)
15003 "Return the (beg . end) range of the body of the property drawer.
15004 BEG and END are the beginning and end of the current subtree, or of
15005 the part before the first headline. If they are not given, they will
15006 be found. If the drawer does not exist and FORCE is non-nil, create
15007 the drawer."
15008 (catch 'exit
15009 (save-excursion
15010 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15011 (progn (org-back-to-heading t) (point))))
15012 (end (or end (and (not (outline-next-heading)) (point-max))
15013 (point))))
15014 (goto-char beg)
15015 (if (re-search-forward org-property-start-re end t)
15016 (setq beg (1+ (match-end 0)))
15017 (if force
15018 (save-excursion
15019 (org-insert-property-drawer)
15020 (setq end (progn (outline-next-heading) (point))))
15021 (throw 'exit nil))
15022 (goto-char beg)
15023 (if (re-search-forward org-property-start-re end t)
15024 (setq beg (1+ (match-end 0)))))
15025 (if (re-search-forward org-property-end-re end t)
15026 (setq end (match-beginning 0))
15027 (or force (throw 'exit nil))
15028 (goto-char beg)
15029 (setq end beg)
15030 (org-indent-line)
15031 (insert ":END:\n"))
15032 (cons beg end)))))
15034 (defun org-entry-properties (&optional pom which specific)
15035 "Get all properties of the entry at point-or-marker POM.
15036 This includes the TODO keyword, the tags, time strings for deadline,
15037 scheduled, and clocking, and any additional properties defined in the
15038 entry. The return value is an alist, keys may occur multiple times
15039 if the property key was used several times.
15040 POM may also be nil, in which case the current entry is used.
15041 If WHICH is nil or `all', get all properties. If WHICH is
15042 `special' or `standard', only get that subclass. If WHICH
15043 is a string only get exactly this property. SPECIFIC can be a string, the
15044 specific property we are interested in. Specifying it can speed
15045 things up because then unnecessary parsing is avoided."
15046 (setq which (or which 'all))
15047 (org-with-point-at pom
15048 (let ((clockstr (substring org-clock-string 0 -1))
15049 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15050 (case-fold-search nil)
15051 beg end range props sum-props key key1 value string clocksum clocksumt)
15052 (save-excursion
15053 (when (condition-case nil
15054 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15055 (error nil))
15056 (setq beg (point))
15057 (setq sum-props (get-text-property (point) 'org-summaries))
15058 (setq clocksum (get-text-property (point) :org-clock-minutes)
15059 clocksumt (get-text-property (point) :org-clock-minutes-today))
15060 (outline-next-heading)
15061 (setq end (point))
15062 (when (memq which '(all special))
15063 ;; Get the special properties, like TODO and tags
15064 (goto-char beg)
15065 (when (and (or (not specific) (string= specific "TODO"))
15066 (looking-at org-todo-line-regexp) (match-end 2))
15067 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15068 (when (and (or (not specific) (string= specific "PRIORITY"))
15069 (looking-at org-priority-regexp))
15070 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15071 (when (or (not specific) (string= specific "FILE"))
15072 (push (cons "FILE" buffer-file-name) props))
15073 (when (and (or (not specific) (string= specific "TAGS"))
15074 (setq value (org-get-tags-string))
15075 (string-match "\\S-" value))
15076 (push (cons "TAGS" value) props))
15077 (when (and (or (not specific) (string= specific "ALLTAGS"))
15078 (setq value (org-get-tags-at)))
15079 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15080 ":"))
15081 props))
15082 (when (or (not specific) (string= specific "BLOCKED"))
15083 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15084 (when (or (not specific)
15085 (member specific
15086 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15087 "TIMESTAMP" "TIMESTAMP_IA")))
15088 (catch 'match
15089 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15090 (setq key (if (match-end 1)
15091 (substring (org-match-string-no-properties 1)
15092 0 -1))
15093 string (if (equal key clockstr)
15094 (org-trim
15095 (buffer-substring-no-properties
15096 (match-beginning 3) (goto-char
15097 (point-at-eol))))
15098 (substring (org-match-string-no-properties 3)
15099 1 -1)))
15100 ;; Get the correct property name from the key. This is
15101 ;; necessary if the user has configured time keywords.
15102 (setq key1 (concat key ":"))
15103 (cond
15104 ((not key)
15105 (setq key
15106 (if (= (char-after (match-beginning 3)) ?\[)
15107 "TIMESTAMP_IA" "TIMESTAMP")))
15108 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15109 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15110 ((equal key1 org-closed-string) (setq key "CLOSED"))
15111 ((equal key1 org-clock-string) (setq key "CLOCK")))
15112 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15113 (progn
15114 (push (cons key string) props)
15115 ;; no need to search further if match is found
15116 (throw 'match t))
15117 (when (or (equal key "CLOCK") (not (assoc key props)))
15118 (push (cons key string) props)))))))
15120 (when (memq which '(all standard))
15121 ;; Get the standard properties, like :PROP: ...
15122 (setq range (org-get-property-block beg end))
15123 (when range
15124 (goto-char (car range))
15125 (while (re-search-forward
15126 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15127 (cdr range) t)
15128 (setq key (org-match-string-no-properties 1)
15129 value (org-trim (or (org-match-string-no-properties 2) "")))
15130 (unless (member key excluded)
15131 (push (cons key (or value "")) props)))))
15132 (if clocksum
15133 (push (cons "CLOCKSUM"
15134 (org-columns-number-to-string (/ (float clocksum) 60.)
15135 'add_times))
15136 props))
15137 (if clocksumt
15138 (push (cons "CLOCKSUM_T"
15139 (org-columns-number-to-string (/ (float clocksumt) 60.)
15140 'add_times))
15141 props))
15142 (unless (assoc "CATEGORY" props)
15143 (push (cons "CATEGORY" (org-get-category)) props))
15144 (append sum-props (nreverse props)))))))
15146 (defun org-entry-get (pom property &optional inherit literal-nil)
15147 "Get value of PROPERTY for entry or content at point-or-marker POM.
15148 If INHERIT is non-nil and the entry does not have the property,
15149 then also check higher levels of the hierarchy.
15150 If INHERIT is the symbol `selective', use inheritance only if the setting
15151 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15152 If the property is present but empty, the return value is the empty string.
15153 If the property is not present at all, nil is returned.
15155 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15156 do not interpret it as the list atom nil. This is used for inheritance
15157 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15158 (org-with-point-at pom
15159 (if (and inherit (if (eq inherit 'selective)
15160 (org-property-inherit-p property)
15162 (org-entry-get-with-inheritance property literal-nil)
15163 (if (member property org-special-properties)
15164 ;; We need a special property. Use `org-entry-properties' to
15165 ;; retrieve it, but specify the wanted property
15166 (cdr (assoc property (org-entry-properties nil 'special property)))
15167 (let ((range (org-get-property-block)))
15168 (when (and range (not (eq (car range) (cdr range))))
15169 (let* ((props (list (or (assoc property org-file-properties)
15170 (assoc property org-global-properties)
15171 (assoc property org-global-properties-fixed))))
15172 (ap (lambda (key)
15173 (when (re-search-forward
15174 (org-re-property key) (cdr range) t)
15175 (setq props
15176 (org-update-property-plist
15178 (if (match-end 1)
15179 (org-match-string-no-properties 1) "")
15180 props)))))
15181 val)
15182 (goto-char (car range))
15183 (funcall ap property)
15184 (goto-char (car range))
15185 (while (funcall ap (concat property "+")))
15186 (setq val (cdr (assoc property props)))
15187 (when val (if literal-nil val (org-not-nil val))))))))))
15189 (defun org-property-or-variable-value (var &optional inherit)
15190 "Check if there is a property fixing the value of VAR.
15191 If yes, return this value. If not, return the current value of the variable."
15192 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15193 (if (and prop (stringp prop) (string-match "\\S-" prop))
15194 (read prop)
15195 (symbol-value var))))
15197 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15198 "Delete the property PROPERTY from entry at point-or-marker POM.
15199 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15200 an empty drawer to delete."
15201 (org-with-point-at pom
15202 (if (member property org-special-properties)
15203 nil ; cannot delete these properties.
15204 (let ((range (org-get-property-block)))
15205 (if (and range
15206 (goto-char (car range))
15207 (re-search-forward
15208 (org-re-property property)
15209 (cdr range) t))
15210 (progn
15211 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15212 (and delete-empty-drawer
15213 (org-remove-empty-drawer-at
15214 delete-empty-drawer (car range)))
15216 nil)))))
15218 ;; Multi-values properties are properties that contain multiple values
15219 ;; These values are assumed to be single words, separated by whitespace.
15220 (defun org-entry-add-to-multivalued-property (pom property value)
15221 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15222 (let* ((old (org-entry-get pom property))
15223 (values (and old (org-split-string old "[ \t]"))))
15224 (setq value (org-entry-protect-space value))
15225 (unless (member value values)
15226 (setq values (append values (list value)))
15227 (org-entry-put pom property
15228 (mapconcat 'identity values " ")))))
15230 (defun org-entry-remove-from-multivalued-property (pom property value)
15231 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15232 (let* ((old (org-entry-get pom property))
15233 (values (and old (org-split-string old "[ \t]"))))
15234 (setq value (org-entry-protect-space value))
15235 (when (member value values)
15236 (setq values (delete value values))
15237 (org-entry-put pom property
15238 (mapconcat 'identity values " ")))))
15240 (defun org-entry-member-in-multivalued-property (pom property value)
15241 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15242 (let* ((old (org-entry-get pom property))
15243 (values (and old (org-split-string old "[ \t]"))))
15244 (setq value (org-entry-protect-space value))
15245 (member value values)))
15247 (defun org-entry-get-multivalued-property (pom property)
15248 "Return a list of values in a multivalued property."
15249 (let* ((value (org-entry-get pom property))
15250 (values (and value (org-split-string value "[ \t]"))))
15251 (mapcar 'org-entry-restore-space values)))
15253 (defun org-entry-put-multivalued-property (pom property &rest values)
15254 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15255 VALUES should be a list of strings. Spaces will be protected."
15256 (org-entry-put pom property
15257 (mapconcat 'org-entry-protect-space values " "))
15258 (let* ((value (org-entry-get pom property))
15259 (values (and value (org-split-string value "[ \t]"))))
15260 (mapcar 'org-entry-restore-space values)))
15262 (defun org-entry-protect-space (s)
15263 "Protect spaces and newline in string S."
15264 (while (string-match " " s)
15265 (setq s (replace-match "%20" t t s)))
15266 (while (string-match "\n" s)
15267 (setq s (replace-match "%0A" t t s)))
15270 (defun org-entry-restore-space (s)
15271 "Restore spaces and newline in string S."
15272 (while (string-match "%20" s)
15273 (setq s (replace-match " " t t s)))
15274 (while (string-match "%0A" s)
15275 (setq s (replace-match "\n" t t s)))
15278 (defvar org-entry-property-inherited-from (make-marker)
15279 "Marker pointing to the entry from where a property was inherited.
15280 Each call to `org-entry-get-with-inheritance' will set this marker to the
15281 location of the entry where the inheritance search matched. If there was
15282 no match, the marker will point nowhere.
15283 Note that also `org-entry-get' calls this function, if the INHERIT flag
15284 is set.")
15286 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15287 "Get PROPERTY of entry or content at point, search higher levels if needed.
15288 The search will stop at the first ancestor which has the property defined.
15289 If the value found is \"nil\", return nil to show that the property
15290 should be considered as undefined (this is the meaning of nil here).
15291 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15292 (move-marker org-entry-property-inherited-from nil)
15293 (let (tmp)
15294 (save-excursion
15295 (save-restriction
15296 (widen)
15297 (catch 'ex
15298 (while t
15299 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15300 (or (ignore-errors (org-back-to-heading t))
15301 (goto-char (point-min)))
15302 (move-marker org-entry-property-inherited-from (point))
15303 (throw 'ex tmp))
15304 (or (ignore-errors (org-up-heading-safe))
15305 (throw 'ex nil))))))
15306 (setq tmp (or tmp
15307 (cdr (assoc property org-file-properties))
15308 (cdr (assoc property org-global-properties))
15309 (cdr (assoc property org-global-properties-fixed))))
15310 (if literal-nil tmp (org-not-nil tmp))))
15312 (defvar org-property-changed-functions nil
15313 "Hook called when the value of a property has changed.
15314 Each hook function should accept two arguments, the name of the property
15315 and the new value.")
15317 (defun org-entry-put (pom property value)
15318 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15319 (org-with-point-at pom
15320 (org-back-to-heading t)
15321 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15322 range)
15323 (cond
15324 ((equal property "TODO")
15325 (when (and (stringp value) (string-match "\\S-" value)
15326 (not (member value org-todo-keywords-1)))
15327 (error "\"%s\" is not a valid TODO state" value))
15328 (if (or (not value)
15329 (not (string-match "\\S-" value)))
15330 (setq value 'none))
15331 (org-todo value)
15332 (org-set-tags nil 'align))
15333 ((equal property "PRIORITY")
15334 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15335 (string-to-char value) ?\ ))
15336 (org-set-tags nil 'align))
15337 ((equal property "CLOCKSUM")
15338 (if (not (re-search-forward
15339 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15340 (error "Cannot find a clock log")
15341 (goto-char (- (match-end 1) 2))
15342 (cond
15343 ((eq value 'earlier) (org-timestamp-down))
15344 ((eq value 'later) (org-timestamp-up)))
15345 (org-clock-sum-current-item)))
15346 ((equal property "SCHEDULED")
15347 (if (re-search-forward org-scheduled-time-regexp end t)
15348 (cond
15349 ((eq value 'earlier) (org-timestamp-change -1 'day))
15350 ((eq value 'later) (org-timestamp-change 1 'day))
15351 (t (call-interactively 'org-schedule)))
15352 (call-interactively 'org-schedule)))
15353 ((equal property "DEADLINE")
15354 (if (re-search-forward org-deadline-time-regexp end t)
15355 (cond
15356 ((eq value 'earlier) (org-timestamp-change -1 'day))
15357 ((eq value 'later) (org-timestamp-change 1 'day))
15358 (t (call-interactively 'org-deadline)))
15359 (call-interactively 'org-deadline)))
15360 ((member property org-special-properties)
15361 (error "The %s property can not yet be set with `org-entry-put'"
15362 property))
15363 (t ; a non-special property
15364 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15365 (setq range (org-get-property-block beg end 'force))
15366 (goto-char (car range))
15367 (if (re-search-forward
15368 (org-re-property-keyword property) (cdr range) t)
15369 (progn
15370 (delete-region (match-beginning 0) (match-end 0))
15371 (goto-char (match-beginning 0)))
15372 (goto-char (cdr range))
15373 (insert "\n")
15374 (backward-char 1)
15375 (org-indent-line))
15376 (insert ":" property ":")
15377 (and value (insert " " value))
15378 (org-indent-line)))))
15379 (run-hook-with-args 'org-property-changed-functions property value)))
15381 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15382 "Get all property keys in the current buffer.
15383 With INCLUDE-SPECIALS, also list the special properties that reflect things
15384 like tags and TODO state.
15385 With INCLUDE-DEFAULTS, also include properties that has special meaning
15386 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15387 and others.
15388 With INCLUDE-COLUMNS, also include property names given in COLUMN
15389 formats in the current buffer."
15390 (let (rtn range cfmt s p)
15391 (save-excursion
15392 (save-restriction
15393 (widen)
15394 (goto-char (point-min))
15395 (while (re-search-forward org-property-start-re nil t)
15396 (setq range (org-get-property-block))
15397 (goto-char (car range))
15398 (while (re-search-forward
15399 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15400 (cdr range) t)
15401 (add-to-list 'rtn (org-match-string-no-properties 1)))
15402 (outline-next-heading))))
15404 (when include-specials
15405 (setq rtn (append org-special-properties rtn)))
15407 (when include-defaults
15408 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15409 (add-to-list 'rtn org-effort-property))
15411 (when include-columns
15412 (save-excursion
15413 (save-restriction
15414 (widen)
15415 (goto-char (point-min))
15416 (while (re-search-forward
15417 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15418 nil t)
15419 (setq cfmt (match-string 2) s 0)
15420 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15421 cfmt s)
15422 (setq s (match-end 0)
15423 p (match-string 1 cfmt))
15424 (unless (or (equal p "ITEM")
15425 (member p org-special-properties))
15426 (add-to-list 'rtn (match-string 1 cfmt))))))))
15428 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15430 (defun org-property-values (key)
15431 "Return a list of all values of property KEY in the current buffer."
15432 (save-excursion
15433 (save-restriction
15434 (widen)
15435 (goto-char (point-min))
15436 (let ((re (org-re-property key))
15437 values)
15438 (while (re-search-forward re nil t)
15439 (add-to-list 'values (org-trim (match-string 1))))
15440 (delete "" values)))))
15442 (defun org-insert-property-drawer ()
15443 "Insert a property drawer into the current entry."
15444 (org-back-to-heading t)
15445 (looking-at org-outline-regexp)
15446 (let ((indent (if org-adapt-indentation
15447 (- (match-end 0) (match-beginning 0))
15449 (beg (point))
15450 (re (concat "^[ \t]*" org-keyword-time-regexp))
15451 end hiddenp)
15452 (outline-next-heading)
15453 (setq end (point))
15454 (goto-char beg)
15455 (while (re-search-forward re end t))
15456 (setq hiddenp (outline-invisible-p))
15457 (end-of-line 1)
15458 (and (equal (char-after) ?\n) (forward-char 1))
15459 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15460 (if (member (match-string 1) '("CLOCK:" ":END:"))
15461 ;; just skip this line
15462 (beginning-of-line 2)
15463 ;; Drawer start, find the end
15464 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15465 (beginning-of-line 1)))
15466 (org-skip-over-state-notes)
15467 (skip-chars-backward " \t\n\r")
15468 (if (eq (char-before) ?*) (forward-char 1))
15469 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15470 (beginning-of-line 0)
15471 (org-indent-to-column indent)
15472 (beginning-of-line 2)
15473 (org-indent-to-column indent)
15474 (beginning-of-line 0)
15475 (if hiddenp
15476 (save-excursion
15477 (org-back-to-heading t)
15478 (hide-entry))
15479 (org-flag-drawer t))))
15481 (defun org-insert-drawer (&optional arg drawer)
15482 "Insert a drawer at point.
15484 Optional argument DRAWER, when non-nil, is a string representing
15485 drawer's name. Otherwise, the user is prompted for a name.
15487 If a region is active, insert the drawer around that region
15488 instead.
15490 Point is left between drawer's boundaries."
15491 (interactive "P")
15492 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15493 "LOGBOOK"))
15494 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15495 ;; internally by Org. They are meant to be inserted
15496 ;; automatically.
15497 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15498 ;; Remove system drawers from list. Note: For some reason,
15499 ;; `org-completing-read' ignores the predicate while
15500 ;; `completing-read' handles it fine.
15501 (drawer (if arg "PROPERTIES"
15502 (or drawer
15503 (completing-read
15504 "Drawer: " org-drawers
15505 (lambda (d) (not (member d system-drawers))))))))
15506 (cond
15507 ;; With C-u, fall back on `org-insert-property-drawer'
15508 (arg (org-insert-property-drawer))
15509 ;; With an active region, insert a drawer at point.
15510 ((not (org-region-active-p))
15511 (progn
15512 (unless (bolp) (insert "\n"))
15513 (insert (format ":%s:\n\n:END:\n" drawer))
15514 (forward-line -2)))
15515 ;; Otherwise, insert the drawer at point
15517 (let ((rbeg (region-beginning))
15518 (rend (copy-marker (region-end))))
15519 (unwind-protect
15520 (progn
15521 (goto-char rbeg)
15522 (beginning-of-line)
15523 (when (save-excursion
15524 (re-search-forward org-outline-regexp-bol rend t))
15525 (error "Drawers cannot contain headlines"))
15526 ;; Position point at the beginning of the first
15527 ;; non-blank line in region. Insert drawer's opening
15528 ;; there, then indent it.
15529 (org-skip-whitespace)
15530 (beginning-of-line)
15531 (insert ":" drawer ":\n")
15532 (forward-line -1)
15533 (indent-for-tab-command)
15534 ;; Move point to the beginning of the first blank line
15535 ;; after the last non-blank line in region. Insert
15536 ;; drawer's closing, then indent it.
15537 (goto-char rend)
15538 (skip-chars-backward " \r\t\n")
15539 (insert "\n:END:")
15540 (deactivate-mark t)
15541 (indent-for-tab-command)
15542 (unless (eolp) (insert "\n")))
15543 ;; Clear marker, whatever the outcome of insertion is.
15544 (set-marker rend nil)))))))
15546 (defvar org-property-set-functions-alist nil
15547 "Property set function alist.
15548 Each entry should have the following format:
15550 (PROPERTY . READ-FUNCTION)
15552 The read function will be called with the same argument as
15553 `org-completing-read'.")
15555 (defun org-set-property-function (property)
15556 "Get the function that should be used to set PROPERTY.
15557 This is computed according to `org-property-set-functions-alist'."
15558 (or (cdr (assoc property org-property-set-functions-alist))
15559 'org-completing-read))
15561 (defun org-read-property-value (property)
15562 "Read PROPERTY value from user."
15563 (let* ((completion-ignore-case t)
15564 (allowed (org-property-get-allowed-values nil property 'table))
15565 (cur (org-entry-get nil property))
15566 (prompt (concat property " value"
15567 (if (and cur (string-match "\\S-" cur))
15568 (concat " [" cur "]") "") ": "))
15569 (set-function (org-set-property-function property))
15570 (val (if allowed
15571 (funcall set-function prompt allowed nil
15572 (not (get-text-property 0 'org-unrestricted
15573 (caar allowed))))
15574 (let (org-completion-use-ido org-completion-use-iswitchb)
15575 (funcall set-function prompt
15576 (mapcar 'list (org-property-values property))
15577 nil nil "" nil cur)))))
15578 (if (equal val "")
15580 val)))
15582 (defvar org-last-set-property nil)
15583 (defvar org-last-set-property-value nil)
15584 (defun org-read-property-name ()
15585 "Read a property name."
15586 (let* ((completion-ignore-case t)
15587 (keys (org-buffer-property-keys nil t t))
15588 (default-prop (or (save-excursion
15589 (save-match-data
15590 (beginning-of-line)
15591 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15592 (null (string= (match-string 1) "END"))
15593 (match-string 1))))
15594 org-last-set-property))
15595 (property (org-icompleting-read
15596 (concat "Property"
15597 (if default-prop (concat " [" default-prop "]") "")
15598 ": ")
15599 (mapcar 'list keys)
15600 nil nil nil nil
15601 default-prop)))
15602 (if (member property keys)
15603 property
15604 (or (cdr (assoc (downcase property)
15605 (mapcar (lambda (x) (cons (downcase x) x))
15606 keys)))
15607 property))))
15609 (defun org-set-property-and-value (use-last)
15610 "Allow to set [PROPERTY]: [value] direction from prompt.
15611 When use-default, don't even ask, just use the last
15612 \"[PROPERTY]: [value]\" string from the history."
15613 (interactive "P")
15614 (let* ((completion-ignore-case t)
15615 (pv (or (and use-last org-last-set-property-value)
15616 (org-completing-read
15617 "Enter a \"[Property]: [value]\" pair: "
15618 nil nil nil nil nil
15619 org-last-set-property-value)))
15620 prop val)
15621 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15622 (setq prop (match-string 1 pv)
15623 val (match-string 2 pv))
15624 (org-set-property prop val))))
15626 (defun org-set-property (property value)
15627 "In the current entry, set PROPERTY to VALUE.
15628 When called interactively, this will prompt for a property name, offering
15629 completion on existing and default properties. And then it will prompt
15630 for a value, offering completion either on allowed values (via an inherited
15631 xxx_ALL property) or on existing values in other instances of this property
15632 in the current file."
15633 (interactive (list nil nil))
15634 (let* ((property (or property (org-read-property-name)))
15635 (value (or value (org-read-property-value property)))
15636 (fn (cdr (assoc property org-properties-postprocess-alist))))
15637 (setq org-last-set-property property)
15638 (setq org-last-set-property-value (concat property ": " value))
15639 ;; Possibly postprocess the inserted value:
15640 (when fn (setq value (funcall fn value)))
15641 (unless (equal (org-entry-get nil property) value)
15642 (org-entry-put nil property value))))
15644 (defun org-delete-property (property &optional delete-empty-drawer)
15645 "In the current entry, delete PROPERTY.
15646 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15647 an empty drawer to delete."
15648 (interactive
15649 (let* ((completion-ignore-case t)
15650 (prop (org-icompleting-read "Property: "
15651 (org-entry-properties nil 'standard))))
15652 (list prop)))
15653 (message "Property %s %s" property
15654 (if (org-entry-delete nil property delete-empty-drawer)
15655 "deleted"
15656 "was not present in the entry")))
15658 (defun org-delete-property-globally (property)
15659 "Remove PROPERTY globally, from all entries."
15660 (interactive
15661 (let* ((completion-ignore-case t)
15662 (prop (org-icompleting-read
15663 "Globally remove property: "
15664 (mapcar 'list (org-buffer-property-keys)))))
15665 (list prop)))
15666 (save-excursion
15667 (save-restriction
15668 (widen)
15669 (goto-char (point-min))
15670 (let ((cnt 0))
15671 (while (re-search-forward
15672 (org-re-property property)
15673 nil t)
15674 (setq cnt (1+ cnt))
15675 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15676 (message "Property \"%s\" removed from %d entries" property cnt)))))
15678 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15680 (defun org-compute-property-at-point ()
15681 "Compute the property at point.
15682 This looks for an enclosing column format, extracts the operator and
15683 then applies it to the property in the column format's scope."
15684 (interactive)
15685 (unless (org-at-property-p)
15686 (error "Not at a property"))
15687 (let ((prop (org-match-string-no-properties 2)))
15688 (org-columns-get-format-and-top-level)
15689 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15690 (error "No operator defined for property %s" prop))
15691 (org-columns-compute prop)))
15693 (defvar org-property-allowed-value-functions nil
15694 "Hook for functions supplying allowed values for a specific property.
15695 The functions must take a single argument, the name of the property, and
15696 return a flat list of allowed values. If \":ETC\" is one of
15697 the values, this means that these values are intended as defaults for
15698 completion, but that other values should be allowed too.
15699 The functions must return nil if they are not responsible for this
15700 property.")
15702 (defun org-property-get-allowed-values (pom property &optional table)
15703 "Get allowed values for the property PROPERTY.
15704 When TABLE is non-nil, return an alist that can directly be used for
15705 completion."
15706 (let (vals)
15707 (cond
15708 ((equal property "TODO")
15709 (setq vals (org-with-point-at pom
15710 (append org-todo-keywords-1 '("")))))
15711 ((equal property "PRIORITY")
15712 (let ((n org-lowest-priority))
15713 (while (>= n org-highest-priority)
15714 (push (char-to-string n) vals)
15715 (setq n (1- n)))))
15716 ((member property org-special-properties))
15717 ((setq vals (run-hook-with-args-until-success
15718 'org-property-allowed-value-functions property)))
15720 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15721 (when (and vals (string-match "\\S-" vals))
15722 (setq vals (car (read-from-string (concat "(" vals ")"))))
15723 (setq vals (mapcar (lambda (x)
15724 (cond ((stringp x) x)
15725 ((numberp x) (number-to-string x))
15726 ((symbolp x) (symbol-name x))
15727 (t "???")))
15728 vals)))))
15729 (when (member ":ETC" vals)
15730 (setq vals (remove ":ETC" vals))
15731 (org-add-props (car vals) '(org-unrestricted t)))
15732 (if table (mapcar 'list vals) vals)))
15734 (defun org-property-previous-allowed-value (&optional previous)
15735 "Switch to the next allowed value for this property."
15736 (interactive)
15737 (org-property-next-allowed-value t))
15739 (defun org-property-next-allowed-value (&optional previous)
15740 "Switch to the next allowed value for this property."
15741 (interactive)
15742 (unless (org-at-property-p)
15743 (error "Not at a property"))
15744 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15745 (key (match-string 2))
15746 (value (match-string 3))
15747 (allowed (or (org-property-get-allowed-values (point) key)
15748 (and (member value '("[ ]" "[-]" "[X]"))
15749 '("[ ]" "[X]"))))
15750 (heading (save-match-data (nth 4 (org-heading-components))))
15751 nval)
15752 (unless allowed
15753 (error "Allowed values for this property have not been defined"))
15754 (if previous (setq allowed (reverse allowed)))
15755 (if (member value allowed)
15756 (setq nval (car (cdr (member value allowed)))))
15757 (setq nval (or nval (car allowed)))
15758 (if (equal nval value)
15759 (error "Only one allowed value for this property"))
15760 (org-at-property-p)
15761 (replace-match (concat " :" key ": " nval) t t)
15762 (org-indent-line)
15763 (beginning-of-line 1)
15764 (skip-chars-forward " \t")
15765 (when (equal prop org-effort-property)
15766 (save-excursion
15767 (org-back-to-heading t)
15768 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15769 (when (string= org-clock-current-task heading)
15770 (setq org-clock-effort nval)
15771 (org-clock-update-mode-line)))
15772 (run-hook-with-args 'org-property-changed-functions key nval)))
15774 (defun org-find-olp (path &optional this-buffer)
15775 "Return a marker pointing to the entry at outline path OLP.
15776 If anything goes wrong, throw an error.
15777 You can wrap this call to catch the error like this:
15779 (condition-case msg
15780 (org-mobile-locate-entry (match-string 4))
15781 (error (nth 1 msg)))
15783 The return value will then be either a string with the error message,
15784 or a marker if everything is OK.
15786 If THIS-BUFFER is set, the outline path does not contain a file,
15787 only headings."
15788 (let* ((file (if this-buffer buffer-file-name (pop path)))
15789 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15790 (level 1)
15791 (lmin 1)
15792 (lmax 1)
15793 limit re end found pos heading cnt flevel)
15794 (unless buffer (error "File not found :%s" file))
15795 (with-current-buffer buffer
15796 (save-excursion
15797 (save-restriction
15798 (widen)
15799 (setq limit (point-max))
15800 (goto-char (point-min))
15801 (while (setq heading (pop path))
15802 (setq re (format org-complex-heading-regexp-format
15803 (regexp-quote heading)))
15804 (setq cnt 0 pos (point))
15805 (while (re-search-forward re end t)
15806 (setq level (- (match-end 1) (match-beginning 1)))
15807 (if (and (>= level lmin) (<= level lmax))
15808 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15809 (when (= cnt 0) (error "Heading not found on level %d: %s"
15810 lmax heading))
15811 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15812 lmax heading))
15813 (goto-char found)
15814 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15815 (setq end (save-excursion (org-end-of-subtree t t))))
15816 (when (org-at-heading-p)
15817 (point-marker)))))))
15819 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15820 "Find node HEADING in BUFFER.
15821 Return a marker to the heading if it was found, or nil if not.
15822 If POS-ONLY is set, return just the position instead of a marker.
15824 The heading text must match exact, but it may have a TODO keyword,
15825 a priority cookie and tags in the standard locations."
15826 (with-current-buffer (or buffer (current-buffer))
15827 (save-excursion
15828 (save-restriction
15829 (widen)
15830 (goto-char (point-min))
15831 (let (case-fold-search)
15832 (if (re-search-forward
15833 (format org-complex-heading-regexp-format
15834 (regexp-quote heading)) nil t)
15835 (if pos-only
15836 (match-beginning 0)
15837 (move-marker (make-marker) (match-beginning 0)))))))))
15839 (defun org-find-exact-heading-in-directory (heading &optional dir)
15840 "Find Org node headline HEADING in all .org files in directory DIR.
15841 When the target headline is found, return a marker to this location."
15842 (let ((files (directory-files (or dir default-directory)
15843 nil "\\`[^.#].*\\.org\\'"))
15844 file visiting m buffer)
15845 (catch 'found
15846 (while (setq file (pop files))
15847 (message "trying %s" file)
15848 (setq visiting (org-find-base-buffer-visiting file))
15849 (setq buffer (or visiting (find-file-noselect file)))
15850 (setq m (org-find-exact-headline-in-buffer
15851 heading buffer))
15852 (when (and (not m) (not visiting)) (kill-buffer buffer))
15853 (and m (throw 'found m))))))
15855 (defun org-find-entry-with-id (ident)
15856 "Locate the entry that contains the ID property with exact value IDENT.
15857 IDENT can be a string, a symbol or a number, this function will search for
15858 the string representation of it.
15859 Return the position where this entry starts, or nil if there is no such entry."
15860 (interactive "sID: ")
15861 (let ((id (cond
15862 ((stringp ident) ident)
15863 ((symbol-name ident) (symbol-name ident))
15864 ((numberp ident) (number-to-string ident))
15865 (t (error "IDENT %s must be a string, symbol or number" ident))))
15866 (case-fold-search nil))
15867 (save-excursion
15868 (save-restriction
15869 (widen)
15870 (goto-char (point-min))
15871 (when (re-search-forward
15872 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15873 nil t)
15874 (org-back-to-heading t)
15875 (point))))))
15877 ;;;; Timestamps
15879 (defvar org-last-changed-timestamp nil)
15880 (defvar org-last-inserted-timestamp nil
15881 "The last time stamp inserted with `org-insert-time-stamp'.")
15882 (defvar org-time-was-given) ; dynamically scoped parameter
15883 (defvar org-end-time-was-given) ; dynamically scoped parameter
15884 (defvar org-ts-what) ; dynamically scoped parameter
15886 (defun org-time-stamp (arg &optional inactive)
15887 "Prompt for a date/time and insert a time stamp.
15888 If the user specifies a time like HH:MM or if this command is
15889 called with at least one prefix argument, the time stamp contains
15890 the date and the time. Otherwise, only the date is be included.
15892 All parts of a date not specified by the user is filled in from
15893 the current date/time. So if you just press return without
15894 typing anything, the time stamp will represent the current
15895 date/time.
15897 If there is already a timestamp at the cursor, it will be
15898 modified.
15900 With two universal prefix arguments, insert an active timestamp
15901 with the current time without prompting the user."
15902 (interactive "P")
15903 (let* ((ts nil)
15904 (default-time
15905 ;; Default time is either today, or, when entering a range,
15906 ;; the range start.
15907 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15908 (save-excursion
15909 (re-search-backward
15910 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15911 (- (point) 20) t)))
15912 (apply 'encode-time (org-parse-time-string (match-string 1)))
15913 (current-time)))
15914 (default-input (and ts (org-get-compact-tod ts)))
15915 (repeater (save-excursion
15916 (save-match-data
15917 (beginning-of-line)
15918 (when (re-search-forward
15919 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15920 (save-excursion (progn (end-of-line) (point))) t)
15921 (match-string 0)))))
15922 org-time-was-given org-end-time-was-given time)
15923 (cond
15924 ((and (org-at-timestamp-p t)
15925 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15926 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15927 (insert "--")
15928 (setq time (let ((this-command this-command))
15929 (org-read-date arg 'totime nil nil
15930 default-time default-input inactive)))
15931 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15932 ((org-at-timestamp-p t)
15933 (setq time (let ((this-command this-command))
15934 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15935 (when (org-at-timestamp-p t) ; just to get the match data
15936 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15937 (replace-match "")
15938 (setq org-last-changed-timestamp
15939 (org-insert-time-stamp
15940 time (or org-time-was-given arg)
15941 inactive nil nil (list org-end-time-was-given)))
15942 (when repeater (goto-char (1- (point))) (insert " " repeater)
15943 (setq org-last-changed-timestamp
15944 (concat (substring org-last-inserted-timestamp 0 -1)
15945 " " repeater ">"))))
15946 (message "Timestamp updated"))
15947 ((equal arg '(16))
15948 (org-insert-time-stamp (current-time) t))
15950 (setq time (let ((this-command this-command))
15951 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15952 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15953 nil nil (list org-end-time-was-given))))))
15955 ;; FIXME: can we use this for something else, like computing time differences?
15956 (defun org-get-compact-tod (s)
15957 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15958 (let* ((t1 (match-string 1 s))
15959 (h1 (string-to-number (match-string 2 s)))
15960 (m1 (string-to-number (match-string 3 s)))
15961 (t2 (and (match-end 4) (match-string 5 s)))
15962 (h2 (and t2 (string-to-number (match-string 6 s))))
15963 (m2 (and t2 (string-to-number (match-string 7 s))))
15964 dh dm)
15965 (if (not t2)
15967 (setq dh (- h2 h1) dm (- m2 m1))
15968 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15969 (concat t1 "+" (number-to-string dh)
15970 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15972 (defun org-time-stamp-inactive (&optional arg)
15973 "Insert an inactive time stamp.
15974 An inactive time stamp is enclosed in square brackets instead of angle
15975 brackets. It is inactive in the sense that it does not trigger agenda entries,
15976 does not link to the calendar and cannot be changed with the S-cursor keys.
15977 So these are more for recording a certain time/date."
15978 (interactive "P")
15979 (org-time-stamp arg 'inactive))
15981 (defvar org-date-ovl (make-overlay 1 1))
15982 (overlay-put org-date-ovl 'face 'org-date-selected)
15983 (org-detach-overlay org-date-ovl)
15985 (defvar org-ans1) ; dynamically scoped parameter
15986 (defvar org-ans2) ; dynamically scoped parameter
15988 (defvar org-plain-time-of-day-regexp) ; defined below
15990 (defvar org-overriding-default-time nil) ; dynamically scoped
15991 (defvar org-read-date-overlay nil)
15992 (defvar org-dcst nil) ; dynamically scoped
15993 (defvar org-read-date-history nil)
15994 (defvar org-read-date-final-answer nil)
15995 (defvar org-read-date-analyze-futurep nil)
15996 (defvar org-read-date-analyze-forced-year nil)
15997 (defvar org-read-date-inactive)
15999 (defvar org-read-date-minibuffer-local-map
16000 (let ((map (make-sparse-keymap)))
16001 (set-keymap-parent map minibuffer-local-map)
16002 (org-defkey map (kbd ".")
16003 (lambda () (interactive)
16004 (org-eval-in-calendar '(calendar-goto-today))))
16005 (org-defkey map [(meta shift left)]
16006 (lambda () (interactive)
16007 (org-eval-in-calendar '(calendar-backward-month 1))))
16008 (org-defkey map [(meta shift right)]
16009 (lambda () (interactive)
16010 (org-eval-in-calendar '(calendar-forward-month 1))))
16011 (org-defkey map [(meta shift up)]
16012 (lambda () (interactive)
16013 (org-eval-in-calendar '(calendar-backward-year 1))))
16014 (org-defkey map [(meta shift down)]
16015 (lambda () (interactive)
16016 (org-eval-in-calendar '(calendar-forward-year 1))))
16017 (org-defkey map [?\e (shift left)]
16018 (lambda () (interactive)
16019 (org-eval-in-calendar '(calendar-backward-month 1))))
16020 (org-defkey map [?\e (shift right)]
16021 (lambda () (interactive)
16022 (org-eval-in-calendar '(calendar-forward-month 1))))
16023 (org-defkey map [?\e (shift up)]
16024 (lambda () (interactive)
16025 (org-eval-in-calendar '(calendar-backward-year 1))))
16026 (org-defkey map [?\e (shift down)]
16027 (lambda () (interactive)
16028 (org-eval-in-calendar '(calendar-forward-year 1))))
16029 (org-defkey map [(shift up)]
16030 (lambda () (interactive)
16031 (org-eval-in-calendar '(calendar-backward-week 1))))
16032 (org-defkey map [(shift down)]
16033 (lambda () (interactive)
16034 (org-eval-in-calendar '(calendar-forward-week 1))))
16035 (org-defkey map [(shift left)]
16036 (lambda () (interactive)
16037 (org-eval-in-calendar '(calendar-backward-day 1))))
16038 (org-defkey map [(shift right)]
16039 (lambda () (interactive)
16040 (org-eval-in-calendar '(calendar-forward-day 1))))
16041 (org-defkey map "!"
16042 (lambda () (interactive)
16043 (org-eval-in-calendar '(diary-view-entries))
16044 (message "")))
16045 (org-defkey map ">"
16046 (lambda () (interactive)
16047 (org-eval-in-calendar '(scroll-calendar-left 1))))
16048 (org-defkey map "<"
16049 (lambda () (interactive)
16050 (org-eval-in-calendar '(scroll-calendar-right 1))))
16051 (org-defkey map "\C-v"
16052 (lambda () (interactive)
16053 (org-eval-in-calendar
16054 '(calendar-scroll-left-three-months 1))))
16055 (org-defkey map "\M-v"
16056 (lambda () (interactive)
16057 (org-eval-in-calendar
16058 '(calendar-scroll-right-three-months 1))))
16059 map)
16060 "Keymap for minibuffer commands when using `org-read-date'.")
16062 (defun org-read-date (&optional org-with-time to-time from-string prompt
16063 default-time default-input inactive)
16064 "Read a date, possibly a time, and make things smooth for the user.
16065 The prompt will suggest to enter an ISO date, but you can also enter anything
16066 which will at least partially be understood by `parse-time-string'.
16067 Unrecognized parts of the date will default to the current day, month, year,
16068 hour and minute. If this command is called to replace a timestamp at point,
16069 or to enter the second timestamp of a range, the default time is taken
16070 from the existing stamp. Furthermore, the command prefers the future,
16071 so if you are giving a date where the year is not given, and the day-month
16072 combination is already past in the current year, it will assume you
16073 mean next year. For details, see the manual. A few examples:
16075 3-2-5 --> 2003-02-05
16076 feb 15 --> currentyear-02-15
16077 2/15 --> currentyear-02-15
16078 sep 12 9 --> 2009-09-12
16079 12:45 --> today 12:45
16080 22 sept 0:34 --> currentyear-09-22 0:34
16081 12 --> currentyear-currentmonth-12
16082 Fri --> nearest Friday (today or later)
16083 etc.
16085 Furthermore you can specify a relative date by giving, as the *first* thing
16086 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16087 change in days weeks, months, years.
16088 With a single plus or minus, the date is relative to today. With a double
16089 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16090 +4d --> four days from today
16091 +4 --> same as above
16092 +2w --> two weeks from today
16093 ++5 --> five days from default date
16095 The function understands only English month and weekday abbreviations.
16097 While prompting, a calendar is popped up - you can also select the
16098 date with the mouse (button 1). The calendar shows a period of three
16099 months. To scroll it to other months, use the keys `>' and `<'.
16100 If you don't like the calendar, turn it off with
16101 \(setq org-read-date-popup-calendar nil)
16103 With optional argument TO-TIME, the date will immediately be converted
16104 to an internal time.
16105 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16106 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16107 still enter a time, and this function will inform the calling routine
16108 about this change. The calling routine may then choose to change the
16109 format used to insert the time stamp into the buffer to include the time.
16110 With optional argument FROM-STRING, read from this string instead from
16111 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16112 the time/date that is used for everything that is not specified by the
16113 user."
16114 (require 'parse-time)
16115 (let* ((org-time-stamp-rounding-minutes
16116 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16117 (org-dcst org-display-custom-times)
16118 (ct (org-current-time))
16119 (org-def (or org-overriding-default-time default-time ct))
16120 (org-defdecode (decode-time org-def))
16121 (dummy (progn
16122 (when (< (nth 2 org-defdecode) org-extend-today-until)
16123 (setcar (nthcdr 2 org-defdecode) -1)
16124 (setcar (nthcdr 1 org-defdecode) 59)
16125 (setq org-def (apply 'encode-time org-defdecode)
16126 org-defdecode (decode-time org-def)))))
16127 (mouse-autoselect-window nil) ; Don't let the mouse jump
16128 (calendar-frame-setup nil)
16129 (calendar-setup nil)
16130 (calendar-move-hook nil)
16131 (calendar-view-diary-initially-flag nil)
16132 (calendar-view-holidays-initially-flag nil)
16133 (timestr (format-time-string
16134 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16135 (prompt (concat (if prompt (concat prompt " ") "")
16136 (format "Date+time [%s]: " timestr)))
16137 ans (org-ans0 "") org-ans1 org-ans2 final)
16139 (cond
16140 (from-string (setq ans from-string))
16141 (org-read-date-popup-calendar
16142 (save-excursion
16143 (save-window-excursion
16144 (calendar)
16145 (org-eval-in-calendar '(setq cursor-type nil) t)
16146 (unwind-protect
16147 (progn
16148 (calendar-forward-day (- (time-to-days org-def)
16149 (calendar-absolute-from-gregorian
16150 (calendar-current-date))))
16151 (org-eval-in-calendar nil t)
16152 (let* ((old-map (current-local-map))
16153 (map (copy-keymap calendar-mode-map))
16154 (minibuffer-local-map
16155 (copy-keymap org-read-date-minibuffer-local-map)))
16156 (org-defkey map (kbd "RET") 'org-calendar-select)
16157 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16158 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16159 (unwind-protect
16160 (progn
16161 (use-local-map map)
16162 (setq org-read-date-inactive inactive)
16163 (add-hook 'post-command-hook 'org-read-date-display)
16164 (setq org-ans0 (read-string prompt default-input
16165 'org-read-date-history nil))
16166 ;; org-ans0: from prompt
16167 ;; org-ans1: from mouse click
16168 ;; org-ans2: from calendar motion
16169 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16170 (remove-hook 'post-command-hook 'org-read-date-display)
16171 (use-local-map old-map)
16172 (when org-read-date-overlay
16173 (delete-overlay org-read-date-overlay)
16174 (setq org-read-date-overlay nil)))))
16175 (bury-buffer "*Calendar*")))))
16177 (t ; Naked prompt only
16178 (unwind-protect
16179 (setq ans (read-string prompt default-input
16180 'org-read-date-history timestr))
16181 (when org-read-date-overlay
16182 (delete-overlay org-read-date-overlay)
16183 (setq org-read-date-overlay nil)))))
16185 (setq final (org-read-date-analyze ans org-def org-defdecode))
16187 (when org-read-date-analyze-forced-year
16188 (message "Year was forced into %s"
16189 (if org-read-date-force-compatible-dates
16190 "compatible range (1970-2037)"
16191 "range representable on this machine"))
16192 (ding))
16194 ;; One round trip to get rid of 34th of August and stuff like that....
16195 (setq final (decode-time (apply 'encode-time final)))
16197 (setq org-read-date-final-answer ans)
16199 (if to-time
16200 (apply 'encode-time final)
16201 (if (and (boundp 'org-time-was-given) org-time-was-given)
16202 (format "%04d-%02d-%02d %02d:%02d"
16203 (nth 5 final) (nth 4 final) (nth 3 final)
16204 (nth 2 final) (nth 1 final))
16205 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16207 (defvar org-def)
16208 (defvar org-defdecode)
16209 (defvar org-with-time)
16210 (defun org-read-date-display ()
16211 "Display the current date prompt interpretation in the minibuffer."
16212 (when org-read-date-display-live
16213 (when org-read-date-overlay
16214 (delete-overlay org-read-date-overlay))
16215 (when (minibufferp (current-buffer))
16216 (save-excursion
16217 (end-of-line 1)
16218 (while (not (equal (buffer-substring
16219 (max (point-min) (- (point) 4)) (point))
16220 " "))
16221 (insert " ")))
16222 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16223 " " (or org-ans1 org-ans2)))
16224 (org-end-time-was-given nil)
16225 (f (org-read-date-analyze ans org-def org-defdecode))
16226 (fmts (if org-dcst
16227 org-time-stamp-custom-formats
16228 org-time-stamp-formats))
16229 (fmt (if (or org-with-time
16230 (and (boundp 'org-time-was-given) org-time-was-given))
16231 (cdr fmts)
16232 (car fmts)))
16233 (txt (format-time-string fmt (apply 'encode-time f)))
16234 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16235 (txt (concat "=> " txt)))
16236 (when (and org-end-time-was-given
16237 (string-match org-plain-time-of-day-regexp txt))
16238 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16239 org-end-time-was-given
16240 (substring txt (match-end 0)))))
16241 (when org-read-date-analyze-futurep
16242 (setq txt (concat txt " (=>F)")))
16243 (setq org-read-date-overlay
16244 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16245 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16247 (defun org-read-date-analyze (ans org-def org-defdecode)
16248 "Analyze the combined answer of the date prompt."
16249 ;; FIXME: cleanup and comment
16250 (let ((nowdecode (decode-time (current-time)))
16251 delta deltan deltaw deltadef year month day
16252 hour minute second wday pm h2 m2 tl wday1
16253 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16254 (setq org-read-date-analyze-futurep nil
16255 org-read-date-analyze-forced-year nil)
16256 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16257 (setq ans "+0"))
16259 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16260 (setq ans (replace-match "" t t ans)
16261 deltan (car delta)
16262 deltaw (nth 1 delta)
16263 deltadef (nth 2 delta)))
16265 ;; Check if there is an iso week date in there. If yes, store the
16266 ;; info and postpone interpreting it until the rest of the parsing
16267 ;; is done.
16268 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16269 (setq iso-year (if (match-end 1)
16270 (org-small-year-to-year
16271 (string-to-number (match-string 1 ans))))
16272 iso-weekday (if (match-end 3)
16273 (string-to-number (match-string 3 ans)))
16274 iso-week (string-to-number (match-string 2 ans)))
16275 (setq ans (replace-match "" t t ans)))
16277 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16278 (when (string-match
16279 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16280 (setq year (if (match-end 2)
16281 (string-to-number (match-string 2 ans))
16282 (progn (setq kill-year t)
16283 (string-to-number (format-time-string "%Y"))))
16284 month (string-to-number (match-string 3 ans))
16285 day (string-to-number (match-string 4 ans)))
16286 (if (< year 100) (setq year (+ 2000 year)))
16287 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16288 t nil ans)))
16290 ;; Help matching dotted european dates
16291 (when (string-match
16292 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16293 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16294 (setq kill-year t)
16295 (string-to-number (format-time-string "%Y")))
16296 day (string-to-number (match-string 1 ans))
16297 month (string-to-number (match-string 2 ans))
16298 ans (replace-match (format "%04d-%02d-%02d" year month day)
16299 t nil ans)))
16301 ;; Help matching american dates, like 5/30 or 5/30/7
16302 (when (string-match
16303 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16304 (setq year (if (match-end 4)
16305 (string-to-number (match-string 4 ans))
16306 (progn (setq kill-year t)
16307 (string-to-number (format-time-string "%Y"))))
16308 month (string-to-number (match-string 1 ans))
16309 day (string-to-number (match-string 2 ans)))
16310 (if (< year 100) (setq year (+ 2000 year)))
16311 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16312 t nil ans)))
16313 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16314 ;; If there is a time with am/pm, and *no* time without it, we convert
16315 ;; so that matching will be successful.
16316 (loop for i from 1 to 2 do ; twice, for end time as well
16317 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16318 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16319 (setq hour (string-to-number (match-string 1 ans))
16320 minute (if (match-end 3)
16321 (string-to-number (match-string 3 ans))
16323 pm (equal ?p
16324 (string-to-char (downcase (match-string 4 ans)))))
16325 (if (and (= hour 12) (not pm))
16326 (setq hour 0)
16327 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16328 (setq ans (replace-match (format "%02d:%02d" hour minute)
16329 t t ans))))
16331 ;; Check if a time range is given as a duration
16332 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16333 (setq hour (string-to-number (match-string 1 ans))
16334 h2 (+ hour (string-to-number (match-string 3 ans)))
16335 minute (string-to-number (match-string 2 ans))
16336 m2 (+ minute (if (match-end 5) (string-to-number
16337 (match-string 5 ans))0)))
16338 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16339 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16340 t t ans)))
16342 ;; Check if there is a time range
16343 (when (boundp 'org-end-time-was-given)
16344 (setq org-time-was-given nil)
16345 (when (and (string-match org-plain-time-of-day-regexp ans)
16346 (match-end 8))
16347 (setq org-end-time-was-given (match-string 8 ans))
16348 (setq ans (concat (substring ans 0 (match-beginning 7))
16349 (substring ans (match-end 7))))))
16351 (setq tl (parse-time-string ans)
16352 day (or (nth 3 tl) (nth 3 org-defdecode))
16353 month (or (nth 4 tl)
16354 (if (and org-read-date-prefer-future
16355 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16356 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16357 (nth 4 org-defdecode)))
16358 year (or (and (not kill-year) (nth 5 tl))
16359 (if (and org-read-date-prefer-future
16360 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16361 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16362 (nth 5 org-defdecode)))
16363 hour (or (nth 2 tl) (nth 2 org-defdecode))
16364 minute (or (nth 1 tl) (nth 1 org-defdecode))
16365 second (or (nth 0 tl) 0)
16366 wday (nth 6 tl))
16368 (when (and (eq org-read-date-prefer-future 'time)
16369 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16370 (equal day (nth 3 nowdecode))
16371 (equal month (nth 4 nowdecode))
16372 (equal year (nth 5 nowdecode))
16373 (nth 2 tl)
16374 (or (< (nth 2 tl) (nth 2 nowdecode))
16375 (and (= (nth 2 tl) (nth 2 nowdecode))
16376 (nth 1 tl)
16377 (< (nth 1 tl) (nth 1 nowdecode)))))
16378 (setq day (1+ day)
16379 futurep t))
16381 ;; Special date definitions below
16382 (cond
16383 (iso-week
16384 ;; There was an iso week
16385 (require 'cal-iso)
16386 (setq futurep nil)
16387 (setq year (or iso-year year)
16388 day (or iso-weekday wday 1)
16389 wday nil ; to make sure that the trigger below does not match
16390 iso-date (calendar-gregorian-from-absolute
16391 (calendar-absolute-from-iso
16392 (list iso-week day year))))
16393 ; FIXME: Should we also push ISO weeks into the future?
16394 ; (when (and org-read-date-prefer-future
16395 ; (not iso-year)
16396 ; (< (calendar-absolute-from-gregorian iso-date)
16397 ; (time-to-days (current-time))))
16398 ; (setq year (1+ year)
16399 ; iso-date (calendar-gregorian-from-absolute
16400 ; (calendar-absolute-from-iso
16401 ; (list iso-week day year)))))
16402 (setq month (car iso-date)
16403 year (nth 2 iso-date)
16404 day (nth 1 iso-date)))
16405 (deltan
16406 (setq futurep nil)
16407 (unless deltadef
16408 (let ((now (decode-time (current-time))))
16409 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16410 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16411 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16412 ((equal deltaw "m") (setq month (+ month deltan)))
16413 ((equal deltaw "y") (setq year (+ year deltan)))))
16414 ((and wday (not (nth 3 tl)))
16415 ;; Weekday was given, but no day, so pick that day in the week
16416 ;; on or after the derived date.
16417 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16418 (unless (equal wday wday1)
16419 (setq day (+ day (% (- wday wday1 -7) 7))))))
16420 (if (and (boundp 'org-time-was-given)
16421 (nth 2 tl))
16422 (setq org-time-was-given t))
16423 (if (< year 100) (setq year (+ 2000 year)))
16424 ;; Check of the date is representable
16425 (if org-read-date-force-compatible-dates
16426 (progn
16427 (if (< year 1970)
16428 (setq year 1970 org-read-date-analyze-forced-year t))
16429 (if (> year 2037)
16430 (setq year 2037 org-read-date-analyze-forced-year t)))
16431 (condition-case nil
16432 (ignore (encode-time second minute hour day month year))
16433 (error
16434 (setq year (nth 5 org-defdecode))
16435 (setq org-read-date-analyze-forced-year t))))
16436 (setq org-read-date-analyze-futurep futurep)
16437 (list second minute hour day month year)))
16439 (defvar parse-time-weekdays)
16440 (defun org-read-date-get-relative (s today default)
16441 "Check string S for special relative date string.
16442 TODAY and DEFAULT are internal times, for today and for a default.
16443 Return shift list (N what def-flag)
16444 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16445 N is the number of WHATs to shift.
16446 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16447 the DEFAULT date rather than TODAY."
16448 (require 'parse-time)
16449 (when (and
16450 (string-match
16451 (concat
16452 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16453 "\\([0-9]+\\)?"
16454 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16455 "\\([ \t]\\|$\\)") s)
16456 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16457 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16458 (string-to-char (substring (match-string 1 s) -1))
16459 ?+))
16460 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16461 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16462 (what (if (match-end 3) (match-string 3 s) "d"))
16463 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16464 (date (if rel default today))
16465 (wday (nth 6 (decode-time date)))
16466 delta)
16467 (if wday1
16468 (progn
16469 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16470 (if (= dir ?-) (setq delta (- delta 7)))
16471 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16472 (list delta "d" rel))
16473 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16475 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16476 "Turn a user-specified date into the internal representation.
16477 The internal representation needed by the calendar is (month day year).
16478 This is a wrapper to handle the brain-dead convention in calendar that
16479 user function argument order change dependent on argument order."
16480 (if (boundp 'calendar-date-style)
16481 (cond
16482 ((eq calendar-date-style 'american)
16483 (list arg1 arg2 arg3))
16484 ((eq calendar-date-style 'european)
16485 (list arg2 arg1 arg3))
16486 ((eq calendar-date-style 'iso)
16487 (list arg2 arg3 arg1)))
16488 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16489 (if (org-bound-and-true-p european-calendar-style)
16490 (list arg2 arg1 arg3)
16491 (list arg1 arg2 arg3)))))
16493 (defun org-eval-in-calendar (form &optional keepdate)
16494 "Eval FORM in the calendar window and return to current window.
16495 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16496 otherwise stick to the current value of `org-ans2'."
16497 (let ((sf (selected-frame))
16498 (sw (selected-window)))
16499 (select-window (get-buffer-window "*Calendar*" t))
16500 (eval form)
16501 (when (and (not keepdate) (calendar-cursor-to-date))
16502 (let* ((date (calendar-cursor-to-date))
16503 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16504 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16505 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16506 (select-window sw)
16507 (org-select-frame-set-input-focus sf)))
16509 (defun org-calendar-select ()
16510 "Return to `org-read-date' with the date currently selected.
16511 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16512 (interactive)
16513 (when (calendar-cursor-to-date)
16514 (let* ((date (calendar-cursor-to-date))
16515 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16516 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16517 (if (active-minibuffer-window) (exit-minibuffer))))
16519 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16520 "Insert a date stamp for the date given by the internal TIME.
16521 WITH-HM means use the stamp format that includes the time of the day.
16522 INACTIVE means use square brackets instead of angular ones, so that the
16523 stamp will not contribute to the agenda.
16524 PRE and POST are optional strings to be inserted before and after the
16525 stamp.
16526 The command returns the inserted time stamp."
16527 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16528 stamp)
16529 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16530 (insert-before-markers (or pre ""))
16531 (when (listp extra)
16532 (setq extra (car extra))
16533 (if (and (stringp extra)
16534 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16535 (setq extra (format "-%02d:%02d"
16536 (string-to-number (match-string 1 extra))
16537 (string-to-number (match-string 2 extra))))
16538 (setq extra nil)))
16539 (when extra
16540 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16541 (insert-before-markers (setq stamp (format-time-string fmt time)))
16542 (insert-before-markers (or post ""))
16543 (setq org-last-inserted-timestamp stamp)))
16545 (defun org-toggle-time-stamp-overlays ()
16546 "Toggle the use of custom time stamp formats."
16547 (interactive)
16548 (setq org-display-custom-times (not org-display-custom-times))
16549 (unless org-display-custom-times
16550 (let ((p (point-min)) (bmp (buffer-modified-p)))
16551 (while (setq p (next-single-property-change p 'display))
16552 (if (and (get-text-property p 'display)
16553 (eq (get-text-property p 'face) 'org-date))
16554 (remove-text-properties
16555 p (setq p (next-single-property-change p 'display))
16556 '(display t))))
16557 (set-buffer-modified-p bmp)))
16558 (if (featurep 'xemacs)
16559 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16560 (org-restart-font-lock)
16561 (setq org-table-may-need-update t)
16562 (if org-display-custom-times
16563 (message "Time stamps are overlaid with custom format")
16564 (message "Time stamp overlays removed")))
16566 (defun org-display-custom-time (beg end)
16567 "Overlay modified time stamp format over timestamp between BEG and END."
16568 (let* ((ts (buffer-substring beg end))
16569 t1 w1 with-hm tf time str w2 (off 0))
16570 (save-match-data
16571 (setq t1 (org-parse-time-string ts t))
16572 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16573 (setq off (- (match-end 0) (match-beginning 0)))))
16574 (setq end (- end off))
16575 (setq w1 (- end beg)
16576 with-hm (and (nth 1 t1) (nth 2 t1))
16577 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16578 time (org-fix-decoded-time t1)
16579 str (org-add-props
16580 (format-time-string
16581 (substring tf 1 -1) (apply 'encode-time time))
16582 nil 'mouse-face 'highlight)
16583 w2 (length str))
16584 (if (not (= w2 w1))
16585 (add-text-properties (1+ beg) (+ 2 beg)
16586 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16587 (if (featurep 'xemacs)
16588 (progn
16589 (put-text-property beg end 'invisible t)
16590 (put-text-property beg end 'end-glyph (make-glyph str)))
16591 (put-text-property beg end 'display str))))
16593 (defun org-translate-time (string)
16594 "Translate all timestamps in STRING to custom format.
16595 But do this only if the variable `org-display-custom-times' is set."
16596 (when org-display-custom-times
16597 (save-match-data
16598 (let* ((start 0)
16599 (re org-ts-regexp-both)
16600 t1 with-hm inactive tf time str beg end)
16601 (while (setq start (string-match re string start))
16602 (setq beg (match-beginning 0)
16603 end (match-end 0)
16604 t1 (save-match-data
16605 (org-parse-time-string (substring string beg end) t))
16606 with-hm (and (nth 1 t1) (nth 2 t1))
16607 inactive (equal (substring string beg (1+ beg)) "[")
16608 tf (funcall (if with-hm 'cdr 'car)
16609 org-time-stamp-custom-formats)
16610 time (org-fix-decoded-time t1)
16611 str (format-time-string
16612 (concat
16613 (if inactive "[" "<") (substring tf 1 -1)
16614 (if inactive "]" ">"))
16615 (apply 'encode-time time))
16616 string (replace-match str t t string)
16617 start (+ start (length str)))))))
16618 string)
16620 (defun org-fix-decoded-time (time)
16621 "Set 0 instead of nil for the first 6 elements of time.
16622 Don't touch the rest."
16623 (let ((n 0))
16624 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16626 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16628 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16629 "Difference between TIMESTAMP-STRING and now in days.
16630 If SECONDS is non-nil, return the difference in seconds."
16631 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16632 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16633 (funcall fdiff (current-time)))))
16635 (defun org-deadline-close (timestamp-string &optional ndays)
16636 "Is the time in TIMESTAMP-STRING close to the current date?"
16637 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16638 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16639 (not (org-entry-is-done-p))))
16641 (defun org-get-wdays (ts &optional delay zero-delay)
16642 "Get the deadline lead time appropriate for timestring TS.
16643 When DELAY is non-nil, get the delay time for scheduled items
16644 instead of the deadline lead time. When ZERO-DELAY is non-nil
16645 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16646 don't try to find the delay cookie in the scheduled timestamp."
16647 (let ((tv (if delay org-scheduled-delay-days
16648 org-deadline-warning-days)))
16649 (cond
16650 ((or (and delay (< tv 0))
16651 (and delay zero-delay (<= tv 0))
16652 (and (not delay) (<= tv 0)))
16653 ;; Enforce this value no matter what
16654 (- tv))
16655 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16656 ;; lead time is specified.
16657 (floor (* (string-to-number (match-string 1 ts))
16658 (cdr (assoc (match-string 2 ts)
16659 '(("d" . 1) ("w" . 7)
16660 ("m" . 30.4) ("y" . 365.25)
16661 ("h" . 0.041667)))))))
16662 ;; go for the default.
16663 (t tv))))
16665 (defun org-calendar-select-mouse (ev)
16666 "Return to `org-read-date' with the date currently selected.
16667 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16668 (interactive "e")
16669 (mouse-set-point ev)
16670 (when (calendar-cursor-to-date)
16671 (let* ((date (calendar-cursor-to-date))
16672 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16673 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16674 (if (active-minibuffer-window) (exit-minibuffer))))
16676 (defun org-check-deadlines (ndays)
16677 "Check if there are any deadlines due or past due.
16678 A deadline is considered due if it happens within `org-deadline-warning-days'
16679 days from today's date. If the deadline appears in an entry marked DONE,
16680 it is not shown. The prefix arg NDAYS can be used to test that many
16681 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16682 (interactive "P")
16683 (let* ((org-warn-days
16684 (cond
16685 ((equal ndays '(4)) 100000)
16686 (ndays (prefix-numeric-value ndays))
16687 (t (abs org-deadline-warning-days))))
16688 (case-fold-search nil)
16689 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16690 (callback
16691 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16693 (message "%d deadlines past-due or due within %d days"
16694 (org-occur regexp nil callback)
16695 org-warn-days)))
16697 (defsubst org-re-timestamp (type)
16698 "Return a regexp for timestamp TYPE.
16699 Allowed values for TYPE are:
16701 all: all timestamps
16702 active: only active timestamps (<...>)
16703 inactive: only inactive timestamps ([...])
16704 scheduled: only scheduled timestamps
16705 deadline: only deadline timestamps
16707 When TYPE is nil, fall back on returning a regexp that matches
16708 both scheduled and deadline timestamps."
16709 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16710 ((eq type 'active) org-ts-regexp)
16711 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16712 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16713 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16714 ((eq type 'scheduled-or-deadline)
16715 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16717 (defun org-check-before-date (date)
16718 "Check if there are deadlines or scheduled entries before DATE."
16719 (interactive (list (org-read-date)))
16720 (let ((case-fold-search nil)
16721 (regexp (org-re-timestamp org-ts-type))
16722 (callback
16723 (lambda () (time-less-p
16724 (org-time-string-to-time (match-string 1))
16725 (org-time-string-to-time date)))))
16726 (message "%d entries before %s"
16727 (org-occur regexp nil callback) date)))
16729 (defun org-check-after-date (date)
16730 "Check if there are deadlines or scheduled entries after DATE."
16731 (interactive (list (org-read-date)))
16732 (let ((case-fold-search nil)
16733 (regexp (org-re-timestamp org-ts-type))
16734 (callback
16735 (lambda () (not
16736 (time-less-p
16737 (org-time-string-to-time (match-string 1))
16738 (org-time-string-to-time date))))))
16739 (message "%d entries after %s"
16740 (org-occur regexp nil callback) date)))
16742 (defun org-check-dates-range (start-date end-date)
16743 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16744 (interactive (list (org-read-date nil nil nil "Range starts")
16745 (org-read-date nil nil nil "Range end")))
16746 (let ((case-fold-search nil)
16747 (regexp (org-re-timestamp org-ts-type))
16748 (callback
16749 (lambda ()
16750 (let ((match (match-string 1)))
16751 (and
16752 (not (time-less-p
16753 (org-time-string-to-time match)
16754 (org-time-string-to-time start-date)))
16755 (time-less-p
16756 (org-time-string-to-time match)
16757 (org-time-string-to-time end-date)))))))
16758 (message "%d entries between %s and %s"
16759 (org-occur regexp nil callback) start-date end-date)))
16761 (defun org-evaluate-time-range (&optional to-buffer)
16762 "Evaluate a time range by computing the difference between start and end.
16763 Normally the result is just printed in the echo area, but with prefix arg
16764 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16765 If the time range is actually in a table, the result is inserted into the
16766 next column.
16767 For time difference computation, a year is assumed to be exactly 365
16768 days in order to avoid rounding problems."
16769 (interactive "P")
16771 (org-clock-update-time-maybe)
16772 (save-excursion
16773 (unless (org-at-date-range-p t)
16774 (goto-char (point-at-bol))
16775 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16776 (if (not (org-at-date-range-p t))
16777 (error "Not at a time-stamp range, and none found in current line")))
16778 (let* ((ts1 (match-string 1))
16779 (ts2 (match-string 2))
16780 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16781 (match-end (match-end 0))
16782 (time1 (org-time-string-to-time ts1))
16783 (time2 (org-time-string-to-time ts2))
16784 (t1 (org-float-time time1))
16785 (t2 (org-float-time time2))
16786 (diff (abs (- t2 t1)))
16787 (negative (< (- t2 t1) 0))
16788 ;; (ys (floor (* 365 24 60 60)))
16789 (ds (* 24 60 60))
16790 (hs (* 60 60))
16791 (fy "%dy %dd %02d:%02d")
16792 (fy1 "%dy %dd")
16793 (fd "%dd %02d:%02d")
16794 (fd1 "%dd")
16795 (fh "%02d:%02d")
16796 y d h m align)
16797 (if havetime
16798 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16800 d (floor (/ diff ds)) diff (mod diff ds)
16801 h (floor (/ diff hs)) diff (mod diff hs)
16802 m (floor (/ diff 60)))
16803 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16805 d (floor (+ (/ diff ds) 0.5))
16806 h 0 m 0))
16807 (if (not to-buffer)
16808 (message "%s" (org-make-tdiff-string y d h m))
16809 (if (org-at-table-p)
16810 (progn
16811 (goto-char match-end)
16812 (setq align t)
16813 (and (looking-at " *|") (goto-char (match-end 0))))
16814 (goto-char match-end))
16815 (if (looking-at
16816 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16817 (replace-match ""))
16818 (if negative (insert " -"))
16819 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16820 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16821 (insert " " (format fh h m))))
16822 (if align (org-table-align))
16823 (message "Time difference inserted")))))
16825 (defun org-make-tdiff-string (y d h m)
16826 (let ((fmt "")
16827 (l nil))
16828 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16829 l (push y l)))
16830 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16831 l (push d l)))
16832 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16833 l (push h l)))
16834 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16835 l (push m l)))
16836 (apply 'format fmt (nreverse l))))
16838 (defun org-time-string-to-time (s &optional buffer pos)
16839 "Convert a timestamp string into internal time."
16840 (condition-case errdata
16841 (apply 'encode-time (org-parse-time-string s))
16842 (error (error "Bad timestamp `%s'%s\nError was: %s"
16843 s (if (not (and buffer pos))
16845 (format " at %d in buffer `%s'" pos buffer))
16846 (cdr errdata)))))
16848 (defun org-time-string-to-seconds (s)
16849 "Convert a timestamp string to a number of seconds."
16850 (org-float-time (org-time-string-to-time s)))
16852 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16853 "Convert a time stamp to an absolute day number.
16854 If there is a specifier for a cyclic time stamp, get the closest
16855 date to DAYNR.
16856 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16857 The variable `date' is bound by the calendar when this is called."
16858 (cond
16859 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16860 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16861 daynr
16862 (+ daynr 1000)))
16863 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16864 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16865 (time-to-days (current-time))) (match-string 0 s)
16866 prefer show-all))
16867 (t (time-to-days
16868 (condition-case errdata
16869 (apply 'encode-time (org-parse-time-string s))
16870 (error (error "Bad timestamp `%s'%s\nError was: %s"
16871 s (if (not (and buffer pos))
16873 (format " at %d in buffer `%s'" pos buffer))
16874 (cdr errdata))))))))
16876 (defun org-days-to-iso-week (days)
16877 "Return the iso week number."
16878 (require 'cal-iso)
16879 (car (calendar-iso-from-absolute days)))
16881 (defun org-small-year-to-year (year)
16882 "Convert 2-digit years into 4-digit years.
16883 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16884 The year 2000 cannot be abbreviated. Any year larger than 99
16885 is returned unchanged."
16886 (if (< year 38)
16887 (setq year (+ 2000 year))
16888 (if (< year 100)
16889 (setq year (+ 1900 year))))
16890 year)
16892 (defun org-time-from-absolute (d)
16893 "Return the time corresponding to date D.
16894 D may be an absolute day number, or a calendar-type list (month day year)."
16895 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16896 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16898 (defun org-calendar-holiday ()
16899 "List of holidays, for Diary display in Org-mode."
16900 (require 'holidays)
16901 (let ((hl (funcall
16902 (if (fboundp 'calendar-check-holidays)
16903 'calendar-check-holidays 'check-calendar-holidays) date)))
16904 (if hl (mapconcat 'identity hl "; "))))
16906 (defun org-diary-sexp-entry (sexp entry date)
16907 "Process a SEXP diary ENTRY for DATE."
16908 (require 'diary-lib)
16909 (let ((result (if calendar-debug-sexp
16910 (let ((stack-trace-on-error t))
16911 (eval (car (read-from-string sexp))))
16912 (condition-case nil
16913 (eval (car (read-from-string sexp)))
16914 (error
16915 (beep)
16916 (message "Bad sexp at line %d in %s: %s"
16917 (org-current-line)
16918 (buffer-file-name) sexp)
16919 (sleep-for 2))))))
16920 (cond ((stringp result) (split-string result "; "))
16921 ((and (consp result)
16922 (not (consp (cdr result)))
16923 (stringp (cdr result))) (cdr result))
16924 ((and (consp result)
16925 (stringp (car result))) result)
16926 (result entry))))
16928 (defun org-diary-to-ical-string (frombuf)
16929 "Get iCalendar entries from diary entries in buffer FROMBUF.
16930 This uses the icalendar.el library."
16931 (let* ((tmpdir (if (featurep 'xemacs)
16932 (temp-directory)
16933 temporary-file-directory))
16934 (tmpfile (make-temp-name
16935 (expand-file-name "orgics" tmpdir)))
16936 buf rtn b e)
16937 (with-current-buffer frombuf
16938 (icalendar-export-region (point-min) (point-max) tmpfile)
16939 (setq buf (find-buffer-visiting tmpfile))
16940 (set-buffer buf)
16941 (goto-char (point-min))
16942 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16943 (setq b (match-beginning 0)))
16944 (goto-char (point-max))
16945 (if (re-search-backward "^END:VEVENT" nil t)
16946 (setq e (match-end 0)))
16947 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16948 (kill-buffer buf)
16949 (delete-file tmpfile)
16950 rtn))
16952 (defun org-closest-date (start current change prefer show-all)
16953 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16954 When PREFER is `past', return a date that is either CURRENT or past.
16955 When PREFER is `future', return a date that is either CURRENT or future.
16956 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16957 ;; Make the proper lists from the dates
16958 (catch 'exit
16959 (let ((a1 '(("h" . hour)
16960 ("d" . day)
16961 ("w" . week)
16962 ("m" . month)
16963 ("y" . year)))
16964 (shour (nth 2 (org-parse-time-string start)))
16965 dn dw sday cday n1 n2 n0
16966 d m y y1 y2 date1 date2 nmonths nm ny m2)
16968 (setq start (org-date-to-gregorian start)
16969 current (org-date-to-gregorian
16970 (if show-all
16971 current
16972 (time-to-days (current-time))))
16973 sday (calendar-absolute-from-gregorian start)
16974 cday (calendar-absolute-from-gregorian current))
16976 (if (<= cday sday) (throw 'exit sday))
16978 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16979 (setq dn (string-to-number (match-string 1 change))
16980 dw (cdr (assoc (match-string 2 change) a1)))
16981 (error "Invalid change specifier: %s" change))
16982 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16983 (cond
16984 ((eq dw 'hour)
16985 (let ((missing-hours
16986 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16987 dn)))
16988 (setq n1 (if (zerop missing-hours) cday
16989 (- cday (1+ (floor (/ missing-hours 24)))))
16990 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16991 ((eq dw 'day)
16992 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16993 n2 (+ n1 dn)))
16994 ((eq dw 'year)
16995 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16996 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16997 (setq date1 (list m d y1)
16998 n1 (calendar-absolute-from-gregorian date1)
16999 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17000 n2 (calendar-absolute-from-gregorian date2)))
17001 ((eq dw 'month)
17002 ;; approx number of month between the two dates
17003 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17004 ;; How often does dn fit in there?
17005 (setq d (nth 1 start) m (car start) y (nth 2 start)
17006 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17007 m (+ m nm)
17008 ny (floor (/ m 12))
17009 y (+ y ny)
17010 m (- m (* ny 12)))
17011 (while (> m 12) (setq m (- m 12) y (1+ y)))
17012 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17013 (setq m2 (+ m dn) y2 y)
17014 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17015 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17016 (while (<= n2 cday)
17017 (setq n1 n2 m m2 y y2)
17018 (setq m2 (+ m dn) y2 y)
17019 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17020 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17021 ;; Make sure n1 is the earlier date
17022 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17023 (if show-all
17024 (cond
17025 ((eq prefer 'past) (if (= cday n2) n2 n1))
17026 ((eq prefer 'future) (if (= cday n1) n1 n2))
17027 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17028 (cond
17029 ((eq prefer 'past) (if (= cday n2) n2 n1))
17030 ((eq prefer 'future) (if (= cday n1) n1 n2))
17031 (t (if (= cday n1) n1 n2)))))))
17033 (defun org-date-to-gregorian (date)
17034 "Turn any specification of DATE into a Gregorian date for the calendar."
17035 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17036 ((and (listp date) (= (length date) 3)) date)
17037 ((stringp date)
17038 (setq date (org-parse-time-string date))
17039 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17040 ((listp date)
17041 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17043 (defun org-parse-time-string (s &optional nodefault)
17044 "Parse the standard Org-mode time string.
17045 This should be a lot faster than the normal `parse-time-string'.
17046 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17047 hour and minute fields will be nil if not given."
17048 (cond ((string-match org-ts-regexp0 s)
17049 (list 0
17050 (if (or (match-beginning 8) (not nodefault))
17051 (string-to-number (or (match-string 8 s) "0")))
17052 (if (or (match-beginning 7) (not nodefault))
17053 (string-to-number (or (match-string 7 s) "0")))
17054 (string-to-number (match-string 4 s))
17055 (string-to-number (match-string 3 s))
17056 (string-to-number (match-string 2 s))
17057 nil nil nil))
17058 ((string-match "^<[^>]+>$" s)
17059 (decode-time (seconds-to-time (org-matcher-time s))))
17060 (t (error "Not a standard Org-mode time string: %s" s))))
17062 (defun org-timestamp-up (&optional arg)
17063 "Increase the date item at the cursor by one.
17064 If the cursor is on the year, change the year. If it is on the month,
17065 the day or the time, change that.
17066 With prefix ARG, change by that many units."
17067 (interactive "p")
17068 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17070 (defun org-timestamp-down (&optional arg)
17071 "Decrease the date item at the cursor by one.
17072 If the cursor is on the year, change the year. If it is on the month,
17073 the day or the time, change that.
17074 With prefix ARG, change by that many units."
17075 (interactive "p")
17076 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17078 (defun org-timestamp-up-day (&optional arg)
17079 "Increase the date in the time stamp by one day.
17080 With prefix ARG, change that many days."
17081 (interactive "p")
17082 (if (and (not (org-at-timestamp-p t))
17083 (org-at-heading-p))
17084 (org-todo 'up)
17085 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17087 (defun org-timestamp-down-day (&optional arg)
17088 "Decrease the date in the time stamp by one day.
17089 With prefix ARG, change that many days."
17090 (interactive "p")
17091 (if (and (not (org-at-timestamp-p t))
17092 (org-at-heading-p))
17093 (org-todo 'down)
17094 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17096 (defun org-at-timestamp-p (&optional inactive-ok)
17097 "Determine if the cursor is in or at a timestamp."
17098 (interactive)
17099 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17100 (pos (point))
17101 (ans (or (looking-at tsr)
17102 (save-excursion
17103 (skip-chars-backward "^[<\n\r\t")
17104 (if (> (point) (point-min)) (backward-char 1))
17105 (and (looking-at tsr)
17106 (> (- (match-end 0) pos) -1))))))
17107 (and ans
17108 (boundp 'org-ts-what)
17109 (setq org-ts-what
17110 (cond
17111 ((= pos (match-beginning 0)) 'bracket)
17112 ;; Point is considered to be "on the bracket" whether
17113 ;; it's really on it or right after it.
17114 ((= pos (1- (match-end 0))) 'bracket)
17115 ((= pos (match-end 0)) 'after)
17116 ((org-pos-in-match-range pos 2) 'year)
17117 ((org-pos-in-match-range pos 3) 'month)
17118 ((org-pos-in-match-range pos 7) 'hour)
17119 ((org-pos-in-match-range pos 8) 'minute)
17120 ((or (org-pos-in-match-range pos 4)
17121 (org-pos-in-match-range pos 5)) 'day)
17122 ((and (> pos (or (match-end 8) (match-end 5)))
17123 (< pos (match-end 0)))
17124 (- pos (or (match-end 8) (match-end 5))))
17125 (t 'day))))
17126 ans))
17128 (defun org-toggle-timestamp-type ()
17129 "Toggle the type (<active> or [inactive]) of a time stamp."
17130 (interactive)
17131 (when (org-at-timestamp-p t)
17132 (let ((beg (match-beginning 0)) (end (match-end 0))
17133 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17134 (save-excursion
17135 (goto-char beg)
17136 (while (re-search-forward "[][<>]" end t)
17137 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17138 t t)))
17139 (message "Timestamp is now %sactive"
17140 (if (equal (char-after beg) ?<) "" "in")))))
17142 (defun org-at-clock-log-p nil
17143 "Is the cursor on the clock log line?"
17144 (save-excursion
17145 (move-beginning-of-line 1)
17146 (looking-at "^[ \t]*CLOCK:")))
17148 (defvar org-clock-history) ; defined in org-clock.el
17149 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17150 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17151 "Change the date in the time stamp at point.
17152 The date will be changed by N times WHAT. WHAT can be `day', `month',
17153 `year', `minute', `second'. If WHAT is not given, the cursor position
17154 in the timestamp determines what will be changed.
17155 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17156 (let ((origin (point)) origin-cat
17157 with-hm inactive
17158 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17159 org-ts-what
17160 extra rem
17161 ts time time0 fixnext clrgx)
17162 (if (not (org-at-timestamp-p t))
17163 (error "Not at a timestamp"))
17164 (if (and (not what) (eq org-ts-what 'bracket))
17165 (org-toggle-timestamp-type)
17166 ;; Point isn't on brackets. Remember the part of the time-stamp
17167 ;; the point was in. Indeed, size of time-stamps may change,
17168 ;; but point must be kept in the same category nonetheless.
17169 (setq origin-cat org-ts-what)
17170 (if (and (not what) (not (eq org-ts-what 'day))
17171 org-display-custom-times
17172 (get-text-property (point) 'display)
17173 (not (get-text-property (1- (point)) 'display)))
17174 (setq org-ts-what 'day))
17175 (setq org-ts-what (or what org-ts-what)
17176 inactive (= (char-after (match-beginning 0)) ?\[)
17177 ts (match-string 0))
17178 (replace-match "")
17179 (when (string-match
17180 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17182 (setq extra (match-string 1 ts))
17183 (if suppress-tmp-delay
17184 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17185 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17186 (setq with-hm t))
17187 (setq time0 (org-parse-time-string ts))
17188 (when (and updown
17189 (eq org-ts-what 'minute)
17190 (not current-prefix-arg))
17191 ;; This looks like s-up and s-down. Change by one rounding step.
17192 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17193 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17194 (setcar (cdr time0) (+ (nth 1 time0)
17195 (if (> n 0) (- rem) (- dm rem))))))
17196 (setq time
17197 (encode-time (or (car time0) 0)
17198 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17199 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17200 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17201 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17202 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17203 (nthcdr 6 time0)))
17204 (when (and (member org-ts-what '(hour minute))
17205 extra
17206 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17207 (setq extra (org-modify-ts-extra
17208 extra
17209 (if (eq org-ts-what 'hour) 2 5)
17210 n dm)))
17211 (when (integerp org-ts-what)
17212 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17213 (if (eq what 'calendar)
17214 (let ((cal-date (org-get-date-from-calendar)))
17215 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17216 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17217 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17218 (setcar time0 (or (car time0) 0))
17219 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17220 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17221 (setq time (apply 'encode-time time0))))
17222 ;; Insert the new time-stamp, and ensure point stays in the same
17223 ;; category as before (i.e. not after the last position in that
17224 ;; category).
17225 (let ((pos (point)))
17226 ;; Stay before inserted string. `save-excursion' is of no use.
17227 (setq org-last-changed-timestamp
17228 (org-insert-time-stamp time with-hm inactive nil nil extra))
17229 (goto-char pos))
17230 (save-match-data
17231 (looking-at org-ts-regexp3)
17232 (goto-char (cond
17233 ;; `day' category ends before `hour' if any, or at
17234 ;; the end of the day name.
17235 ((eq origin-cat 'day)
17236 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17237 ((eq origin-cat 'hour) (min (match-end 7) origin))
17238 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17239 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17240 ;; `year' and `month' have both fixed size: point
17241 ;; couldn't have moved into another part.
17242 (t origin))))
17243 ;; Update clock if on a CLOCK line.
17244 (org-clock-update-time-maybe)
17245 ;; Maybe adjust the closest clock in `org-clock-history'
17246 (when org-clock-adjust-closest
17247 (if (not (and (org-at-clock-log-p)
17248 (< 1 (length (delq nil (mapcar 'marker-position
17249 org-clock-history))))))
17250 (message "No clock to adjust")
17251 (cond ((save-excursion ; fix previous clock?
17252 (re-search-backward org-ts-regexp0 nil t)
17253 (org-looking-back (concat org-clock-string " \\[")))
17254 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17255 ((save-excursion ; fix next clock?
17256 (re-search-backward org-ts-regexp0 nil t)
17257 (looking-at (concat org-ts-regexp0 "\\] =>")))
17258 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17259 (save-window-excursion
17260 ;; Find closest clock to point, adjust the previous/next one in history
17261 (let* ((p (save-excursion (org-back-to-heading t)))
17262 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17263 (clfixnth
17264 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17265 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17266 (if (not clfixpos)
17267 (message "No clock to adjust")
17268 (save-excursion
17269 (org-goto-marker-or-bmk clfixpos)
17270 (org-show-subtree)
17271 (when (re-search-forward clrgx nil t)
17272 (goto-char (match-beginning 1))
17273 (let (org-clock-adjust-closest)
17274 (org-timestamp-change n org-ts-what updown))
17275 (message "Clock adjusted in %s for heading: %s"
17276 (file-name-nondirectory (buffer-file-name))
17277 (org-get-heading t t)))))))))
17278 ;; Try to recenter the calendar window, if any.
17279 (if (and org-calendar-follow-timestamp-change
17280 (get-buffer-window "*Calendar*" t)
17281 (memq org-ts-what '(day month year)))
17282 (org-recenter-calendar (time-to-days time))))))
17284 (defun org-modify-ts-extra (s pos n dm)
17285 "Change the different parts of the lead-time and repeat fields in timestamp."
17286 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17287 ng h m new rem)
17288 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17289 (cond
17290 ((or (org-pos-in-match-range pos 2)
17291 (org-pos-in-match-range pos 3))
17292 (setq m (string-to-number (match-string 3 s))
17293 h (string-to-number (match-string 2 s)))
17294 (if (org-pos-in-match-range pos 2)
17295 (setq h (+ h n))
17296 (setq n (* dm (org-no-warnings (signum n))))
17297 (when (not (= 0 (setq rem (% m dm))))
17298 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17299 (setq m (+ m n)))
17300 (if (< m 0) (setq m (+ m 60) h (1- h)))
17301 (if (> m 59) (setq m (- m 60) h (1+ h)))
17302 (setq h (min 24 (max 0 h)))
17303 (setq ng 1 new (format "-%02d:%02d" h m)))
17304 ((org-pos-in-match-range pos 6)
17305 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17306 ((org-pos-in-match-range pos 5)
17307 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17309 ((org-pos-in-match-range pos 9)
17310 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17311 ((org-pos-in-match-range pos 8)
17312 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17314 (when ng
17315 (setq s (concat
17316 (substring s 0 (match-beginning ng))
17318 (substring s (match-end ng))))))
17321 (defun org-recenter-calendar (date)
17322 "If the calendar is visible, recenter it to DATE."
17323 (let ((cwin (get-buffer-window "*Calendar*" t)))
17324 (when cwin
17325 (let ((calendar-move-hook nil))
17326 (with-selected-window cwin
17327 (calendar-goto-date (if (listp date) date
17328 (calendar-gregorian-from-absolute date))))))))
17330 (defun org-goto-calendar (&optional arg)
17331 "Go to the Emacs calendar at the current date.
17332 If there is a time stamp in the current line, go to that date.
17333 A prefix ARG can be used to force the current date."
17334 (interactive "P")
17335 (let ((tsr org-ts-regexp) diff
17336 (calendar-move-hook nil)
17337 (calendar-view-holidays-initially-flag nil)
17338 (calendar-view-diary-initially-flag nil))
17339 (if (or (org-at-timestamp-p)
17340 (save-excursion
17341 (beginning-of-line 1)
17342 (looking-at (concat ".*" tsr))))
17343 (let ((d1 (time-to-days (current-time)))
17344 (d2 (time-to-days
17345 (org-time-string-to-time (match-string 1)))))
17346 (setq diff (- d2 d1))))
17347 (calendar)
17348 (calendar-goto-today)
17349 (if (and diff (not arg)) (calendar-forward-day diff))))
17351 (defun org-get-date-from-calendar ()
17352 "Return a list (month day year) of date at point in calendar."
17353 (with-current-buffer "*Calendar*"
17354 (save-match-data
17355 (calendar-cursor-to-date))))
17357 (defun org-date-from-calendar ()
17358 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17359 If there is already a time stamp at the cursor position, update it."
17360 (interactive)
17361 (if (org-at-timestamp-p t)
17362 (org-timestamp-change 0 'calendar)
17363 (let ((cal-date (org-get-date-from-calendar)))
17364 (org-insert-time-stamp
17365 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17367 (defcustom org-effort-durations
17368 `(("h" . 60)
17369 ("d" . ,(* 60 8))
17370 ("w" . ,(* 60 8 5))
17371 ("m" . ,(* 60 8 5 4))
17372 ("y" . ,(* 60 8 5 40)))
17373 "Conversion factor to minutes for an effort modifier.
17375 Each entry has the form (MODIFIER . MINUTES).
17377 In an effort string, a number followed by MODIFIER is multiplied
17378 by the specified number of MINUTES to obtain an effort in
17379 minutes.
17381 For example, if the value of this variable is ((\"hours\" . 60)), then an
17382 effort string \"2hours\" is equivalent to 120 minutes."
17383 :group 'org-agenda
17384 :version "24.1"
17385 :type '(alist :key-type (string :tag "Modifier")
17386 :value-type (number :tag "Minutes")))
17388 (defun org-minutes-to-clocksum-string (m)
17389 "Format number of minutes as a clocksum string.
17390 The format is determined by `org-time-clocksum-format',
17391 `org-time-clocksum-use-fractional' and
17392 `org-time-clocksum-fractional-format' and
17393 `org-time-clocksum-use-effort-durations'."
17394 (let ((clocksum "") h d w mo y fmt n)
17395 (setq h (if org-time-clocksum-use-effort-durations
17396 (cdr (assoc "h" org-effort-durations)) 60)
17397 d (if org-time-clocksum-use-effort-durations
17398 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17399 w (if org-time-clocksum-use-effort-durations
17400 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17401 mo (if org-time-clocksum-use-effort-durations
17402 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17403 y (if org-time-clocksum-use-effort-durations
17404 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17405 ;; fractional format
17406 (if org-time-clocksum-use-fractional
17407 (cond
17408 ;; single format string
17409 ((stringp org-time-clocksum-fractional-format)
17410 (format org-time-clocksum-fractional-format (/ m (float h))))
17411 ;; choice of fractional formats for different time units
17412 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17413 (> (/ (truncate m) (* y d h)) 0))
17414 (format fmt (/ m (* y d (float h)))))
17415 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17416 (> (/ (truncate m) (* mo d h)) 0))
17417 (format fmt (/ m (* mo d (float h)))))
17418 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17419 (> (/ (truncate m) (* w d h)) 0))
17420 (format fmt (/ m (* w d (float h)))))
17421 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17422 (> (/ (truncate m) (* d h)) 0))
17423 (format fmt (/ m (* d (float h)))))
17424 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17425 (> (/ (truncate m) h) 0))
17426 (format fmt (/ m (float h))))
17427 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17428 (format fmt m))
17429 ;; fall back to smallest time unit with a format
17430 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17431 (format fmt (/ m (float h))))
17432 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17433 (format fmt (/ m (* d (float h)))))
17434 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17435 (format fmt (/ m (* w d (float h)))))
17436 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17437 (format fmt (/ m (* mo d (float h)))))
17438 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17439 (format fmt (/ m (* y d (float h))))))
17440 ;; standard (non-fractional) format, with single format string
17441 (if (stringp org-time-clocksum-format)
17442 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17443 ;; separate formats components
17444 (and (setq fmt (plist-get org-time-clocksum-format :years))
17445 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17446 (plist-get org-time-clocksum-format :require-years))
17447 (setq clocksum (concat clocksum (format fmt n))
17448 m (- m (* n y d h))))
17449 (and (setq fmt (plist-get org-time-clocksum-format :months))
17450 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17451 (plist-get org-time-clocksum-format :require-months))
17452 (setq clocksum (concat clocksum (format fmt n))
17453 m (- m (* n mo d h))))
17454 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17455 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17456 (plist-get org-time-clocksum-format :require-weeks))
17457 (setq clocksum (concat clocksum (format fmt n))
17458 m (- m (* n w d h))))
17459 (and (setq fmt (plist-get org-time-clocksum-format :days))
17460 (or (> (setq n (/ (truncate m) (* d h))) 0)
17461 (plist-get org-time-clocksum-format :require-days))
17462 (setq clocksum (concat clocksum (format fmt n))
17463 m (- m (* n d h))))
17464 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17465 (or (> (setq n (/ (truncate m) h)) 0)
17466 (plist-get org-time-clocksum-format :require-hours))
17467 (setq clocksum (concat clocksum (format fmt n))
17468 m (- m (* n h))))
17469 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17470 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17471 (setq clocksum (concat clocksum (format fmt m))))
17472 ;; return formatted time duration
17473 clocksum))))
17475 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17476 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17477 "Org mode version 8.0")
17479 (defun org-hours-to-clocksum-string (n)
17480 (org-minutes-to-clocksum-string (* n 60)))
17482 (defun org-hh:mm-string-to-minutes (s)
17483 "Convert a string H:MM to a number of minutes.
17484 If the string is just a number, interpret it as minutes.
17485 In fact, the first hh:mm or number in the string will be taken,
17486 there can be extra stuff in the string.
17487 If no number is found, the return value is 0."
17488 (cond
17489 ((integerp s) s)
17490 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17491 (+ (* (string-to-number (match-string 1 s)) 60)
17492 (string-to-number (match-string 2 s))))
17493 ((string-match "\\([0-9]+\\)" s)
17494 (string-to-number (match-string 1 s)))
17495 (t 0)))
17497 (defcustom org-image-actual-width t
17498 "Should we use the actual width of images when inlining them?
17500 When set to `t', always use the image width.
17502 When set to a number, use imagemagick (when available) to set
17503 the image's width to this value.
17505 When set to a number in a list, try to get the width from any
17506 #+ATTR.* keyword if it matches a width specification like
17508 #+ATTR_HTML: :width 300px
17510 and fall back on that number if none is found.
17512 When set to nil, try to get the width from an #+ATTR.* keyword
17513 and fall back on the original width if none is found.
17515 This requires Emacs >= 24.1, build with imagemagick support."
17516 :group 'org-appearance
17517 :version "24.4"
17518 :package-version '(Org . "8.0")
17519 :type '(choice
17520 (const :tag "Use the image width" t)
17521 (integer :tag "Use a number of pixels")
17522 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17523 (const :tag "Use #+ATTR* or don't resize" nil)))
17525 (defcustom org-agenda-inhibit-startup nil
17526 "Inhibit startup when preparing agenda buffers.
17527 When this variable is `t' (the default), the initialization of
17528 the Org agenda buffers is inhibited: e.g. the visibility state
17529 is not set, the tables are not re-aligned, etc."
17530 :type 'boolean
17531 :version "24.3"
17532 :group 'org-agenda)
17534 (defun org-duration-string-to-minutes (s &optional output-to-string)
17535 "Convert a duration string S to minutes.
17537 A bare number is interpreted as minutes, modifiers can be set by
17538 customizing `org-effort-durations' (which see).
17540 Entries containing a colon are interpreted as H:MM by
17541 `org-hh:mm-string-to-minutes'."
17542 (let ((result 0)
17543 (re (concat "\\([0-9.]+\\) *\\("
17544 (regexp-opt (mapcar 'car org-effort-durations))
17545 "\\)")))
17546 (while (string-match re s)
17547 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17548 (string-to-number (match-string 1 s))))
17549 (setq s (replace-match "" nil t s)))
17550 (setq result (floor result))
17551 (incf result (org-hh:mm-string-to-minutes s))
17552 (if output-to-string (number-to-string result) result)))
17554 ;;;; Files
17556 (defun org-save-all-org-buffers ()
17557 "Save all Org-mode buffers without user confirmation."
17558 (interactive)
17559 (message "Saving all Org-mode buffers...")
17560 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17561 (when (featurep 'org-id) (org-id-locations-save))
17562 (message "Saving all Org-mode buffers... done"))
17564 (defun org-revert-all-org-buffers ()
17565 "Revert all Org-mode buffers.
17566 Prompt for confirmation when there are unsaved changes.
17567 Be sure you know what you are doing before letting this function
17568 overwrite your changes.
17570 This function is useful in a setup where one tracks org files
17571 with a version control system, to revert on one machine after pulling
17572 changes from another. I believe the procedure must be like this:
17574 1. M-x org-save-all-org-buffers
17575 2. Pull changes from the other machine, resolve conflicts
17576 3. M-x org-revert-all-org-buffers"
17577 (interactive)
17578 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17579 (error "Abort"))
17580 (save-excursion
17581 (save-window-excursion
17582 (mapc
17583 (lambda (b)
17584 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17585 (with-current-buffer b buffer-file-name))
17586 (org-pop-to-buffer-same-window b)
17587 (revert-buffer t 'no-confirm)))
17588 (buffer-list))
17589 (when (and (featurep 'org-id) org-id-track-globally)
17590 (org-id-locations-load)))))
17592 ;;;; Agenda files
17594 ;;;###autoload
17595 (defun org-switchb (&optional arg)
17596 "Switch between Org buffers.
17597 With one prefix argument, restrict available buffers to files.
17598 With two prefix arguments, restrict available buffers to agenda files.
17600 Defaults to `iswitchb' for buffer name completion.
17601 Set `org-completion-use-ido' to make it use ido instead."
17602 (interactive "P")
17603 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17604 ((equal arg '(16)) (org-buffer-list 'agenda))
17605 (t (org-buffer-list))))
17606 (org-completion-use-iswitchb org-completion-use-iswitchb)
17607 (org-completion-use-ido org-completion-use-ido))
17608 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17609 (setq org-completion-use-iswitchb t))
17610 (org-pop-to-buffer-same-window
17611 (org-icompleting-read "Org buffer: "
17612 (mapcar 'list (mapcar 'buffer-name blist))
17613 nil t))))
17615 ;;; Define some older names previously used for this functionality
17616 ;;;###autoload
17617 (defalias 'org-ido-switchb 'org-switchb)
17618 ;;;###autoload
17619 (defalias 'org-iswitchb 'org-switchb)
17621 (defun org-buffer-list (&optional predicate exclude-tmp)
17622 "Return a list of Org buffers.
17623 PREDICATE can be `export', `files' or `agenda'.
17625 export restrict the list to Export buffers.
17626 files restrict the list to buffers visiting Org files.
17627 agenda restrict the list to buffers visiting agenda files.
17629 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17630 (let* ((bfn nil)
17631 (agenda-files (and (eq predicate 'agenda)
17632 (mapcar 'file-truename (org-agenda-files t))))
17633 (filter
17634 (cond
17635 ((eq predicate 'files)
17636 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17637 ((eq predicate 'export)
17638 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17639 ((eq predicate 'agenda)
17640 (lambda (b)
17641 (with-current-buffer b
17642 (and (derived-mode-p 'org-mode)
17643 (setq bfn (buffer-file-name b))
17644 (member (file-truename bfn) agenda-files)))))
17645 (t (lambda (b) (with-current-buffer b
17646 (or (derived-mode-p 'org-mode)
17647 (string-match "\*Org .*Export"
17648 (buffer-name b)))))))))
17649 (delq nil
17650 (mapcar
17651 (lambda(b)
17652 (if (and (funcall filter b)
17653 (or (not exclude-tmp)
17654 (not (string-match "tmp" (buffer-name b)))))
17656 nil))
17657 (buffer-list)))))
17659 (defun org-agenda-files (&optional unrestricted archives)
17660 "Get the list of agenda files.
17661 Optional UNRESTRICTED means return the full list even if a restriction
17662 is currently in place.
17663 When ARCHIVES is t, include all archive files that are really being
17664 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17665 `org-agenda-archives-mode' is t."
17666 (let ((files
17667 (cond
17668 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17669 ((stringp org-agenda-files) (org-read-agenda-file-list))
17670 ((listp org-agenda-files) org-agenda-files)
17671 (t (error "Invalid value of `org-agenda-files'")))))
17672 (setq files (apply 'append
17673 (mapcar (lambda (f)
17674 (if (file-directory-p f)
17675 (directory-files
17676 f t org-agenda-file-regexp)
17677 (list f)))
17678 files)))
17679 (when org-agenda-skip-unavailable-files
17680 (setq files (delq nil
17681 (mapcar (function
17682 (lambda (file)
17683 (and (file-readable-p file) file)))
17684 files))))
17685 (when (or (eq archives t)
17686 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17687 (setq files (org-add-archive-files files)))
17688 files))
17690 (defun org-agenda-file-p (&optional file)
17691 "Return non-nil, if FILE is an agenda file.
17692 If FILE is omitted, use the file associated with the current
17693 buffer."
17694 (member (or file (buffer-file-name))
17695 (org-agenda-files t)))
17697 (defun org-edit-agenda-file-list ()
17698 "Edit the list of agenda files.
17699 Depending on setup, this either uses customize to edit the variable
17700 `org-agenda-files', or it visits the file that is holding the list. In the
17701 latter case, the buffer is set up in a way that saving it automatically kills
17702 the buffer and restores the previous window configuration."
17703 (interactive)
17704 (if (stringp org-agenda-files)
17705 (let ((cw (current-window-configuration)))
17706 (find-file org-agenda-files)
17707 (org-set-local 'org-window-configuration cw)
17708 (org-add-hook 'after-save-hook
17709 (lambda ()
17710 (set-window-configuration
17711 (prog1 org-window-configuration
17712 (kill-buffer (current-buffer))))
17713 (org-install-agenda-files-menu)
17714 (message "New agenda file list installed"))
17715 nil 'local)
17716 (message "%s" (substitute-command-keys
17717 "Edit list and finish with \\[save-buffer]")))
17718 (customize-variable 'org-agenda-files)))
17720 (defun org-store-new-agenda-file-list (list)
17721 "Set new value for the agenda file list and save it correctly."
17722 (if (stringp org-agenda-files)
17723 (let ((fe (org-read-agenda-file-list t)) b u)
17724 (while (setq b (find-buffer-visiting org-agenda-files))
17725 (kill-buffer b))
17726 (with-temp-file org-agenda-files
17727 (insert
17728 (mapconcat
17729 (lambda (f) ;; Keep un-expanded entries.
17730 (if (setq u (assoc f fe))
17731 (cdr u)
17733 list "\n")
17734 "\n")))
17735 (let ((org-mode-hook nil) (org-inhibit-startup t)
17736 (org-insert-mode-line-in-empty-file nil))
17737 (setq org-agenda-files list)
17738 (customize-save-variable 'org-agenda-files org-agenda-files))))
17740 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17741 "Read the list of agenda files from a file.
17742 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17743 filenames, used by `org-store-new-agenda-file-list' to write back
17744 un-expanded file names."
17745 (when (file-directory-p org-agenda-files)
17746 (error "`org-agenda-files' cannot be a single directory"))
17747 (when (stringp org-agenda-files)
17748 (with-temp-buffer
17749 (insert-file-contents org-agenda-files)
17750 (mapcar
17751 (lambda (f)
17752 (let ((e (expand-file-name (substitute-in-file-name f)
17753 org-directory)))
17754 (if pair-with-expansion
17755 (cons e f)
17756 e)))
17757 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17759 ;;;###autoload
17760 (defun org-cycle-agenda-files ()
17761 "Cycle through the files in `org-agenda-files'.
17762 If the current buffer visits an agenda file, find the next one in the list.
17763 If the current buffer does not, find the first agenda file."
17764 (interactive)
17765 (let* ((fs (org-agenda-files t))
17766 (files (append fs (list (car fs))))
17767 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17768 file)
17769 (unless files (error "No agenda files"))
17770 (catch 'exit
17771 (while (setq file (pop files))
17772 (if (equal (file-truename file) tcf)
17773 (when (car files)
17774 (find-file (car files))
17775 (throw 'exit t))))
17776 (find-file (car fs)))
17777 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17779 (defun org-agenda-file-to-front (&optional to-end)
17780 "Move/add the current file to the top of the agenda file list.
17781 If the file is not present in the list, it is added to the front. If it is
17782 present, it is moved there. With optional argument TO-END, add/move to the
17783 end of the list."
17784 (interactive "P")
17785 (let ((org-agenda-skip-unavailable-files nil)
17786 (file-alist (mapcar (lambda (x)
17787 (cons (file-truename x) x))
17788 (org-agenda-files t)))
17789 (ctf (file-truename
17790 (or buffer-file-name
17791 (error "Please save the current buffer to a file"))))
17792 x had)
17793 (setq x (assoc ctf file-alist) had x)
17795 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17796 (if to-end
17797 (setq file-alist (append (delq x file-alist) (list x)))
17798 (setq file-alist (cons x (delq x file-alist))))
17799 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17800 (org-install-agenda-files-menu)
17801 (message "File %s to %s of agenda file list"
17802 (if had "moved" "added") (if to-end "end" "front"))))
17804 (defun org-remove-file (&optional file)
17805 "Remove current file from the list of files in variable `org-agenda-files'.
17806 These are the files which are being checked for agenda entries.
17807 Optional argument FILE means use this file instead of the current."
17808 (interactive)
17809 (let* ((org-agenda-skip-unavailable-files nil)
17810 (file (or file buffer-file-name
17811 (error "Current buffer does not visit a file")))
17812 (true-file (file-truename file))
17813 (afile (abbreviate-file-name file))
17814 (files (delq nil (mapcar
17815 (lambda (x)
17816 (if (equal true-file
17817 (file-truename x))
17818 nil x))
17819 (org-agenda-files t)))))
17820 (if (not (= (length files) (length (org-agenda-files t))))
17821 (progn
17822 (org-store-new-agenda-file-list files)
17823 (org-install-agenda-files-menu)
17824 (message "Removed file: %s" afile))
17825 (message "File was not in list: %s (not removed)" afile))))
17827 (defun org-file-menu-entry (file)
17828 (vector file (list 'find-file file) t))
17830 (defun org-check-agenda-file (file)
17831 "Make sure FILE exists. If not, ask user what to do."
17832 (when (not (file-exists-p file))
17833 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17834 (abbreviate-file-name file))
17835 (let ((r (downcase (read-char-exclusive))))
17836 (cond
17837 ((equal r ?r)
17838 (org-remove-file file)
17839 (throw 'nextfile t))
17840 (t (error "Abort"))))))
17842 (defun org-get-agenda-file-buffer (file)
17843 "Get a buffer visiting FILE. If the buffer needs to be created, add
17844 it to the list of buffers which might be released later."
17845 (let ((buf (org-find-base-buffer-visiting file)))
17846 (if buf
17847 buf ; just return it
17848 ;; Make a new buffer and remember it
17849 (setq buf (find-file-noselect file))
17850 (if buf (push buf org-agenda-new-buffers))
17851 buf)))
17853 (defun org-release-buffers (blist)
17854 "Release all buffers in list, asking the user for confirmation when needed.
17855 When a buffer is unmodified, it is just killed. When modified, it is saved
17856 \(if the user agrees) and then killed."
17857 (let (buf file)
17858 (while (setq buf (pop blist))
17859 (setq file (buffer-file-name buf))
17860 (when (and (buffer-modified-p buf)
17861 file
17862 (y-or-n-p (format "Save file %s? " file)))
17863 (with-current-buffer buf (save-buffer)))
17864 (kill-buffer buf))))
17866 (defun org-agenda-prepare-buffers (files)
17867 "Create buffers for all agenda files, protect archived trees and comments."
17868 (interactive)
17869 (let ((pa '(:org-archived t))
17870 (pc '(:org-comment t))
17871 (pall '(:org-archived t :org-comment t))
17872 (inhibit-read-only t)
17873 (org-inhibit-startup org-agenda-inhibit-startup)
17874 (rea (concat ":" org-archive-tag ":"))
17875 file re org-tag-alist)
17876 (setq org-tag-alist-for-agenda nil
17877 org-tag-groups-alist-for-agenda nil)
17878 (save-excursion
17879 (save-restriction
17880 (while (setq file (pop files))
17881 (catch 'nextfile
17882 (if (bufferp file)
17883 (set-buffer file)
17884 (org-check-agenda-file file)
17885 (set-buffer (org-get-agenda-file-buffer file)))
17886 (widen)
17887 (org-set-regexps-and-options-for-tags)
17888 (org-refresh-category-properties)
17889 (org-refresh-properties org-effort-property 'org-effort)
17890 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17891 (setq org-todo-keywords-for-agenda
17892 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17893 (setq org-done-keywords-for-agenda
17894 (append org-done-keywords-for-agenda org-done-keywords))
17895 (setq org-todo-keyword-alist-for-agenda
17896 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17897 (setq org-drawers-for-agenda
17898 (append org-drawers-for-agenda org-drawers))
17899 (setq org-tag-alist-for-agenda
17900 (append org-tag-alist-for-agenda org-tag-alist))
17901 (if org-group-tags
17902 (setq org-tag-groups-alist-for-agenda
17903 (org-uniquify-alist
17904 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17905 (org-with-silent-modifications
17906 (save-excursion
17907 (remove-text-properties (point-min) (point-max) pall)
17908 (when org-agenda-skip-archived-trees
17909 (goto-char (point-min))
17910 (while (re-search-forward rea nil t)
17911 (if (org-at-heading-p t)
17912 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17913 (goto-char (point-min))
17914 (setq re (format org-heading-keyword-regexp-format
17915 org-comment-string))
17916 (while (re-search-forward re nil t)
17917 (add-text-properties
17918 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17919 (setq org-todo-keywords-for-agenda
17920 (org-uniquify org-todo-keywords-for-agenda))
17921 (setq org-todo-keyword-alist-for-agenda
17922 (org-uniquify org-todo-keyword-alist-for-agenda))))
17925 ;;;; CDLaTeX minor mode
17927 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17928 "Keymap for the minor `org-cdlatex-mode'.")
17930 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17931 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17932 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17933 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17934 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17936 (defvar org-cdlatex-texmathp-advice-is-done nil
17937 "Flag remembering if we have applied the advice to texmathp already.")
17939 (define-minor-mode org-cdlatex-mode
17940 "Toggle the minor `org-cdlatex-mode'.
17941 This mode supports entering LaTeX environment and math in LaTeX fragments
17942 in Org-mode.
17943 \\{org-cdlatex-mode-map}"
17944 nil " OCDL" nil
17945 (when org-cdlatex-mode
17946 (require 'cdlatex)
17947 (run-hooks 'cdlatex-mode-hook)
17948 (cdlatex-compute-tables))
17949 (unless org-cdlatex-texmathp-advice-is-done
17950 (setq org-cdlatex-texmathp-advice-is-done t)
17951 (defadvice texmathp (around org-math-always-on activate)
17952 "Always return t in org-mode buffers.
17953 This is because we want to insert math symbols without dollars even outside
17954 the LaTeX math segments. If Orgmode thinks that point is actually inside
17955 an embedded LaTeX fragment, let texmathp do its job.
17956 \\[org-cdlatex-mode-map]"
17957 (interactive)
17958 (let (p)
17959 (cond
17960 ((not (derived-mode-p 'org-mode)) ad-do-it)
17961 ((eq this-command 'cdlatex-math-symbol)
17962 (setq ad-return-value t
17963 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17965 (let ((p (org-inside-LaTeX-fragment-p)))
17966 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17967 (setq ad-return-value t
17968 texmathp-why '("Org-mode embedded math" . 0))
17969 (if p ad-do-it)))))))))
17971 (defun turn-on-org-cdlatex ()
17972 "Unconditionally turn on `org-cdlatex-mode'."
17973 (org-cdlatex-mode 1))
17975 (defun org-try-cdlatex-tab ()
17976 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17977 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17978 - inside a LaTeX fragment, or
17979 - after the first word in a line, where an abbreviation expansion could
17980 insert a LaTeX environment."
17981 (when org-cdlatex-mode
17982 (cond
17983 ;; Before any word on the line: No expansion possible.
17984 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17985 ;; Just after first word on the line: Expand it. Make sure it
17986 ;; cannot happen on headlines, though.
17987 ((save-excursion
17988 (skip-chars-backward "a-zA-Z0-9*")
17989 (skip-chars-backward " \t")
17990 (and (bolp) (not (org-at-heading-p))))
17991 (cdlatex-tab) t)
17992 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17994 (defun org-cdlatex-underscore-caret (&optional arg)
17995 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17996 Revert to the normal definition outside of these fragments."
17997 (interactive "P")
17998 (if (org-inside-LaTeX-fragment-p)
17999 (call-interactively 'cdlatex-sub-superscript)
18000 (let (org-cdlatex-mode)
18001 (call-interactively (key-binding (vector last-input-event))))))
18003 (defun org-cdlatex-math-modify (&optional arg)
18004 "Execute `cdlatex-math-modify' in LaTeX fragments.
18005 Revert to the normal definition outside of these fragments."
18006 (interactive "P")
18007 (if (org-inside-LaTeX-fragment-p)
18008 (call-interactively 'cdlatex-math-modify)
18009 (let (org-cdlatex-mode)
18010 (call-interactively (key-binding (vector last-input-event))))))
18014 ;;;; LaTeX fragments
18016 (defvar org-latex-regexps
18017 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18018 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18019 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18020 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18021 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18022 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18023 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18024 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18025 "Regular expressions for matching embedded LaTeX.")
18027 (defun org-inside-LaTeX-fragment-p ()
18028 "Test if point is inside a LaTeX fragment.
18029 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18030 sequence appearing also before point.
18031 Even though the matchers for math are configurable, this function assumes
18032 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18033 delimiters are skipped when they have been removed by customization.
18034 The return value is nil, or a cons cell with the delimiter and the
18035 position of this delimiter.
18037 This function does a reasonably good job, but can locally be fooled by
18038 for example currency specifications. For example it will assume being in
18039 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18040 fragments that are properly closed, but during editing, we have to live
18041 with the uncertainty caused by missing closing delimiters. This function
18042 looks only before point, not after."
18043 (catch 'exit
18044 (let ((pos (point))
18045 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18046 (lim (progn
18047 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18048 (point)))
18049 dd-on str (start 0) m re)
18050 (goto-char pos)
18051 (when dodollar
18052 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18053 re (nth 1 (assoc "$" org-latex-regexps)))
18054 (while (string-match re str start)
18055 (cond
18056 ((= (match-end 0) (length str))
18057 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18058 ((= (match-end 0) (- (length str) 5))
18059 (throw 'exit nil))
18060 (t (setq start (match-end 0))))))
18061 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18062 (goto-char pos)
18063 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18064 (and (match-beginning 2) (throw 'exit nil))
18065 ;; count $$
18066 (while (re-search-backward "\\$\\$" lim t)
18067 (setq dd-on (not dd-on)))
18068 (goto-char pos)
18069 (if dd-on (cons "$$" m))))))
18071 (defun org-inside-latex-macro-p ()
18072 "Is point inside a LaTeX macro or its arguments?"
18073 (save-match-data
18074 (org-in-regexp
18075 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18077 (defvar org-latex-fragment-image-overlays nil
18078 "List of overlays carrying the images of latex fragments.")
18079 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18081 (defun org-remove-latex-fragment-image-overlays ()
18082 "Remove all overlays with LaTeX fragment images in current buffer."
18083 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18084 (setq org-latex-fragment-image-overlays nil))
18086 (defun org-preview-latex-fragment (&optional subtree)
18087 "Preview the LaTeX fragment at point, or all locally or globally.
18088 If the cursor is in a LaTeX fragment, create the image and overlay
18089 it over the source code. If there is no fragment at point, display
18090 all fragments in the current text, from one headline to the next. With
18091 prefix SUBTREE, display all fragments in the current subtree. With a
18092 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18093 the cursor is before the first headline,
18094 display all fragments in the buffer.
18095 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18096 (interactive "P")
18097 (unless buffer-file-name
18098 (error "Can't preview LaTeX fragment in a non-file buffer"))
18099 (org-remove-latex-fragment-image-overlays)
18100 (save-excursion
18101 (save-restriction
18102 (let (beg end at msg)
18103 (cond
18104 ((or (equal subtree '(16))
18105 (not (save-excursion
18106 (re-search-backward org-outline-regexp-bol nil t))))
18107 (setq beg (point-min) end (point-max)
18108 msg "Creating images for buffer...%s"))
18109 ((equal subtree '(4))
18110 (org-back-to-heading)
18111 (setq beg (point) end (org-end-of-subtree t)
18112 msg "Creating images for subtree...%s"))
18114 (if (setq at (org-inside-LaTeX-fragment-p))
18115 (goto-char (max (point-min) (- (cdr at) 2)))
18116 (org-back-to-heading))
18117 (setq beg (point) end (progn (outline-next-heading) (point))
18118 msg (if at "Creating image...%s"
18119 "Creating images for entry...%s"))))
18120 (message msg "")
18121 (narrow-to-region beg end)
18122 (goto-char beg)
18123 (org-format-latex
18124 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18125 (file-name-nondirectory
18126 buffer-file-name)))
18127 default-directory 'overlays msg at 'forbuffer
18128 org-latex-create-formula-image-program)
18129 (message msg "done. Use `C-c C-c' to remove images.")))))
18131 (defun org-format-latex (prefix &optional dir overlays msg at
18132 forbuffer processing-type)
18133 "Replace LaTeX fragments with links to an image, and produce images.
18134 Some of the options can be changed using the variable
18135 `org-format-latex-options'."
18136 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18137 (let* ((prefixnodir (file-name-nondirectory prefix))
18138 (absprefix (expand-file-name prefix dir))
18139 (todir (file-name-directory absprefix))
18140 (opt org-format-latex-options)
18141 (optnew org-format-latex-options)
18142 (matchers (plist-get opt :matchers))
18143 (re-list org-latex-regexps)
18144 (cnt 0) txt hash link beg end re e checkdir
18145 string
18146 m n block-type block linkfile movefile ov)
18147 ;; Check the different regular expressions
18148 (while (setq e (pop re-list))
18149 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18150 block (if block-type "\n\n" ""))
18151 (when (member m matchers)
18152 (goto-char (point-min))
18153 (while (re-search-forward re nil t)
18154 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18155 (or (not overlays)
18156 (not (eq (get-char-property (match-beginning n)
18157 'org-overlay-type)
18158 'org-latex-overlay))))
18159 (cond
18160 ((eq processing-type 'verbatim))
18161 ((eq processing-type 'mathjax)
18162 ;; Prepare for MathJax processing.
18163 (setq string (match-string n))
18164 (when (member m '("$" "$1"))
18165 (save-excursion
18166 (delete-region (match-beginning n) (match-end n))
18167 (goto-char (match-beginning n))
18168 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18169 ((or (eq processing-type 'dvipng)
18170 (eq processing-type 'imagemagick))
18171 ;; Process to an image.
18172 (setq txt (match-string n)
18173 beg (match-beginning n) end (match-end n)
18174 cnt (1+ cnt))
18175 (let ((face (face-at-point))
18176 (fg (plist-get opt :foreground))
18177 (bg (plist-get opt :background))
18178 ;; Ensure full list is printed.
18179 print-length print-level)
18180 (when forbuffer
18181 ;; Get the colors from the face at point.
18182 (goto-char beg)
18183 (when (eq fg 'auto)
18184 (setq fg (face-attribute face :foreground nil 'default)))
18185 (when (eq bg 'auto)
18186 (setq bg (face-attribute face :background nil 'default)))
18187 (setq optnew (copy-sequence opt))
18188 (plist-put optnew :foreground fg)
18189 (plist-put optnew :background bg))
18190 (setq hash (sha1 (prin1-to-string
18191 (list org-format-latex-header
18192 org-latex-default-packages-alist
18193 org-latex-packages-alist
18194 org-format-latex-options
18195 forbuffer txt fg bg)))
18196 linkfile (format "%s_%s.png" prefix hash)
18197 movefile (format "%s_%s.png" absprefix hash)))
18198 (setq link (concat block "[[file:" linkfile "]]" block))
18199 (if msg (message msg cnt))
18200 (goto-char beg)
18201 (unless checkdir ; Ensure the directory exists.
18202 (setq checkdir t)
18203 (or (file-directory-p todir) (make-directory todir t)))
18204 (unless (file-exists-p movefile)
18205 (org-create-formula-image
18206 txt movefile optnew forbuffer processing-type))
18207 (if overlays
18208 (progn
18209 (mapc (lambda (o)
18210 (if (eq (overlay-get o 'org-overlay-type)
18211 'org-latex-overlay)
18212 (delete-overlay o)))
18213 (overlays-in beg end))
18214 (setq ov (make-overlay beg end))
18215 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18216 (if (featurep 'xemacs)
18217 (progn
18218 (overlay-put ov 'invisible t)
18219 (overlay-put
18220 ov 'end-glyph
18221 (make-glyph (vector 'png :file movefile))))
18222 (overlay-put
18223 ov 'display
18224 (list 'image :type 'png :file movefile :ascent 'center)))
18225 (push ov org-latex-fragment-image-overlays)
18226 (goto-char end))
18227 (delete-region beg end)
18228 (insert (org-add-props link
18229 (list 'org-latex-src
18230 (replace-regexp-in-string
18231 "\"" "" txt)
18232 'org-latex-src-embed-type
18233 (if block-type 'paragraph 'character))))))
18234 ((eq processing-type 'mathml)
18235 ;; Process to MathML
18236 (unless (save-match-data (org-format-latex-mathml-available-p))
18237 (error "LaTeX to MathML converter not configured"))
18238 (setq txt (match-string n)
18239 beg (match-beginning n) end (match-end n)
18240 cnt (1+ cnt))
18241 (if msg (message msg cnt))
18242 (goto-char beg)
18243 (delete-region beg end)
18244 (insert (org-format-latex-as-mathml
18245 txt block-type prefix dir)))
18247 (error "Unknown conversion type %s for latex fragments"
18248 processing-type)))))))))
18250 (defun org-create-math-formula (latex-frag &optional mathml-file)
18251 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18252 Use `org-latex-to-mathml-convert-command'. If the conversion is
18253 sucessful, return the portion between \"<math...> </math>\"
18254 elements otherwise return nil. When MATHML-FILE is specified,
18255 write the results in to that file. When invoked as an
18256 interactive command, prompt for LATEX-FRAG, with initial value
18257 set to the current active region and echo the results for user
18258 inspection."
18259 (interactive (list (let ((frag (when (org-region-active-p)
18260 (buffer-substring-no-properties
18261 (region-beginning) (region-end)))))
18262 (read-string "LaTeX Fragment: " frag nil frag))))
18263 (unless latex-frag (error "Invalid latex-frag"))
18264 (let* ((tmp-in-file (file-relative-name
18265 (make-temp-name (expand-file-name "ltxmathml-in"))))
18266 (ignore (write-region latex-frag nil tmp-in-file))
18267 (tmp-out-file (file-relative-name
18268 (make-temp-name (expand-file-name "ltxmathml-out"))))
18269 (cmd (format-spec
18270 org-latex-to-mathml-convert-command
18271 `((?j . ,(shell-quote-argument
18272 (expand-file-name org-latex-to-mathml-jar-file)))
18273 (?I . ,(shell-quote-argument tmp-in-file))
18274 (?o . ,(shell-quote-argument tmp-out-file)))))
18275 mathml shell-command-output)
18276 (when (org-called-interactively-p 'any)
18277 (unless (org-format-latex-mathml-available-p)
18278 (error "LaTeX to MathML converter not configured")))
18279 (message "Running %s" cmd)
18280 (setq shell-command-output (shell-command-to-string cmd))
18281 (setq mathml
18282 (when (file-readable-p tmp-out-file)
18283 (with-current-buffer (find-file-noselect tmp-out-file t)
18284 (goto-char (point-min))
18285 (when (re-search-forward
18286 (concat
18287 (regexp-quote
18288 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18289 "\\(.\\|\n\\)*"
18290 (regexp-quote "</math>")) nil t)
18291 (prog1 (match-string 0) (kill-buffer))))))
18292 (cond
18293 (mathml
18294 (setq mathml
18295 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18296 (when mathml-file
18297 (write-region mathml nil mathml-file))
18298 (when (org-called-interactively-p 'any)
18299 (message mathml)))
18300 ((message "LaTeX to MathML conversion failed")
18301 (message shell-command-output)))
18302 (delete-file tmp-in-file)
18303 (when (file-exists-p tmp-out-file)
18304 (delete-file tmp-out-file))
18305 mathml))
18307 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18308 prefix &optional dir)
18309 "Use `org-create-math-formula' but check local cache first."
18310 (let* ((absprefix (expand-file-name prefix dir))
18311 (print-length nil) (print-level nil)
18312 (formula-id (concat
18313 "formula-"
18314 (sha1
18315 (prin1-to-string
18316 (list latex-frag
18317 org-latex-to-mathml-convert-command)))))
18318 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18319 (formula-cache-dir (file-name-directory formula-cache)))
18321 (unless (file-directory-p formula-cache-dir)
18322 (make-directory formula-cache-dir t))
18324 (unless (file-exists-p formula-cache)
18325 (org-create-math-formula latex-frag formula-cache))
18327 (if (file-exists-p formula-cache)
18328 ;; Successful conversion. Return the link to MathML file.
18329 (org-add-props
18330 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18331 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18332 'org-latex-src-embed-type (if latex-frag-type
18333 'paragraph 'character)))
18334 ;; Failed conversion. Return the LaTeX fragment verbatim
18335 latex-frag)))
18337 (defun org-create-formula-image (string tofile options buffer &optional type)
18338 "Create an image from LaTeX source using dvipng or convert.
18339 This function calls either `org-create-formula-image-with-dvipng'
18340 or `org-create-formula-image-with-imagemagick' depending on the
18341 value of `org-latex-create-formula-image-program' or on the value
18342 of the optional TYPE variable.
18344 Note: ultimately these two function should be combined as they
18345 share a good deal of logic."
18346 (org-check-external-command
18347 "latex" "needed to convert LaTeX fragments to images")
18348 (funcall
18349 (case (or type org-latex-create-formula-image-program)
18350 ('dvipng
18351 (org-check-external-command
18352 "dvipng" "needed to convert LaTeX fragments to images")
18353 #'org-create-formula-image-with-dvipng)
18354 ('imagemagick
18355 (org-check-external-command
18356 "convert" "you need to install imagemagick")
18357 #'org-create-formula-image-with-imagemagick)
18358 (t (error
18359 "invalid value of `org-latex-create-formula-image-program'")))
18360 string tofile options buffer))
18362 (declare-function org-export--get-global-options "ox" (&optional backend))
18363 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18364 (defun org-create-formula--latex-header ()
18365 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18366 (org-latex-guess-inputenc
18367 (org-splice-latex-header
18368 org-format-latex-header
18369 org-latex-default-packages-alist
18370 org-latex-packages-alist t
18371 (plist-get
18372 (org-combine-plists
18373 (org-export--get-global-options 'latex)
18374 (org-export--get-inbuffer-options 'latex))
18375 :latex-header))))
18377 ;; This function borrows from Ganesh Swami's latex2png.el
18378 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18379 "This calls dvipng."
18380 (require 'ox-latex)
18381 (let* ((tmpdir (if (featurep 'xemacs)
18382 (temp-directory)
18383 temporary-file-directory))
18384 (texfilebase (make-temp-name
18385 (expand-file-name "orgtex" tmpdir)))
18386 (texfile (concat texfilebase ".tex"))
18387 (dvifile (concat texfilebase ".dvi"))
18388 (pngfile (concat texfilebase ".png"))
18389 (fnh (if (featurep 'xemacs)
18390 (font-height (face-font 'default))
18391 (face-attribute 'default :height nil)))
18392 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18393 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18394 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18395 "Black"))
18396 (bg (or (plist-get options (if buffer :background :html-background))
18397 "Transparent")))
18398 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18399 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18400 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18401 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18402 (let ((latex-header (org-create-formula--latex-header)))
18403 (with-temp-file texfile
18404 (insert latex-header)
18405 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18406 (let ((dir default-directory))
18407 (condition-case nil
18408 (progn
18409 (cd tmpdir)
18410 (call-process "latex" nil nil nil texfile))
18411 (error nil))
18412 (cd dir))
18413 (if (not (file-exists-p dvifile))
18414 (progn (message "Failed to create dvi file from %s" texfile) nil)
18415 (condition-case nil
18416 (if (featurep 'xemacs)
18417 (call-process "dvipng" nil nil nil
18418 "-fg" fg "-bg" bg
18419 "-T" "tight"
18420 "-o" pngfile
18421 dvifile)
18422 (call-process "dvipng" nil nil nil
18423 "-fg" fg "-bg" bg
18424 "-D" dpi
18425 ;;"-x" scale "-y" scale
18426 "-T" "tight"
18427 "-o" pngfile
18428 dvifile))
18429 (error nil))
18430 (if (not (file-exists-p pngfile))
18431 (if org-format-latex-signal-error
18432 (error "Failed to create png file from %s" texfile)
18433 (message "Failed to create png file from %s" texfile)
18434 nil)
18435 ;; Use the requested file name and clean up
18436 (copy-file pngfile tofile 'replace)
18437 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18438 (if (file-exists-p (concat texfilebase e))
18439 (delete-file (concat texfilebase e))))
18440 pngfile))))
18442 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18443 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18444 "This calls convert, which is included into imagemagick."
18445 (require 'ox-latex)
18446 (let* ((tmpdir (if (featurep 'xemacs)
18447 (temp-directory)
18448 temporary-file-directory))
18449 (texfilebase (make-temp-name
18450 (expand-file-name "orgtex" tmpdir)))
18451 (texfile (concat texfilebase ".tex"))
18452 (pdffile (concat texfilebase ".pdf"))
18453 (pngfile (concat texfilebase ".png"))
18454 (fnh (if (featurep 'xemacs)
18455 (font-height (face-font 'default))
18456 (face-attribute 'default :height nil)))
18457 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18458 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18459 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18460 "black"))
18461 (bg (or (plist-get options (if buffer :background :html-background))
18462 "white")))
18463 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18464 (setq fg (org-latex-color-format fg)))
18465 (if (eq bg 'default) (setq bg (org-latex-color :background))
18466 (setq bg (org-latex-color-format
18467 (if (string= bg "Transparent") "white" bg))))
18468 (let ((latex-header (org-create-formula--latex-header)))
18469 (with-temp-file texfile
18470 (insert latex-header)
18471 (insert "\n\\begin{document}\n"
18472 "\\definecolor{fg}{rgb}{" fg "}\n"
18473 "\\definecolor{bg}{rgb}{" bg "}\n"
18474 "\n\\pagecolor{bg}\n"
18475 "\n{\\color{fg}\n"
18476 string
18477 "\n}\n"
18478 "\n\\end{document}\n")))
18479 (org-latex-compile texfile t)
18480 (if (not (file-exists-p pdffile))
18481 (progn (message "Failed to create pdf file from %s" texfile) nil)
18482 (condition-case nil
18483 (if (featurep 'xemacs)
18484 (call-process "convert" nil nil nil
18485 "-density" "96"
18486 "-trim"
18487 "-antialias"
18488 pdffile
18489 "-quality" "100"
18490 ;; "-sharpen" "0x1.0"
18491 pngfile)
18492 (call-process "convert" nil nil nil
18493 "-density" dpi
18494 "-trim"
18495 "-antialias"
18496 pdffile
18497 "-quality" "100"
18498 ;; "-sharpen" "0x1.0"
18499 pngfile))
18500 (error nil))
18501 (if (not (file-exists-p pngfile))
18502 (if org-format-latex-signal-error
18503 (error "Failed to create png file from %s" texfile)
18504 (message "Failed to create png file from %s" texfile)
18505 nil)
18506 ;; Use the requested file name and clean up
18507 (copy-file pngfile tofile 'replace)
18508 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18509 (if (file-exists-p (concat texfilebase e))
18510 (delete-file (concat texfilebase e))))
18511 pngfile))))
18513 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18514 "Fill a LaTeX header template TPL.
18515 In the template, the following place holders will be recognized:
18517 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18518 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18519 [PACKAGES] \\usepackage statements for PKG
18520 [NO-PACKAGES] do not include PKG
18521 [EXTRA] the string EXTRA
18522 [NO-EXTRA] do not include EXTRA
18524 For backward compatibility, if both the positive and the negative place
18525 holder is missing, the positive one (without the \"NO-\") will be
18526 assumed to be present at the end of the template.
18527 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18528 EXTRA is a string.
18529 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18530 (let (rpl (end ""))
18531 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18532 (setq rpl (if (or (match-end 1) (not def-pkg))
18533 "" (org-latex-packages-to-string def-pkg snippets-p t))
18534 tpl (replace-match rpl t t tpl))
18535 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18537 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18538 (setq rpl (if (or (match-end 1) (not pkg))
18539 "" (org-latex-packages-to-string pkg snippets-p t))
18540 tpl (replace-match rpl t t tpl))
18541 (if pkg (setq end
18542 (concat end "\n"
18543 (org-latex-packages-to-string pkg snippets-p)))))
18545 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18546 (setq rpl (if (or (match-end 1) (not extra))
18547 "" (concat extra "\n"))
18548 tpl (replace-match rpl t t tpl))
18549 (if (and extra (string-match "\\S-" extra))
18550 (setq end (concat end "\n" extra))))
18552 (if (string-match "\\S-" end)
18553 (concat tpl "\n" end)
18554 tpl)))
18556 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18557 "Turn an alist of packages into a string with the \\usepackage macros."
18558 (setq pkg (mapconcat (lambda(p)
18559 (cond
18560 ((stringp p) p)
18561 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18562 (format "%% Package %s omitted" (cadr p)))
18563 ((equal "" (car p))
18564 (format "\\usepackage{%s}" (cadr p)))
18566 (format "\\usepackage[%s]{%s}"
18567 (car p) (cadr p)))))
18569 "\n"))
18570 (if newline (concat pkg "\n") pkg))
18572 (defun org-dvipng-color (attr)
18573 "Return a RGB color specification for dvipng."
18574 (apply 'format "rgb %s %s %s"
18575 (mapcar 'org-normalize-color
18576 (if (featurep 'xemacs)
18577 (color-rgb-components
18578 (face-property 'default
18579 (cond ((eq attr :foreground) 'foreground)
18580 ((eq attr :background) 'background))))
18581 (color-values (face-attribute 'default attr nil))))))
18583 (defun org-dvipng-color-format (color-name)
18584 "Convert COLOR-NAME to a RGB color value for dvipng."
18585 (apply 'format "rgb %s %s %s"
18586 (mapcar 'org-normalize-color
18587 (color-values color-name))))
18589 (defun org-latex-color (attr)
18590 "Return a RGB color for the LaTeX color package."
18591 (apply 'format "%s,%s,%s"
18592 (mapcar 'org-normalize-color
18593 (if (featurep 'xemacs)
18594 (color-rgb-components
18595 (face-property 'default
18596 (cond ((eq attr :foreground) 'foreground)
18597 ((eq attr :background) 'background))))
18598 (color-values (face-attribute 'default attr nil))))))
18600 (defun org-latex-color-format (color-name)
18601 "Convert COLOR-NAME to a RGB color value."
18602 (apply 'format "%s,%s,%s"
18603 (mapcar 'org-normalize-color
18604 (color-values color-name))))
18606 (defun org-normalize-color (value)
18607 "Return string to be used as color value for an RGB component."
18608 (format "%g" (/ value 65535.0)))
18612 ;; Image display
18614 (defvar org-inline-image-overlays nil)
18615 (make-variable-buffer-local 'org-inline-image-overlays)
18617 (defun org-toggle-inline-images (&optional include-linked)
18618 "Toggle the display of inline images.
18619 INCLUDE-LINKED is passed to `org-display-inline-images'."
18620 (interactive "P")
18621 (if org-inline-image-overlays
18622 (progn
18623 (org-remove-inline-images)
18624 (message "Inline image display turned off"))
18625 (org-display-inline-images include-linked)
18626 (if (and (org-called-interactively-p)
18627 org-inline-image-overlays)
18628 (message "%d images displayed inline"
18629 (length org-inline-image-overlays))
18630 (message "No images to display inline"))))
18632 (defun org-redisplay-inline-images ()
18633 "Refresh the display of inline images."
18634 (interactive)
18635 (if (not org-inline-image-overlays)
18636 (org-toggle-inline-images)
18637 (org-toggle-inline-images)
18638 (org-toggle-inline-images)))
18640 (defun org-display-inline-images (&optional include-linked refresh beg end)
18641 "Display inline images.
18642 Normally only links without a description part are inlined, because this
18643 is how it will work for export. When INCLUDE-LINKED is set, also links
18644 with a description part will be inlined. This can be nice for a quick
18645 look at those images, but it does not reflect what exported files will look
18646 like.
18647 When REFRESH is set, refresh existing images between BEG and END.
18648 This will create new image displays only if necessary.
18649 BEG and END default to the buffer boundaries."
18650 (interactive "P")
18651 (unless refresh
18652 (org-remove-inline-images)
18653 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18654 (save-excursion
18655 (save-restriction
18656 (widen)
18657 (setq beg (or beg (point-min)) end (or end (point-max)))
18658 (goto-char beg)
18659 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18660 (substring (org-image-file-name-regexp) 0 -2)
18661 "\\)\\]" (if include-linked "" "\\]")))
18662 (case-fold-search t)
18663 old file ov img type attrwidth width)
18664 (while (re-search-forward re end t)
18665 (setq old (get-char-property-and-overlay (match-beginning 1)
18666 'org-image-overlay)
18667 file (expand-file-name
18668 (concat (or (match-string 3) "") (match-string 4))))
18669 (when (image-type-available-p 'imagemagick)
18670 (setq attrwidth (if (or (listp org-image-actual-width)
18671 (null org-image-actual-width))
18672 (save-excursion
18673 (save-match-data
18674 (when (re-search-backward
18675 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18676 (save-excursion
18677 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18678 (string-to-number (match-string 1))))))
18679 width (cond ((eq org-image-actual-width t) nil)
18680 ((null org-image-actual-width) attrwidth)
18681 ((numberp org-image-actual-width)
18682 org-image-actual-width)
18683 ((listp org-image-actual-width)
18684 (or attrwidth (car org-image-actual-width))))
18685 type (if width 'imagemagick)))
18686 (when (file-exists-p file)
18687 (if (and (car-safe old) refresh)
18688 (image-refresh (overlay-get (cdr old) 'display))
18689 (setq img (save-match-data (create-image file type nil :width width)))
18690 (when img
18691 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18692 (overlay-put ov 'display img)
18693 (overlay-put ov 'face 'default)
18694 (overlay-put ov 'org-image-overlay t)
18695 (overlay-put ov 'modification-hooks
18696 (list 'org-display-inline-remove-overlay))
18697 (push ov org-inline-image-overlays)))))))))
18699 (define-obsolete-function-alias
18700 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18702 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18703 "Remove inline-display overlay if a corresponding region is modified."
18704 (let ((inhibit-modification-hooks t))
18705 (when (and ov after)
18706 (delete ov org-inline-image-overlays)
18707 (delete-overlay ov))))
18709 (defun org-remove-inline-images ()
18710 "Remove inline display of images."
18711 (interactive)
18712 (mapc 'delete-overlay org-inline-image-overlays)
18713 (setq org-inline-image-overlays nil))
18715 ;;;; Key bindings
18717 ;; Outline functions from `outline-mode-prefix-map'
18718 ;; that can be remapped in Org:
18719 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18720 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18721 (define-key org-mode-map [remap outline-forward-same-level]
18722 'org-forward-heading-same-level)
18723 (define-key org-mode-map [remap outline-backward-same-level]
18724 'org-backward-heading-same-level)
18725 (define-key org-mode-map [remap show-branches]
18726 'org-kill-note-or-show-branches)
18727 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18728 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18729 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18731 ;; Outline functions from `outline-mode-prefix-map' that can not
18732 ;; be remapped in Org:
18734 ;; - the column "key binding" shows whether the Outline function is still
18735 ;; available in Org mode on the same key that it has been bound to in
18736 ;; Outline mode:
18737 ;; - "overridden": key used for a different functionality in Org mode
18738 ;; - else: key still bound to the same Outline function in Org mode
18740 ;; | Outline function | key binding | Org replacement |
18741 ;; |------------------------------------+-------------+-----------------------|
18742 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18743 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18744 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18745 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18746 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18747 ;; | `show-entry' | overridden | no replacement |
18748 ;; | `show-children' | `C-c C-i' | visibility cycling |
18749 ;; | `show-branches' | `C-c C-k' | still same function |
18750 ;; | `show-subtree' | overridden | visibility cycling |
18751 ;; | `show-all' | overridden | no replacement |
18752 ;; | `hide-subtree' | overridden | visibility cycling |
18753 ;; | `hide-body' | overridden | no replacement |
18754 ;; | `hide-entry' | overridden | visibility cycling |
18755 ;; | `hide-leaves' | overridden | no replacement |
18756 ;; | `hide-sublevels' | overridden | no replacement |
18757 ;; | `hide-other' | overridden | no replacement |
18759 ;; Make `C-c C-x' a prefix key
18760 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18762 ;; TAB key with modifiers
18763 (org-defkey org-mode-map "\C-i" 'org-cycle)
18764 (org-defkey org-mode-map [(tab)] 'org-cycle)
18765 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18766 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18767 ;; The following line is necessary under Suse GNU/Linux
18768 (unless (featurep 'xemacs)
18769 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18770 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18771 (define-key org-mode-map [backtab] 'org-shifttab)
18773 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18774 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18775 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18777 ;; Cursor keys with modifiers
18778 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18779 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18780 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18781 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18783 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18784 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18785 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18786 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18788 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18789 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18790 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18791 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18793 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18794 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18795 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18796 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18798 ;; Babel keys
18799 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18800 (mapc (lambda (pair)
18801 (define-key org-babel-map (car pair) (cdr pair)))
18802 org-babel-key-bindings)
18804 ;;; Extra keys for tty access.
18805 ;; We only set them when really needed because otherwise the
18806 ;; menus don't show the simple keys
18808 (when (or org-use-extra-keys
18809 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18810 (not window-system))
18811 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18812 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18813 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18814 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18815 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18816 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18817 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18818 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18819 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18820 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18821 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18822 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18823 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18824 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18825 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18826 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18827 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18828 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18829 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18830 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18831 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18832 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18833 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18834 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18835 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18836 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18837 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18838 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18840 ;; All the other keys
18842 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18843 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18844 (if (boundp 'narrow-map)
18845 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18846 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18847 (if (boundp 'narrow-map)
18848 (org-defkey narrow-map "b" 'org-narrow-to-block)
18849 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18850 (if (boundp 'narrow-map)
18851 (org-defkey narrow-map "e" 'org-narrow-to-element)
18852 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18853 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18854 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18855 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18856 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18857 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18858 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18859 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18860 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18861 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18862 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18863 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18864 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18865 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18866 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18867 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18868 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18869 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18870 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18871 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18872 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18873 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18874 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18875 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18876 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18877 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18878 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18879 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18880 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18881 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18882 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18883 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18884 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18885 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18886 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18887 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18888 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18889 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18890 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18891 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18892 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18893 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18894 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18895 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18896 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18897 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18898 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18899 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18900 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18901 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18902 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18903 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18904 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18905 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18906 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18907 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18908 (org-defkey org-mode-map "\C-c^" 'org-sort)
18909 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18910 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18911 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18912 (org-defkey org-mode-map "\C-m" 'org-return)
18913 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18914 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18915 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18916 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18917 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18918 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18919 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18920 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18921 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18922 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18923 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18924 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18925 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18926 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18927 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18928 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18929 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18930 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18931 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18932 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18933 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18934 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18935 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18937 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18938 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18939 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18941 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18942 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18943 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18944 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18945 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18946 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18947 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18948 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18949 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18950 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18951 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18952 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18953 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18954 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18955 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18956 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18957 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18958 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18959 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18960 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18961 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18962 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18963 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18965 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18966 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18967 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18968 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18969 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18971 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18973 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18975 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18976 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18978 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18981 (when (featurep 'xemacs)
18982 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18985 (defconst org-speed-commands-default
18987 ("Outline Navigation")
18988 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18989 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18990 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18991 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18992 ("F" . org-next-block)
18993 ("B" . org-previous-block)
18994 ("u" . (org-speed-move-safe 'outline-up-heading))
18995 ("j" . org-goto)
18996 ("g" . (org-refile t))
18997 ("Outline Visibility")
18998 ("c" . org-cycle)
18999 ("C" . org-shifttab)
19000 (" " . org-display-outline-path)
19001 ("=" . org-columns)
19002 ("Outline Structure Editing")
19003 ("U" . org-shiftmetaup)
19004 ("D" . org-shiftmetadown)
19005 ("r" . org-metaright)
19006 ("l" . org-metaleft)
19007 ("R" . org-shiftmetaright)
19008 ("L" . org-shiftmetaleft)
19009 ("i" . (progn (forward-char 1) (call-interactively
19010 'org-insert-heading-respect-content)))
19011 ("^" . org-sort)
19012 ("w" . org-refile)
19013 ("a" . org-archive-subtree-default-with-confirmation)
19014 ("@" . org-mark-subtree)
19015 ("#" . org-toggle-comment)
19016 ("Clock Commands")
19017 ("I" . org-clock-in)
19018 ("O" . org-clock-out)
19019 ("Meta Data Editing")
19020 ("t" . org-todo)
19021 ("," . (org-priority))
19022 ("0" . (org-priority ?\ ))
19023 ("1" . (org-priority ?A))
19024 ("2" . (org-priority ?B))
19025 ("3" . (org-priority ?C))
19026 (":" . org-set-tags-command)
19027 ("e" . org-set-effort)
19028 ("E" . org-inc-effort)
19029 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19030 (org-entry-put (point) "APPT_WARNTIME" m)))
19031 ("Agenda Views etc")
19032 ("v" . org-agenda)
19033 ("/" . org-sparse-tree)
19034 ("Misc")
19035 ("o" . org-open-at-point)
19036 ("?" . org-speed-command-help)
19037 ("<" . (org-agenda-set-restriction-lock 'subtree))
19038 (">" . (org-agenda-remove-restriction-lock))
19040 "The default speed commands.")
19042 (defun org-print-speed-command (e)
19043 (if (> (length (car e)) 1)
19044 (progn
19045 (princ "\n")
19046 (princ (car e))
19047 (princ "\n")
19048 (princ (make-string (length (car e)) ?-))
19049 (princ "\n"))
19050 (princ (car e))
19051 (princ " ")
19052 (if (symbolp (cdr e))
19053 (princ (symbol-name (cdr e)))
19054 (prin1 (cdr e)))
19055 (princ "\n")))
19057 (defun org-speed-command-help ()
19058 "Show the available speed commands."
19059 (interactive)
19060 (if (not org-use-speed-commands)
19061 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19062 (with-output-to-temp-buffer "*Help*"
19063 (princ "User-defined Speed commands\n===========================\n")
19064 (mapc 'org-print-speed-command org-speed-commands-user)
19065 (princ "\n")
19066 (princ "Built-in Speed commands\n=======================\n")
19067 (mapc 'org-print-speed-command org-speed-commands-default))
19068 (with-current-buffer "*Help*"
19069 (setq truncate-lines t))))
19071 (defun org-speed-move-safe (cmd)
19072 "Execute CMD, but make sure that the cursor always ends up in a headline.
19073 If not, return to the original position and throw an error."
19074 (interactive)
19075 (let ((pos (point)))
19076 (call-interactively cmd)
19077 (unless (and (bolp) (org-at-heading-p))
19078 (goto-char pos)
19079 (error "Boundary reached while executing %s" cmd))))
19081 (defvar org-self-insert-command-undo-counter 0)
19083 (defvar org-table-auto-blank-field) ; defined in org-table.el
19084 (defvar org-speed-command nil)
19086 (define-obsolete-function-alias
19087 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19089 (defun org-speed-command-activate (keys)
19090 "Hook for activating single-letter speed commands.
19091 `org-speed-commands-default' specifies a minimal command set.
19092 Use `org-speed-commands-user' for further customization."
19093 (when (or (and (bolp) (looking-at org-outline-regexp))
19094 (and (functionp org-use-speed-commands)
19095 (funcall org-use-speed-commands)))
19096 (cdr (assoc keys (append org-speed-commands-user
19097 org-speed-commands-default)))))
19099 (define-obsolete-function-alias
19100 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19102 (defun org-babel-speed-command-activate (keys)
19103 "Hook for activating single-letter code block commands."
19104 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19105 (cdr (assoc keys org-babel-key-bindings))))
19107 (defcustom org-speed-command-hook
19108 '(org-speed-command-default-hook org-babel-speed-command-hook)
19109 "Hook for activating speed commands at strategic locations.
19110 Hook functions are called in sequence until a valid handler is
19111 found.
19113 Each hook takes a single argument, a user-pressed command key
19114 which is also a `self-insert-command' from the global map.
19116 Within the hook, examine the cursor position and the command key
19117 and return nil or a valid handler as appropriate. Handler could
19118 be one of an interactive command, a function, or a form.
19120 Set `org-use-speed-commands' to non-nil value to enable this
19121 hook. The default setting is `org-speed-command-activate'."
19122 :group 'org-structure
19123 :version "24.1"
19124 :type 'hook)
19126 (defun org-self-insert-command (N)
19127 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19128 If the cursor is in a table looking at whitespace, the whitespace is
19129 overwritten, and the table is not marked as requiring realignment."
19130 (interactive "p")
19131 (org-check-before-invisible-edit 'insert)
19132 (cond
19133 ((and org-use-speed-commands
19134 (setq org-speed-command
19135 (run-hook-with-args-until-success
19136 'org-speed-command-hook (this-command-keys))))
19137 (cond
19138 ((commandp org-speed-command)
19139 (setq this-command org-speed-command)
19140 (call-interactively org-speed-command))
19141 ((functionp org-speed-command)
19142 (funcall org-speed-command))
19143 ((and org-speed-command (listp org-speed-command))
19144 (eval org-speed-command))
19145 (t (let (org-use-speed-commands)
19146 (call-interactively 'org-self-insert-command)))))
19147 ((and
19148 (org-table-p)
19149 (progn
19150 ;; check if we blank the field, and if that triggers align
19151 (and (featurep 'org-table) org-table-auto-blank-field
19152 (member last-command
19153 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19154 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19155 ;; got extra space, this field does not determine column width
19156 (let (org-table-may-need-update) (org-table-blank-field))
19157 ;; no extra space, this field may determine column width
19158 (org-table-blank-field)))
19160 (eq N 1)
19161 (looking-at "[^|\n]* |"))
19162 (let (org-table-may-need-update)
19163 (goto-char (1- (match-end 0)))
19164 (backward-delete-char 1)
19165 (goto-char (match-beginning 0))
19166 (self-insert-command N)))
19168 (setq org-table-may-need-update t)
19169 (self-insert-command N)
19170 (org-fix-tags-on-the-fly)
19171 (if org-self-insert-cluster-for-undo
19172 (if (not (eq last-command 'org-self-insert-command))
19173 (setq org-self-insert-command-undo-counter 1)
19174 (if (>= org-self-insert-command-undo-counter 20)
19175 (setq org-self-insert-command-undo-counter 1)
19176 (and (> org-self-insert-command-undo-counter 0)
19177 buffer-undo-list (listp buffer-undo-list)
19178 (not (cadr buffer-undo-list)) ; remove nil entry
19179 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19180 (setq org-self-insert-command-undo-counter
19181 (1+ org-self-insert-command-undo-counter))))))))
19183 (defun org-check-before-invisible-edit (kind)
19184 "Check is editing if kind KIND would be dangerous with invisible text around.
19185 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19186 ;; First, try to get out of here as quickly as possible, to reduce overhead
19187 (if (and org-catch-invisible-edits
19188 (or (not (boundp 'visible-mode)) (not visible-mode))
19189 (or (get-char-property (point) 'invisible)
19190 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19191 ;; OK, we need to take a closer look
19192 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19193 (invisible-before-point (if (bobp) nil (get-char-property
19194 (1- (point)) 'invisible)))
19195 (border-and-ok-direction
19197 ;; Check if we are acting predictably before invisible text
19198 (and invisible-at-point (not invisible-before-point)
19199 (memq kind '(insert delete-backward)))
19200 ;; Check if we are acting predictably after invisible text
19201 ;; This works not well, and I have turned it off. It seems
19202 ;; better to always show and stop after invisible text.
19203 ;; (and (not invisible-at-point) invisible-before-point
19204 ;; (memq kind '(insert delete)))
19206 (when (or (memq invisible-at-point '(outline org-hide-block t))
19207 (memq invisible-before-point '(outline org-hide-block t)))
19208 (if (eq org-catch-invisible-edits 'error)
19209 (error "Editing in invisible areas is prohibited - make visible first"))
19210 (if (and org-custom-properties-overlays
19211 (y-or-n-p "Display invisible properties in this buffer? "))
19212 (org-toggle-custom-properties-visibility)
19213 ;; Make the area visible
19214 (save-excursion
19215 (if invisible-before-point
19216 (goto-char (previous-single-char-property-change
19217 (point) 'invisible)))
19218 (org-cycle))
19219 (cond
19220 ((eq org-catch-invisible-edits 'show)
19221 ;; That's it, we do the edit after showing
19222 (message
19223 "Unfolding invisible region around point before editing")
19224 (sit-for 1))
19225 ((and (eq org-catch-invisible-edits 'smart)
19226 border-and-ok-direction)
19227 (message "Unfolding invisible region around point before editing"))
19229 ;; Don't do the edit, make the user repeat it in full visibility
19230 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19232 (defun org-fix-tags-on-the-fly ()
19233 (when (and (equal (char-after (point-at-bol)) ?*)
19234 (org-at-heading-p))
19235 (org-align-tags-here org-tags-column)))
19237 (defun org-delete-backward-char (N)
19238 "Like `delete-backward-char', insert whitespace at field end in tables.
19239 When deleting backwards, in tables this function will insert whitespace in
19240 front of the next \"|\" separator, to keep the table aligned. The table will
19241 still be marked for re-alignment if the field did fill the entire column,
19242 because, in this case the deletion might narrow the column."
19243 (interactive "p")
19244 (save-match-data
19245 (org-check-before-invisible-edit 'delete-backward)
19246 (if (and (org-table-p)
19247 (eq N 1)
19248 (string-match "|" (buffer-substring (point-at-bol) (point)))
19249 (looking-at ".*?|"))
19250 (let ((pos (point))
19251 (noalign (looking-at "[^|\n\r]* |"))
19252 (c org-table-may-need-update))
19253 (backward-delete-char N)
19254 (if (not overwrite-mode)
19255 (progn
19256 (skip-chars-forward "^|")
19257 (insert " ")
19258 (goto-char (1- pos))))
19259 ;; noalign: if there were two spaces at the end, this field
19260 ;; does not determine the width of the column.
19261 (if noalign (setq org-table-may-need-update c)))
19262 (backward-delete-char N)
19263 (org-fix-tags-on-the-fly))))
19265 (defun org-delete-char (N)
19266 "Like `delete-char', but insert whitespace at field end in tables.
19267 When deleting characters, in tables this function will insert whitespace in
19268 front of the next \"|\" separator, to keep the table aligned. The table will
19269 still be marked for re-alignment if the field did fill the entire column,
19270 because, in this case the deletion might narrow the column."
19271 (interactive "p")
19272 (save-match-data
19273 (org-check-before-invisible-edit 'delete)
19274 (if (and (org-table-p)
19275 (not (bolp))
19276 (not (= (char-after) ?|))
19277 (eq N 1))
19278 (if (looking-at ".*?|")
19279 (let ((pos (point))
19280 (noalign (looking-at "[^|\n\r]* |"))
19281 (c org-table-may-need-update))
19282 (replace-match
19283 (concat (substring (match-string 0) 1 -1) " |") nil t)
19284 (goto-char pos)
19285 ;; noalign: if there were two spaces at the end, this field
19286 ;; does not determine the width of the column.
19287 (if noalign (setq org-table-may-need-update c)))
19288 (delete-char N))
19289 (delete-char N)
19290 (org-fix-tags-on-the-fly))))
19292 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19293 (put 'org-self-insert-command 'delete-selection t)
19294 (put 'orgtbl-self-insert-command 'delete-selection t)
19295 (put 'org-delete-char 'delete-selection 'supersede)
19296 (put 'org-delete-backward-char 'delete-selection 'supersede)
19297 (put 'org-yank 'delete-selection 'yank)
19299 ;; Make `flyspell-mode' delay after some commands
19300 (put 'org-self-insert-command 'flyspell-delayed t)
19301 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19302 (put 'org-delete-char 'flyspell-delayed t)
19303 (put 'org-delete-backward-char 'flyspell-delayed t)
19305 ;; Make pabbrev-mode expand after org-mode commands
19306 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19307 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19309 ;; How to do this: Measure non-white length of current string
19310 ;; If equal to column width, we should realign.
19312 (defun org-remap (map &rest commands)
19313 "In MAP, remap the functions given in COMMANDS.
19314 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19315 (let (new old)
19316 (while commands
19317 (setq old (pop commands) new (pop commands))
19318 (if (fboundp 'command-remapping)
19319 (org-defkey map (vector 'remap old) new)
19320 (substitute-key-definition old new map global-map)))))
19322 (defun org-transpose-words ()
19323 "Transpose words for Org.
19324 This uses the `org-mode-transpose-word-syntax-table' syntax
19325 table, which interprets characters in `org-emphasis-alist' as
19326 word constituants."
19327 (interactive)
19328 (with-syntax-table org-mode-transpose-word-syntax-table
19329 (call-interactively 'transpose-words)))
19330 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19332 (when (eq org-enable-table-editor 'optimized)
19333 ;; If the user wants maximum table support, we need to hijack
19334 ;; some standard editing functions
19335 (org-remap org-mode-map
19336 'self-insert-command 'org-self-insert-command
19337 'delete-char 'org-delete-char
19338 'delete-backward-char 'org-delete-backward-char)
19339 (org-defkey org-mode-map "|" 'org-force-self-insert))
19341 (defvar org-ctrl-c-ctrl-c-hook nil
19342 "Hook for functions attaching themselves to `C-c C-c'.
19344 This can be used to add additional functionality to the C-c C-c
19345 key which executes context-dependent commands. This hook is run
19346 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19347 run after the last test.
19349 Each function will be called with no arguments. The function
19350 must check if the context is appropriate for it to act. If yes,
19351 it should do its thing and then return a non-nil value. If the
19352 context is wrong, just do nothing and return nil.")
19354 (defvar org-ctrl-c-ctrl-c-final-hook nil
19355 "Hook for functions attaching themselves to `C-c C-c'.
19357 This can be used to add additional functionality to the C-c C-c
19358 key which executes context-dependent commands. This hook is run
19359 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19360 before the first test.
19362 Each function will be called with no arguments. The function
19363 must check if the context is appropriate for it to act. If yes,
19364 it should do its thing and then return a non-nil value. If the
19365 context is wrong, just do nothing and return nil.")
19367 (defvar org-tab-first-hook nil
19368 "Hook for functions to attach themselves to TAB.
19369 See `org-ctrl-c-ctrl-c-hook' for more information.
19370 This hook runs as the first action when TAB is pressed, even before
19371 `org-cycle' messes around with the `outline-regexp' to cater for
19372 inline tasks and plain list item folding.
19373 If any function in this hook returns t, any other actions that
19374 would have been caused by TAB (such as table field motion or visibility
19375 cycling) will not occur.")
19377 (defvar org-tab-after-check-for-table-hook nil
19378 "Hook for functions to attach themselves to TAB.
19379 See `org-ctrl-c-ctrl-c-hook' for more information.
19380 This hook runs after it has been established that the cursor is not in a
19381 table, but before checking if the cursor is in a headline or if global cycling
19382 should be done.
19383 If any function in this hook returns t, not other actions like visibility
19384 cycling will be done.")
19386 (defvar org-tab-after-check-for-cycling-hook nil
19387 "Hook for functions to attach themselves to TAB.
19388 See `org-ctrl-c-ctrl-c-hook' for more information.
19389 This hook runs after it has been established that not table field motion and
19390 not visibility should be done because of current context. This is probably
19391 the place where a package like yasnippets can hook in.")
19393 (defvar org-tab-before-tab-emulation-hook nil
19394 "Hook for functions to attach themselves to TAB.
19395 See `org-ctrl-c-ctrl-c-hook' for more information.
19396 This hook runs after every other options for TAB have been exhausted, but
19397 before indentation and \t insertion takes place.")
19399 (defvar org-metaleft-hook nil
19400 "Hook for functions attaching themselves to `M-left'.
19401 See `org-ctrl-c-ctrl-c-hook' for more information.")
19402 (defvar org-metaright-hook nil
19403 "Hook for functions attaching themselves to `M-right'.
19404 See `org-ctrl-c-ctrl-c-hook' for more information.")
19405 (defvar org-metaup-hook nil
19406 "Hook for functions attaching themselves to `M-up'.
19407 See `org-ctrl-c-ctrl-c-hook' for more information.")
19408 (defvar org-metadown-hook nil
19409 "Hook for functions attaching themselves to `M-down'.
19410 See `org-ctrl-c-ctrl-c-hook' for more information.")
19411 (defvar org-shiftmetaleft-hook nil
19412 "Hook for functions attaching themselves to `M-S-left'.
19413 See `org-ctrl-c-ctrl-c-hook' for more information.")
19414 (defvar org-shiftmetaright-hook nil
19415 "Hook for functions attaching themselves to `M-S-right'.
19416 See `org-ctrl-c-ctrl-c-hook' for more information.")
19417 (defvar org-shiftmetaup-hook nil
19418 "Hook for functions attaching themselves to `M-S-up'.
19419 See `org-ctrl-c-ctrl-c-hook' for more information.")
19420 (defvar org-shiftmetadown-hook nil
19421 "Hook for functions attaching themselves to `M-S-down'.
19422 See `org-ctrl-c-ctrl-c-hook' for more information.")
19423 (defvar org-metareturn-hook nil
19424 "Hook for functions attaching themselves to `M-RET'.
19425 See `org-ctrl-c-ctrl-c-hook' for more information.")
19426 (defvar org-shiftup-hook nil
19427 "Hook for functions attaching themselves to `S-up'.
19428 See `org-ctrl-c-ctrl-c-hook' for more information.")
19429 (defvar org-shiftup-final-hook nil
19430 "Hook for functions attaching themselves to `S-up'.
19431 This one runs after all other options except shift-select have been excluded.
19432 See `org-ctrl-c-ctrl-c-hook' for more information.")
19433 (defvar org-shiftdown-hook nil
19434 "Hook for functions attaching themselves to `S-down'.
19435 See `org-ctrl-c-ctrl-c-hook' for more information.")
19436 (defvar org-shiftdown-final-hook nil
19437 "Hook for functions attaching themselves to `S-down'.
19438 This one runs after all other options except shift-select have been excluded.
19439 See `org-ctrl-c-ctrl-c-hook' for more information.")
19440 (defvar org-shiftleft-hook nil
19441 "Hook for functions attaching themselves to `S-left'.
19442 See `org-ctrl-c-ctrl-c-hook' for more information.")
19443 (defvar org-shiftleft-final-hook nil
19444 "Hook for functions attaching themselves to `S-left'.
19445 This one runs after all other options except shift-select have been excluded.
19446 See `org-ctrl-c-ctrl-c-hook' for more information.")
19447 (defvar org-shiftright-hook nil
19448 "Hook for functions attaching themselves to `S-right'.
19449 See `org-ctrl-c-ctrl-c-hook' for more information.")
19450 (defvar org-shiftright-final-hook nil
19451 "Hook for functions attaching themselves to `S-right'.
19452 This one runs after all other options except shift-select have been excluded.
19453 See `org-ctrl-c-ctrl-c-hook' for more information.")
19455 (defun org-modifier-cursor-error ()
19456 "Throw an error, a modified cursor command was applied in wrong context."
19457 (error "This command is active in special context like tables, headlines or items"))
19459 (defun org-shiftselect-error ()
19460 "Throw an error because Shift-Cursor command was applied in wrong context."
19461 (if (and (boundp 'shift-select-mode) shift-select-mode)
19462 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19463 (error "This command works only in special context like headlines or timestamps")))
19465 (defun org-call-for-shift-select (cmd)
19466 (let ((this-command-keys-shift-translated t))
19467 (call-interactively cmd)))
19469 (defun org-shifttab (&optional arg)
19470 "Global visibility cycling or move to previous table field.
19471 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19472 on context.
19473 See the individual commands for more information."
19474 (interactive "P")
19475 (cond
19476 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19477 ((integerp arg)
19478 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19479 (message "Content view to level: %d" arg)
19480 (org-content (prefix-numeric-value arg2))
19481 (setq org-cycle-global-status 'overview)))
19482 (t (call-interactively 'org-global-cycle))))
19484 (defun org-shiftmetaleft ()
19485 "Promote subtree or delete table column.
19486 Calls `org-promote-subtree', `org-outdent-item-tree', or
19487 `org-table-delete-column', depending on context. See the
19488 individual commands for more information."
19489 (interactive)
19490 (cond
19491 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19492 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19493 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19494 ((if (not (org-region-active-p)) (org-at-item-p)
19495 (save-excursion (goto-char (region-beginning))
19496 (org-at-item-p)))
19497 (call-interactively 'org-outdent-item-tree))
19498 (t (org-modifier-cursor-error))))
19500 (defun org-shiftmetaright ()
19501 "Demote subtree or insert table column.
19502 Calls `org-demote-subtree', `org-indent-item-tree', or
19503 `org-table-insert-column', depending on context. See the
19504 individual commands for more information."
19505 (interactive)
19506 (cond
19507 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19508 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19509 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19510 ((if (not (org-region-active-p)) (org-at-item-p)
19511 (save-excursion (goto-char (region-beginning))
19512 (org-at-item-p)))
19513 (call-interactively 'org-indent-item-tree))
19514 (t (org-modifier-cursor-error))))
19516 (defun org-shiftmetaup (&optional arg)
19517 "Move subtree up or kill table row.
19518 Calls `org-move-subtree-up' or `org-table-kill-row' or
19519 `org-move-item-up' or `org-timestamp-up', depending on context.
19520 See the individual commands for more information."
19521 (interactive "P")
19522 (cond
19523 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19524 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19525 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19526 ((org-at-item-p) (call-interactively 'org-move-item-up))
19527 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19528 (call-interactively 'org-timestamp-up)))
19529 (t (call-interactively 'org-drag-line-backward))))
19531 (defun org-shiftmetadown (&optional arg)
19532 "Move subtree down or insert table row.
19533 Calls `org-move-subtree-down' or `org-table-insert-row' or
19534 `org-move-item-down' or `org-timestamp-up', depending on context.
19535 See the individual commands for more information."
19536 (interactive "P")
19537 (cond
19538 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19539 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19540 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19541 ((org-at-item-p) (call-interactively 'org-move-item-down))
19542 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19543 (call-interactively 'org-timestamp-down)))
19544 (t (call-interactively 'org-drag-line-forward))))
19546 (defsubst org-hidden-tree-error ()
19547 (error
19548 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19550 (defun org-metaleft (&optional arg)
19551 "Promote heading or move table column to left.
19552 Calls `org-do-promote' or `org-table-move-column', depending on context.
19553 With no specific context, calls the Emacs default `backward-word'.
19554 See the individual commands for more information."
19555 (interactive "P")
19556 (cond
19557 ((run-hook-with-args-until-success 'org-metaleft-hook))
19558 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19559 ((org-with-limited-levels
19560 (or (org-at-heading-p)
19561 (and (org-region-active-p)
19562 (save-excursion
19563 (goto-char (region-beginning))
19564 (org-at-heading-p)))))
19565 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19566 (call-interactively 'org-do-promote))
19567 ;; At an inline task.
19568 ((org-at-heading-p)
19569 (call-interactively 'org-inlinetask-promote))
19570 ((or (org-at-item-p)
19571 (and (org-region-active-p)
19572 (save-excursion
19573 (goto-char (region-beginning))
19574 (org-at-item-p))))
19575 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19576 (call-interactively 'org-outdent-item))
19577 (t (call-interactively 'backward-word))))
19579 (defun org-metaright (&optional arg)
19580 "Demote a subtree, a list item or move table column to right.
19581 In front of a drawer or a block keyword, indent it correctly.
19582 With no specific context, calls the Emacs default `forward-word'.
19583 See the individual commands for more information."
19584 (interactive "P")
19585 (cond
19586 ((run-hook-with-args-until-success 'org-metaright-hook))
19587 ((org-at-table-p) (call-interactively 'org-table-move-column))
19588 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19589 ((org-at-block-p) (call-interactively 'org-indent-block))
19590 ((org-with-limited-levels
19591 (or (org-at-heading-p)
19592 (and (org-region-active-p)
19593 (save-excursion
19594 (goto-char (region-beginning))
19595 (org-at-heading-p)))))
19596 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19597 (call-interactively 'org-do-demote))
19598 ;; At an inline task.
19599 ((org-at-heading-p)
19600 (call-interactively 'org-inlinetask-demote))
19601 ((or (org-at-item-p)
19602 (and (org-region-active-p)
19603 (save-excursion
19604 (goto-char (region-beginning))
19605 (org-at-item-p))))
19606 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19607 (call-interactively 'org-indent-item))
19608 (t (call-interactively 'forward-word))))
19610 (defun org-check-for-hidden (what)
19611 "Check if there are hidden headlines/items in the current visual line.
19612 WHAT can be either `headlines' or `items'. If the current line is
19613 an outline or item heading and it has a folded subtree below it,
19614 this function returns t, nil otherwise."
19615 (let ((re (cond
19616 ((eq what 'headlines) org-outline-regexp-bol)
19617 ((eq what 'items) (org-item-beginning-re))
19618 (t (error "This should not happen"))))
19619 beg end)
19620 (save-excursion
19621 (catch 'exit
19622 (unless (org-region-active-p)
19623 (setq beg (point-at-bol))
19624 (beginning-of-line 2)
19625 (while (and (not (eobp)) ;; this is like `next-line'
19626 (get-char-property (1- (point)) 'invisible))
19627 (beginning-of-line 2))
19628 (setq end (point))
19629 (goto-char beg)
19630 (goto-char (point-at-eol))
19631 (setq end (max end (point)))
19632 (while (re-search-forward re end t)
19633 (if (get-char-property (match-beginning 0) 'invisible)
19634 (throw 'exit t))))
19635 nil))))
19637 (defun org-metaup (&optional arg)
19638 "Move subtree up or move table row up.
19639 Calls `org-move-subtree-up' or `org-table-move-row' or
19640 `org-move-item-up', depending on context. See the individual commands
19641 for more information."
19642 (interactive "P")
19643 (cond
19644 ((run-hook-with-args-until-success 'org-metaup-hook))
19645 ((org-region-active-p)
19646 (let* ((a (min (region-beginning) (region-end)))
19647 (b (1- (max (region-beginning) (region-end))))
19648 (c (save-excursion (goto-char a)
19649 (move-beginning-of-line 0)))
19650 (d (save-excursion (goto-char a)
19651 (move-end-of-line 0) (point))))
19652 (transpose-regions a b c d)
19653 (goto-char c)))
19654 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19655 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19656 ((org-at-item-p) (call-interactively 'org-move-item-up))
19657 (t (org-drag-element-backward))))
19659 (defun org-metadown (&optional arg)
19660 "Move subtree down or move table row down.
19661 Calls `org-move-subtree-down' or `org-table-move-row' or
19662 `org-move-item-down', depending on context. See the individual
19663 commands for more information."
19664 (interactive "P")
19665 (cond
19666 ((run-hook-with-args-until-success 'org-metadown-hook))
19667 ((org-region-active-p)
19668 (let* ((a (min (region-beginning) (region-end)))
19669 (b (max (region-beginning) (region-end)))
19670 (c (save-excursion (goto-char b)
19671 (move-beginning-of-line 1)))
19672 (d (save-excursion (goto-char b)
19673 (move-end-of-line 1) (1+ (point)))))
19674 (transpose-regions a b c d)
19675 (goto-char d)))
19676 ((org-at-table-p) (call-interactively 'org-table-move-row))
19677 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19678 ((org-at-item-p) (call-interactively 'org-move-item-down))
19679 (t (org-drag-element-forward))))
19681 (defun org-shiftup (&optional arg)
19682 "Increase item in timestamp or increase priority of current headline.
19683 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19684 depending on context. See the individual commands for more information."
19685 (interactive "P")
19686 (cond
19687 ((run-hook-with-args-until-success 'org-shiftup-hook))
19688 ((and org-support-shift-select (org-region-active-p))
19689 (org-call-for-shift-select 'previous-line))
19690 ((org-at-timestamp-p t)
19691 (call-interactively (if org-edit-timestamp-down-means-later
19692 'org-timestamp-down 'org-timestamp-up)))
19693 ((and (not (eq org-support-shift-select 'always))
19694 org-enable-priority-commands
19695 (org-at-heading-p))
19696 (call-interactively 'org-priority-up))
19697 ((and (not org-support-shift-select) (org-at-item-p))
19698 (call-interactively 'org-previous-item))
19699 ((org-clocktable-try-shift 'up arg))
19700 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19701 (org-support-shift-select
19702 (org-call-for-shift-select 'previous-line))
19703 (t (org-shiftselect-error))))
19705 (defun org-shiftdown (&optional arg)
19706 "Decrease item in timestamp or decrease priority of current headline.
19707 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19708 depending on context. See the individual commands for more information."
19709 (interactive "P")
19710 (cond
19711 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19712 ((and org-support-shift-select (org-region-active-p))
19713 (org-call-for-shift-select 'next-line))
19714 ((org-at-timestamp-p t)
19715 (call-interactively (if org-edit-timestamp-down-means-later
19716 'org-timestamp-up 'org-timestamp-down)))
19717 ((and (not (eq org-support-shift-select 'always))
19718 org-enable-priority-commands
19719 (org-at-heading-p))
19720 (call-interactively 'org-priority-down))
19721 ((and (not org-support-shift-select) (org-at-item-p))
19722 (call-interactively 'org-next-item))
19723 ((org-clocktable-try-shift 'down arg))
19724 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19725 (org-support-shift-select
19726 (org-call-for-shift-select 'next-line))
19727 (t (org-shiftselect-error))))
19729 (defun org-shiftright (&optional arg)
19730 "Cycle the thing at point or in the current line, depending on context.
19731 Depending on context, this does one of the following:
19733 - switch a timestamp at point one day into the future
19734 - on a headline, switch to the next TODO keyword.
19735 - on an item, switch entire list to the next bullet type
19736 - on a property line, switch to the next allowed value
19737 - on a clocktable definition line, move time block into the future"
19738 (interactive "P")
19739 (cond
19740 ((run-hook-with-args-until-success 'org-shiftright-hook))
19741 ((and org-support-shift-select (org-region-active-p))
19742 (org-call-for-shift-select 'forward-char))
19743 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19744 ((and (not (eq org-support-shift-select 'always))
19745 (org-at-heading-p))
19746 (let ((org-inhibit-logging
19747 (not org-treat-S-cursor-todo-selection-as-state-change))
19748 (org-inhibit-blocking
19749 (not org-treat-S-cursor-todo-selection-as-state-change)))
19750 (org-call-with-arg 'org-todo 'right)))
19751 ((or (and org-support-shift-select
19752 (not (eq org-support-shift-select 'always))
19753 (org-at-item-bullet-p))
19754 (and (not org-support-shift-select) (org-at-item-p)))
19755 (org-call-with-arg 'org-cycle-list-bullet nil))
19756 ((and (not (eq org-support-shift-select 'always))
19757 (org-at-property-p))
19758 (call-interactively 'org-property-next-allowed-value))
19759 ((org-clocktable-try-shift 'right arg))
19760 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19761 (org-support-shift-select
19762 (org-call-for-shift-select 'forward-char))
19763 (t (org-shiftselect-error))))
19765 (defun org-shiftleft (&optional arg)
19766 "Cycle the thing at point or in the current line, depending on context.
19767 Depending on context, this does one of the following:
19769 - switch a timestamp at point one day into the past
19770 - on a headline, switch to the previous TODO keyword.
19771 - on an item, switch entire list to the previous bullet type
19772 - on a property line, switch to the previous allowed value
19773 - on a clocktable definition line, move time block into the past"
19774 (interactive "P")
19775 (cond
19776 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19777 ((and org-support-shift-select (org-region-active-p))
19778 (org-call-for-shift-select 'backward-char))
19779 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19780 ((and (not (eq org-support-shift-select 'always))
19781 (org-at-heading-p))
19782 (let ((org-inhibit-logging
19783 (not org-treat-S-cursor-todo-selection-as-state-change))
19784 (org-inhibit-blocking
19785 (not org-treat-S-cursor-todo-selection-as-state-change)))
19786 (org-call-with-arg 'org-todo 'left)))
19787 ((or (and org-support-shift-select
19788 (not (eq org-support-shift-select 'always))
19789 (org-at-item-bullet-p))
19790 (and (not org-support-shift-select) (org-at-item-p)))
19791 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19792 ((and (not (eq org-support-shift-select 'always))
19793 (org-at-property-p))
19794 (call-interactively 'org-property-previous-allowed-value))
19795 ((org-clocktable-try-shift 'left arg))
19796 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19797 (org-support-shift-select
19798 (org-call-for-shift-select 'backward-char))
19799 (t (org-shiftselect-error))))
19801 (defun org-shiftcontrolright ()
19802 "Switch to next TODO set."
19803 (interactive)
19804 (cond
19805 ((and org-support-shift-select (org-region-active-p))
19806 (org-call-for-shift-select 'forward-word))
19807 ((and (not (eq org-support-shift-select 'always))
19808 (org-at-heading-p))
19809 (org-call-with-arg 'org-todo 'nextset))
19810 (org-support-shift-select
19811 (org-call-for-shift-select 'forward-word))
19812 (t (org-shiftselect-error))))
19814 (defun org-shiftcontrolleft ()
19815 "Switch to previous TODO set."
19816 (interactive)
19817 (cond
19818 ((and org-support-shift-select (org-region-active-p))
19819 (org-call-for-shift-select 'backward-word))
19820 ((and (not (eq org-support-shift-select 'always))
19821 (org-at-heading-p))
19822 (org-call-with-arg 'org-todo 'previousset))
19823 (org-support-shift-select
19824 (org-call-for-shift-select 'backward-word))
19825 (t (org-shiftselect-error))))
19827 (defun org-shiftcontrolup (&optional n)
19828 "Change timestamps synchronously up in CLOCK log lines.
19829 Optional argument N tells to change by that many units."
19830 (interactive "P")
19831 (cond ((and (not org-support-shift-select)
19832 (org-at-clock-log-p)
19833 (org-at-timestamp-p t))
19834 (org-clock-timestamps-up n))
19835 (t (org-shiftselect-error))))
19837 (defun org-shiftcontroldown (&optional n)
19838 "Change timestamps synchronously down in CLOCK log lines.
19839 Optional argument N tells to change by that many units."
19840 (interactive "P")
19841 (cond ((and (not org-support-shift-select)
19842 (org-at-clock-log-p)
19843 (org-at-timestamp-p t))
19844 (org-clock-timestamps-down n))
19845 (t (org-shiftselect-error))))
19847 (defun org-ctrl-c-ret ()
19848 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19849 (interactive)
19850 (cond
19851 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19852 (t (call-interactively 'org-insert-heading))))
19854 (defun org-find-visible ()
19855 (let ((s (point)))
19856 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19857 (get-char-property s 'invisible)))
19859 (defun org-find-invisible ()
19860 (let ((s (point)))
19861 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19862 (not (get-char-property s 'invisible))))
19865 (defun org-copy-visible (beg end)
19866 "Copy the visible parts of the region."
19867 (interactive "r")
19868 (let (snippets s)
19869 (save-excursion
19870 (save-restriction
19871 (narrow-to-region beg end)
19872 (setq s (goto-char (point-min)))
19873 (while (not (= (point) (point-max)))
19874 (goto-char (org-find-invisible))
19875 (push (buffer-substring s (point)) snippets)
19876 (setq s (goto-char (org-find-visible))))))
19877 (kill-new (apply 'concat (nreverse snippets)))))
19879 (defun org-copy-special ()
19880 "Copy region in table or copy current subtree.
19881 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19882 See the individual commands for more information."
19883 (interactive)
19884 (call-interactively
19885 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19887 (defun org-cut-special ()
19888 "Cut region in table or cut current subtree.
19889 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19890 See the individual commands for more information."
19891 (interactive)
19892 (call-interactively
19893 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19895 (defun org-paste-special (arg)
19896 "Paste rectangular region into table, or past subtree relative to level.
19897 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19898 See the individual commands for more information."
19899 (interactive "P")
19900 (if (org-at-table-p)
19901 (org-table-paste-rectangle)
19902 (org-paste-subtree arg)))
19904 (defsubst org-in-fixed-width-region-p ()
19905 "Is point in a fixed-width region?"
19906 (save-match-data
19907 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19909 (defun org-edit-special (&optional arg)
19910 "Call a special editor for the element at point.
19911 When at a table, call the formula editor with `org-table-edit-formulas'.
19912 When in a source code block, call `org-edit-src-code'.
19913 When in a fixed-width region, call `org-edit-fixed-width-region'.
19914 When at an #+INCLUDE keyword, visit the included file.
19915 On a link, call `ffap' to visit the link at point.
19916 Otherwise, return a user error."
19917 (interactive)
19918 (let ((element (org-element-at-point)))
19919 (assert (not buffer-read-only) nil
19920 "Buffer is read-only: %s" (buffer-name))
19921 (case (org-element-type element)
19922 (src-block
19923 (if (not arg) (org-edit-src-code)
19924 (let* ((info (org-babel-get-src-block-info))
19925 (lang (nth 0 info))
19926 (params (nth 2 info))
19927 (session (cdr (assq :session params))))
19928 (if (not session) (org-edit-src-code)
19929 ;; At a src-block with a session and function called with
19930 ;; an ARG: switch to the buffer related to the inferior
19931 ;; process.
19932 (funcall (intern (concat "org-babel-prep-session:" lang))
19933 session params)))))
19934 (keyword
19935 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19936 (find-file
19937 (org-remove-double-quotes
19938 (car (org-split-string (org-element-property :value element)))))
19939 (user-error "No special environment to edit here")))
19940 (table
19941 (if (eq (org-element-property :type element) 'table.el)
19942 (org-edit-src-code)
19943 (call-interactively 'org-table-edit-formulas)))
19944 ;; Only Org tables contain `table-row' type elements.
19945 (table-row (call-interactively 'org-table-edit-formulas))
19946 ((example-block export-block) (org-edit-src-code))
19947 (fixed-width (org-edit-fixed-width-region))
19948 (otherwise
19949 ;; No notable element at point. Though, we may be at a link,
19950 ;; which is an object. Thus, scan deeper.
19951 (if (eq (org-element-type (org-element-context element)) 'link)
19952 (call-interactively 'ffap)
19953 (user-error "No special environment to edit here"))))))
19955 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19956 (defun org-ctrl-c-ctrl-c (&optional arg)
19957 "Set tags in headline, or update according to changed information at point.
19959 This command does many different things, depending on context:
19961 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19962 this is what we do.
19964 - If the cursor is on a statistics cookie, update it.
19966 - If the cursor is in a headline, prompt for tags and insert them
19967 into the current line, aligned to `org-tags-column'. When called
19968 with prefix arg, realign all tags in the current buffer.
19970 - If the cursor is in one of the special #+KEYWORD lines, this
19971 triggers scanning the buffer for these lines and updating the
19972 information.
19974 - If the cursor is inside a table, realign the table. This command
19975 works even if the automatic table editor has been turned off.
19977 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19978 the entire table.
19980 - If the cursor is at a footnote reference or definition, jump to
19981 the corresponding definition or references, respectively.
19983 - If the cursor is a the beginning of a dynamic block, update it.
19985 - If the current buffer is a capture buffer, close note and file it.
19987 - If the cursor is on a <<<target>>>, update radio targets and
19988 corresponding links in this buffer.
19990 - If the cursor is on a numbered item in a plain list, renumber the
19991 ordered list.
19993 - If the cursor is on a checkbox, toggle it.
19995 - If the cursor is on a code block, evaluate it. The variable
19996 `org-confirm-babel-evaluate' can be used to control prompting
19997 before code block evaluation, by default every code block
19998 evaluation requires confirmation. Code block evaluation can be
19999 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20000 (interactive "P")
20001 (cond
20002 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20003 org-occur-highlights
20004 org-latex-fragment-image-overlays)
20005 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20006 (org-remove-occur-highlights)
20007 (org-remove-latex-fragment-image-overlays)
20008 (message "Temporary highlights/overlays removed from current buffer"))
20009 ((and (local-variable-p 'org-finish-function (current-buffer))
20010 (fboundp org-finish-function))
20011 (funcall org-finish-function))
20012 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20014 (let* ((context (org-element-context)) (type (org-element-type context)))
20015 ;; Test if point is within a blank line.
20016 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20017 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20018 (user-error "C-c C-c can do nothing useful at this location"))
20019 ;; For convenience: at the first line of a paragraph on the
20020 ;; same line as an item, apply function on that item instead.
20021 (when (eq type 'paragraph)
20022 (let ((parent (org-element-property :parent context)))
20023 (when (and (eq (org-element-type parent) 'item)
20024 (= (point-at-bol) (org-element-property :begin parent)))
20025 (setq context parent type 'item))))
20026 ;; Act according to type of element or object at point.
20027 (case type
20028 (clock (org-clock-update-time-maybe))
20029 (dynamic-block
20030 (save-excursion
20031 (goto-char (org-element-property :post-affiliated context))
20032 (org-update-dblock)))
20033 (footnote-definition
20034 (goto-char (org-element-property :post-affiliated context))
20035 (call-interactively 'org-footnote-action))
20036 (footnote-reference (call-interactively 'org-footnote-action))
20037 ((headline inlinetask)
20038 (save-excursion (goto-char (org-element-property :begin context))
20039 (call-interactively 'org-set-tags)))
20040 (item
20041 ;; At an item: a double C-u set checkbox to "[-]"
20042 ;; unconditionally, whereas a single one will toggle its
20043 ;; presence. Without an universal argument, if the item
20044 ;; has a checkbox, toggle it. Otherwise repair the list.
20045 (let* ((box (org-element-property :checkbox context))
20046 (struct (org-element-property :structure context))
20047 (old-struct (copy-tree struct))
20048 (parents (org-list-parents-alist struct))
20049 (prevs (org-list-prevs-alist struct))
20050 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20051 (org-list-set-checkbox
20052 (org-element-property :begin context) struct
20053 (cond ((equal arg '(16)) "[-]")
20054 ((and (not box) (equal arg '(4))) "[ ]")
20055 ((or (not box) (equal arg '(4))) nil)
20056 ((eq box 'on) "[ ]")
20057 (t "[X]")))
20058 ;; Mimic `org-list-write-struct' but with grabbing
20059 ;; a return value from `org-list-struct-fix-box'.
20060 (org-list-struct-fix-ind struct parents 2)
20061 (org-list-struct-fix-item-end struct)
20062 (org-list-struct-fix-bul struct prevs)
20063 (org-list-struct-fix-ind struct parents)
20064 (let ((block-item
20065 (org-list-struct-fix-box struct parents prevs orderedp)))
20066 (if (and box (equal struct old-struct))
20067 (if (equal arg '(16))
20068 (message "Checkboxes already reset")
20069 (user-error "Cannot toggle this checkbox: %s"
20070 (if (eq box 'on)
20071 "all subitems checked"
20072 "unchecked subitems")))
20073 (org-list-struct-apply-struct struct old-struct)
20074 (org-update-checkbox-count-maybe))
20075 (when block-item
20076 (message "Checkboxes were removed due to empty box at line %d"
20077 (org-current-line block-item))))))
20078 (keyword
20079 (let ((org-inhibit-startup-visibility-stuff t)
20080 (org-startup-align-all-tables nil))
20081 (when (boundp 'org-table-coordinate-overlays)
20082 (mapc 'delete-overlay org-table-coordinate-overlays)
20083 (setq org-table-coordinate-overlays nil))
20084 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20085 (message "Local setup has been refreshed"))
20086 (plain-list
20087 ;; At a plain list, with a double C-u argument, set
20088 ;; checkboxes of each item to "[-]", whereas a single one
20089 ;; will toggle their presence according to the state of the
20090 ;; first item in the list. Without an argument, repair the
20091 ;; list.
20092 (let* ((begin (org-element-property :contents-begin context))
20093 (struct (org-element-property :structure context))
20094 (old-struct (copy-tree struct))
20095 (first-box (save-excursion
20096 (goto-char begin)
20097 (looking-at org-list-full-item-re)
20098 (match-string-no-properties 3)))
20099 (new-box (cond ((equal arg '(16)) "[-]")
20100 ((equal arg '(4)) (unless first-box "[ ]"))
20101 ((equal first-box "[X]") "[ ]")
20102 (t "[X]"))))
20103 (cond
20104 (arg
20105 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20106 (org-list-get-all-items
20107 begin struct (org-list-prevs-alist struct))))
20108 ((and first-box (eq (point) begin))
20109 ;; For convenience, when point is at bol on the first
20110 ;; item of the list and no argument is provided, simply
20111 ;; toggle checkbox of that item, if any.
20112 (org-list-set-checkbox begin struct new-box)))
20113 (org-list-write-struct
20114 struct (org-list-parents-alist struct) old-struct)
20115 (org-update-checkbox-count-maybe)
20116 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
20117 ((property-drawer node-property)
20118 (call-interactively 'org-property-action))
20119 ((radio-target target)
20120 (call-interactively 'org-update-radio-target-regexp))
20121 (statistics-cookie
20122 (call-interactively 'org-update-statistics-cookies))
20123 ((table table-cell table-row)
20124 ;; At a table, recalculate every field and align it. Also
20125 ;; send the table if necessary. If the table has
20126 ;; a `table.el' type, just give up. At a table row or
20127 ;; cell, maybe recalculate line but always align table.
20128 (if (eq (org-element-property :type context) 'table.el)
20129 (message "Use C-c ' to edit table.el tables")
20130 (let ((org-enable-table-editor t))
20131 (if (or (eq type 'table)
20132 ;; Check if point is at a TBLFM line.
20133 (and (eq type 'table-row)
20134 (= (point) (org-element-property :end context))))
20135 (save-excursion
20136 (goto-char (org-element-property :contents-begin context))
20137 (org-call-with-arg 'org-table-recalculate (or arg t))
20138 (orgtbl-send-table 'maybe))
20139 (org-table-maybe-eval-formula)
20140 (cond (arg (call-interactively 'org-table-recalculate))
20141 ((org-table-maybe-recalculate-line))
20142 (t (org-table-align)))))))
20143 (timestamp (org-timestamp-change 0 'day))
20144 (otherwise
20145 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20146 (user-error
20147 "C-c C-c can do nothing useful at this location")))))))))
20149 (defun org-mode-restart ()
20150 "Restart Org-mode, to scan again for special lines.
20151 Also updates the keyword regular expressions."
20152 (interactive)
20153 (org-mode)
20154 (message "Org-mode restarted"))
20156 (defun org-kill-note-or-show-branches ()
20157 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20158 (interactive)
20159 (if (not org-finish-function)
20160 (progn
20161 (hide-subtree)
20162 (call-interactively 'show-branches))
20163 (let ((org-note-abort t))
20164 (funcall org-finish-function))))
20166 (defun org-return (&optional indent)
20167 "Goto next table row or insert a newline.
20168 Calls `org-table-next-row' or `newline', depending on context.
20169 See the individual commands for more information."
20170 (interactive)
20171 (let (org-ts-what)
20172 (cond
20173 ((or (bobp) (org-in-src-block-p))
20174 (if indent (newline-and-indent) (newline)))
20175 ((org-at-table-p)
20176 (org-table-justify-field-maybe)
20177 (call-interactively 'org-table-next-row))
20178 ;; when `newline-and-indent' is called within a list, make sure
20179 ;; text moved stays inside the item.
20180 ((and (org-in-item-p) indent)
20181 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20182 (progn
20183 (save-match-data (newline))
20184 (org-indent-line-to (length (match-string 0))))
20185 (let ((ind (org-get-indentation)))
20186 (newline)
20187 (if (org-looking-back org-list-end-re)
20188 (org-indent-line)
20189 (org-indent-line-to ind)))))
20190 ((and org-return-follows-link
20191 (org-at-timestamp-p t)
20192 (not (eq org-ts-what 'after)))
20193 (org-follow-timestamp-link))
20194 ((and org-return-follows-link
20195 (let ((tprop (get-text-property (point) 'face)))
20196 (or (eq tprop 'org-link)
20197 (and (listp tprop) (memq 'org-link tprop)))))
20198 (call-interactively 'org-open-at-point))
20199 ((and (org-at-heading-p)
20200 (looking-at
20201 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20202 (org-show-entry)
20203 (end-of-line 1)
20204 (newline))
20205 (t (if indent (newline-and-indent) (newline))))))
20207 (defun org-return-indent ()
20208 "Goto next table row or insert a newline and indent.
20209 Calls `org-table-next-row' or `newline-and-indent', depending on
20210 context. See the individual commands for more information."
20211 (interactive)
20212 (org-return t))
20214 (defun org-ctrl-c-star ()
20215 "Compute table, or change heading status of lines.
20216 Calls `org-table-recalculate' or `org-toggle-heading',
20217 depending on context."
20218 (interactive)
20219 (cond
20220 ((org-at-table-p)
20221 (call-interactively 'org-table-recalculate))
20223 ;; Convert all lines in region to list items
20224 (call-interactively 'org-toggle-heading))))
20226 (defun org-ctrl-c-minus ()
20227 "Insert separator line in table or modify bullet status of line.
20228 Also turns a plain line or a region of lines into list items.
20229 Calls `org-table-insert-hline', `org-toggle-item', or
20230 `org-cycle-list-bullet', depending on context."
20231 (interactive)
20232 (cond
20233 ((org-at-table-p)
20234 (call-interactively 'org-table-insert-hline))
20235 ((org-region-active-p)
20236 (call-interactively 'org-toggle-item))
20237 ((org-in-item-p)
20238 (call-interactively 'org-cycle-list-bullet))
20240 (call-interactively 'org-toggle-item))))
20242 (defun org-toggle-item (arg)
20243 "Convert headings or normal lines to items, items to normal lines.
20244 If there is no active region, only the current line is considered.
20246 If the first non blank line in the region is a headline, convert
20247 all headlines to items, shifting text accordingly.
20249 If it is an item, convert all items to normal lines.
20251 If it is normal text, change region into a list of items.
20252 With a prefix argument ARG, change the region in a single item."
20253 (interactive "P")
20254 (let ((shift-text
20255 (function
20256 ;; Shift text in current section to IND, from point to END.
20257 ;; The function leaves point to END line.
20258 (lambda (ind end)
20259 (let ((min-i 1000) (end (copy-marker end)))
20260 ;; First determine the minimum indentation (MIN-I) of
20261 ;; the text.
20262 (save-excursion
20263 (catch 'exit
20264 (while (< (point) end)
20265 (let ((i (org-get-indentation)))
20266 (cond
20267 ;; Skip blank lines and inline tasks.
20268 ((looking-at "^[ \t]*$"))
20269 ((looking-at org-outline-regexp-bol))
20270 ;; We can't find less than 0 indentation.
20271 ((zerop i) (throw 'exit (setq min-i 0)))
20272 ((< i min-i) (setq min-i i))))
20273 (forward-line))))
20274 ;; Then indent each line so that a line indented to
20275 ;; MIN-I becomes indented to IND. Ignore blank lines
20276 ;; and inline tasks in the process.
20277 (let ((delta (- ind min-i)))
20278 (while (< (point) end)
20279 (unless (or (looking-at "^[ \t]*$")
20280 (looking-at org-outline-regexp-bol))
20281 (org-indent-line-to (+ (org-get-indentation) delta)))
20282 (forward-line)))))))
20283 (skip-blanks
20284 (function
20285 ;; Return beginning of first non-blank line, starting from
20286 ;; line at POS.
20287 (lambda (pos)
20288 (save-excursion
20289 (goto-char pos)
20290 (skip-chars-forward " \r\t\n")
20291 (point-at-bol)))))
20292 beg end)
20293 ;; Determine boundaries of changes.
20294 (if (org-region-active-p)
20295 (setq beg (funcall skip-blanks (region-beginning))
20296 end (copy-marker (region-end)))
20297 (setq beg (funcall skip-blanks (point-at-bol))
20298 end (copy-marker (point-at-eol))))
20299 ;; Depending on the starting line, choose an action on the text
20300 ;; between BEG and END.
20301 (org-with-limited-levels
20302 (save-excursion
20303 (goto-char beg)
20304 (cond
20305 ;; Case 1. Start at an item: de-itemize. Note that it only
20306 ;; happens when a region is active: `org-ctrl-c-minus'
20307 ;; would call `org-cycle-list-bullet' otherwise.
20308 ((org-at-item-p)
20309 (while (< (point) end)
20310 (when (org-at-item-p)
20311 (skip-chars-forward " \t")
20312 (delete-region (point) (match-end 0)))
20313 (forward-line)))
20314 ;; Case 2. Start at an heading: convert to items.
20315 ((org-at-heading-p)
20316 (let* ((bul (org-list-bullet-string "-"))
20317 (bul-len (length bul))
20318 ;; Indentation of the first heading. It should be
20319 ;; relative to the indentation of its parent, if any.
20320 (start-ind (save-excursion
20321 (cond
20322 ((not org-adapt-indentation) 0)
20323 ((not (outline-previous-heading)) 0)
20324 (t (length (match-string 0))))))
20325 ;; Level of first heading. Further headings will be
20326 ;; compared to it to determine hierarchy in the list.
20327 (ref-level (org-reduced-level (org-outline-level))))
20328 (while (< (point) end)
20329 (let* ((level (org-reduced-level (org-outline-level)))
20330 (delta (max 0 (- level ref-level))))
20331 ;; If current headline is less indented than the first
20332 ;; one, set it as reference, in order to preserve
20333 ;; subtrees.
20334 (when (< level ref-level) (setq ref-level level))
20335 (replace-match bul t t)
20336 (org-indent-line-to (+ start-ind (* delta bul-len)))
20337 ;; Ensure all text down to END (or SECTION-END) belongs
20338 ;; to the newly created item.
20339 (let ((section-end (save-excursion
20340 (or (outline-next-heading) (point)))))
20341 (forward-line)
20342 (funcall shift-text
20343 (+ start-ind (* (1+ delta) bul-len))
20344 (min end section-end)))))))
20345 ;; Case 3. Normal line with ARG: make the first line of region
20346 ;; an item, and shift indentation of others lines to
20347 ;; set them as item's body.
20348 (arg (let* ((bul (org-list-bullet-string "-"))
20349 (bul-len (length bul))
20350 (ref-ind (org-get-indentation)))
20351 (skip-chars-forward " \t")
20352 (insert bul)
20353 (forward-line)
20354 (while (< (point) end)
20355 ;; Ensure that lines less indented than first one
20356 ;; still get included in item body.
20357 (funcall shift-text
20358 (+ ref-ind bul-len)
20359 (min end (save-excursion (or (outline-next-heading)
20360 (point)))))
20361 (forward-line))))
20362 ;; Case 4. Normal line without ARG: turn each non-item line
20363 ;; into an item.
20365 (while (< (point) end)
20366 (unless (or (org-at-heading-p) (org-at-item-p))
20367 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20368 (replace-match
20369 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20370 (forward-line))))))))
20372 (defun org-toggle-heading (&optional nstars)
20373 "Convert headings to normal text, or items or text to headings.
20374 If there is no active region, only convert the current line.
20376 With a \\[universal-argument] prefix, convert the whole list at
20377 point into heading.
20379 In a region:
20381 - If the first non blank line is a headline, remove the stars
20382 from all headlines in the region.
20384 - If it is a normal line, turn each and every normal line (i.e.,
20385 not an heading or an item) in the region into headings. If you
20386 want to convert only the first line of this region, use one
20387 universal prefix argument.
20389 - If it is a plain list item, turn all plain list items into headings.
20391 When converting a line into a heading, the number of stars is chosen
20392 such that the lines become children of the current entry. However,
20393 when a numeric prefix argument is given, its value determines the
20394 number of stars to add."
20395 (interactive "P")
20396 (let ((skip-blanks
20397 (function
20398 ;; Return beginning of first non-blank line, starting from
20399 ;; line at POS.
20400 (lambda (pos)
20401 (save-excursion
20402 (goto-char pos)
20403 (while (org-at-comment-p) (forward-line))
20404 (skip-chars-forward " \r\t\n")
20405 (point-at-bol)))))
20406 beg end toggled)
20407 ;; Determine boundaries of changes. If a universal prefix has
20408 ;; been given, put the list in a region. If region ends at a bol,
20409 ;; do not consider the last line to be in the region.
20411 (when (and current-prefix-arg (org-at-item-p))
20412 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20413 (org-mark-element))
20415 (if (org-region-active-p)
20416 (setq beg (funcall skip-blanks (region-beginning))
20417 end (copy-marker (save-excursion
20418 (goto-char (region-end))
20419 (if (bolp) (point) (point-at-eol)))))
20420 (setq beg (funcall skip-blanks (point-at-bol))
20421 end (copy-marker (point-at-eol))))
20422 ;; Ensure inline tasks don't count as headings.
20423 (org-with-limited-levels
20424 (save-excursion
20425 (goto-char beg)
20426 (cond
20427 ;; Case 1. Started at an heading: de-star headings.
20428 ((org-at-heading-p)
20429 (while (< (point) end)
20430 (when (org-at-heading-p t)
20431 (looking-at org-outline-regexp) (replace-match "")
20432 (setq toggled t))
20433 (forward-line)))
20434 ;; Case 2. Started at an item: change items into headlines.
20435 ;; One star will be added by `org-list-to-subtree'.
20436 ((org-at-item-p)
20437 (let* ((stars (make-string
20438 ;; subtract the star that will be added again by
20439 ;; `org-list-to-subtree'
20440 (if (numberp nstars) (1- nstars)
20441 (or (org-current-level) 0))
20442 ?*))
20443 (add-stars
20444 (cond (nstars "") ; stars from prefix only
20445 ((equal stars "") "") ; before first heading
20446 (org-odd-levels-only "*") ; inside heading, odd
20447 (t "")))) ; inside heading, oddeven
20448 (while (< (point) end)
20449 (when (org-at-item-p)
20450 ;; Pay attention to cases when region ends before list.
20451 (let* ((struct (org-list-struct))
20452 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20453 (save-restriction
20454 (narrow-to-region (point) list-end)
20455 (insert
20456 (org-list-to-subtree
20457 (org-list-parse-list t)
20458 '(:istart (concat stars add-stars (funcall get-stars depth))
20459 :icount (concat stars add-stars (funcall get-stars depth)))))))
20460 (setq toggled t))
20461 (forward-line))))
20462 ;; Case 3. Started at normal text: make every line an heading,
20463 ;; skipping headlines and items.
20464 (t (let* ((stars
20465 (make-string
20466 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20467 (add-stars
20468 (cond (nstars "") ; stars from prefix only
20469 ((equal stars "") "*") ; before first heading
20470 (org-odd-levels-only "**") ; inside heading, odd
20471 (t "*"))) ; inside heading, oddeven
20472 (rpl (concat stars add-stars " "))
20473 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20474 (while (< (point) (if (equal nstars '(4)) lend end))
20475 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20476 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20477 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20478 (forward-line)))))))
20479 (unless toggled (message "Cannot toggle heading from here"))))
20481 (defun org-meta-return (&optional arg)
20482 "Insert a new heading or wrap a region in a table.
20483 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20484 See the individual commands for more information."
20485 (interactive "P")
20486 (cond
20487 ((run-hook-with-args-until-success 'org-metareturn-hook))
20488 ((or (org-at-drawer-p) (org-at-property-p))
20489 (newline-and-indent))
20490 ((org-at-table-p)
20491 (call-interactively 'org-table-wrap-region))
20492 (t (call-interactively 'org-insert-heading))))
20494 ;;; Menu entries
20496 (defsubst org-in-subtree-not-table-p ()
20497 "Are we in a subtree and not in a table?"
20498 (and (not (org-before-first-heading-p))
20499 (not (org-at-table-p))))
20501 ;; Define the Org-mode menus
20502 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20503 '("Tbl"
20504 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20505 ["Next Field" org-cycle (org-at-table-p)]
20506 ["Previous Field" org-shifttab (org-at-table-p)]
20507 ["Next Row" org-return (org-at-table-p)]
20508 "--"
20509 ["Blank Field" org-table-blank-field (org-at-table-p)]
20510 ["Edit Field" org-table-edit-field (org-at-table-p)]
20511 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20512 "--"
20513 ("Column"
20514 ["Move Column Left" org-metaleft (org-at-table-p)]
20515 ["Move Column Right" org-metaright (org-at-table-p)]
20516 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20517 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20518 ("Row"
20519 ["Move Row Up" org-metaup (org-at-table-p)]
20520 ["Move Row Down" org-metadown (org-at-table-p)]
20521 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20522 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20523 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20524 "--"
20525 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20526 ("Rectangle"
20527 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20528 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20529 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20530 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20531 "--"
20532 ("Calculate"
20533 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20534 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20535 ["Edit Formulas" org-edit-special (org-at-table-p)]
20536 "--"
20537 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20538 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20539 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20540 "--"
20541 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20542 "--"
20543 ["Sum Column/Rectangle" org-table-sum
20544 (or (org-at-table-p) (org-region-active-p))]
20545 ["Which Column?" org-table-current-column (org-at-table-p)])
20546 ["Debug Formulas"
20547 org-table-toggle-formula-debugger
20548 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20549 ["Show Col/Row Numbers"
20550 org-table-toggle-coordinate-overlays
20551 :style toggle
20552 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20553 "--"
20554 ["Create" org-table-create (and (not (org-at-table-p))
20555 org-enable-table-editor)]
20556 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20557 ["Import from File" org-table-import (not (org-at-table-p))]
20558 ["Export to File" org-table-export (org-at-table-p)]
20559 "--"
20560 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20562 (easy-menu-define org-org-menu org-mode-map "Org menu"
20563 '("Org"
20564 ("Show/Hide"
20565 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20566 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20567 ["Sparse Tree..." org-sparse-tree t]
20568 ["Reveal Context" org-reveal t]
20569 ["Show All" show-all t]
20570 "--"
20571 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20572 "--"
20573 ["New Heading" org-insert-heading t]
20574 ("Navigate Headings"
20575 ["Up" outline-up-heading t]
20576 ["Next" outline-next-visible-heading t]
20577 ["Previous" outline-previous-visible-heading t]
20578 ["Next Same Level" outline-forward-same-level t]
20579 ["Previous Same Level" outline-backward-same-level t]
20580 "--"
20581 ["Jump" org-goto t])
20582 ("Edit Structure"
20583 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20584 "--"
20585 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20586 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20587 "--"
20588 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20589 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20590 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20591 "--"
20592 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20593 "--"
20594 ["Copy visible text" org-copy-visible t]
20595 "--"
20596 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20597 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20598 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20599 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20600 "--"
20601 ["Sort Region/Children" org-sort t]
20602 "--"
20603 ["Convert to odd levels" org-convert-to-odd-levels t]
20604 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20605 ("Editing"
20606 ["Emphasis..." org-emphasize t]
20607 ["Edit Source Example" org-edit-special t]
20608 "--"
20609 ["Footnote new/jump" org-footnote-action t]
20610 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20611 ("Archive"
20612 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20613 "--"
20614 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20615 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20616 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20618 "--"
20619 ("Hyperlinks"
20620 ["Store Link (Global)" org-store-link t]
20621 ["Find existing link to here" org-occur-link-in-agenda-files t]
20622 ["Insert Link" org-insert-link t]
20623 ["Follow Link" org-open-at-point t]
20624 "--"
20625 ["Next link" org-next-link t]
20626 ["Previous link" org-previous-link t]
20627 "--"
20628 ["Descriptive Links"
20629 org-toggle-link-display
20630 :style radio
20631 :selected org-descriptive-links
20633 ["Literal Links"
20634 org-toggle-link-display
20635 :style radio
20636 :selected (not org-descriptive-links)])
20637 "--"
20638 ("TODO Lists"
20639 ["TODO/DONE/-" org-todo t]
20640 ("Select keyword"
20641 ["Next keyword" org-shiftright (org-at-heading-p)]
20642 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20643 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20644 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20645 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20646 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20647 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20648 "--"
20649 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20650 :selected org-enforce-todo-dependencies :style toggle :active t]
20651 "Settings for tree at point"
20652 ["Do Children sequentially" org-toggle-ordered-property :style radio
20653 :selected (org-entry-get nil "ORDERED")
20654 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20655 ["Do Children parallel" org-toggle-ordered-property :style radio
20656 :selected (not (org-entry-get nil "ORDERED"))
20657 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20658 "--"
20659 ["Set Priority" org-priority t]
20660 ["Priority Up" org-shiftup t]
20661 ["Priority Down" org-shiftdown t]
20662 "--"
20663 ["Get news from all feeds" org-feed-update-all t]
20664 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20665 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20666 ("TAGS and Properties"
20667 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20668 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20669 "--"
20670 ["Set property" org-set-property (not (org-before-first-heading-p))]
20671 ["Column view of properties" org-columns t]
20672 ["Insert Column View DBlock" org-insert-columns-dblock t])
20673 ("Dates and Scheduling"
20674 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20675 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20676 ("Change Date"
20677 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20678 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20679 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20680 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20681 ["Compute Time Range" org-evaluate-time-range t]
20682 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20683 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20684 "--"
20685 ["Custom time format" org-toggle-time-stamp-overlays
20686 :style radio :selected org-display-custom-times]
20687 "--"
20688 ["Goto Calendar" org-goto-calendar t]
20689 ["Date from Calendar" org-date-from-calendar t]
20690 "--"
20691 ["Start/Restart Timer" org-timer-start t]
20692 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20693 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20694 ["Insert Timer String" org-timer t]
20695 ["Insert Timer Item" org-timer-item t])
20696 ("Logging work"
20697 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20698 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20699 ["Clock out" org-clock-out t]
20700 ["Clock cancel" org-clock-cancel t]
20701 "--"
20702 ["Mark as default task" org-clock-mark-default-task t]
20703 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20704 ["Goto running clock" org-clock-goto t]
20705 "--"
20706 ["Display times" org-clock-display t]
20707 ["Create clock table" org-clock-report t]
20708 "--"
20709 ["Record DONE time"
20710 (progn (setq org-log-done (not org-log-done))
20711 (message "Switching to %s will %s record a timestamp"
20712 (car org-done-keywords)
20713 (if org-log-done "automatically" "not")))
20714 :style toggle :selected org-log-done])
20715 "--"
20716 ["Agenda Command..." org-agenda t]
20717 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20718 ("File List for Agenda")
20719 ("Special views current file"
20720 ["TODO Tree" org-show-todo-tree t]
20721 ["Check Deadlines" org-check-deadlines t]
20722 ["Timeline" org-timeline t]
20723 ["Tags/Property tree" org-match-sparse-tree t])
20724 "--"
20725 ["Export/Publish..." org-export-dispatch t]
20726 ("LaTeX"
20727 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20728 :selected org-cdlatex-mode]
20729 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20730 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20731 ["Modify math symbol" org-cdlatex-math-modify
20732 (org-inside-LaTeX-fragment-p)]
20733 ["Insert citation" org-reftex-citation t]
20734 "--"
20735 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20736 "--"
20737 ("MobileOrg"
20738 ["Push Files and Views" org-mobile-push t]
20739 ["Get Captured and Flagged" org-mobile-pull t]
20740 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20741 "--"
20742 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20743 "--"
20744 ("Documentation"
20745 ["Show Version" org-version t]
20746 ["Info Documentation" org-info t])
20747 ("Customize"
20748 ["Browse Org Group" org-customize t]
20749 "--"
20750 ["Expand This Menu" org-create-customize-menu
20751 (fboundp 'customize-menu-create)])
20752 ["Send bug report" org-submit-bug-report t]
20753 "--"
20754 ("Refresh/Reload"
20755 ["Refresh setup current buffer" org-mode-restart t]
20756 ["Reload Org (after update)" org-reload t]
20757 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20760 (defun org-info (&optional node)
20761 "Read documentation for Org-mode in the info system.
20762 With optional NODE, go directly to that node."
20763 (interactive)
20764 (info (format "(org)%s" (or node ""))))
20766 ;;;###autoload
20767 (defun org-submit-bug-report ()
20768 "Submit a bug report on Org-mode via mail.
20770 Don't hesitate to report any problems or inaccurate documentation.
20772 If you don't have setup sending mail from (X)Emacs, please copy the
20773 output buffer into your mail program, as it gives us important
20774 information about your Org-mode version and configuration."
20775 (interactive)
20776 (require 'reporter)
20777 (org-load-modules-maybe)
20778 (org-require-autoloaded-modules)
20779 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20780 (reporter-submit-bug-report
20781 "emacs-orgmode@gnu.org"
20782 (org-version nil 'full)
20783 (let (list)
20784 (save-window-excursion
20785 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20786 (delete-other-windows)
20787 (erase-buffer)
20788 (insert "You are about to submit a bug report to the Org-mode mailing list.
20790 We would like to add your full Org-mode and Outline configuration to the
20791 bug report. This greatly simplifies the work of the maintainer and
20792 other experts on the mailing list.
20794 HOWEVER, some variables you have customized may contain private
20795 information. The names of customers, colleagues, or friends, might
20796 appear in the form of file names, tags, todo states, or search strings.
20797 If you answer yes to the prompt, you might want to check and remove
20798 such private information before sending the email.")
20799 (add-text-properties (point-min) (point-max) '(face org-warning))
20800 (when (yes-or-no-p "Include your Org-mode configuration ")
20801 (mapatoms
20802 (lambda (v)
20803 (and (boundp v)
20804 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20805 (or (and (symbol-value v)
20806 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20807 (and
20808 (get v 'custom-type) (get v 'standard-value)
20809 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20810 (push v list)))))
20811 (kill-buffer (get-buffer "*Warn about privacy*"))
20812 list))
20813 nil nil
20814 "Remember to cover the basics, that is, what you expected to happen and
20815 what in fact did happen. You don't know how to make a good report? See
20817 http://orgmode.org/manual/Feedback.html#Feedback
20819 Your bug report will be posted to the Org-mode mailing list.
20820 ------------------------------------------------------------------------")
20821 (save-excursion
20822 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20823 (replace-match "\\1Bug: \\3 [\\2]")))))
20826 (defun org-install-agenda-files-menu ()
20827 (let ((bl (buffer-list)))
20828 (save-excursion
20829 (while bl
20830 (set-buffer (pop bl))
20831 (if (derived-mode-p 'org-mode) (setq bl nil)))
20832 (when (derived-mode-p 'org-mode)
20833 (easy-menu-change
20834 '("Org") "File List for Agenda"
20835 (append
20836 (list
20837 ["Edit File List" (org-edit-agenda-file-list) t]
20838 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20839 ["Remove Current File from List" org-remove-file t]
20840 ["Cycle through agenda files" org-cycle-agenda-files t]
20841 ["Occur in all agenda files" org-occur-in-agenda-files t]
20842 "--")
20843 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20845 ;;;; Documentation
20847 (defun org-require-autoloaded-modules ()
20848 (interactive)
20849 (mapc 'require
20850 '(org-agenda org-archive org-attach org-clock org-colview org-id
20851 org-remember org-table org-timer)))
20853 ;;;###autoload
20854 (defun org-reload (&optional uncompiled)
20855 "Reload all org lisp files.
20856 With prefix arg UNCOMPILED, load the uncompiled versions."
20857 (interactive "P")
20858 (require 'loadhist)
20859 (let* ((org-dir (org-find-library-dir "org"))
20860 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20861 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20862 (remove-re (mapconcat 'identity
20863 (mapcar (lambda (f) (concat "^" f "$"))
20864 (list (if (featurep 'xemacs)
20865 "org-colview"
20866 "org-colview-xemacs")
20867 "org" "org-loaddefs" "org-version"))
20868 "\\|"))
20869 (feats (delete-dups
20870 (mapcar 'file-name-sans-extension
20871 (mapcar 'file-name-nondirectory
20872 (delq nil
20873 (mapcar 'feature-file
20874 features))))))
20875 (lfeat (append
20876 (sort
20877 (setq feats
20878 (delq nil (mapcar
20879 (lambda (f)
20880 (if (and (string-match feature-re f)
20881 (not (string-match remove-re f)))
20882 f nil))
20883 feats)))
20884 'string-lessp)
20885 (list "org-version" "org")))
20886 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20887 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20888 load-uncore load-misses)
20889 (setq load-misses
20890 (delq 't
20891 (mapcar (lambda (f)
20892 (or (org-load-noerror-mustsuffix (concat org-dir f))
20893 (and (string= org-dir contrib-dir)
20894 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20895 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20896 (add-to-list 'load-uncore f 'append)
20899 lfeat)))
20900 (if load-uncore
20901 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20902 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20903 (if load-misses
20904 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20905 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20906 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20908 ;;;###autoload
20909 (defun org-customize ()
20910 "Call the customize function with org as argument."
20911 (interactive)
20912 (org-load-modules-maybe)
20913 (org-require-autoloaded-modules)
20914 (customize-browse 'org))
20916 (defun org-create-customize-menu ()
20917 "Create a full customization menu for Org-mode, insert it into the menu."
20918 (interactive)
20919 (org-load-modules-maybe)
20920 (org-require-autoloaded-modules)
20921 (if (fboundp 'customize-menu-create)
20922 (progn
20923 (easy-menu-change
20924 '("Org") "Customize"
20925 `(["Browse Org group" org-customize t]
20926 "--"
20927 ,(customize-menu-create 'org)
20928 ["Set" Custom-set t]
20929 ["Save" Custom-save t]
20930 ["Reset to Current" Custom-reset-current t]
20931 ["Reset to Saved" Custom-reset-saved t]
20932 ["Reset to Standard Settings" Custom-reset-standard t]))
20933 (message "\"Org\"-menu now contains full customization menu"))
20934 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20936 ;;;; Miscellaneous stuff
20938 ;;; Generally useful functions
20940 (defun org-get-at-bol (property)
20941 "Get text property PROPERTY at beginning of line."
20942 (get-text-property (point-at-bol) property))
20944 (defun org-find-text-property-in-string (prop s)
20945 "Return the first non-nil value of property PROP in string S."
20946 (or (get-text-property 0 prop s)
20947 (get-text-property (or (next-single-property-change 0 prop s) 0)
20948 prop s)))
20950 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20951 "Display the given MESSAGE as a warning."
20952 (if (fboundp 'display-warning)
20953 (display-warning 'org message
20954 (if (featurep 'xemacs) 'warning :warning))
20955 (let ((buf (get-buffer-create "*Org warnings*")))
20956 (with-current-buffer buf
20957 (goto-char (point-max))
20958 (insert "Warning (Org): " message)
20959 (unless (bolp)
20960 (newline)))
20961 (display-buffer buf)
20962 (sit-for 0))))
20964 (defun org-eval (form)
20965 "Eval FORM and return result."
20966 (condition-case error
20967 (eval form)
20968 (error (format "%%![Error: %s]" error))))
20970 (defun org-in-clocktable-p ()
20971 "Check if the cursor is in a clocktable."
20972 (let ((pos (point)) start)
20973 (save-excursion
20974 (end-of-line 1)
20975 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20976 (setq start (match-beginning 0))
20977 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20978 (>= (match-end 0) pos)
20979 start))))
20981 (defun org-in-commented-line ()
20982 "Is point in a line starting with `#'?"
20983 (equal (char-after (point-at-bol)) ?#))
20985 (defun org-in-indented-comment-line ()
20986 "Is point in a line starting with `#' after some white space?"
20987 (save-excursion
20988 (save-match-data
20989 (goto-char (point-at-bol))
20990 (looking-at "[ \t]*#"))))
20992 (defun org-in-verbatim-emphasis ()
20993 (save-match-data
20994 (and (org-in-regexp org-emph-re 2)
20995 (>= (point) (match-beginning 3))
20996 (<= (point) (match-end 4))
20997 (member (match-string 3) '("=" "~")))))
20999 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21000 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21001 (if (and marker (marker-buffer marker)
21002 (buffer-live-p (marker-buffer marker)))
21003 (progn
21004 (org-pop-to-buffer-same-window (marker-buffer marker))
21005 (if (or (> marker (point-max)) (< marker (point-min)))
21006 (widen))
21007 (goto-char marker)
21008 (org-show-context 'org-goto))
21009 (if bookmark
21010 (bookmark-jump bookmark)
21011 (error "Cannot find location"))))
21013 (defun org-quote-csv-field (s)
21014 "Quote field for inclusion in CSV material."
21015 (if (string-match "[\",]" s)
21016 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21019 (defun org-force-self-insert (N)
21020 "Needed to enforce self-insert under remapping."
21021 (interactive "p")
21022 (self-insert-command N))
21024 (defun org-string-width (s)
21025 "Compute width of string, ignoring invisible characters.
21026 This ignores character with invisibility property `org-link', and also
21027 characters with property `org-cwidth', because these will become invisible
21028 upon the next fontification round."
21029 (let (b l)
21030 (when (or (eq t buffer-invisibility-spec)
21031 (assq 'org-link buffer-invisibility-spec))
21032 (while (setq b (text-property-any 0 (length s)
21033 'invisible 'org-link s))
21034 (setq s (concat (substring s 0 b)
21035 (substring s (or (next-single-property-change
21036 b 'invisible s) (length s)))))))
21037 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21038 (setq s (concat (substring s 0 b)
21039 (substring s (or (next-single-property-change
21040 b 'org-cwidth s) (length s))))))
21041 (setq l (string-width s) b -1)
21042 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21043 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21046 (defun org-shorten-string (s maxlength)
21047 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21048 If the string is shorter or has length MAXLENGTH, just return the
21049 original string. If it is longer, the functions finds a space in the
21050 string, breaks this string off at that locations and adds three dots
21051 as ellipsis. Including the ellipsis, the string will not be longer
21052 than MAXLENGTH. If finding a good breaking point in the string does
21053 not work, the string is just chopped off in the middle of a word
21054 if necessary."
21055 (if (<= (length s) maxlength)
21057 (let* ((n (max (- maxlength 4) 1))
21058 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21059 (if (string-match re s)
21060 (concat (match-string 1 s) "...")
21061 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21063 (defun org-get-indentation (&optional line)
21064 "Get the indentation of the current line, interpreting tabs.
21065 When LINE is given, assume it represents a line and compute its indentation."
21066 (if line
21067 (if (string-match "^ *" (org-remove-tabs line))
21068 (match-end 0))
21069 (save-excursion
21070 (beginning-of-line 1)
21071 (skip-chars-forward " \t")
21072 (current-column))))
21074 (defun org-get-string-indentation (s)
21075 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21076 (let ((n -1) (i 0) (w tab-width) c)
21077 (catch 'exit
21078 (while (< (setq n (1+ n)) (length s))
21079 (setq c (aref s n))
21080 (cond ((= c ?\ ) (setq i (1+ i)))
21081 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21082 (t (throw 'exit t)))))
21085 (defun org-remove-tabs (s &optional width)
21086 "Replace tabulators in S with spaces.
21087 Assumes that s is a single line, starting in column 0."
21088 (setq width (or width tab-width))
21089 (while (string-match "\t" s)
21090 (setq s (replace-match
21091 (make-string
21092 (- (* width (/ (+ (match-beginning 0) width) width))
21093 (match-beginning 0)) ?\ )
21094 t t s)))
21097 (defun org-fix-indentation (line ind)
21098 "Fix indentation in LINE.
21099 IND is a cons cell with target and minimum indentation.
21100 If the current indentation in LINE is smaller than the minimum,
21101 leave it alone. If it is larger than ind, set it to the target."
21102 (let* ((l (org-remove-tabs line))
21103 (i (org-get-indentation l))
21104 (i1 (car ind)) (i2 (cdr ind)))
21105 (if (>= i i2) (setq l (substring line i2)))
21106 (if (> i1 0)
21107 (concat (make-string i1 ?\ ) l)
21108 l)))
21110 (defun org-remove-indentation (code &optional n)
21111 "Remove the maximum common indentation from the lines in CODE.
21112 N may optionally be the number of spaces to remove."
21113 (with-temp-buffer
21114 (insert code)
21115 (org-do-remove-indentation n)
21116 (buffer-string)))
21118 (defun org-do-remove-indentation (&optional n)
21119 "Remove the maximum common indentation from the buffer."
21120 (untabify (point-min) (point-max))
21121 (let ((min 10000) re)
21122 (if n
21123 (setq min n)
21124 (goto-char (point-min))
21125 (while (re-search-forward "^ *[^ \n]" nil t)
21126 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21127 (unless (or (= min 0) (= min 10000))
21128 (setq re (format "^ \\{%d\\}" min))
21129 (goto-char (point-min))
21130 (while (re-search-forward re nil t)
21131 (replace-match "")
21132 (end-of-line 1))
21133 min)))
21135 (defun org-fill-template (template alist)
21136 "Find each %key of ALIST in TEMPLATE and replace it."
21137 (let ((case-fold-search nil)
21138 entry key value)
21139 (setq alist (sort (copy-sequence alist)
21140 (lambda (a b) (< (length (car a)) (length (car b))))))
21141 (while (setq entry (pop alist))
21142 (setq template
21143 (replace-regexp-in-string
21144 (concat "%" (regexp-quote (car entry)))
21145 (or (cdr entry) "") template t t)))
21146 template))
21148 (defun org-base-buffer (buffer)
21149 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21150 (if (not buffer)
21151 buffer
21152 (or (buffer-base-buffer buffer)
21153 buffer)))
21155 (defun org-trim (s)
21156 "Remove whitespace at beginning and end of string."
21157 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21158 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21161 (defun org-wrap (string &optional width lines)
21162 "Wrap string to either a number of lines, or a width in characters.
21163 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21164 that costs. If there is a word longer than WIDTH, the text is actually
21165 wrapped to the length of that word.
21166 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21167 many lines, whatever width that takes.
21168 The return value is a list of lines, without newlines at the end."
21169 (let* ((words (org-split-string string "[ \t\n]+"))
21170 (maxword (apply 'max (mapcar 'org-string-width words)))
21171 w ll)
21172 (cond (width
21173 (org-do-wrap words (max maxword width)))
21174 (lines
21175 (setq w maxword)
21176 (setq ll (org-do-wrap words maxword))
21177 (if (<= (length ll) lines)
21179 (setq ll words)
21180 (while (> (length ll) lines)
21181 (setq w (1+ w))
21182 (setq ll (org-do-wrap words w)))
21183 ll))
21184 (t (error "Cannot wrap this")))))
21186 (defun org-do-wrap (words width)
21187 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21188 (let (lines line)
21189 (while words
21190 (setq line (pop words))
21191 (while (and words (< (+ (length line) (length (car words))) width))
21192 (setq line (concat line " " (pop words))))
21193 (setq lines (push line lines)))
21194 (nreverse lines)))
21196 (defun org-split-string (string &optional separators)
21197 "Splits STRING into substrings at SEPARATORS.
21198 No empty strings are returned if there are matches at the beginning
21199 and end of string."
21200 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21201 (start 0)
21202 notfirst
21203 (list nil))
21204 (while (and (string-match rexp string
21205 (if (and notfirst
21206 (= start (match-beginning 0))
21207 (< start (length string)))
21208 (1+ start) start))
21209 (< (match-beginning 0) (length string)))
21210 (setq notfirst t)
21211 (or (eq (match-beginning 0) 0)
21212 (and (eq (match-beginning 0) (match-end 0))
21213 (eq (match-beginning 0) start))
21214 (setq list
21215 (cons (substring string start (match-beginning 0))
21216 list)))
21217 (setq start (match-end 0)))
21218 (or (eq start (length string))
21219 (setq list
21220 (cons (substring string start)
21221 list)))
21222 (nreverse list)))
21224 (defun org-quote-vert (s)
21225 "Replace \"|\" with \"\\vert\"."
21226 (while (string-match "|" s)
21227 (setq s (replace-match "\\vert" t t s)))
21230 (defun org-uuidgen-p (s)
21231 "Is S an ID created by UUIDGEN?"
21232 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21234 (defun org-in-src-block-p (&optional inside)
21235 "Whether point is in a code source block.
21236 When INSIDE is non-nil, don't consider we are within a src block
21237 when point is at #+BEGIN_SRC or #+END_SRC."
21238 (let ((case-fold-search t) ov)
21239 (or (and (setq ov (overlays-at (point)))
21240 (memq 'org-block-background
21241 (overlay-properties (car ov))))
21242 (and (not inside)
21243 (save-match-data
21244 (save-excursion
21245 (beginning-of-line)
21246 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21248 (defun org-context ()
21249 "Return a list of contexts of the current cursor position.
21250 If several contexts apply, all are returned.
21251 Each context entry is a list with a symbol naming the context, and
21252 two positions indicating start and end of the context. Possible
21253 contexts are:
21255 :headline anywhere in a headline
21256 :headline-stars on the leading stars in a headline
21257 :todo-keyword on a TODO keyword (including DONE) in a headline
21258 :tags on the TAGS in a headline
21259 :priority on the priority cookie in a headline
21260 :item on the first line of a plain list item
21261 :item-bullet on the bullet/number of a plain list item
21262 :checkbox on the checkbox in a plain list item
21263 :table in an org-mode table
21264 :table-special on a special filed in a table
21265 :table-table in a table.el table
21266 :clocktable in a clocktable
21267 :src-block in a source block
21268 :link on a hyperlink
21269 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21270 :target on a <<target>>
21271 :radio-target on a <<<radio-target>>>
21272 :latex-fragment on a LaTeX fragment
21273 :latex-preview on a LaTeX fragment with overlaid preview image
21275 This function expects the position to be visible because it uses font-lock
21276 faces as a help to recognize the following contexts: :table-special, :link,
21277 and :keyword."
21278 (let* ((f (get-text-property (point) 'face))
21279 (faces (if (listp f) f (list f)))
21280 (case-fold-search t)
21281 (p (point)) clist o)
21282 ;; First the large context
21283 (cond
21284 ((org-at-heading-p t)
21285 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21286 (when (progn
21287 (beginning-of-line 1)
21288 (looking-at org-todo-line-tags-regexp))
21289 (push (org-point-in-group p 1 :headline-stars) clist)
21290 (push (org-point-in-group p 2 :todo-keyword) clist)
21291 (push (org-point-in-group p 4 :tags) clist))
21292 (goto-char p)
21293 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21294 (if (looking-at "\\[#[A-Z0-9]\\]")
21295 (push (org-point-in-group p 0 :priority) clist)))
21297 ((org-at-item-p)
21298 (push (org-point-in-group p 2 :item-bullet) clist)
21299 (push (list :item (point-at-bol)
21300 (save-excursion (org-end-of-item) (point)))
21301 clist)
21302 (and (org-at-item-checkbox-p)
21303 (push (org-point-in-group p 0 :checkbox) clist)))
21305 ((org-at-table-p)
21306 (push (list :table (org-table-begin) (org-table-end)) clist)
21307 (if (memq 'org-formula faces)
21308 (push (list :table-special
21309 (previous-single-property-change p 'face)
21310 (next-single-property-change p 'face)) clist)))
21311 ((org-at-table-p 'any)
21312 (push (list :table-table) clist)))
21313 (goto-char p)
21315 (let ((case-fold-search t))
21316 ;; New the "medium" contexts: clocktables, source blocks
21317 (cond ((org-in-clocktable-p)
21318 (push (list :clocktable
21319 (and (or (looking-at "#\\+BEGIN: clocktable")
21320 (search-backward "#+BEGIN: clocktable" nil t))
21321 (match-beginning 0))
21322 (and (re-search-forward "#\\+END:?" nil t)
21323 (match-end 0))) clist))
21324 ((org-in-src-block-p)
21325 (push (list :src-block
21326 (and (or (looking-at "#\\+BEGIN_SRC")
21327 (search-backward "#+BEGIN_SRC" nil t))
21328 (match-beginning 0))
21329 (and (search-forward "#+END_SRC" nil t)
21330 (match-beginning 0))) clist))))
21331 (goto-char p)
21333 ;; Now the small context
21334 (cond
21335 ((org-at-timestamp-p)
21336 (push (org-point-in-group p 0 :timestamp) clist))
21337 ((memq 'org-link faces)
21338 (push (list :link
21339 (previous-single-property-change p 'face)
21340 (next-single-property-change p 'face)) clist))
21341 ((memq 'org-special-keyword faces)
21342 (push (list :keyword
21343 (previous-single-property-change p 'face)
21344 (next-single-property-change p 'face)) clist))
21345 ((org-at-target-p)
21346 (push (org-point-in-group p 0 :target) clist)
21347 (goto-char (1- (match-beginning 0)))
21348 (if (looking-at org-radio-target-regexp)
21349 (push (org-point-in-group p 0 :radio-target) clist))
21350 (goto-char p))
21351 ((setq o (car (delq nil
21352 (mapcar
21353 (lambda (x)
21354 (if (memq x org-latex-fragment-image-overlays) x))
21355 (overlays-at (point))))))
21356 (push (list :latex-fragment
21357 (overlay-start o) (overlay-end o)) clist)
21358 (push (list :latex-preview
21359 (overlay-start o) (overlay-end o)) clist))
21360 ((org-inside-LaTeX-fragment-p)
21361 ;; FIXME: positions wrong.
21362 (push (list :latex-fragment (point) (point)) clist)))
21364 (setq clist (nreverse (delq nil clist)))
21365 clist))
21367 ;; FIXME: Compare with at-regexp-p Do we need both?
21368 (defun org-in-regexp (re &optional nlines visually)
21369 "Check if point is inside a match of regexp.
21370 Normally only the current line is checked, but you can include NLINES extra
21371 lines both before and after point into the search.
21372 If VISUALLY is set, require that the cursor is not after the match but
21373 really on, so that the block visually is on the match."
21374 (catch 'exit
21375 (let ((pos (point))
21376 (eol (point-at-eol (+ 1 (or nlines 0))))
21377 (inc (if visually 1 0)))
21378 (save-excursion
21379 (beginning-of-line (- 1 (or nlines 0)))
21380 (while (re-search-forward re eol t)
21381 (if (and (<= (match-beginning 0) pos)
21382 (>= (+ inc (match-end 0)) pos))
21383 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21385 (defun org-at-regexp-p (regexp)
21386 "Is point inside a match of REGEXP in the current line?"
21387 (catch 'exit
21388 (save-excursion
21389 (let ((pos (point)) (end (point-at-eol)))
21390 (beginning-of-line 1)
21391 (while (re-search-forward regexp end t)
21392 (if (and (<= (match-beginning 0) pos)
21393 (>= (match-end 0) pos))
21394 (throw 'exit t)))
21395 nil))))
21397 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21398 "Non-nil when point is between matches of START-RE and END-RE.
21400 Also return a non-nil value when point is on one of the matches.
21402 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21403 buffer positions. Default values are the positions of headlines
21404 surrounding the point.
21406 The functions returns a cons cell whose car (resp. cdr) is the
21407 position before START-RE (resp. after END-RE)."
21408 (save-match-data
21409 (let ((pos (point))
21410 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21411 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21412 beg end)
21413 (save-excursion
21414 ;; Point is on a block when on START-RE or if START-RE can be
21415 ;; found before it...
21416 (and (or (org-at-regexp-p start-re)
21417 (re-search-backward start-re limit-up t))
21418 (setq beg (match-beginning 0))
21419 ;; ... and END-RE after it...
21420 (goto-char (match-end 0))
21421 (re-search-forward end-re limit-down t)
21422 (> (setq end (match-end 0)) pos)
21423 ;; ... without another START-RE in-between.
21424 (goto-char (match-beginning 0))
21425 (not (re-search-backward start-re (1+ beg) t))
21426 ;; Return value.
21427 (cons beg end))))))
21429 (defun org-in-block-p (names)
21430 "Non-nil when point belongs to a block whose name belongs to NAMES.
21432 NAMES is a list of strings containing names of blocks.
21434 Return first block name matched, or nil. Beware that in case of
21435 nested blocks, the returned name may not belong to the closest
21436 block from point."
21437 (save-match-data
21438 (catch 'exit
21439 (let ((case-fold-search t)
21440 (lim-up (save-excursion (outline-previous-heading)))
21441 (lim-down (save-excursion (outline-next-heading))))
21442 (mapc (lambda (name)
21443 (let ((n (regexp-quote name)))
21444 (when (org-between-regexps-p
21445 (concat "^[ \t]*#\\+begin_" n)
21446 (concat "^[ \t]*#\\+end_" n)
21447 lim-up lim-down)
21448 (throw 'exit n))))
21449 names))
21450 nil)))
21452 (defun org-occur-in-agenda-files (regexp &optional nlines)
21453 "Call `multi-occur' with buffers for all agenda files."
21454 (interactive "sOrg-files matching: \np")
21455 (let* ((files (org-agenda-files))
21456 (tnames (mapcar 'file-truename files))
21457 (extra org-agenda-text-search-extra-files)
21459 (when (eq (car extra) 'agenda-archives)
21460 (setq extra (cdr extra))
21461 (setq files (org-add-archive-files files)))
21462 (while (setq f (pop extra))
21463 (unless (member (file-truename f) tnames)
21464 (add-to-list 'files f 'append)
21465 (add-to-list 'tnames (file-truename f) 'append)))
21466 (multi-occur
21467 (mapcar (lambda (x)
21468 (with-current-buffer
21469 (or (get-file-buffer x) (find-file-noselect x))
21470 (widen)
21471 (current-buffer)))
21472 files)
21473 regexp)))
21475 (if (boundp 'occur-mode-find-occurrence-hook)
21476 ;; Emacs 23
21477 (add-hook 'occur-mode-find-occurrence-hook
21478 (lambda ()
21479 (when (derived-mode-p 'org-mode)
21480 (org-reveal))))
21481 ;; Emacs 22
21482 (defadvice occur-mode-goto-occurrence
21483 (after org-occur-reveal activate)
21484 (and (derived-mode-p 'org-mode) (org-reveal)))
21485 (defadvice occur-mode-goto-occurrence-other-window
21486 (after org-occur-reveal activate)
21487 (and (derived-mode-p 'org-mode) (org-reveal)))
21488 (defadvice occur-mode-display-occurrence
21489 (after org-occur-reveal activate)
21490 (when (derived-mode-p 'org-mode)
21491 (let ((pos (occur-mode-find-occurrence)))
21492 (with-current-buffer (marker-buffer pos)
21493 (save-excursion
21494 (goto-char pos)
21495 (org-reveal)))))))
21497 (defun org-occur-link-in-agenda-files ()
21498 "Create a link and search for it in the agendas.
21499 The link is not stored in `org-stored-links', it is just created
21500 for the search purpose."
21501 (interactive)
21502 (let ((link (condition-case nil
21503 (org-store-link nil)
21504 (error "Unable to create a link to here"))))
21505 (org-occur-in-agenda-files (regexp-quote link))))
21507 (defun org-reverse-string (string)
21508 "Return the reverse of STRING."
21509 (apply 'string (reverse (string-to-list string))))
21511 (defun org-uniquify (list)
21512 "Remove duplicate elements from LIST."
21513 (let (res)
21514 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21515 res))
21517 (defun org-uniquify-alist (alist)
21518 "Merge duplicate elements of an alist.
21520 For example, in this alist:
21522 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21523 => '((a 1 3) (b 2))
21525 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21526 (let (rtn)
21527 (mapc
21528 (lambda (e)
21529 (let (n)
21530 (if (not (assoc (car e) rtn))
21531 (push e rtn)
21532 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21533 (setq rtn (assq-delete-all (car e) rtn))
21534 (push n rtn))))
21535 alist)
21536 rtn))
21538 (defun org-delete-all (elts list)
21539 "Remove all elements in ELTS from LIST."
21540 (while elts
21541 (setq list (delete (pop elts) list)))
21542 list)
21544 (defun org-count (cl-item cl-seq)
21545 "Count the number of occurrences of ITEM in SEQ.
21546 Taken from `count' in cl-seq.el with all keyword arguments removed."
21547 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21548 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21549 (while (< cl-start cl-end)
21550 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21551 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21552 (setq cl-start (1+ cl-start)))
21553 cl-count))
21555 (defun org-remove-if (predicate seq)
21556 "Remove everything from SEQ that fulfills PREDICATE."
21557 (let (res e)
21558 (while seq
21559 (setq e (pop seq))
21560 (if (not (funcall predicate e)) (push e res)))
21561 (nreverse res)))
21563 (defun org-remove-if-not (predicate seq)
21564 "Remove everything from SEQ that does not fulfill PREDICATE."
21565 (let (res e)
21566 (while seq
21567 (setq e (pop seq))
21568 (if (funcall predicate e) (push e res)))
21569 (nreverse res)))
21571 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21572 "Reduce two-argument FUNCTION across SEQ.
21573 Taken from `reduce' in cl-seq.el with all keyword arguments but
21574 \":initial-value\" removed."
21575 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21576 (cadr (memq :initial-value cl-keys)))
21577 (cl-seq (pop cl-seq))
21578 (t (funcall cl-func)))))
21579 (while cl-seq
21580 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21581 cl-accum))
21583 (defun org-back-over-empty-lines ()
21584 "Move backwards over whitespace, to the beginning of the first empty line.
21585 Returns the number of empty lines passed."
21586 (let ((pos (point)))
21587 (if (cdr (assoc 'heading org-blank-before-new-entry))
21588 (skip-chars-backward " \t\n\r")
21589 (unless (eobp)
21590 (forward-line -1)))
21591 (beginning-of-line 2)
21592 (goto-char (min (point) pos))
21593 (count-lines (point) pos)))
21595 (defun org-skip-whitespace ()
21596 (skip-chars-forward " \t\n\r"))
21598 (defun org-point-in-group (point group &optional context)
21599 "Check if POINT is in match-group GROUP.
21600 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21601 match. If the match group does not exist or point is not inside it,
21602 return nil."
21603 (and (match-beginning group)
21604 (>= point (match-beginning group))
21605 (<= point (match-end group))
21606 (if context
21607 (list context (match-beginning group) (match-end group))
21608 t)))
21610 (defun org-switch-to-buffer-other-window (&rest args)
21611 "Switch to buffer in a second window on the current frame.
21612 In particular, do not allow pop-up frames.
21613 Returns the newly created buffer."
21614 (org-no-popups
21615 (apply 'switch-to-buffer-other-window args)))
21617 (defun org-combine-plists (&rest plists)
21618 "Create a single property list from all plists in PLISTS.
21619 The process starts by copying the first list, and then setting properties
21620 from the other lists. Settings in the last list are the most significant
21621 ones and overrule settings in the other lists."
21622 (let ((rtn (copy-sequence (pop plists)))
21623 p v ls)
21624 (while plists
21625 (setq ls (pop plists))
21626 (while ls
21627 (setq p (pop ls) v (pop ls))
21628 (setq rtn (plist-put rtn p v))))
21629 rtn))
21631 (defun org-replace-escapes (string table)
21632 "Replace %-escapes in STRING with values in TABLE.
21633 TABLE is an association list with keys like \"%a\" and string values.
21634 The sequences in STRING may contain normal field width and padding information,
21635 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21636 so values can contain further %-escapes if they are define later in TABLE."
21637 (let ((tbl (copy-alist table))
21638 (case-fold-search nil)
21639 (pchg 0)
21640 e re rpl)
21641 (while (setq e (pop tbl))
21642 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21643 (when (and (cdr e) (string-match re (cdr e)))
21644 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21645 (safe "SREF"))
21646 (add-text-properties 0 3 (list 'sref sref) safe)
21647 (setcdr e (replace-match safe t t (cdr e)))))
21648 (while (string-match re string)
21649 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21650 (cdr e)))
21651 (setq string (replace-match rpl t t string))))
21652 (while (setq pchg (next-property-change pchg string))
21653 (let ((sref (get-text-property pchg 'sref string)))
21654 (when (and sref (string-match "SREF" string pchg))
21655 (setq string (replace-match sref t t string)))))
21656 string))
21658 (defun org-sublist (list start end)
21659 "Return a section of LIST, from START to END.
21660 Counting starts at 1."
21661 (let (rtn (c start))
21662 (setq list (nthcdr (1- start) list))
21663 (while (and list (<= c end))
21664 (push (pop list) rtn)
21665 (setq c (1+ c)))
21666 (nreverse rtn)))
21668 (defun org-find-base-buffer-visiting (file)
21669 "Like `find-buffer-visiting' but always return the base buffer and
21670 not an indirect buffer."
21671 (let ((buf (or (get-file-buffer file)
21672 (find-buffer-visiting file))))
21673 (if buf
21674 (or (buffer-base-buffer buf) buf)
21675 nil)))
21677 (defun org-image-file-name-regexp (&optional extensions)
21678 "Return regexp matching the file names of images.
21679 If EXTENSIONS is given, only match these."
21680 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21681 (image-file-name-regexp)
21682 (let ((image-file-name-extensions
21683 (or extensions
21684 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21685 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21686 (concat "\\."
21687 (regexp-opt (nconc (mapcar 'upcase
21688 image-file-name-extensions)
21689 image-file-name-extensions)
21691 "\\'"))))
21693 (defun org-file-image-p (file &optional extensions)
21694 "Return non-nil if FILE is an image."
21695 (save-match-data
21696 (string-match (org-image-file-name-regexp extensions) file)))
21698 (defun org-get-cursor-date (&optional with-time)
21699 "Return the date at cursor in as a time.
21700 This works in the calendar and in the agenda, anywhere else it just
21701 returns the current time.
21702 If WITH-TIME is non-nil, returns the time of the event at point (in
21703 the agenda) or the current time of the day."
21704 (let (date day defd tp tm hod mod)
21705 (when with-time
21706 (setq tp (get-text-property (point) 'time))
21707 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21708 (setq hod (string-to-number (match-string 1 tp))
21709 mod (string-to-number (match-string 2 tp))))
21710 (or tp (setq hod (nth 2 (decode-time (current-time)))
21711 mod (nth 1 (decode-time (current-time))))))
21712 (cond
21713 ((eq major-mode 'calendar-mode)
21714 (setq date (calendar-cursor-to-date)
21715 defd (encode-time 0 (or mod 0) (or hod 0)
21716 (nth 1 date) (nth 0 date) (nth 2 date))))
21717 ((eq major-mode 'org-agenda-mode)
21718 (setq day (get-text-property (point) 'day))
21719 (if day
21720 (setq date (calendar-gregorian-from-absolute day)
21721 defd (encode-time 0 (or mod 0) (or hod 0)
21722 (nth 1 date) (nth 0 date) (nth 2 date))))))
21723 (or defd (current-time))))
21725 (defun org-mark-subtree (&optional up)
21726 "Mark the current subtree.
21727 This puts point at the start of the current subtree, and mark at
21728 the end. If a numeric prefix UP is given, move up into the
21729 hierarchy of headlines by UP levels before marking the subtree."
21730 (interactive "P")
21731 (org-with-limited-levels
21732 (cond ((org-at-heading-p) (beginning-of-line))
21733 ((org-before-first-heading-p) (error "Not in a subtree"))
21734 (t (outline-previous-visible-heading 1))))
21735 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21736 (if (org-called-interactively-p 'any)
21737 (call-interactively 'org-mark-element)
21738 (org-mark-element)))
21741 ;;; Indentation
21743 (defun org-indent-line ()
21744 "Indent line depending on context."
21745 (interactive)
21746 (let* ((pos (point))
21747 (itemp (org-at-item-p))
21748 (case-fold-search t)
21749 (org-drawer-regexp (or org-drawer-regexp "\000"))
21750 (inline-task-p (and (featurep 'org-inlinetask)
21751 (org-inlinetask-in-task-p)))
21752 (inline-re (and inline-task-p
21753 (org-inlinetask-outline-regexp)))
21754 column)
21755 (if (and orgstruct-is-++ (eq pos (point)))
21756 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21757 (indent-according-to-mode))
21758 (beginning-of-line 1)
21759 (cond
21760 ;; Headings
21761 ((looking-at org-outline-regexp) (setq column 0))
21762 ;; Footnote definition
21763 ((looking-at org-footnote-definition-re) (setq column 0))
21764 ;; Literal examples
21765 ((looking-at "[ \t]*:\\( \\|$\\)")
21766 (setq column (org-get-indentation))) ; do nothing
21767 ;; Lists
21768 ((ignore-errors (goto-char (org-in-item-p)))
21769 (setq column (if itemp
21770 (org-get-indentation)
21771 (org-list-item-body-column (point))))
21772 (goto-char pos))
21773 ;; Drawers
21774 ((and (looking-at "[ \t]*:END:")
21775 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21776 (save-excursion
21777 (goto-char (1- (match-beginning 1)))
21778 (setq column (current-column))))
21779 ;; Special blocks
21780 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21781 (save-excursion
21782 (re-search-backward
21783 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21784 (setq column (org-get-indentation (match-string 0))))
21785 ((and (not (looking-at "[ \t]*#\\+begin_"))
21786 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21787 (save-excursion
21788 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21789 (setq column
21790 (cond ((equal (downcase (match-string 1)) "src")
21791 ;; src blocks: let `org-edit-src-exit' handle them
21792 (org-get-indentation))
21793 ((equal (downcase (match-string 1)) "example")
21794 (max (org-get-indentation)
21795 (org-get-indentation (match-string 0))))
21797 (org-get-indentation (match-string 0))))))
21798 ;; This line has nothing special, look at the previous relevant
21799 ;; line to compute indentation
21801 (beginning-of-line 0)
21802 (while (and (not (bobp))
21803 (not (looking-at org-table-line-regexp))
21804 (not (looking-at org-drawer-regexp))
21805 ;; When point started in an inline task, do not move
21806 ;; above task starting line.
21807 (not (and inline-task-p (looking-at inline-re)))
21808 ;; Skip drawers, blocks, empty lines, verbatim,
21809 ;; comments, tables, footnotes definitions, lists,
21810 ;; inline tasks.
21811 (or (and (looking-at "[ \t]*:END:")
21812 (re-search-backward org-drawer-regexp nil t))
21813 (and (looking-at "[ \t]*#\\+end_")
21814 (re-search-backward "[ \t]*#\\+begin_"nil t))
21815 (looking-at "[ \t]*[\n:#|]")
21816 (looking-at org-footnote-definition-re)
21817 (and (ignore-errors (goto-char (org-in-item-p)))
21818 (goto-char
21819 (org-list-get-top-point (org-list-struct))))
21820 (and (not inline-task-p)
21821 (featurep 'org-inlinetask)
21822 (org-inlinetask-in-task-p)
21823 (or (org-inlinetask-goto-beginning) t))))
21824 (beginning-of-line 0))
21825 (cond
21826 ;; There was an heading above.
21827 ((looking-at "\\*+[ \t]+")
21828 (if (not org-adapt-indentation)
21829 (setq column 0)
21830 (goto-char (match-end 0))
21831 (setq column (current-column))))
21832 ;; A drawer had started and is unfinished
21833 ((looking-at org-drawer-regexp)
21834 (goto-char (1- (match-beginning 1)))
21835 (setq column (current-column)))
21836 ;; Else, nothing noticeable found: get indentation and go on.
21837 (t (setq column (org-get-indentation))))))
21838 ;; Now apply indentation and move cursor accordingly
21839 (goto-char pos)
21840 (if (<= (current-column) (current-indentation))
21841 (org-indent-line-to column)
21842 (save-excursion (org-indent-line-to column)))
21843 ;; Special polishing for properties, see `org-property-format'
21844 (setq column (current-column))
21845 (beginning-of-line 1)
21846 (if (looking-at
21847 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21848 (replace-match (concat (match-string 1)
21849 (format org-property-format
21850 (match-string 2) (match-string 3)))
21851 t t))
21852 (org-move-to-column column))))
21854 (defun org-indent-drawer ()
21855 "Indent the drawer at point."
21856 (interactive)
21857 (let ((p (point))
21858 (e (and (save-excursion (re-search-forward ":END:" nil t))
21859 (match-end 0)))
21860 (folded
21861 (save-excursion
21862 (end-of-line)
21863 (when (overlays-at (point))
21864 (member 'invisible (overlay-properties
21865 (car (overlays-at (point)))))))))
21866 (when folded (org-cycle))
21867 (indent-for-tab-command)
21868 (while (and (move-beginning-of-line 2) (< (point) e))
21869 (indent-for-tab-command))
21870 (goto-char p)
21871 (when folded (org-cycle)))
21872 (message "Drawer at point indented"))
21874 (defun org-indent-block ()
21875 "Indent the block at point."
21876 (interactive)
21877 (let ((p (point))
21878 (case-fold-search t)
21879 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21880 (match-end 0)))
21881 (folded
21882 (save-excursion
21883 (end-of-line)
21884 (when (overlays-at (point))
21885 (member 'invisible (overlay-properties
21886 (car (overlays-at (point)))))))))
21887 (when folded (org-cycle))
21888 (indent-for-tab-command)
21889 (while (and (move-beginning-of-line 2) (< (point) e))
21890 (indent-for-tab-command))
21891 (goto-char p)
21892 (when folded (org-cycle)))
21893 (message "Block at point indented"))
21895 (defun org-indent-region (start end)
21896 "Indent region."
21897 (interactive "r")
21898 (save-excursion
21899 (let ((line-end (org-current-line end)))
21900 (goto-char start)
21901 (while (< (org-current-line) line-end)
21902 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21903 (t (call-interactively 'org-indent-line)))
21904 (move-beginning-of-line 2)))))
21907 ;;; Filling
21909 ;; We use our own fill-paragraph and auto-fill functions.
21911 ;; `org-fill-paragraph' relies on adaptive filling and context
21912 ;; checking. Appropriate `fill-prefix' is computed with
21913 ;; `org-adaptive-fill-function'.
21915 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21916 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21917 ;; `org-adaptive-fill-function' value. Internally,
21918 ;; `org-comment-line-break-function' breaks the line.
21920 ;; `org-setup-filling' installs filling and auto-filling related
21921 ;; variables during `org-mode' initialization.
21923 (defun org-setup-filling ()
21924 (interactive)
21925 ;; Prevent auto-fill from inserting unwanted new items.
21926 (when (boundp 'fill-nobreak-predicate)
21927 (org-set-local
21928 'fill-nobreak-predicate
21929 (org-uniquify
21930 (append fill-nobreak-predicate
21931 '(org-fill-paragraph-separate-nobreak-p
21932 org-fill-line-break-nobreak-p
21933 org-fill-paragraph-with-timestamp-nobreak-p)))))
21934 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21935 (org-set-local 'auto-fill-inhibit-regexp nil)
21936 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21937 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21938 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21940 (defvar org-element-paragraph-separate) ; org-element.el
21941 (defun org-fill-paragraph-separate-nobreak-p ()
21942 "Non-nil when a line break at point would insert a new item."
21943 (looking-at (substring org-element-paragraph-separate 1)))
21945 (defun org-fill-line-break-nobreak-p ()
21946 "Non-nil when a line break at point would create an Org line break."
21947 (save-excursion
21948 (skip-chars-backward "[ \t]")
21949 (skip-chars-backward "\\\\")
21950 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21952 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21953 "Non-nil when a line break at point would insert a new item."
21954 (and (org-at-timestamp-p t)
21955 (not (looking-at org-ts-regexp-both))))
21957 (declare-function message-in-body-p "message" ())
21958 (defvar orgtbl-line-start-regexp) ; From org-table.el
21959 (defun org-adaptive-fill-function ()
21960 "Compute a fill prefix for the current line.
21961 Return fill prefix, as a string, or nil if current line isn't
21962 meant to be filled."
21963 (let (prefix)
21964 (catch 'exit
21965 (when (derived-mode-p 'message-mode)
21966 (save-excursion
21967 (beginning-of-line)
21968 (cond ((or (not (message-in-body-p))
21969 (looking-at orgtbl-line-start-regexp))
21970 (throw 'exit nil))
21971 ((looking-at message-cite-prefix-regexp)
21972 (throw 'exit (match-string-no-properties 0)))
21973 ((looking-at org-outline-regexp)
21974 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21975 (org-with-wide-buffer
21976 (let* ((p (line-beginning-position))
21977 (element (save-excursion (beginning-of-line)
21978 (org-element-at-point)))
21979 (type (org-element-type element))
21980 (post-affiliated (org-element-property :post-affiliated element)))
21981 (unless (and post-affiliated (< p post-affiliated))
21982 (case type
21983 (comment (looking-at "[ \t]*# ?") (match-string 0))
21984 (footnote-definition "")
21985 ((item plain-list)
21986 (make-string (org-list-item-body-column
21987 (or post-affiliated
21988 (org-element-property :begin element)))
21989 ? ))
21990 (paragraph
21991 ;; Fill prefix is usually the same as the current line,
21992 ;; except if the paragraph is at the beginning of an item.
21993 (let ((parent (org-element-property :parent element)))
21994 (cond ((eq (org-element-type parent) 'item)
21995 (make-string (org-list-item-body-column
21996 (org-element-property :begin parent))
21997 ? ))
21998 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21999 (match-string 0))
22000 (t ""))))
22001 (comment-block
22002 ;; Only fill contents if P is within block boundaries.
22003 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22004 (forward-line)
22005 (point)))
22006 (cend (save-excursion
22007 (goto-char (org-element-property :end element))
22008 (skip-chars-backward " \r\t\n")
22009 (line-beginning-position))))
22010 (when (and (>= p cbeg) (< p cend))
22011 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22012 (match-string 0)
22013 "")))))))))))
22015 (declare-function message-goto-body "message" ())
22016 (defvar message-cite-prefix-regexp) ; From message.el
22017 (defun org-fill-paragraph (&optional justify)
22018 "Fill element at point, when applicable.
22020 This function only applies to comment blocks, comments, example
22021 blocks and paragraphs. Also, as a special case, re-align table
22022 when point is at one.
22024 If JUSTIFY is non-nil (interactively, with prefix argument),
22025 justify as well. If `sentence-end-double-space' is non-nil, then
22026 period followed by one space does not end a sentence, so don't
22027 break a line there. The variable `fill-column' controls the
22028 width for filling.
22030 For convenience, when point is at a plain list, an item or
22031 a footnote definition, try to fill the first paragraph within."
22032 (interactive)
22033 (if (and (derived-mode-p 'message-mode)
22034 (or (not (message-in-body-p))
22035 (save-excursion (move-beginning-of-line 1)
22036 (looking-at message-cite-prefix-regexp))))
22037 ;; First ensure filling is correct in message-mode.
22038 (let ((fill-paragraph-function
22039 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22040 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22041 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22042 (paragraph-separate
22043 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22044 (fill-paragraph nil))
22045 (with-syntax-table org-mode-transpose-word-syntax-table
22046 ;; Move to end of line in order to get the first paragraph
22047 ;; within a plain list or a footnote definition.
22048 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22049 ;; First check if point is in a blank line at the beginning of
22050 ;; the buffer. In that case, ignore filling.
22051 (case (org-element-type element)
22052 ;; Use major mode filling function is src blocks.
22053 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22054 ;; Align Org tables, leave table.el tables as-is.
22055 (table-row (org-table-align) t)
22056 (table
22057 (when (eq (org-element-property :type element) 'org)
22058 (org-table-align))
22060 (paragraph
22061 ;; Paragraphs may contain `line-break' type objects.
22062 (let ((beg (max (point-min)
22063 (org-element-property :contents-begin element)))
22064 (end (min (point-max)
22065 (org-element-property :contents-end element))))
22066 ;; Do nothing if point is at an affiliated keyword.
22067 (if (< (line-end-position) beg) t
22068 (when (derived-mode-p 'message-mode)
22069 ;; In `message-mode', do not fill following citation
22070 ;; in current paragraph nor text before message body.
22071 (let ((body-start (save-excursion (message-goto-body))))
22072 (when body-start (setq beg (max body-start beg))))
22073 (when (save-excursion
22074 (re-search-forward
22075 (concat "^" message-cite-prefix-regexp) end t))
22076 (setq end (match-beginning 0))))
22077 ;; Fill paragraph, taking line breaks into account.
22078 ;; For that, slice the paragraph using line breaks as
22079 ;; separators, and fill the parts in reverse order to
22080 ;; avoid messing with markers.
22081 (save-excursion
22082 (goto-char end)
22083 (mapc
22084 (lambda (pos)
22085 (fill-region-as-paragraph pos (point) justify)
22086 (goto-char pos))
22087 ;; Find the list of ending positions for line breaks
22088 ;; in the current paragraph. Add paragraph
22089 ;; beginning to include first slice.
22090 (nreverse
22091 (cons beg
22092 (org-element-map
22093 (org-element--parse-objects
22094 beg end nil (org-element-restriction 'paragraph))
22095 'line-break
22096 (lambda (lb) (org-element-property :end lb)))))))
22097 t)))
22098 ;; Contents of `comment-block' type elements should be
22099 ;; filled as plain text, but only if point is within block
22100 ;; markers.
22101 (comment-block
22102 (let* ((case-fold-search t)
22103 (beg (save-excursion
22104 (goto-char (org-element-property :begin element))
22105 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22106 (forward-line)
22107 (point)))
22108 (end (save-excursion
22109 (goto-char (org-element-property :end element))
22110 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22111 (line-beginning-position))))
22112 (when (and (>= (point) beg) (< (point) end))
22113 (fill-region-as-paragraph
22114 (save-excursion
22115 (end-of-line)
22116 (re-search-backward "^[ \t]*$" beg 'move)
22117 (line-beginning-position))
22118 (save-excursion
22119 (beginning-of-line)
22120 (re-search-forward "^[ \t]*$" end 'move)
22121 (line-beginning-position))
22122 justify)))
22124 ;; Fill comments.
22125 (comment (fill-comment-paragraph justify))
22126 ;; Ignore every other element.
22127 (otherwise t))))))
22129 (defun org-auto-fill-function ()
22130 "Auto-fill function."
22131 ;; Check if auto-filling is meaningful.
22132 (let ((fc (current-fill-column)))
22133 (when (and fc (> (current-column) fc))
22134 (let* ((fill-prefix (org-adaptive-fill-function))
22135 ;; Enforce empty fill prefix, if required. Otherwise, it
22136 ;; will be computed again.
22137 (adaptive-fill-mode (not (equal fill-prefix ""))))
22138 (when fill-prefix (do-auto-fill))))))
22140 (defun org-comment-line-break-function (&optional soft)
22141 "Break line at point and indent, continuing comment if within one.
22142 The inserted newline is marked hard if variable
22143 `use-hard-newlines' is true, unless optional argument SOFT is
22144 non-nil."
22145 (if soft (insert-and-inherit ?\n) (newline 1))
22146 (save-excursion (forward-char -1) (delete-horizontal-space))
22147 (delete-horizontal-space)
22148 (indent-to-left-margin)
22149 (insert-before-markers-and-inherit fill-prefix))
22152 ;;; Comments
22154 ;; Org comments syntax is quite complex. It requires the entire line
22155 ;; to be just a comment. Also, even with the right syntax at the
22156 ;; beginning of line, some some elements (i.e. verse-block or
22157 ;; example-block) don't accept comments. Usual Emacs comment commands
22158 ;; cannot cope with those requirements. Therefore, Org replaces them.
22160 ;; Org still relies on `comment-dwim', but cannot trust
22161 ;; `comment-only-p'. So, `comment-region-function' and
22162 ;; `uncomment-region-function' both point
22163 ;; to`org-comment-or-uncomment-region'. Eventually,
22164 ;; `org-insert-comment' takes care of insertion of comments at the
22165 ;; beginning of line.
22167 ;; `org-setup-comments-handling' install comments related variables
22168 ;; during `org-mode' initialization.
22170 (defun org-setup-comments-handling ()
22171 (interactive)
22172 (org-set-local 'comment-use-syntax nil)
22173 (org-set-local 'comment-start "# ")
22174 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22175 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22176 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22177 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22179 (defun org-insert-comment ()
22180 "Insert an empty comment above current line.
22181 If the line is empty, insert comment at its beginning."
22182 (beginning-of-line)
22183 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22184 (org-indent-line)
22185 (insert "# "))
22187 (defvar comment-empty-lines) ; From newcomment.el.
22188 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22189 "Comment or uncomment each non-blank line in the region.
22190 Uncomment each non-blank line between BEG and END if it only
22191 contains commented lines. Otherwise, comment them."
22192 (save-restriction
22193 ;; Restrict region
22194 (narrow-to-region (save-excursion (goto-char beg)
22195 (skip-chars-forward " \r\t\n" end)
22196 (line-beginning-position))
22197 (save-excursion (goto-char end)
22198 (skip-chars-backward " \r\t\n" beg)
22199 (line-end-position)))
22200 (let ((uncommentp
22201 ;; UNCOMMENTP is non-nil when every non blank line between
22202 ;; BEG and END is a comment.
22203 (save-excursion
22204 (goto-char (point-min))
22205 (while (and (not (eobp))
22206 (let ((element (org-element-at-point)))
22207 (and (eq (org-element-type element) 'comment)
22208 (goto-char (min (point-max)
22209 (org-element-property
22210 :end element)))))))
22211 (eobp))))
22212 (if uncommentp
22213 ;; Only blank lines and comments in region: uncomment it.
22214 (save-excursion
22215 (goto-char (point-min))
22216 (while (not (eobp))
22217 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22218 (replace-match "" nil nil nil 1))
22219 (forward-line)))
22220 ;; Comment each line in region.
22221 (let ((min-indent (point-max)))
22222 ;; First find the minimum indentation across all lines.
22223 (save-excursion
22224 (goto-char (point-min))
22225 (while (and (not (eobp)) (not (zerop min-indent)))
22226 (unless (looking-at "[ \t]*$")
22227 (setq min-indent (min min-indent (current-indentation))))
22228 (forward-line)))
22229 ;; Then loop over all lines.
22230 (save-excursion
22231 (goto-char (point-min))
22232 (while (not (eobp))
22233 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22234 ;; Don't get fooled by invisible text (e.g. link path)
22235 ;; when moving to column MIN-INDENT.
22236 (let ((buffer-invisibility-spec nil))
22237 (org-move-to-column min-indent t))
22238 (insert comment-start))
22239 (forward-line))))))))
22242 ;;; Planning
22244 ;; This section contains tools to operate on timestamp objects, as
22245 ;; returned by, e.g. `org-element-context'.
22247 (defun org-timestamp-has-time-p (timestamp)
22248 "Non-nil when TIMESTAMP has a time specified."
22249 (org-element-property :hour-start timestamp))
22251 (defun org-timestamp-format (timestamp format &optional end utc)
22252 "Format a TIMESTAMP element into a string.
22254 FORMAT is a format specifier to be passed to
22255 `format-time-string'.
22257 When optional argument END is non-nil, use end of date-range or
22258 time-range, if possible.
22260 When optional argument UTC is non-nil, time will be expressed as
22261 Universal Time."
22262 (format-time-string
22263 format
22264 (apply 'encode-time
22265 (cons 0
22266 (mapcar
22267 (lambda (prop) (or (org-element-property prop timestamp) 0))
22268 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22269 '(:minute-start :hour-start :day-start :month-start
22270 :year-start)))))
22271 utc))
22273 (defun org-timestamp-split-range (timestamp &optional end)
22274 "Extract a timestamp object from a date or time range.
22276 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22277 the end of the range. Otherwise, extract its start.
22279 Return a new timestamp object sharing the same parent as
22280 TIMESTAMP."
22281 (let ((type (org-element-property :type timestamp)))
22282 (if (memq type '(active inactive diary)) timestamp
22283 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22284 ;; Set new type.
22285 (org-element-put-property
22286 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22287 ;; Copy start properties over end properties if END is
22288 ;; non-nil. Otherwise, copy end properties over `start' ones.
22289 (let ((p-alist '((:minute-start . :minute-end)
22290 (:hour-start . :hour-end)
22291 (:day-start . :day-end)
22292 (:month-start . :month-end)
22293 (:year-start . :year-end))))
22294 (dolist (p-cell p-alist)
22295 (org-element-put-property
22296 split-ts
22297 (funcall (if end 'car 'cdr) p-cell)
22298 (org-element-property
22299 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22300 ;; Eventually refresh `:raw-value'.
22301 (org-element-put-property split-ts :raw-value nil)
22302 (org-element-put-property
22303 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22305 (defun org-timestamp-translate (timestamp &optional boundary)
22306 "Apply `org-translate-time' on a TIMESTAMP object.
22307 When optional argument BOUNDARY is non-nil, it is either the
22308 symbol `start' or `end'. In this case, only translate the
22309 starting or ending part of TIMESTAMP if it is a date or time
22310 range. Otherwise, translate both parts."
22311 (if (and (not boundary)
22312 (memq (org-element-property :type timestamp)
22313 '(active-range inactive-range)))
22314 (concat
22315 (org-translate-time
22316 (org-element-property :raw-value
22317 (org-timestamp-split-range timestamp)))
22318 "--"
22319 (org-translate-time
22320 (org-element-property :raw-value
22321 (org-timestamp-split-range timestamp t))))
22322 (org-translate-time
22323 (org-element-property
22324 :raw-value
22325 (if (not boundary) timestamp
22326 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22330 ;;; Other stuff.
22332 (defun org-toggle-fixed-width-section (arg)
22333 "Toggle the fixed-width export.
22334 If there is no active region, the QUOTE keyword at the current headline is
22335 inserted or removed. When present, it causes the text between this headline
22336 and the next to be exported as fixed-width text, and unmodified.
22337 If there is an active region, this command adds or removes a colon as the
22338 first character of this line. If the first character of a line is a colon,
22339 this line is also exported in fixed-width font."
22340 (interactive "P")
22341 (let* ((cc 0)
22342 (regionp (org-region-active-p))
22343 (beg (if regionp (region-beginning) (point)))
22344 (end (if regionp (region-end)))
22345 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22346 (case-fold-search nil)
22347 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22348 off)
22349 (if regionp
22350 (save-excursion
22351 (goto-char beg)
22352 (setq cc (current-column))
22353 (beginning-of-line 1)
22354 (setq off (looking-at re))
22355 (while (> nlines 0)
22356 (setq nlines (1- nlines))
22357 (beginning-of-line 1)
22358 (cond
22359 (arg
22360 (org-move-to-column cc t)
22361 (insert ": \n")
22362 (forward-line -1))
22363 ((and off (looking-at re))
22364 (replace-match "" t t nil 1))
22365 ((not off) (org-move-to-column cc t) (insert ": ")))
22366 (forward-line 1)))
22367 (save-excursion
22368 (org-back-to-heading)
22369 (cond
22370 ((looking-at (format org-heading-keyword-regexp-format
22371 org-quote-string))
22372 (goto-char (match-end 1))
22373 (looking-at (concat " +" org-quote-string))
22374 (replace-match "" t t)
22375 (when (eolp) (insert " ")))
22376 ((looking-at org-outline-regexp)
22377 (goto-char (match-end 0))
22378 (insert org-quote-string " ")))))))
22380 (defun org-reftex-citation ()
22381 "Use reftex-citation to insert a citation into the buffer.
22382 This looks for a line like
22384 #+BIBLIOGRAPHY: foo plain option:-d
22386 and derives from it that foo.bib is the bibliography file relevant
22387 for this document. It then installs the necessary environment for RefTeX
22388 to work in this buffer and calls `reftex-citation' to insert a citation
22389 into the buffer.
22391 Export of such citations to both LaTeX and HTML is handled by the contributed
22392 package org-exp-bibtex by Taru Karttunen."
22393 (interactive)
22394 (let ((reftex-docstruct-symbol 'rds)
22395 (reftex-cite-format "\\cite{%l}")
22396 rds bib)
22397 (save-excursion
22398 (save-restriction
22399 (widen)
22400 (let ((case-fold-search t)
22401 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22402 (if (not (save-excursion
22403 (or (re-search-forward re nil t)
22404 (re-search-backward re nil t))))
22405 (error "No bibliography defined in file")
22406 (setq bib (concat (match-string 1) ".bib")
22407 rds (list (list 'bib bib)))))))
22408 (call-interactively 'reftex-citation)))
22410 ;;;; Functions extending outline functionality
22412 (defun org-beginning-of-line (&optional arg)
22413 "Go to the beginning of the current line. If that is invisible, continue
22414 to a visible line beginning. This makes the function of C-a more intuitive.
22415 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22416 first attempt, and only move to after the tags when the cursor is already
22417 beyond the end of the headline."
22418 (interactive "P")
22419 (let ((pos (point))
22420 (special (if (consp org-special-ctrl-a/e)
22421 (car org-special-ctrl-a/e)
22422 org-special-ctrl-a/e))
22423 refpos)
22424 (if (org-bound-and-true-p visual-line-mode)
22425 (beginning-of-visual-line 1)
22426 (beginning-of-line 1))
22427 (if (and arg (fboundp 'move-beginning-of-line))
22428 (call-interactively 'move-beginning-of-line)
22429 (if (bobp)
22431 (backward-char 1)
22432 (if (org-truely-invisible-p)
22433 (while (and (not (bobp)) (org-truely-invisible-p))
22434 (backward-char 1)
22435 (beginning-of-line 1))
22436 (forward-char 1))))
22437 (when special
22438 (cond
22439 ((and (looking-at org-complex-heading-regexp)
22440 (= (char-after (match-end 1)) ?\ ))
22441 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22442 (point-at-eol)))
22443 (goto-char
22444 (if (eq special t)
22445 (cond ((> pos refpos) refpos)
22446 ((= pos (point)) refpos)
22447 (t (point)))
22448 (cond ((> pos (point)) (point))
22449 ((not (eq last-command this-command)) (point))
22450 (t refpos)))))
22451 ((org-at-item-p)
22452 ;; Being at an item and not looking at an the item means point
22453 ;; was previously moved to beginning of a visual line, which
22454 ;; doesn't contain the item. Therefore, do nothing special,
22455 ;; just stay here.
22456 (when (looking-at org-list-full-item-re)
22457 ;; Set special position at first white space character after
22458 ;; bullet, and check-box, if any.
22459 (let ((after-bullet
22460 (let ((box (match-end 3)))
22461 (if (not box) (match-end 1)
22462 (let ((after (char-after box)))
22463 (if (and after (= after ? )) (1+ box) box))))))
22464 ;; Special case: Move point to special position when
22465 ;; currently after it or at beginning of line.
22466 (if (eq special t)
22467 (when (or (> pos after-bullet) (= (point) pos))
22468 (goto-char after-bullet))
22469 ;; Reversed case: Move point to special position when
22470 ;; point was already at beginning of line and command is
22471 ;; repeated.
22472 (when (and (= (point) pos) (eq last-command this-command))
22473 (goto-char after-bullet))))))))
22474 (org-no-warnings
22475 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22477 (defun org-end-of-line (&optional arg)
22478 "Go to the end of the line.
22479 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22480 tags on the first attempt, and only move to after the tags when
22481 the cursor is already beyond the end of the headline."
22482 (interactive "P")
22483 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22484 org-special-ctrl-a/e))
22485 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22486 'end-of-visual-line)
22487 ((fboundp 'move-end-of-line) 'move-end-of-line)
22488 (t 'end-of-line))))
22489 (if (or (not special) arg) (call-interactively move-fun)
22490 (let* ((element (save-excursion (beginning-of-line)
22491 (org-element-at-point)))
22492 (type (org-element-type element)))
22493 (cond
22494 ((memq type '(headline inlinetask))
22495 (let ((pos (point)))
22496 (beginning-of-line 1)
22497 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22498 (if (eq special t)
22499 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22500 (goto-char (match-beginning 1))
22501 (goto-char (match-end 0)))
22502 (if (or (< pos (match-end 0))
22503 (not (eq this-command last-command)))
22504 (goto-char (match-end 0))
22505 (goto-char (match-beginning 1))))
22506 (call-interactively move-fun))))
22507 ((org-element-property :hiddenp element)
22508 ;; If element is hidden, `move-end-of-line' would put point
22509 ;; after it. Use `end-of-line' to stay on current line.
22510 (call-interactively 'end-of-line))
22511 (t (call-interactively move-fun)))))
22512 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22514 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22515 (define-key org-mode-map "\C-e" 'org-end-of-line)
22517 (defun org-backward-sentence (&optional arg)
22518 "Go to beginning of sentence, or beginning of table field.
22519 This will call `backward-sentence' or `org-table-beginning-of-field',
22520 depending on context."
22521 (interactive "P")
22522 (cond
22523 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22524 (t (call-interactively 'backward-sentence))))
22526 (defun org-forward-sentence (&optional arg)
22527 "Go to end of sentence, or end of table field.
22528 This will call `forward-sentence' or `org-table-end-of-field',
22529 depending on context."
22530 (interactive "P")
22531 (cond
22532 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22533 (t (call-interactively 'forward-sentence))))
22535 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22536 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22538 (defun org-kill-line (&optional arg)
22539 "Kill line, to tags or end of line."
22540 (interactive "P")
22541 (cond
22542 ((or (not org-special-ctrl-k)
22543 (bolp)
22544 (not (org-at-heading-p)))
22545 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22546 org-ctrl-k-protect-subtree)
22547 (if (or (eq org-ctrl-k-protect-subtree 'error)
22548 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22549 (error "C-k aborted - would kill hidden subtree")))
22550 (call-interactively
22551 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22552 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22553 (kill-region (point) (match-beginning 1))
22554 (org-set-tags nil t))
22555 (t (kill-region (point) (point-at-eol)))))
22557 (define-key org-mode-map "\C-k" 'org-kill-line)
22559 (defun org-yank (&optional arg)
22560 "Yank. If the kill is a subtree, treat it specially.
22561 This command will look at the current kill and check if is a single
22562 subtree, or a series of subtrees[1]. If it passes the test, and if the
22563 cursor is at the beginning of a line or after the stars of a currently
22564 empty headline, then the yank is handled specially. How exactly depends
22565 on the value of the following variables, both set by default.
22567 org-yank-folded-subtrees
22568 When set, the subtree(s) will be folded after insertion, but only
22569 if doing so would now swallow text after the yanked text.
22571 org-yank-adjusted-subtrees
22572 When set, the subtree will be promoted or demoted in order to
22573 fit into the local outline tree structure, which means that the level
22574 will be adjusted so that it becomes the smaller one of the two
22575 *visible* surrounding headings.
22577 Any prefix to this command will cause `yank' to be called directly with
22578 no special treatment. In particular, a simple \\[universal-argument] prefix \
22579 will just
22580 plainly yank the text as it is.
22582 \[1] The test checks if the first non-white line is a heading
22583 and if there are no other headings with fewer stars."
22584 (interactive "P")
22585 (org-yank-generic 'yank arg))
22587 (defun org-yank-generic (command arg)
22588 "Perform some yank-like command.
22590 This function implements the behavior described in the `org-yank'
22591 documentation. However, it has been generalized to work for any
22592 interactive command with similar behavior."
22594 ;; pretend to be command COMMAND
22595 (setq this-command command)
22597 (if arg
22598 (call-interactively command)
22600 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22601 (and (org-kill-is-subtree-p)
22602 (or (bolp)
22603 (and (looking-at "[ \t]*$")
22604 (string-match
22605 "\\`\\*+\\'"
22606 (buffer-substring (point-at-bol) (point)))))))
22607 swallowp)
22608 (cond
22609 ((and subtreep org-yank-folded-subtrees)
22610 (let ((beg (point))
22611 end)
22612 (if (and subtreep org-yank-adjusted-subtrees)
22613 (org-paste-subtree nil nil 'for-yank)
22614 (call-interactively command))
22616 (setq end (point))
22617 (goto-char beg)
22618 (when (and (bolp) subtreep
22619 (not (setq swallowp
22620 (org-yank-folding-would-swallow-text beg end))))
22621 (org-with-limited-levels
22622 (or (looking-at org-outline-regexp)
22623 (re-search-forward org-outline-regexp-bol end t))
22624 (while (and (< (point) end) (looking-at org-outline-regexp))
22625 (hide-subtree)
22626 (org-cycle-show-empty-lines 'folded)
22627 (condition-case nil
22628 (outline-forward-same-level 1)
22629 (error (goto-char end))))))
22630 (when swallowp
22631 (message
22632 "Inserted text not folded because that would swallow text"))
22634 (goto-char end)
22635 (skip-chars-forward " \t\n\r")
22636 (beginning-of-line 1)
22637 (push-mark beg 'nomsg)))
22638 ((and subtreep org-yank-adjusted-subtrees)
22639 (let ((beg (point-at-bol)))
22640 (org-paste-subtree nil nil 'for-yank)
22641 (push-mark beg 'nomsg)))
22643 (call-interactively command))))))
22645 (defun org-yank-folding-would-swallow-text (beg end)
22646 "Would hide-subtree at BEG swallow any text after END?"
22647 (let (level)
22648 (org-with-limited-levels
22649 (save-excursion
22650 (goto-char beg)
22651 (when (or (looking-at org-outline-regexp)
22652 (re-search-forward org-outline-regexp-bol end t))
22653 (setq level (org-outline-level)))
22654 (goto-char end)
22655 (skip-chars-forward " \t\r\n\v\f")
22656 (if (or (eobp)
22657 (and (bolp) (looking-at org-outline-regexp)
22658 (<= (org-outline-level) level)))
22659 nil ; Nothing would be swallowed
22660 t))))) ; something would swallow
22662 (define-key org-mode-map "\C-y" 'org-yank)
22664 (defun org-truely-invisible-p ()
22665 "Check if point is at a character currently not visible.
22666 This version does not only check the character property, but also
22667 `visible-mode'."
22668 ;; Early versions of noutline don't have `outline-invisible-p'.
22669 (if (org-bound-and-true-p visible-mode)
22671 (outline-invisible-p)))
22673 (defun org-invisible-p2 ()
22674 "Check if point is at a character currently not visible."
22675 (save-excursion
22676 (if (and (eolp) (not (bobp))) (backward-char 1))
22677 ;; Early versions of noutline don't have `outline-invisible-p'.
22678 (outline-invisible-p)))
22680 (defun org-back-to-heading (&optional invisible-ok)
22681 "Call `outline-back-to-heading', but provide a better error message."
22682 (condition-case nil
22683 (outline-back-to-heading invisible-ok)
22684 (error (error "Before first headline at position %d in buffer %s"
22685 (point) (current-buffer)))))
22687 (defun org-before-first-heading-p ()
22688 "Before first heading?"
22689 (save-excursion
22690 (end-of-line)
22691 (null (re-search-backward org-outline-regexp-bol nil t))))
22693 (defun org-at-heading-p (&optional ignored)
22694 (outline-on-heading-p t))
22695 ;; Compatibility alias with Org versions < 7.8.03
22696 (defalias 'org-on-heading-p 'org-at-heading-p)
22698 (defun org-at-comment-p nil
22699 "Is cursor in a line starting with a # character?"
22700 (save-excursion
22701 (beginning-of-line)
22702 (looking-at "^#")))
22704 (defun org-at-drawer-p nil
22705 "Is cursor at a drawer keyword?"
22706 (save-excursion
22707 (move-beginning-of-line 1)
22708 (looking-at org-drawer-regexp)))
22710 (defun org-at-block-p nil
22711 "Is cursor at a block keyword?"
22712 (save-excursion
22713 (move-beginning-of-line 1)
22714 (looking-at org-block-regexp)))
22716 (defun org-point-at-end-of-empty-headline ()
22717 "If point is at the end of an empty headline, return t, else nil.
22718 If the heading only contains a TODO keyword, it is still still considered
22719 empty."
22720 (and (looking-at "[ \t]*$")
22721 (when org-todo-line-regexp
22722 (save-excursion
22723 (beginning-of-line 1)
22724 (let ((case-fold-search nil))
22725 (looking-at org-todo-line-regexp)
22726 (string= (match-string 3) ""))))))
22728 (defun org-at-heading-or-item-p ()
22729 (or (org-at-heading-p) (org-at-item-p)))
22731 (defun org-at-target-p ()
22732 (or (org-in-regexp org-radio-target-regexp)
22733 (org-in-regexp org-target-regexp)))
22734 ;; Compatibility alias with Org versions < 7.8.03
22735 (defalias 'org-on-target-p 'org-at-target-p)
22737 (defun org-up-heading-all (arg)
22738 "Move to the heading line of which the present line is a subheading.
22739 This function considers both visible and invisible heading lines.
22740 With argument, move up ARG levels."
22741 (if (fboundp 'outline-up-heading-all)
22742 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22743 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22745 (defun org-up-heading-safe ()
22746 "Move to the heading line of which the present line is a subheading.
22747 This version will not throw an error. It will return the level of the
22748 headline found, or nil if no higher level is found.
22750 Also, this function will be a lot faster than `outline-up-heading',
22751 because it relies on stars being the outline starters. This can really
22752 make a significant difference in outlines with very many siblings."
22753 (let (start-level re)
22754 (org-back-to-heading t)
22755 (setq start-level (funcall outline-level))
22756 (if (equal start-level 1)
22758 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22759 (if (re-search-backward re nil t)
22760 (funcall outline-level)))))
22762 (defun org-first-sibling-p ()
22763 "Is this heading the first child of its parents?"
22764 (interactive)
22765 (let ((re org-outline-regexp-bol)
22766 level l)
22767 (unless (org-at-heading-p t)
22768 (error "Not at a heading"))
22769 (setq level (funcall outline-level))
22770 (save-excursion
22771 (if (not (re-search-backward re nil t))
22773 (setq l (funcall outline-level))
22774 (< l level)))))
22776 (defun org-goto-sibling (&optional previous)
22777 "Goto the next sibling, even if it is invisible.
22778 When PREVIOUS is set, go to the previous sibling instead. Returns t
22779 when a sibling was found. When none is found, return nil and don't
22780 move point."
22781 (let ((fun (if previous 're-search-backward 're-search-forward))
22782 (pos (point))
22783 (re org-outline-regexp-bol)
22784 level l)
22785 (when (condition-case nil (org-back-to-heading t) (error nil))
22786 (setq level (funcall outline-level))
22787 (catch 'exit
22788 (or previous (forward-char 1))
22789 (while (funcall fun re nil t)
22790 (setq l (funcall outline-level))
22791 (when (< l level) (goto-char pos) (throw 'exit nil))
22792 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22793 (goto-char pos)
22794 nil))))
22796 (defun org-show-siblings ()
22797 "Show all siblings of the current headline."
22798 (save-excursion
22799 (while (org-goto-sibling) (org-flag-heading nil)))
22800 (save-excursion
22801 (while (org-goto-sibling 'previous)
22802 (org-flag-heading nil))))
22804 (defun org-goto-first-child ()
22805 "Goto the first child, even if it is invisible.
22806 Return t when a child was found. Otherwise don't move point and
22807 return nil."
22808 (let (level (pos (point)) (re org-outline-regexp-bol))
22809 (when (condition-case nil (org-back-to-heading t) (error nil))
22810 (setq level (outline-level))
22811 (forward-char 1)
22812 (if (and (re-search-forward re nil t) (> (outline-level) level))
22813 (progn (goto-char (match-beginning 0)) t)
22814 (goto-char pos) nil))))
22816 (defun org-show-hidden-entry ()
22817 "Show an entry where even the heading is hidden."
22818 (save-excursion
22819 (org-show-entry)))
22821 (defun org-flag-heading (flag &optional entry)
22822 "Flag the current heading. FLAG non-nil means make invisible.
22823 When ENTRY is non-nil, show the entire entry."
22824 (save-excursion
22825 (org-back-to-heading t)
22826 ;; Check if we should show the entire entry
22827 (if entry
22828 (progn
22829 (org-show-entry)
22830 (save-excursion
22831 (and (outline-next-heading)
22832 (org-flag-heading nil))))
22833 (outline-flag-region (max (point-min) (1- (point)))
22834 (save-excursion (outline-end-of-heading) (point))
22835 flag))))
22837 (defun org-get-next-sibling ()
22838 "Move to next heading of the same level, and return point.
22839 If there is no such heading, return nil.
22840 This is like outline-next-sibling, but invisible headings are ok."
22841 (let ((level (funcall outline-level)))
22842 (outline-next-heading)
22843 (while (and (not (eobp)) (> (funcall outline-level) level))
22844 (outline-next-heading))
22845 (if (or (eobp) (< (funcall outline-level) level))
22847 (point))))
22849 (defun org-get-last-sibling ()
22850 "Move to previous heading of the same level, and return point.
22851 If there is no such heading, return nil."
22852 (let ((opoint (point))
22853 (level (funcall outline-level)))
22854 (outline-previous-heading)
22855 (when (and (/= (point) opoint) (outline-on-heading-p t))
22856 (while (and (> (funcall outline-level) level)
22857 (not (bobp)))
22858 (outline-previous-heading))
22859 (if (< (funcall outline-level) level)
22861 (point)))))
22863 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22864 "Goto to the end of a subtree."
22865 ;; This contains an exact copy of the original function, but it uses
22866 ;; `org-back-to-heading', to make it work also in invisible
22867 ;; trees. And is uses an invisible-ok argument.
22868 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22869 ;; Furthermore, when used inside Org, finding the end of a large subtree
22870 ;; with many children and grandchildren etc, this can be much faster
22871 ;; than the outline version.
22872 (org-back-to-heading invisible-ok)
22873 (let ((first t)
22874 (level (funcall outline-level)))
22875 (if (and (derived-mode-p 'org-mode) (< level 1000))
22876 ;; A true heading (not a plain list item), in Org-mode
22877 ;; This means we can easily find the end by looking
22878 ;; only for the right number of stars. Using a regexp to do
22879 ;; this is so much faster than using a Lisp loop.
22880 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22881 (forward-char 1)
22882 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22883 ;; something else, do it the slow way
22884 (while (and (not (eobp))
22885 (or first (> (funcall outline-level) level)))
22886 (setq first nil)
22887 (outline-next-heading)))
22888 (unless to-heading
22889 (if (memq (preceding-char) '(?\n ?\^M))
22890 (progn
22891 ;; Go to end of line before heading
22892 (forward-char -1)
22893 (if (memq (preceding-char) '(?\n ?\^M))
22894 ;; leave blank line before heading
22895 (forward-char -1))))))
22896 (point))
22898 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22899 "Use Org version in org-mode, for dramatic speed-up."
22900 (if (derived-mode-p 'org-mode)
22901 (progn
22902 (org-end-of-subtree nil t)
22903 (unless (eobp) (backward-char 1)))
22904 ad-do-it))
22906 (defun org-end-of-meta-data-and-drawers ()
22907 "Jump to the first text after meta data and drawers in the current entry.
22908 This will move over empty lines, lines with planning time stamps,
22909 clocking lines, and drawers."
22910 (org-back-to-heading t)
22911 (let ((end (save-excursion (outline-next-heading) (point)))
22912 (re (concat "\\(" org-drawer-regexp "\\)"
22913 "\\|" "[ \t]*" org-keyword-time-regexp)))
22914 (forward-line 1)
22915 (while (re-search-forward re end t)
22916 (if (not (match-end 1))
22917 ;; empty or planning line
22918 (forward-line 1)
22919 ;; a drawer, find the end
22920 (re-search-forward "^[ \t]*:END:" end 'move)
22921 (forward-line 1)))
22922 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22923 (point)))
22925 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22926 "Move forward to the ARG'th subheading at same level as this one.
22927 Stop at the first and last subheadings of a superior heading.
22928 Normally this only looks at visible headings, but when INVISIBLE-OK is
22929 non-nil it will also look at invisible ones."
22930 (interactive "p")
22931 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22932 (if (and arg (< arg 0))
22933 (goto-char (point-min))
22934 (outline-next-heading))
22935 (org-at-heading-p)
22936 (let ((level (- (match-end 0) (match-beginning 0) 1))
22937 (f (if (and arg (< arg 0))
22938 're-search-backward
22939 're-search-forward))
22940 (count (if arg (abs arg) 1))
22941 (result (point)))
22942 (forward-char (if (and arg (< arg 0)) -1 1))
22943 (while (and (> count 0)
22944 (funcall f org-outline-regexp-bol nil 'move))
22945 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22946 (cond ((< l level) (setq count 0))
22947 ((and (= l level)
22948 (or invisible-ok
22949 (progn
22950 (goto-char (line-beginning-position))
22951 (not (outline-invisible-p)))))
22952 (setq count (1- count))
22953 (when (eq l level)
22954 (setq result (point)))))))
22955 (goto-char result))
22956 (beginning-of-line 1)))
22958 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22959 "Move backward to the ARG'th subheading at same level as this one.
22960 Stop at the first and last subheadings of a superior heading."
22961 (interactive "p")
22962 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22964 (defun org-next-block (arg &optional backward block-regexp)
22965 "Jump to the next block.
22966 With a prefix argument ARG, jump forward ARG many source blocks.
22967 When BACKWARD is non-nil, jump to the previous block.
22968 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22969 (interactive "p")
22970 (let ((re (or block-regexp org-block-regexp))
22971 (re-search-fn (or (and backward 're-search-backward)
22972 're-search-forward)))
22973 (if (looking-at re) (forward-char 1))
22974 (condition-case nil
22975 (funcall re-search-fn re nil nil arg)
22976 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22977 (goto-char (match-beginning 0)) (org-show-context)))
22979 (defun org-previous-block (arg &optional block-regexp)
22980 "Jump to the previous block.
22981 With a prefix argument ARG, jump backward ARG many source blocks.
22982 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22983 (interactive "p")
22984 (org-next-block arg t block-regexp))
22986 (defun org-forward-element ()
22987 "Move forward by one element.
22988 Move to the next element at the same level, when possible."
22989 (interactive)
22990 (cond ((eobp) (user-error "Cannot move further down"))
22991 ((org-with-limited-levels (org-at-heading-p))
22992 (let ((origin (point)))
22993 (goto-char (org-end-of-subtree nil t))
22994 (unless (org-with-limited-levels (org-at-heading-p))
22995 (goto-char origin)
22996 (user-error "Cannot move further down"))))
22998 (let* ((elem (org-element-at-point))
22999 (end (org-element-property :end elem))
23000 (parent (org-element-property :parent elem)))
23001 (if (and parent (= (org-element-property :contents-end parent) end))
23002 (goto-char (org-element-property :end parent))
23003 (goto-char end))))))
23005 (defun org-backward-element ()
23006 "Move backward by one element.
23007 Move to the previous element at the same level, when possible."
23008 (interactive)
23009 (cond ((bobp) (user-error "Cannot move further up"))
23010 ((org-with-limited-levels (org-at-heading-p))
23011 ;; At a headline, move to the previous one, if any, or stay
23012 ;; here.
23013 (let ((origin (point)))
23014 (org-with-limited-levels (org-backward-heading-same-level 1))
23015 ;; When current headline has no sibling above, move to its
23016 ;; parent.
23017 (when (= (point) origin)
23018 (or (org-with-limited-levels (org-up-heading-safe))
23019 (progn (goto-char origin)
23020 (user-error "Cannot move further up"))))))
23022 (let* ((trail (org-element-at-point 'keep-trail))
23023 (elem (car trail))
23024 (prev-elem (nth 1 trail))
23025 (beg (org-element-property :begin elem)))
23026 (cond
23027 ;; Move to beginning of current element if point isn't
23028 ;; there already.
23029 ((/= (point) beg) (goto-char beg))
23030 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23031 ((org-before-first-heading-p) (goto-char (point-min)))
23032 (t (org-back-to-heading)))))))
23034 (defun org-up-element ()
23035 "Move to upper element."
23036 (interactive)
23037 (if (org-with-limited-levels (org-at-heading-p))
23038 (unless (org-up-heading-safe) (error "No surrounding element"))
23039 (let* ((elem (org-element-at-point))
23040 (parent (org-element-property :parent elem)))
23041 (if parent (goto-char (org-element-property :begin parent))
23042 (if (org-with-limited-levels (org-before-first-heading-p))
23043 (error "No surrounding element")
23044 (org-with-limited-levels (org-back-to-heading)))))))
23046 (defvar org-element-greater-elements)
23047 (defun org-down-element ()
23048 "Move to inner element."
23049 (interactive)
23050 (let ((element (org-element-at-point)))
23051 (cond
23052 ((memq (org-element-type element) '(plain-list table))
23053 (goto-char (org-element-property :contents-begin element))
23054 (forward-char))
23055 ((memq (org-element-type element) org-element-greater-elements)
23056 ;; If contents are hidden, first disclose them.
23057 (when (org-element-property :hiddenp element) (org-cycle))
23058 (goto-char (or (org-element-property :contents-begin element)
23059 (error "No content for this element"))))
23060 (t (error "No inner element")))))
23062 (defun org-drag-element-backward ()
23063 "Move backward element at point."
23064 (interactive)
23065 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23066 (let* ((trail (org-element-at-point 'keep-trail))
23067 (elem (car trail))
23068 (prev-elem (nth 1 trail)))
23069 ;; Error out if no previous element or previous element is
23070 ;; a parent of the current one.
23071 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23072 (error "Cannot drag element backward")
23073 (let ((pos (point)))
23074 (org-element-swap-A-B prev-elem elem)
23075 (goto-char (+ (org-element-property :begin prev-elem)
23076 (- pos (org-element-property :begin elem)))))))))
23078 (defun org-drag-element-forward ()
23079 "Move forward element at point."
23080 (interactive)
23081 (let* ((pos (point))
23082 (elem (org-element-at-point)))
23083 (when (= (point-max) (org-element-property :end elem))
23084 (error "Cannot drag element forward"))
23085 (goto-char (org-element-property :end elem))
23086 (let ((next-elem (org-element-at-point)))
23087 (when (or (org-element-nested-p elem next-elem)
23088 (and (eq (org-element-type next-elem) 'headline)
23089 (not (eq (org-element-type elem) 'headline))))
23090 (goto-char pos)
23091 (error "Cannot drag element forward"))
23092 ;; Compute new position of point: it's shifted by NEXT-ELEM
23093 ;; body's length (without final blanks) and by the length of
23094 ;; blanks between ELEM and NEXT-ELEM.
23095 (let ((size-next (- (save-excursion
23096 (goto-char (org-element-property :end next-elem))
23097 (skip-chars-backward " \r\t\n")
23098 (forward-line)
23099 ;; Small correction if buffer doesn't end
23100 ;; with a newline character.
23101 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23102 (org-element-property :begin next-elem)))
23103 (size-blank (- (org-element-property :end elem)
23104 (save-excursion
23105 (goto-char (org-element-property :end elem))
23106 (skip-chars-backward " \r\t\n")
23107 (forward-line)
23108 (point)))))
23109 (org-element-swap-A-B elem next-elem)
23110 (goto-char (+ pos size-next size-blank))))))
23112 (defun org-drag-line-forward (arg)
23113 "Drag the line at point ARG lines forward."
23114 (interactive "p")
23115 (dotimes (n (abs arg))
23116 (let ((c (current-column)))
23117 (if (< 0 arg)
23118 (progn
23119 (beginning-of-line 2)
23120 (transpose-lines 1)
23121 (beginning-of-line 0))
23122 (transpose-lines 1)
23123 (beginning-of-line -1))
23124 (org-move-to-column c))))
23126 (defun org-drag-line-backward (arg)
23127 "Drag the line at point ARG lines backward."
23128 (interactive "p")
23129 (org-drag-line-forward (- arg)))
23131 (defun org-mark-element ()
23132 "Put point at beginning of this element, mark at end.
23134 Interactively, if this command is repeated or (in Transient Mark
23135 mode) if the mark is active, it marks the next element after the
23136 ones already marked."
23137 (interactive)
23138 (let (deactivate-mark)
23139 (if (and (org-called-interactively-p 'any)
23140 (or (and (eq last-command this-command) (mark t))
23141 (and transient-mark-mode mark-active)))
23142 (set-mark
23143 (save-excursion
23144 (goto-char (mark))
23145 (goto-char (org-element-property :end (org-element-at-point)))))
23146 (let ((element (org-element-at-point)))
23147 (end-of-line)
23148 (push-mark (org-element-property :end element) t t)
23149 (goto-char (org-element-property :begin element))))))
23151 (defun org-narrow-to-element ()
23152 "Narrow buffer to current element."
23153 (interactive)
23154 (let ((elem (org-element-at-point)))
23155 (cond
23156 ((eq (car elem) 'headline)
23157 (narrow-to-region
23158 (org-element-property :begin elem)
23159 (org-element-property :end elem)))
23160 ((memq (car elem) org-element-greater-elements)
23161 (narrow-to-region
23162 (org-element-property :contents-begin elem)
23163 (org-element-property :contents-end elem)))
23165 (narrow-to-region
23166 (org-element-property :begin elem)
23167 (org-element-property :end elem))))))
23169 (defun org-transpose-element ()
23170 "Transpose current and previous elements, keeping blank lines between.
23171 Point is moved after both elements."
23172 (interactive)
23173 (org-skip-whitespace)
23174 (let ((end (org-element-property :end (org-element-at-point))))
23175 (org-drag-element-backward)
23176 (goto-char end)))
23178 (defun org-unindent-buffer ()
23179 "Un-indent the visible part of the buffer.
23180 Relative indentation (between items, inside blocks, etc.) isn't
23181 modified."
23182 (interactive)
23183 (unless (eq major-mode 'org-mode)
23184 (error "Cannot un-indent a buffer not in Org mode"))
23185 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23186 unindent-tree ; For byte-compiler.
23187 (unindent-tree
23188 (function
23189 (lambda (contents)
23190 (mapc
23191 (lambda (element)
23192 (if (memq (org-element-type element) '(headline section))
23193 (funcall unindent-tree (org-element-contents element))
23194 (save-excursion
23195 (save-restriction
23196 (narrow-to-region
23197 (org-element-property :begin element)
23198 (org-element-property :end element))
23199 (org-do-remove-indentation)))))
23200 (reverse contents))))))
23201 (funcall unindent-tree (org-element-contents parse-tree))))
23203 (defun org-show-subtree ()
23204 "Show everything after this heading at deeper levels."
23205 (interactive)
23206 (outline-flag-region
23207 (point)
23208 (save-excursion
23209 (org-end-of-subtree t t))
23210 nil))
23212 (defun org-show-entry ()
23213 "Show the body directly following this heading.
23214 Show the heading too, if it is currently invisible."
23215 (interactive)
23216 (save-excursion
23217 (condition-case nil
23218 (progn
23219 (org-back-to-heading t)
23220 (outline-flag-region
23221 (max (point-min) (1- (point)))
23222 (save-excursion
23223 (if (re-search-forward
23224 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23225 (match-beginning 1)
23226 (point-max)))
23227 nil)
23228 (org-cycle-hide-drawers 'children))
23229 (error nil))))
23231 (defun org-make-options-regexp (kwds &optional extra)
23232 "Make a regular expression for keyword lines."
23233 (concat
23234 "^#\\+\\("
23235 (mapconcat 'regexp-quote kwds "\\|")
23236 (if extra (concat "\\|" extra))
23237 "\\):[ \t]*\\(.*\\)"))
23239 ;; Make isearch reveal the necessary context
23240 (defun org-isearch-end ()
23241 "Reveal context after isearch exits."
23242 (when isearch-success ; only if search was successful
23243 (if (featurep 'xemacs)
23244 ;; Under XEmacs, the hook is run in the correct place,
23245 ;; we directly show the context.
23246 (org-show-context 'isearch)
23247 ;; In Emacs the hook runs *before* restoring the overlays.
23248 ;; So we have to use a one-time post-command-hook to do this.
23249 ;; (Emacs 22 has a special variable, see function `org-mode')
23250 (unless (and (boundp 'isearch-mode-end-hook-quit)
23251 isearch-mode-end-hook-quit)
23252 ;; Only when the isearch was not quitted.
23253 (org-add-hook 'post-command-hook 'org-isearch-post-command
23254 'append 'local)))
23255 (org-fix-ellipsis-at-bol)))
23257 (defun org-isearch-post-command ()
23258 "Remove self from hook, and show context."
23259 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23260 (org-show-context 'isearch))
23263 ;;;; Integration with and fixes for other packages
23265 ;;; Imenu support
23267 (defvar org-imenu-markers nil
23268 "All markers currently used by Imenu.")
23269 (make-variable-buffer-local 'org-imenu-markers)
23271 (defun org-imenu-new-marker (&optional pos)
23272 "Return a new marker for use by Imenu, and remember the marker."
23273 (let ((m (make-marker)))
23274 (move-marker m (or pos (point)))
23275 (push m org-imenu-markers)
23278 (defun org-imenu-get-tree ()
23279 "Produce the index for Imenu."
23280 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23281 (setq org-imenu-markers nil)
23282 (let* ((n org-imenu-depth)
23283 (re (concat "^" (org-get-limited-outline-regexp)))
23284 (subs (make-vector (1+ n) nil))
23285 (last-level 0)
23286 m level head0 head)
23287 (save-excursion
23288 (save-restriction
23289 (widen)
23290 (goto-char (point-max))
23291 (while (re-search-backward re nil t)
23292 (setq level (org-reduced-level (funcall outline-level)))
23293 (when (and (<= level n)
23294 (looking-at org-complex-heading-regexp)
23295 (setq head0 (org-match-string-no-properties 4)))
23296 (setq head (org-link-display-format head0)
23297 m (org-imenu-new-marker))
23298 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23299 (if (>= level last-level)
23300 (push (cons head m) (aref subs level))
23301 (push (cons head (aref subs (1+ level))) (aref subs level))
23302 (loop for i from (1+ level) to n do (aset subs i nil)))
23303 (setq last-level level)))))
23304 (aref subs 1)))
23306 (eval-after-load "imenu"
23307 '(progn
23308 (add-hook 'imenu-after-jump-hook
23309 (lambda ()
23310 (if (derived-mode-p 'org-mode)
23311 (org-show-context 'org-goto))))))
23313 (defun org-link-display-format (link)
23314 "Replace a link with its the description.
23315 If there is no description, use the link target."
23316 (save-match-data
23317 (if (string-match org-bracket-link-analytic-regexp link)
23318 (replace-match (if (match-end 5)
23319 (match-string 5 link)
23320 (concat (match-string 1 link)
23321 (match-string 3 link)))
23322 nil t link)
23323 link)))
23325 (defun org-toggle-link-display ()
23326 "Toggle the literal or descriptive display of links."
23327 (interactive)
23328 (if org-descriptive-links
23329 (progn (org-remove-from-invisibility-spec '(org-link))
23330 (org-restart-font-lock)
23331 (setq org-descriptive-links nil))
23332 (progn (add-to-invisibility-spec '(org-link))
23333 (org-restart-font-lock)
23334 (setq org-descriptive-links t))))
23336 ;; Speedbar support
23338 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23339 "Overlay marking the agenda restriction line in speedbar.")
23340 (overlay-put org-speedbar-restriction-lock-overlay
23341 'face 'org-agenda-restriction-lock)
23342 (overlay-put org-speedbar-restriction-lock-overlay
23343 'help-echo "Agendas are currently limited to this item.")
23344 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23346 (defun org-speedbar-set-agenda-restriction ()
23347 "Restrict future agenda commands to the location at point in speedbar.
23348 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23349 (interactive)
23350 (require 'org-agenda)
23351 (let (p m tp np dir txt)
23352 (cond
23353 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23354 'org-imenu t))
23355 (setq m (get-text-property p 'org-imenu-marker))
23356 (with-current-buffer (marker-buffer m)
23357 (goto-char m)
23358 (org-agenda-set-restriction-lock 'subtree)))
23359 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23360 'speedbar-function 'speedbar-find-file))
23361 (setq tp (previous-single-property-change
23362 (1+ p) 'speedbar-function)
23363 np (next-single-property-change
23364 tp 'speedbar-function)
23365 dir (speedbar-line-directory)
23366 txt (buffer-substring-no-properties (or tp (point-min))
23367 (or np (point-max))))
23368 (with-current-buffer (find-file-noselect
23369 (let ((default-directory dir))
23370 (expand-file-name txt)))
23371 (unless (derived-mode-p 'org-mode)
23372 (error "Cannot restrict to non-Org-mode file"))
23373 (org-agenda-set-restriction-lock 'file)))
23374 (t (error "Don't know how to restrict Org-mode's agenda")))
23375 (move-overlay org-speedbar-restriction-lock-overlay
23376 (point-at-bol) (point-at-eol))
23377 (setq current-prefix-arg nil)
23378 (org-agenda-maybe-redo)))
23380 (eval-after-load "speedbar"
23381 '(progn
23382 (speedbar-add-supported-extension ".org")
23383 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23384 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23385 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23386 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23387 (add-hook 'speedbar-visiting-tag-hook
23388 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23390 ;;; Fixes and Hacks for problems with other packages
23392 ;; Make flyspell not check words in links, to not mess up our keymap
23393 (defvar org-element-affiliated-keywords) ; From org-element.el
23394 (defvar org-element-block-name-alist) ; From org-element.el
23395 (defun org-mode-flyspell-verify ()
23396 "Don't let flyspell put overlays at active buttons, or on
23397 {todo,all-time,additional-option-like}-keywords."
23398 (require 'org-element) ; For `org-element-affiliated-keywords'
23399 (let ((pos (max (1- (point)) (point-min)))
23400 (word (thing-at-point 'word)))
23401 (and (not (get-text-property pos 'keymap))
23402 (not (get-text-property pos 'org-no-flyspell))
23403 (not (member word org-todo-keywords-1))
23404 (not (member word org-all-time-keywords))
23405 (not (member word org-options-keywords))
23406 (not (member word (mapcar 'car org-startup-options)))
23407 (not (member-ignore-case word org-element-affiliated-keywords))
23408 (not (member-ignore-case word (org-get-export-keywords)))
23409 (not (member-ignore-case
23410 word (mapcar 'car org-element-block-name-alist)))
23411 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23413 (defun org-remove-flyspell-overlays-in (beg end)
23414 "Remove flyspell overlays in region."
23415 (and (org-bound-and-true-p flyspell-mode)
23416 (fboundp 'flyspell-delete-region-overlays)
23417 (flyspell-delete-region-overlays beg end))
23418 (add-text-properties beg end '(org-no-flyspell t)))
23420 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23421 (eval-after-load "bookmark"
23422 '(if (boundp 'bookmark-after-jump-hook)
23423 ;; We can use the hook
23424 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23425 ;; Hook not available, use advice
23426 (defadvice bookmark-jump (after org-make-visible activate)
23427 "Make the position visible."
23428 (org-bookmark-jump-unhide))))
23430 ;; Make sure saveplace shows the location if it was hidden
23431 (eval-after-load "saveplace"
23432 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23433 "Make the position visible."
23434 (org-bookmark-jump-unhide)))
23436 ;; Make sure ecb shows the location if it was hidden
23437 (eval-after-load "ecb"
23438 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23439 "Make hierarchy visible when jumping into location from ECB tree buffer."
23440 (if (derived-mode-p 'org-mode)
23441 (org-show-context))))
23443 (defun org-bookmark-jump-unhide ()
23444 "Unhide the current position, to show the bookmark location."
23445 (and (derived-mode-p 'org-mode)
23446 (or (outline-invisible-p)
23447 (save-excursion (goto-char (max (point-min) (1- (point))))
23448 (outline-invisible-p)))
23449 (org-show-context 'bookmark-jump)))
23451 ;; Make session.el ignore our circular variable
23452 (eval-after-load "session"
23453 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23455 ;;;; Experimental code
23457 (defun org-closed-in-range ()
23458 "Sparse tree of items closed in a certain time range.
23459 Still experimental, may disappear in the future."
23460 (interactive)
23461 ;; Get the time interval from the user.
23462 (let* ((time1 (org-float-time
23463 (org-read-date nil 'to-time nil "Starting date: ")))
23464 (time2 (org-float-time
23465 (org-read-date nil 'to-time nil "End date:")))
23466 ;; callback function
23467 (callback (lambda ()
23468 (let ((time
23469 (org-float-time
23470 (apply 'encode-time
23471 (org-parse-time-string
23472 (match-string 1))))))
23473 ;; check if time in interval
23474 (and (>= time time1) (<= time time2))))))
23475 ;; make tree, check each match with the callback
23476 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23478 ;;;; Finish up
23480 (provide 'org)
23482 (run-hooks 'org-load-hook)
23484 ;;; org.el ends here