Revert "org-capture.el (org-capture): Don't store multiple links over lines in the...
[org-mode.git] / lisp / org.el
blobb354b0f66d2ca482a3571c78b1853911134e2247
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)
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 A triple prefix arg force storing a link for each line in the
9299 active region."
9300 (interactive "P")
9301 (org-load-modules-maybe)
9302 (if (and (equal arg '(64)) (org-region-active-p))
9303 (save-excursion
9304 (let ((end (region-end)))
9305 (goto-char (region-beginning))
9306 (set-mark (point))
9307 (while (< (point-at-eol) end)
9308 (move-end-of-line 1) (activate-mark)
9309 (let (current-prefix-arg)
9310 (call-interactively 'org-store-link))
9311 (move-beginning-of-line 2)
9312 (set-mark (point)))))
9313 (org-with-limited-levels
9314 (setq org-store-link-plist nil)
9315 (let (link cpltxt desc description search
9316 txt custom-id agenda-link sfuns sfunsn)
9317 (cond
9319 ;; Store a link using an external link type
9320 ((and (not (equal arg '(16)))
9321 (setq sfuns
9322 (delq
9323 nil (mapcar (lambda (f)
9324 (let (fs) (if (funcall f) (push f fs))))
9325 org-store-link-functions))
9326 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9327 (or (and (cdr sfuns)
9328 (funcall (intern
9329 (completing-read
9330 "Which function for creating the link? "
9331 sfunsn t (car sfunsn)))))
9332 (funcall (caar sfuns)))
9333 (setq link (plist-get org-store-link-plist :link)
9334 desc (or (plist-get org-store-link-plist
9335 :description) link))))
9337 ;; Store a link from a source code buffer
9338 ((org-src-edit-buffer-p)
9339 (let (label gc)
9340 (while (or (not label)
9341 (save-excursion
9342 (save-restriction
9343 (widen)
9344 (goto-char (point-min))
9345 (re-search-forward
9346 (regexp-quote (format org-coderef-label-format label))
9347 nil t))))
9348 (when label (message "Label exists already") (sit-for 2))
9349 (setq label (read-string "Code line label: " label)))
9350 (end-of-line 1)
9351 (setq link (format org-coderef-label-format label))
9352 (setq gc (- 79 (length link)))
9353 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9354 (insert link)
9355 (setq link (concat "(" label ")") desc nil)))
9357 ;; We are in the agenda, link to referenced location
9358 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9359 (let ((m (or (get-text-property (point) 'org-hd-marker)
9360 (get-text-property (point) 'org-marker))))
9361 (when m
9362 (org-with-point-at m
9363 (setq agenda-link
9364 (if (org-called-interactively-p 'any)
9365 (call-interactively 'org-store-link)
9366 (org-store-link nil)))))))
9368 ((eq major-mode 'calendar-mode)
9369 (let ((cd (calendar-cursor-to-date)))
9370 (setq link
9371 (format-time-string
9372 (car org-time-stamp-formats)
9373 (apply 'encode-time
9374 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9375 nil nil nil))))
9376 (org-store-link-props :type "calendar" :date cd)))
9378 ((eq major-mode 'help-mode)
9379 (setq link (concat "help:" (save-excursion
9380 (goto-char (point-min))
9381 (looking-at "^[^ ]+")
9382 (match-string 0))))
9383 (org-store-link-props :type "help"))
9385 ((eq major-mode 'w3-mode)
9386 (setq cpltxt (if (and (buffer-name)
9387 (not (string-match "Untitled" (buffer-name))))
9388 (buffer-name)
9389 (url-view-url t))
9390 link (url-view-url t))
9391 (org-store-link-props :type "w3" :url (url-view-url t)))
9393 ((eq major-mode 'image-mode)
9394 (setq cpltxt (concat "file:"
9395 (abbreviate-file-name buffer-file-name))
9396 link cpltxt)
9397 (org-store-link-props :type "image" :file buffer-file-name))
9399 ;; In dired, store a link to the file of the current line
9400 ((eq major-mode 'dired-mode)
9401 (let ((file (dired-get-filename nil t)))
9402 (setq file (if file
9403 (abbreviate-file-name
9404 (expand-file-name (dired-get-filename nil t)))
9405 ;; otherwise, no file so use current directory.
9406 default-directory))
9407 (setq cpltxt (concat "file:" file)
9408 link cpltxt)))
9410 ((setq search (run-hook-with-args-until-success
9411 'org-create-file-search-functions))
9412 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9413 "::" search))
9414 (setq cpltxt (or description link)))
9416 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9417 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9418 (cond
9419 ;; Store a link using the radio target at point
9420 ((org-in-regexp "<<\\(.*?\\)>>")
9421 (setq cpltxt
9422 (concat "file:"
9423 (abbreviate-file-name
9424 (buffer-file-name (buffer-base-buffer)))
9425 "::" (match-string 1))
9426 link cpltxt))
9427 ((and (featurep 'org-id)
9428 (or (eq org-id-link-to-org-use-id t)
9429 (and (org-called-interactively-p 'any)
9430 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9431 (and (eq org-id-link-to-org-use-id
9432 'create-if-interactive-and-no-custom-id)
9433 (not custom-id))))
9434 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9435 ;; Store a link using the ID at point
9436 (setq link (condition-case nil
9437 (prog1 (org-id-store-link)
9438 (setq desc (plist-get org-store-link-plist
9439 :description)))
9440 (error
9441 ;; Probably before first headline, link only to file
9442 (concat "file:"
9443 (abbreviate-file-name
9444 (buffer-file-name (buffer-base-buffer))))))))
9446 ;; Just link to current headline
9447 (setq cpltxt (concat "file:"
9448 (abbreviate-file-name
9449 (buffer-file-name (buffer-base-buffer)))))
9450 ;; Add a context search string
9451 (when (org-xor org-context-in-file-links arg)
9452 (let* ((ee (org-element-at-point))
9453 (et (org-element-type ee))
9454 (ev (plist-get (cadr ee) :value))
9455 (ek (plist-get (cadr ee) :key))
9456 (eok (and (stringp ek) (string-match "name\\|target" ek))))
9457 (setq txt (cond
9458 ((org-at-heading-p) nil)
9459 ((and (eq et 'keyword) eok) ev)
9460 ((org-region-active-p)
9461 (buffer-substring (region-beginning) (region-end)))))
9462 (when (or (null txt) (string-match "\\S-" txt))
9463 (setq cpltxt
9464 (concat cpltxt "::"
9465 (condition-case nil
9466 (org-make-org-heading-search-string txt)
9467 (error "")))
9468 desc (or (and (eq et 'keyword) eok ev)
9469 (nth 4 (ignore-errors (org-heading-components)))
9470 "NONE")))))
9471 (if (string-match "::\\'" cpltxt)
9472 (setq cpltxt (substring cpltxt 0 -2)))
9473 (setq link cpltxt))))
9475 ((buffer-file-name (buffer-base-buffer))
9476 ;; Just link to this file here.
9477 (setq cpltxt (concat "file:"
9478 (abbreviate-file-name
9479 (buffer-file-name (buffer-base-buffer)))))
9480 ;; Add a context string.
9481 (when (org-xor org-context-in-file-links arg)
9482 (setq txt (if (org-region-active-p)
9483 (buffer-substring (region-beginning) (region-end))
9484 (buffer-substring (point-at-bol) (point-at-eol))))
9485 ;; Only use search option if there is some text.
9486 (when (string-match "\\S-" txt)
9487 (setq cpltxt
9488 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9489 desc "NONE")))
9490 (setq link cpltxt))
9492 ((org-called-interactively-p 'interactive)
9493 (user-error "No method for storing a link from this buffer"))
9495 (t (setq link nil)))
9497 ;; We're done setting link and desc, clean up
9498 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9499 (setq link (or link cpltxt)
9500 desc (or desc cpltxt))
9501 (cond ((equal desc "NONE") (setq desc nil))
9502 ((string-match org-bracket-link-regexp desc)
9503 (setq desc
9504 (replace-regexp-in-string
9505 org-bracket-link-regexp
9506 (concat "\\3" (if (equal (length (match-string 0 desc))
9507 (length desc)) "*" "")) desc))))
9509 ;; Return the link
9510 (if (not (and (or (org-called-interactively-p 'any)
9511 executing-kbd-macro) link))
9512 (or agenda-link (and link (org-make-link-string link desc)))
9513 (push (list link desc) org-stored-links)
9514 (message "Stored: %s" (or desc link))
9515 (when custom-id
9516 (setq link (concat "file:" (abbreviate-file-name
9517 (buffer-file-name)) "::#" custom-id))
9518 (push (list link desc) org-stored-links)))))))
9520 (defun org-store-link-props (&rest plist)
9521 "Store link properties, extract names and addresses."
9522 (let (x adr)
9523 (when (setq x (plist-get plist :from))
9524 (setq adr (mail-extract-address-components x))
9525 (setq plist (plist-put plist :fromname (car adr)))
9526 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9527 (when (setq x (plist-get plist :to))
9528 (setq adr (mail-extract-address-components x))
9529 (setq plist (plist-put plist :toname (car adr)))
9530 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9531 (let ((from (plist-get plist :from))
9532 (to (plist-get plist :to)))
9533 (when (and from to org-from-is-user-regexp)
9534 (setq plist
9535 (plist-put plist :fromto
9536 (if (string-match org-from-is-user-regexp from)
9537 (concat "to %t")
9538 (concat "from %f"))))))
9539 (setq org-store-link-plist plist))
9541 (defun org-add-link-props (&rest plist)
9542 "Add these properties to the link property list."
9543 (let (key value)
9544 (while plist
9545 (setq key (pop plist) value (pop plist))
9546 (setq org-store-link-plist
9547 (plist-put org-store-link-plist key value)))))
9549 (defun org-email-link-description (&optional fmt)
9550 "Return the description part of an email link.
9551 This takes information from `org-store-link-plist' and formats it
9552 according to FMT (default from `org-email-link-description-format')."
9553 (setq fmt (or fmt org-email-link-description-format))
9554 (let* ((p org-store-link-plist)
9555 (to (plist-get p :toaddress))
9556 (from (plist-get p :fromaddress))
9557 (table
9558 (list
9559 (cons "%c" (plist-get p :fromto))
9560 (cons "%F" (plist-get p :from))
9561 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9562 (cons "%T" (plist-get p :to))
9563 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9564 (cons "%s" (plist-get p :subject))
9565 (cons "%d" (plist-get p :date))
9566 (cons "%m" (plist-get p :message-id)))))
9567 (when (string-match "%c" fmt)
9568 ;; Check if the user wrote this message
9569 (if (and org-from-is-user-regexp from to
9570 (save-match-data (string-match org-from-is-user-regexp from)))
9571 (setq fmt (replace-match "to %t" t t fmt))
9572 (setq fmt (replace-match "from %f" t t fmt))))
9573 (org-replace-escapes fmt table)))
9575 (defun org-make-org-heading-search-string (&optional string)
9576 "Make search string for the current headline or STRING."
9577 (let ((s (or string
9578 (and (derived-mode-p 'org-mode)
9579 (save-excursion
9580 (org-back-to-heading t)
9581 (org-element-property :raw-value (org-element-at-point))))))
9582 (lines org-context-in-file-links))
9583 (or string (setq s (concat "*" s))) ; Add * for headlines
9584 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9585 (when (and string (integerp lines) (> lines 0))
9586 (let ((slines (org-split-string s "\n")))
9587 (when (< lines (length slines))
9588 (setq s (mapconcat
9589 'identity
9590 (reverse (nthcdr (- (length slines) lines)
9591 (reverse slines))) "\n")))))
9592 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9594 (defun org-make-link-string (link &optional description)
9595 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9596 (unless (string-match "\\S-" link)
9597 (error "Empty link"))
9598 (when (and description
9599 (stringp description)
9600 (not (string-match "\\S-" description)))
9601 (setq description nil))
9602 (when (stringp description)
9603 ;; Remove brackets from the description, they are fatal.
9604 (while (string-match "\\[" description)
9605 (setq description (replace-match "{" t t description)))
9606 (while (string-match "\\]" description)
9607 (setq description (replace-match "}" t t description))))
9608 (when (equal link description)
9609 ;; No description needed, it is identical
9610 (setq description nil))
9611 (when (and (not description)
9612 (not (string-match (org-image-file-name-regexp) link))
9613 (not (equal link (org-link-escape link))))
9614 (setq description (org-extract-attributes link)))
9615 (setq link
9616 (cond ((string-match (org-image-file-name-regexp) link) link)
9617 ((string-match org-link-types-re link)
9618 (concat (match-string 1 link)
9619 (org-link-escape (substring link (match-end 1)))))
9620 (t (org-link-escape link))))
9621 (concat "[[" link "]"
9622 (if description (concat "[" description "]") "")
9623 "]"))
9625 (defconst org-link-escape-chars
9626 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9627 "List of characters that should be escaped in link.
9628 This is the list that is used for internal purposes.")
9630 (defconst org-link-escape-chars-browser
9631 '(?\ )
9632 "List of escapes for characters that are problematic in links.
9633 This is the list that is used before handing over to the browser.")
9635 (defun org-link-escape (text &optional table merge)
9636 "Return percent escaped representation of TEXT.
9637 TEXT is a string with the text to escape.
9638 Optional argument TABLE is a list with characters that should be
9639 escaped. When nil, `org-link-escape-chars' is used.
9640 If optional argument MERGE is set, merge TABLE into
9641 `org-link-escape-chars'."
9642 (cond
9643 ((and table merge)
9644 (mapc (lambda (defchr)
9645 (unless (member defchr table)
9646 (setq table (cons defchr table)))) org-link-escape-chars))
9647 ((null table)
9648 (setq table org-link-escape-chars)))
9649 (mapconcat
9650 (lambda (char)
9651 (if (or (member char table)
9652 (and (or (< char 32) (= char 37) (> char 126))
9653 org-url-hexify-p))
9654 (mapconcat (lambda (sequence-element)
9655 (format "%%%.2X" sequence-element))
9656 (or (encode-coding-char char 'utf-8)
9657 (error "Unable to percent escape character: %s"
9658 (char-to-string char))) "")
9659 (char-to-string char))) text ""))
9661 (defun org-link-unescape (str)
9662 "Unhex hexified Unicode strings as returned from the JavaScript function
9663 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9664 (unless (and (null str) (string= "" str))
9665 (let ((pos 0) (case-fold-search t) unhexed)
9666 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9667 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9668 (setq str (replace-match unhexed t t str))
9669 (setq pos (+ pos (length unhexed))))))
9670 str)
9672 (defun org-link-unescape-compound (hex)
9673 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9674 Note: this function also decodes single byte encodings like
9675 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9676 (save-match-data
9677 (let* ((bytes (cdr (split-string hex "%")))
9678 (ret "")
9679 (eat 0)
9680 (sum 0))
9681 (while bytes
9682 (let* ((val (string-to-number (pop bytes) 16))
9683 (shift-xor
9684 (if (= 0 eat)
9685 (cond
9686 ((>= val 252) (cons 6 252))
9687 ((>= val 248) (cons 5 248))
9688 ((>= val 240) (cons 4 240))
9689 ((>= val 224) (cons 3 224))
9690 ((>= val 192) (cons 2 192))
9691 (t (cons 0 0)))
9692 (cons 6 128))))
9693 (if (>= val 192) (setq eat (car shift-xor)))
9694 (setq val (logxor val (cdr shift-xor)))
9695 (setq sum (+ (lsh sum (car shift-xor)) val))
9696 (if (> eat 0) (setq eat (- eat 1)))
9697 (cond
9698 ((= 0 eat) ;multi byte
9699 (setq ret (concat ret (org-char-to-string sum)))
9700 (setq sum 0))
9701 ((not bytes) ; single byte(s)
9702 (setq ret (org-link-unescape-single-byte-sequence hex))))
9703 )) ;; end (while bytes
9704 ret )))
9706 (defun org-link-unescape-single-byte-sequence (hex)
9707 "Unhexify hex-encoded single byte character sequences."
9708 (mapconcat (lambda (byte)
9709 (char-to-string (string-to-number byte 16)))
9710 (cdr (split-string hex "%")) ""))
9712 (defun org-xor (a b)
9713 "Exclusive or."
9714 (if a (not b) b))
9716 (defun org-fixup-message-id-for-http (s)
9717 "Replace special characters in a message id, so it can be used in an http query."
9718 (when (string-match "%" s)
9719 (setq s (mapconcat (lambda (c)
9720 (if (eq c ?%)
9721 "%25"
9722 (char-to-string c)))
9723 s "")))
9724 (while (string-match "<" s)
9725 (setq s (replace-match "%3C" t t s)))
9726 (while (string-match ">" s)
9727 (setq s (replace-match "%3E" t t s)))
9728 (while (string-match "@" s)
9729 (setq s (replace-match "%40" t t s)))
9732 (defun org-link-prettify (link)
9733 "Return a human-readable representation of LINK.
9734 The car of LINK must be a raw link the cdr of LINK must be either
9735 a link description or nil."
9736 (let ((desc (or (cadr link) "<no description>")))
9737 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9738 "<" (car link) ">")))
9740 ;;;###autoload
9741 (defun org-insert-link-global ()
9742 "Insert a link like Org-mode does.
9743 This command can be called in any mode to insert a link in Org-mode syntax."
9744 (interactive)
9745 (org-load-modules-maybe)
9746 (org-run-like-in-org-mode 'org-insert-link))
9748 (defun org-insert-all-links (&optional keep)
9749 "Insert all links in `org-stored-links'."
9750 (interactive "P")
9751 (let ((links (copy-sequence org-stored-links)) l)
9752 (while (setq l (if keep (pop links) (pop org-stored-links)))
9753 (insert "- ")
9754 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9755 (insert "\n"))))
9757 (defun org-link-fontify-links-to-this-file ()
9758 "Fontify links to the current file in `org-stored-links'."
9759 (let ((f (buffer-file-name)) a b)
9760 (setq a (mapcar (lambda(l)
9761 (let ((ll (car l)))
9762 (when (and (string-match "^file:\\(.+\\)::" ll)
9763 (equal f (expand-file-name (match-string 1 ll))))
9764 ll)))
9765 org-stored-links))
9766 (when (featurep 'org-id)
9767 (setq b (mapcar (lambda(l)
9768 (let ((ll (car l)))
9769 (when (and (string-match "^id:\\(.+\\)$" ll)
9770 (equal f (expand-file-name
9771 (or (org-id-find-id-file
9772 (match-string 1 ll)) ""))))
9773 ll)))
9774 org-stored-links)))
9775 (mapcar (lambda(l)
9776 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9777 (delq nil (append a b)))))
9779 (defvar org-link-links-in-this-file nil)
9780 (defun org-insert-link (&optional complete-file link-location default-description)
9781 "Insert a link. At the prompt, enter the link.
9783 Completion can be used to insert any of the link protocol prefixes like
9784 http or ftp in use.
9786 The history can be used to select a link previously stored with
9787 `org-store-link'. When the empty string is entered (i.e. if you just
9788 press RET at the prompt), the link defaults to the most recently
9789 stored link. As SPC triggers completion in the minibuffer, you need to
9790 use M-SPC or C-q SPC to force the insertion of a space character.
9792 You will also be prompted for a description, and if one is given, it will
9793 be displayed in the buffer instead of the link.
9795 If there is already a link at point, this command will allow you to edit link
9796 and description parts.
9798 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9799 be selected using completion. The path to the file will be relative to the
9800 current directory if the file is in the current directory or a subdirectory.
9801 Otherwise, the link will be the absolute path as completed in the minibuffer
9802 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9803 option `org-link-file-path-type'.
9805 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9806 the current directory or below.
9808 With three \\[universal-argument] prefixes, negate the meaning of
9809 `org-keep-stored-link-after-insertion'.
9811 If `org-make-link-description-function' is non-nil, this function will be
9812 called with the link target, and the result will be the default
9813 link description.
9815 If the LINK-LOCATION parameter is non-nil, this value will be
9816 used as the link location instead of reading one interactively.
9818 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9819 be used as the default description."
9820 (interactive "P")
9821 (let* ((wcf (current-window-configuration))
9822 (origbuf (current-buffer))
9823 (region (if (org-region-active-p)
9824 (buffer-substring (region-beginning) (region-end))))
9825 (remove (and region (list (region-beginning) (region-end))))
9826 (desc region)
9827 tmphist ; byte-compile incorrectly complains about this
9828 (link link-location)
9829 (abbrevs org-link-abbrev-alist-local)
9830 entry file all-prefixes auto-desc)
9831 (cond
9832 (link-location) ; specified by arg, just use it.
9833 ((org-in-regexp org-bracket-link-regexp 1)
9834 ;; We do have a link at point, and we are going to edit it.
9835 (setq remove (list (match-beginning 0) (match-end 0)))
9836 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9837 (setq link (read-string "Link: "
9838 (org-link-unescape
9839 (org-match-string-no-properties 1)))))
9840 ((or (org-in-regexp org-angle-link-re)
9841 (org-in-regexp org-plain-link-re))
9842 ;; Convert to bracket link
9843 (setq remove (list (match-beginning 0) (match-end 0))
9844 link (read-string "Link: "
9845 (org-remove-angle-brackets (match-string 0)))))
9846 ((member complete-file '((4) (16)))
9847 ;; Completing read for file names.
9848 (setq link (org-file-complete-link complete-file)))
9850 ;; Read link, with completion for stored links.
9851 (org-link-fontify-links-to-this-file)
9852 (org-switch-to-buffer-other-window "*Org Links*")
9853 (with-current-buffer "*Org Links*"
9854 (erase-buffer)
9855 (insert "Insert a link.
9856 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9857 (when org-stored-links
9858 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9859 (insert (mapconcat 'org-link-prettify
9860 (reverse org-stored-links) "\n")))
9861 (goto-char (point-min)))
9862 (let ((cw (selected-window)))
9863 (select-window (get-buffer-window "*Org Links*" 'visible))
9864 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9865 (unless (pos-visible-in-window-p (point-max))
9866 (org-fit-window-to-buffer))
9867 (and (window-live-p cw) (select-window cw)))
9868 ;; Fake a link history, containing the stored links.
9869 (setq tmphist (append (mapcar 'car org-stored-links)
9870 org-insert-link-history))
9871 (setq all-prefixes (append (mapcar 'car abbrevs)
9872 (mapcar 'car org-link-abbrev-alist)
9873 org-link-types))
9874 (unwind-protect
9875 (progn
9876 (setq link
9877 (org-completing-read
9878 "Link: "
9879 (append
9880 (mapcar (lambda (x) (concat x ":"))
9881 all-prefixes)
9882 (mapcar 'car org-stored-links))
9883 nil nil nil
9884 'tmphist
9885 (caar org-stored-links)))
9886 (if (not (string-match "\\S-" link))
9887 (error "No link selected"))
9888 (mapc (lambda(l)
9889 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9890 org-stored-links)
9891 (if (or (member link all-prefixes)
9892 (and (equal ":" (substring link -1))
9893 (member (substring link 0 -1) all-prefixes)
9894 (setq link (substring link 0 -1))))
9895 (setq link (with-current-buffer origbuf
9896 (org-link-try-special-completion link)))))
9897 (set-window-configuration wcf)
9898 (kill-buffer "*Org Links*"))
9899 (setq entry (assoc link org-stored-links))
9900 (or entry (push link org-insert-link-history))
9901 (setq desc (or desc (nth 1 entry)))))
9903 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9904 (not org-keep-stored-link-after-insertion))
9905 (setq org-stored-links (delq (assoc link org-stored-links)
9906 org-stored-links)))
9908 (if (string-match org-plain-link-re link)
9909 ;; URL-like link, normalize the use of angular brackets.
9910 (setq link (org-remove-angle-brackets link)))
9912 ;; Check if we are linking to the current file with a search
9913 ;; option If yes, simplify the link by using only the search
9914 ;; option.
9915 (when (and buffer-file-name
9916 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9917 (let* ((path (match-string 1 link))
9918 (case-fold-search nil)
9919 (search (match-string 2 link)))
9920 (save-match-data
9921 (if (equal (file-truename buffer-file-name) (file-truename path))
9922 ;; We are linking to this same file, with a search option
9923 (setq link search)))))
9925 ;; Check if we can/should use a relative path. If yes, simplify the link
9926 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9927 (let* ((type (match-string 1 link))
9928 (path (match-string 2 link))
9929 (origpath path)
9930 (case-fold-search nil))
9931 (cond
9932 ((or (eq org-link-file-path-type 'absolute)
9933 (equal complete-file '(16)))
9934 (setq path (abbreviate-file-name (expand-file-name path))))
9935 ((eq org-link-file-path-type 'noabbrev)
9936 (setq path (expand-file-name path)))
9937 ((eq org-link-file-path-type 'relative)
9938 (setq path (file-relative-name path)))
9940 (save-match-data
9941 (if (string-match (concat "^" (regexp-quote
9942 (expand-file-name
9943 (file-name-as-directory
9944 default-directory))))
9945 (expand-file-name path))
9946 ;; We are linking a file with relative path name.
9947 (setq path (substring (expand-file-name path)
9948 (match-end 0)))
9949 (setq path (abbreviate-file-name (expand-file-name path)))))))
9950 (setq link (concat type path))
9951 (if (equal desc origpath)
9952 (setq desc path))))
9954 (if org-make-link-description-function
9955 (setq desc
9956 (or (condition-case nil
9957 (funcall org-make-link-description-function link desc)
9958 (error (progn (message "Can't get link description from `%s'"
9959 (symbol-name org-make-link-description-function))
9960 (sit-for 2) nil)))
9961 (read-string "Description: " default-description)))
9962 (if default-description (setq desc default-description)
9963 (setq desc (or (and auto-desc desc)
9964 (read-string "Description: " desc)))))
9966 (unless (string-match "\\S-" desc) (setq desc nil))
9967 (if remove (apply 'delete-region remove))
9968 (insert (org-make-link-string link desc))))
9970 (defun org-link-try-special-completion (type)
9971 "If there is completion support for link type TYPE, offer it."
9972 (let ((fun (intern (concat "org-" type "-complete-link"))))
9973 (if (functionp fun)
9974 (funcall fun)
9975 (read-string "Link (no completion support): " (concat type ":")))))
9977 (defun org-file-complete-link (&optional arg)
9978 "Create a file link using completion."
9979 (let (file link)
9980 (setq file (org-iread-file-name "File: "))
9981 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9982 (pwd1 (file-name-as-directory (abbreviate-file-name
9983 (expand-file-name ".")))))
9984 (cond
9985 ((equal arg '(16))
9986 (setq link (concat
9987 "file:"
9988 (abbreviate-file-name (expand-file-name file)))))
9989 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9990 (setq link (concat "file:" (match-string 1 file))))
9991 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9992 (expand-file-name file))
9993 (setq link (concat
9994 "file:" (match-string 1 (expand-file-name file)))))
9995 (t (setq link (concat "file:" file)))))
9996 link))
9998 (defun org-iread-file-name (&rest args)
9999 "Read-file-name using `ido-mode' speedup if available.
10000 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10001 See `read-file-name' for a description of parameters."
10002 (org-without-partial-completion
10003 (if (and org-completion-use-ido
10004 (fboundp 'ido-read-file-name)
10005 (boundp 'ido-mode) ido-mode
10006 (listp (second args)))
10007 (let ((ido-enter-matching-directory nil))
10008 (apply 'ido-read-file-name args))
10009 (apply 'read-file-name args))))
10011 (defun org-completing-read (&rest args)
10012 "Completing-read with SPACE being a normal character."
10013 (let ((enable-recursive-minibuffers t)
10014 (minibuffer-local-completion-map
10015 (copy-keymap minibuffer-local-completion-map)))
10016 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10017 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10018 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10019 (apply 'org-icompleting-read args)))
10021 (defun org-completing-read-no-i (&rest args)
10022 (let (org-completion-use-ido org-completion-use-iswitchb)
10023 (apply 'org-completing-read args)))
10025 (defun org-iswitchb-completing-read (prompt choices &rest args)
10026 "Use iswitch as a completing-read replacement to choose from choices.
10027 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10028 from."
10029 (let* ((iswitchb-use-virtual-buffers nil)
10030 (iswitchb-make-buflist-hook
10031 (lambda ()
10032 (setq iswitchb-temp-buflist choices))))
10033 (iswitchb-read-buffer prompt)))
10035 (defun org-icompleting-read (&rest args)
10036 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10037 (org-without-partial-completion
10038 (if (and org-completion-use-ido
10039 (fboundp 'ido-completing-read)
10040 (boundp 'ido-mode) ido-mode
10041 (listp (second args)))
10042 (let ((ido-enter-matching-directory nil))
10043 (apply 'ido-completing-read (concat (car args))
10044 (if (consp (car (nth 1 args)))
10045 (mapcar 'car (nth 1 args))
10046 (nth 1 args))
10047 (cddr args)))
10048 (if (and org-completion-use-iswitchb
10049 (boundp 'iswitchb-mode) iswitchb-mode
10050 (listp (second args)))
10051 (apply 'org-iswitchb-completing-read (concat (car args))
10052 (if (consp (car (nth 1 args)))
10053 (mapcar 'car (nth 1 args))
10054 (nth 1 args))
10055 (cddr args))
10056 (apply 'completing-read args)))))
10058 (defun org-extract-attributes (s)
10059 "Extract the attributes cookie from a string and set as text property."
10060 (let (a attr (start 0) key value)
10061 (save-match-data
10062 (when (string-match "{{\\([^}]+\\)}}$" s)
10063 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10064 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10065 (setq key (match-string 1 a) value (match-string 2 a)
10066 start (match-end 0)
10067 attr (plist-put attr (intern key) value))))
10068 (org-add-props s nil 'org-attr attr))
10071 (defun org-extract-attributes-from-string (tag)
10072 (let (key value attr)
10073 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10074 (setq key (match-string 1 tag) value (match-string 2 tag)
10075 tag (replace-match "" t t tag)
10076 attr (plist-put attr (intern key) value)))
10077 (cons tag attr)))
10079 (defun org-attributes-to-string (plist)
10080 "Format a property list into an HTML attribute list."
10081 (let ((s "") key value)
10082 (while plist
10083 (setq key (pop plist) value (pop plist))
10084 (and value
10085 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10088 ;;; Opening/following a link
10090 (defvar org-link-search-failed nil)
10092 (defvar org-open-link-functions nil
10093 "Hook for functions finding a plain text link.
10094 These functions must take a single argument, the link content.
10095 They will be called for links that look like [[link text][description]]
10096 when LINK TEXT does not have a protocol like \"http:\" and does not look
10097 like a filename (e.g. \"./blue.png\").
10099 These functions will be called *before* Org attempts to resolve the
10100 link by doing text searches in the current buffer - so if you want a
10101 link \"[[target]]\" to still find \"<<target>>\", your function should
10102 handle this as a special case.
10104 When the function does handle the link, it must return a non-nil value.
10105 If it decides that it is not responsible for this link, it must return
10106 nil to indicate that that Org-mode can continue with other options
10107 like exact and fuzzy text search.")
10109 (defun org-next-link (&optional search-backward)
10110 "Move forward to the next link.
10111 If the link is in hidden text, expose it."
10112 (interactive "P")
10113 (when (and org-link-search-failed (eq this-command last-command))
10114 (goto-char (point-min))
10115 (message "Link search wrapped back to beginning of buffer"))
10116 (setq org-link-search-failed nil)
10117 (let* ((pos (point))
10118 (ct (org-context))
10119 (a (assoc :link ct))
10120 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10121 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10122 ((looking-at org-any-link-re)
10123 ;; Don't stay stuck at link without an org-link face
10124 (forward-char (if search-backward -1 1))))
10125 (if (funcall srch-fun org-any-link-re nil t)
10126 (progn
10127 (goto-char (match-beginning 0))
10128 (if (outline-invisible-p) (org-show-context)))
10129 (goto-char pos)
10130 (setq org-link-search-failed t)
10131 (message "No further link found"))))
10133 (defun org-previous-link ()
10134 "Move backward to the previous link.
10135 If the link is in hidden text, expose it."
10136 (interactive)
10137 (funcall 'org-next-link t))
10139 (defun org-translate-link (s)
10140 "Translate a link string if a translation function has been defined."
10141 (if (and org-link-translation-function
10142 (fboundp org-link-translation-function)
10143 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10144 (progn
10145 (setq s (funcall org-link-translation-function
10146 (match-string 1 s) (match-string 2 s)))
10147 (concat (car s) ":" (cdr s)))
10150 (defun org-translate-link-from-planner (type path)
10151 "Translate a link from Emacs Planner syntax so that Org can follow it.
10152 This is still an experimental function, your mileage may vary."
10153 (cond
10154 ((member type '("http" "https" "news" "ftp"))
10155 ;; standard Internet links are the same.
10156 nil)
10157 ((and (equal type "irc") (string-match "^//" path))
10158 ;; Planner has two / at the beginning of an irc link, we have 1.
10159 ;; We should have zero, actually....
10160 (setq path (substring path 1)))
10161 ((and (equal type "lisp") (string-match "^/" path))
10162 ;; Planner has a slash, we do not.
10163 (setq type "elisp" path (substring path 1)))
10164 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10165 ;; A typical message link. Planner has the id after the final slash,
10166 ;; we separate it with a hash mark
10167 (setq path (concat (match-string 1 path) "#"
10168 (org-remove-angle-brackets (match-string 2 path)))))
10170 (cons type path))
10172 (defun org-find-file-at-mouse (ev)
10173 "Open file link or URL at mouse."
10174 (interactive "e")
10175 (mouse-set-point ev)
10176 (org-open-at-point 'in-emacs))
10178 (defun org-open-at-mouse (ev)
10179 "Open file link or URL at mouse.
10180 See the docstring of `org-open-file' for details."
10181 (interactive "e")
10182 (mouse-set-point ev)
10183 (if (eq major-mode 'org-agenda-mode)
10184 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10185 (org-open-at-point))
10187 (defvar org-window-config-before-follow-link nil
10188 "The window configuration before following a link.
10189 This is saved in case the need arises to restore it.")
10191 (defvar org-open-link-marker (make-marker)
10192 "Marker pointing to the location where `org-open-at-point; was called.")
10194 ;;;###autoload
10195 (defun org-open-at-point-global ()
10196 "Follow a link like Org-mode does.
10197 This command can be called in any mode to follow a link that has
10198 Org-mode syntax."
10199 (interactive)
10200 (org-run-like-in-org-mode 'org-open-at-point))
10202 ;;;###autoload
10203 (defun org-open-link-from-string (s &optional arg reference-buffer)
10204 "Open a link in the string S, as if it was in Org-mode."
10205 (interactive "sLink: \nP")
10206 (let ((reference-buffer (or reference-buffer (current-buffer))))
10207 (with-temp-buffer
10208 (let ((org-inhibit-startup (not reference-buffer)))
10209 (org-mode)
10210 (insert s)
10211 (goto-char (point-min))
10212 (when reference-buffer
10213 (setq org-link-abbrev-alist-local
10214 (with-current-buffer reference-buffer
10215 org-link-abbrev-alist-local)))
10216 (org-open-at-point arg reference-buffer)))))
10218 (defvar org-open-at-point-functions nil
10219 "Hook that is run when following a link at point.
10221 Functions in this hook must return t if they identify and follow
10222 a link at point. If they don't find anything interesting at point,
10223 they must return nil.")
10225 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10226 (defun org-open-at-point (&optional arg reference-buffer)
10227 "Open link at or after point.
10228 If there is no link at point, this function will search forward up to
10229 the end of the current line.
10230 Normally, files will be opened by an appropriate application. If the
10231 optional prefix argument ARG is non-nil, Emacs will visit the file.
10232 With a double prefix argument, try to open outside of Emacs, in the
10233 application the system uses for this file type."
10234 (interactive "P")
10235 ;; if in a code block, then open the block's results
10236 (unless (call-interactively #'org-babel-open-src-block-result)
10237 (org-load-modules-maybe)
10238 (move-marker org-open-link-marker (point))
10239 (setq org-window-config-before-follow-link (current-window-configuration))
10240 (org-remove-occur-highlights nil nil t)
10241 (cond
10242 ((and (org-at-heading-p)
10243 (not (org-at-timestamp-p t))
10244 (not (org-in-regexp
10245 (concat org-plain-link-re "\\|"
10246 org-bracket-link-regexp "\\|"
10247 org-angle-link-re "\\|"
10248 "[ \t]:[^ \t\n]+:[ \t]*$")))
10249 (not (get-text-property (point) 'org-linked-text)))
10250 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10251 (lk0 (car lkall))
10252 (lk (if (stringp lk0) (list lk0) lk0))
10253 (lkend (cdr lkall)))
10254 (mapcar (lambda(l)
10255 (search-forward l nil lkend)
10256 (goto-char (match-beginning 0))
10257 (org-open-at-point))
10258 lk))
10259 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10260 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10261 ((and (org-at-timestamp-p t)
10262 (not (org-in-regexp org-bracket-link-regexp)))
10263 (org-follow-timestamp-link))
10264 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10265 (not (org-in-regexp org-any-link-re)))
10266 (org-footnote-action))
10268 (let (type path link line search (pos (point)))
10269 (catch 'match
10270 (save-excursion
10271 (skip-chars-forward "^]\n\r")
10272 (when (org-in-regexp org-bracket-link-regexp 1)
10273 (setq link (org-extract-attributes
10274 (org-link-unescape (org-match-string-no-properties 1))))
10275 (while (string-match " *\n *" link)
10276 (setq link (replace-match " " t t link)))
10277 (setq link (org-link-expand-abbrev link))
10278 (cond
10279 ((or (file-name-absolute-p link)
10280 (string-match "^\\.\\.?/" link))
10281 (setq type "file" path link))
10282 ((string-match org-link-re-with-space3 link)
10283 (setq type (match-string 1 link) path (match-string 2 link)))
10284 ((string-match "^help:+\\(.+\\)" link)
10285 (setq type "help" path (match-string 1 link)))
10286 (t (setq type "thisfile" path link)))
10287 (throw 'match t)))
10289 (when (get-text-property (point) 'org-linked-text)
10290 (setq type "thisfile"
10291 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10292 (1+ (point)) (point))
10293 path (buffer-substring
10294 (or (previous-single-property-change pos 'org-linked-text)
10295 (point-min))
10296 (or (next-single-property-change pos 'org-linked-text)
10297 (point-max))))
10298 (throw 'match t))
10300 (save-excursion
10301 (when (or (org-in-regexp org-angle-link-re)
10302 (let ((match (org-in-regexp org-plain-link-re)))
10303 ;; Check a plain link is not within a bracket link
10304 (and match
10305 (save-excursion
10306 (progn
10307 (goto-char (car match))
10308 (not (org-in-regexp org-bracket-link-regexp))))))
10309 (let ((line_ending (save-excursion (end-of-line) (point))))
10310 ;; We are in a line before a plain or bracket link
10311 (or (re-search-forward org-plain-link-re line_ending t)
10312 (re-search-forward org-bracket-link-regexp line_ending t))))
10313 (setq type (match-string 1)
10314 path (org-link-unescape (match-string 2)))
10315 (throw 'match t)))
10316 (save-excursion
10317 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10318 (setq type "tags"
10319 path (match-string 1))
10320 (while (string-match ":" path)
10321 (setq path (replace-match "+" t t path)))
10322 (throw 'match t)))
10323 (when (org-in-regexp "<\\([^><\n]+\\)>")
10324 (setq type "tree-match"
10325 path (match-string 1))
10326 (throw 'match t)))
10327 (unless path
10328 (user-error "No link found"))
10330 ;; switch back to reference buffer
10331 ;; needed when if called in a temporary buffer through
10332 ;; org-open-link-from-string
10333 (with-current-buffer (or reference-buffer (current-buffer))
10335 ;; Remove any trailing spaces in path
10336 (if (string-match " +\\'" path)
10337 (setq path (replace-match "" t t path)))
10338 (if (and org-link-translation-function
10339 (fboundp org-link-translation-function))
10340 ;; Check if we need to translate the link
10341 (let ((tmp (funcall org-link-translation-function type path)))
10342 (setq type (car tmp) path (cdr tmp))))
10344 (cond
10346 ((assoc type org-link-protocols)
10347 (funcall (nth 1 (assoc type org-link-protocols)) path))
10349 ((equal type "help")
10350 (let ((f-or-v (intern path)))
10351 (cond ((fboundp f-or-v)
10352 (describe-function f-or-v))
10353 ((boundp f-or-v)
10354 (describe-variable f-or-v))
10355 (t (error "Not a known function or variable")))))
10357 ((equal type "mailto")
10358 (let ((cmd (car org-link-mailto-program))
10359 (args (cdr org-link-mailto-program)) args1
10360 (address path) (subject "") a)
10361 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10362 (setq address (match-string 1 path)
10363 subject (org-link-escape (match-string 2 path))))
10364 (while args
10365 (cond
10366 ((not (stringp (car args))) (push (pop args) args1))
10367 (t (setq a (pop args))
10368 (if (string-match "%a" a)
10369 (setq a (replace-match address t t a)))
10370 (if (string-match "%s" a)
10371 (setq a (replace-match subject t t a)))
10372 (push a args1))))
10373 (apply cmd (nreverse args1))))
10375 ((member type '("http" "https" "ftp" "news"))
10376 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10377 (org-link-escape
10378 path org-link-escape-chars-browser)
10379 path))))
10381 ((string= type "doi")
10382 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10383 (org-link-escape
10384 path org-link-escape-chars-browser)
10385 path))))
10387 ((member type '("message"))
10388 (browse-url (concat type ":" path)))
10390 ((string= type "tags")
10391 (org-tags-view arg path))
10393 ((string= type "tree-match")
10394 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10396 ((string= type "file")
10397 (if (string-match "::\\([0-9]+\\)\\'" path)
10398 (setq line (string-to-number (match-string 1 path))
10399 path (substring path 0 (match-beginning 0)))
10400 (if (string-match "::\\(.+\\)\\'" path)
10401 (setq search (match-string 1 path)
10402 path (substring path 0 (match-beginning 0)))))
10403 (if (string-match "[*?{]" (file-name-nondirectory path))
10404 (dired path)
10405 (org-open-file path arg line search)))
10407 ((string= type "shell")
10408 (let ((buf (generate-new-buffer "*Org Shell Output"))
10409 (cmd path))
10410 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10411 (string-match org-confirm-shell-link-not-regexp cmd))
10412 (not org-confirm-shell-link-function)
10413 (funcall org-confirm-shell-link-function
10414 (format "Execute \"%s\" in shell? "
10415 (org-add-props cmd nil
10416 'face 'org-warning))))
10417 (progn
10418 (message "Executing %s" cmd)
10419 (shell-command cmd buf)
10420 (if (featurep 'midnight)
10421 (setq clean-buffer-list-kill-buffer-names
10422 (cons buf clean-buffer-list-kill-buffer-names))))
10423 (error "Abort"))))
10425 ((string= type "elisp")
10426 (let ((cmd path))
10427 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10428 (string-match org-confirm-elisp-link-not-regexp cmd))
10429 (not org-confirm-elisp-link-function)
10430 (funcall org-confirm-elisp-link-function
10431 (format "Execute \"%s\" as elisp? "
10432 (org-add-props cmd nil
10433 'face 'org-warning))))
10434 (message "%s => %s" cmd
10435 (if (equal (string-to-char cmd) ?\()
10436 (eval (read cmd))
10437 (call-interactively (read cmd))))
10438 (error "Abort"))))
10440 ((and (string= type "thisfile")
10441 (run-hook-with-args-until-success
10442 'org-open-link-functions path)))
10444 ((string= type "thisfile")
10445 (if arg
10446 (switch-to-buffer-other-window
10447 (org-get-buffer-for-internal-link (current-buffer)))
10448 (org-mark-ring-push))
10449 (let ((cmd `(org-link-search
10450 ,path
10451 ,(cond ((equal arg '(4)) ''occur)
10452 ((equal arg '(16)) ''org-occur))
10453 ,pos)))
10454 (condition-case nil (let ((org-link-search-inhibit-query t))
10455 (eval cmd))
10456 (error (progn (widen) (eval cmd))))))
10458 (t (browse-url-at-point)))))))
10459 (move-marker org-open-link-marker nil)
10460 (run-hook-with-args 'org-follow-link-hook)))
10462 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10463 "Offer links in the current entry and return the selected link.
10464 If there is only one link, return it.
10465 If NTH is an integer, return the NTH link found.
10466 If ZERO is a string, check also this string for a link, and if
10467 there is one, return it."
10468 (with-current-buffer buffer
10469 (save-excursion
10470 (save-restriction
10471 (widen)
10472 (goto-char marker)
10473 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10474 "\\(" org-angle-link-re "\\)\\|"
10475 "\\(" org-plain-link-re "\\)"))
10476 (cnt ?0)
10477 (in-emacs (if (integerp nth) nil nth))
10478 have-zero end links link c)
10479 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10480 (push (match-string 0 zero) links)
10481 (setq cnt (1- cnt) have-zero t))
10482 (save-excursion
10483 (org-back-to-heading t)
10484 (setq end (save-excursion (outline-next-heading) (point)))
10485 (while (re-search-forward re end t)
10486 (push (match-string 0) links))
10487 (setq links (org-uniquify (reverse links))))
10488 (cond
10489 ((null links)
10490 (message "No links"))
10491 ((equal (length links) 1)
10492 (setq link (car links)))
10493 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10494 (setq link (nth (if have-zero nth (1- nth)) links)))
10495 (t ; we have to select a link
10496 (save-excursion
10497 (save-window-excursion
10498 (delete-other-windows)
10499 (with-output-to-temp-buffer "*Select Link*"
10500 (mapc (lambda (l)
10501 (if (not (string-match org-bracket-link-regexp l))
10502 (princ (format "[%c] %s\n" (incf cnt)
10503 (org-remove-angle-brackets l)))
10504 (if (match-end 3)
10505 (princ (format "[%c] %s (%s)\n" (incf cnt)
10506 (match-string 3 l) (match-string 1 l)))
10507 (princ (format "[%c] %s\n" (incf cnt)
10508 (match-string 1 l))))))
10509 links))
10510 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10511 (message "Select link to open, RET to open all:")
10512 (setq c (read-char-exclusive))
10513 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10514 (when (equal c ?q) (error "Abort"))
10515 (if (equal c ?\C-m)
10516 (setq link links)
10517 (setq nth (- c ?0))
10518 (if have-zero (setq nth (1+ nth)))
10519 (unless (and (integerp nth) (>= (length links) nth))
10520 (error "Invalid link selection"))
10521 (setq link (nth (1- nth) links)))))
10522 (cons link end))))))
10524 ;; Add special file links that specify the way of opening
10526 (org-add-link-type "file+sys" 'org-open-file-with-system)
10527 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10528 (defun org-open-file-with-system (path)
10529 "Open file at PATH using the system way of opening it."
10530 (org-open-file path 'system))
10531 (defun org-open-file-with-emacs (path)
10532 "Open file at PATH in Emacs."
10533 (org-open-file path 'emacs))
10536 ;;; File search
10538 (defvar org-create-file-search-functions nil
10539 "List of functions to construct the right search string for a file link.
10540 These functions are called in turn with point at the location to
10541 which the link should point.
10543 A function in the hook should first test if it would like to
10544 handle this file type, for example by checking the `major-mode'
10545 or the file extension. If it decides not to handle this file, it
10546 should just return nil to give other functions a chance. If it
10547 does handle the file, it must return the search string to be used
10548 when following the link. The search string will be part of the
10549 file link, given after a double colon, and `org-open-at-point'
10550 will automatically search for it. If special measures must be
10551 taken to make the search successful, another function should be
10552 added to the companion hook `org-execute-file-search-functions',
10553 which see.
10555 A function in this hook may also use `setq' to set the variable
10556 `description' to provide a suggestion for the descriptive text to
10557 be used for this link when it gets inserted into an Org-mode
10558 buffer with \\[org-insert-link].")
10560 (defvar org-execute-file-search-functions nil
10561 "List of functions to execute a file search triggered by a link.
10563 Functions added to this hook must accept a single argument, the
10564 search string that was part of the file link, the part after the
10565 double colon. The function must first check if it would like to
10566 handle this search, for example by checking the `major-mode' or
10567 the file extension. If it decides not to handle this search, it
10568 should just return nil to give other functions a chance. If it
10569 does handle the search, it must return a non-nil value to keep
10570 other functions from trying.
10572 Each function can access the current prefix argument through the
10573 variable `current-prefix-arg'. Note that a single prefix is used
10574 to force opening a link in Emacs, so it may be good to only use a
10575 numeric or double prefix to guide the search function.
10577 In case this is needed, a function in this hook can also restore
10578 the window configuration before `org-open-at-point' was called using:
10580 (set-window-configuration org-window-config-before-follow-link)")
10582 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10583 (defun org-link-search (s &optional type avoid-pos stealth)
10584 "Search for a link search option.
10585 If S is surrounded by forward slashes, it is interpreted as a
10586 regular expression. In org-mode files, this will create an `org-occur'
10587 sparse tree. In ordinary files, `occur' will be used to list matches.
10588 If the current buffer is in `dired-mode', grep will be used to search
10589 in all files. If AVOID-POS is given, ignore matches near that position.
10591 When optional argument STEALTH is non-nil, do not modify
10592 visibility around point, thus ignoring
10593 `org-show-hierarchy-above', `org-show-following-heading' and
10594 `org-show-siblings' variables."
10595 (let ((case-fold-search t)
10596 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10597 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10598 (append '(("") (" ") ("\t") ("\n"))
10599 org-emphasis-alist)
10600 "\\|") "\\)"))
10601 (pos (point))
10602 (pre nil) (post nil)
10603 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10604 (cond
10605 ;; First check if there are any special search functions
10606 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10607 ;; Now try the builtin stuff
10608 ((and (equal (string-to-char s0) ?#)
10609 (> (length s0) 1)
10610 (save-excursion
10611 (goto-char (point-min))
10612 (and
10613 (re-search-forward
10614 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10615 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10616 (setq type 'dedicated
10617 pos (match-beginning 0))))
10618 ;; There is an exact target for this
10619 (goto-char pos)
10620 (org-back-to-heading t)))
10621 ((save-excursion
10622 (goto-char (point-min))
10623 (and
10624 (re-search-forward
10625 (concat "<<" (regexp-quote s0) ">>") nil t)
10626 (setq type 'dedicated
10627 pos (match-beginning 0))))
10628 ;; There is an exact target for this
10629 (goto-char pos))
10630 ((save-excursion
10631 (goto-char (point-min))
10632 (and
10633 (re-search-forward
10634 (format "^[ \t]*#\\+\\(?:TARGET\\|NAME\\): %s"
10635 (regexp-quote s0)) nil t)
10636 (setq type 'dedicated pos (match-beginning 0))))
10637 ;; Found an invisible target.
10638 (goto-char pos))
10639 ((and (string-match "^(\\(.*\\))$" s0)
10640 (save-excursion
10641 (goto-char (point-min))
10642 (and
10643 (re-search-forward
10644 (concat "[^[]" (regexp-quote
10645 (format org-coderef-label-format
10646 (match-string 1 s0))))
10647 nil t)
10648 (setq type 'dedicated
10649 pos (1+ (match-beginning 0))))))
10650 ;; There is a coderef target for this
10651 (goto-char pos))
10652 ((string-match "^/\\(.*\\)/$" s)
10653 ;; A regular expression
10654 (cond
10655 ((derived-mode-p 'org-mode)
10656 (org-occur (match-string 1 s)))
10657 (t (org-do-occur (match-string 1 s)))))
10658 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10659 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10660 (goto-char (point-min))
10661 (cond
10662 ((let (case-fold-search)
10663 (re-search-forward (format org-complex-heading-regexp-format
10664 (regexp-quote s))
10665 nil t))
10666 ;; OK, found a match
10667 (setq type 'dedicated)
10668 (goto-char (match-beginning 0)))
10669 ((and (not org-link-search-inhibit-query)
10670 (eq org-link-search-must-match-exact-headline 'query-to-create)
10671 (y-or-n-p "No match - create this as a new heading? "))
10672 (goto-char (point-max))
10673 (or (bolp) (newline))
10674 (insert "* " s "\n")
10675 (beginning-of-line 0))
10677 (goto-char pos)
10678 (error "No match"))))
10680 ;; A normal search string
10681 (when (equal (string-to-char s) ?*)
10682 ;; Anchor on headlines, post may include tags.
10683 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10684 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10685 s (substring s 1)))
10686 (remove-text-properties
10687 0 (length s)
10688 '(face nil mouse-face nil keymap nil fontified nil) s)
10689 ;; Make a series of regular expressions to find a match
10690 (setq words (org-split-string s "[ \n\r\t]+")
10692 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10693 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10694 "\\)" markers)
10695 re2a_ (concat "\\(" (mapconcat 'downcase words
10696 "[ \t\r\n]+") "\\)[ \t\r\n]")
10697 re2a (concat "[ \t\r\n]" re2a_)
10698 re4_ (concat "\\(" (mapconcat 'downcase words
10699 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10700 re4 (concat "[^a-zA-Z_]" re4_)
10702 re1 (concat pre re2 post)
10703 re3 (concat pre (if pre re4_ re4) post)
10704 re5 (concat pre ".*" re4)
10705 re2 (concat pre re2)
10706 re2a (concat pre (if pre re2a_ re2a))
10707 re4 (concat pre (if pre re4_ re4))
10708 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10709 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10710 re5 "\\)"
10712 (cond
10713 ((eq type 'org-occur) (org-occur reall))
10714 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10715 (t (goto-char (point-min))
10716 (setq type 'fuzzy)
10717 (if (or (and (org-search-not-self 1 re0 nil t)
10718 (setq type 'dedicated))
10719 (org-search-not-self 1 re1 nil t)
10720 (org-search-not-self 1 re2 nil t)
10721 (org-search-not-self 1 re2a nil t)
10722 (org-search-not-self 1 re3 nil t)
10723 (org-search-not-self 1 re4 nil t)
10724 (org-search-not-self 1 re5 nil t))
10725 (goto-char (match-beginning 1))
10726 (goto-char pos)
10727 (error "No match"))))))
10728 (and (derived-mode-p 'org-mode)
10729 (not stealth)
10730 (org-show-context 'link-search))
10731 type))
10733 (defun org-search-not-self (group &rest args)
10734 "Execute `re-search-forward', but only accept matches that do not
10735 enclose the position of `org-open-link-marker'."
10736 (let ((m org-open-link-marker))
10737 (catch 'exit
10738 (while (apply 're-search-forward args)
10739 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10740 (goto-char (match-end group))
10741 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10742 (> (match-beginning 0) (marker-position m))
10743 (< (match-end 0) (marker-position m)))
10744 (save-match-data
10745 (or (not (org-in-regexp
10746 org-bracket-link-analytic-regexp 1))
10747 (not (match-end 4)) ; no description
10748 (and (<= (match-beginning 4) (point))
10749 (>= (match-end 4) (point))))))
10750 (throw 'exit (point))))))))
10752 (defun org-get-buffer-for-internal-link (buffer)
10753 "Return a buffer to be used for displaying the link target of internal links."
10754 (cond
10755 ((not org-display-internal-link-with-indirect-buffer)
10756 buffer)
10757 ((string-match "(Clone)$" (buffer-name buffer))
10758 (message "Buffer is already a clone, not making another one")
10759 ;; we also do not modify visibility in this case
10760 buffer)
10761 (t ; make a new indirect buffer for displaying the link
10762 (let* ((bn (buffer-name buffer))
10763 (ibn (concat bn "(Clone)"))
10764 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10765 (with-current-buffer ib (org-overview))
10766 ib))))
10768 (defun org-do-occur (regexp &optional cleanup)
10769 "Call the Emacs command `occur'.
10770 If CLEANUP is non-nil, remove the printout of the regular expression
10771 in the *Occur* buffer. This is useful if the regex is long and not useful
10772 to read."
10773 (occur regexp)
10774 (when cleanup
10775 (let ((cwin (selected-window)) win beg end)
10776 (when (setq win (get-buffer-window "*Occur*"))
10777 (select-window win))
10778 (goto-char (point-min))
10779 (when (re-search-forward "match[a-z]+" nil t)
10780 (setq beg (match-end 0))
10781 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10782 (setq end (1- (match-beginning 0)))))
10783 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10784 (goto-char (point-min))
10785 (select-window cwin))))
10787 ;;; The mark ring for links jumps
10789 (defvar org-mark-ring nil
10790 "Mark ring for positions before jumps in Org-mode.")
10791 (defvar org-mark-ring-last-goto nil
10792 "Last position in the mark ring used to go back.")
10793 ;; Fill and close the ring
10794 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10795 (loop for i from 1 to org-mark-ring-length do
10796 (push (make-marker) org-mark-ring))
10797 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10798 org-mark-ring)
10800 (defun org-mark-ring-push (&optional pos buffer)
10801 "Put the current position or POS into the mark ring and rotate it."
10802 (interactive)
10803 (setq pos (or pos (point)))
10804 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10805 (move-marker (car org-mark-ring)
10806 (or pos (point))
10807 (or buffer (current-buffer)))
10808 (message "%s"
10809 (substitute-command-keys
10810 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10812 (defun org-mark-ring-goto (&optional n)
10813 "Jump to the previous position in the mark ring.
10814 With prefix arg N, jump back that many stored positions. When
10815 called several times in succession, walk through the entire ring.
10816 Org-mode commands jumping to a different position in the current file,
10817 or to another Org-mode file, automatically push the old position
10818 onto the ring."
10819 (interactive "p")
10820 (let (p m)
10821 (if (eq last-command this-command)
10822 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10823 (setq p org-mark-ring))
10824 (setq org-mark-ring-last-goto p)
10825 (setq m (car p))
10826 (org-pop-to-buffer-same-window (marker-buffer m))
10827 (goto-char m)
10828 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10830 (defun org-remove-angle-brackets (s)
10831 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10832 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10834 (defun org-add-angle-brackets (s)
10835 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10836 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10838 (defun org-remove-double-quotes (s)
10839 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10840 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10843 ;;; Following specific links
10845 (defun org-follow-timestamp-link ()
10846 "Open an agenda view for the time-stamp date/range at point."
10847 (cond
10848 ((org-at-date-range-p t)
10849 (let ((org-agenda-start-on-weekday)
10850 (t1 (match-string 1))
10851 (t2 (match-string 2)) tt1 tt2)
10852 (setq tt1 (time-to-days (org-time-string-to-time t1))
10853 tt2 (time-to-days (org-time-string-to-time t2)))
10854 (let ((org-agenda-buffer-tmp-name
10855 (format "*Org Agenda(a:%s)"
10856 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10857 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10858 ((org-at-timestamp-p t)
10859 (let ((org-agenda-buffer-tmp-name
10860 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10861 (org-agenda-list nil (time-to-days (org-time-string-to-time
10862 (substring (match-string 1) 0 10)))
10863 1)))
10864 (t (error "This should not happen"))))
10867 ;;; Following file links
10868 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10869 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10870 (declare-function mailcap-mime-info
10871 "mailcap" (string &optional request no-decode))
10872 (defvar org-wait nil)
10873 (defun org-open-file (path &optional in-emacs line search)
10874 "Open the file at PATH.
10875 First, this expands any special file name abbreviations. Then the
10876 configuration variable `org-file-apps' is checked if it contains an
10877 entry for this file type, and if yes, the corresponding command is launched.
10879 If no application is found, Emacs simply visits the file.
10881 With optional prefix argument IN-EMACS, Emacs will visit the file.
10882 With a double \\[universal-argument] \\[universal-argument] \
10883 prefix arg, Org tries to avoid opening in Emacs
10884 and to use an external application to visit the file.
10886 Optional LINE specifies a line to go to, optional SEARCH a string
10887 to search for. If LINE or SEARCH is given, the file will be
10888 opened in Emacs, unless an entry from org-file-apps that makes
10889 use of groups in a regexp matches.
10891 If you want to change the way frames are used when following a
10892 link, please customize `org-link-frame-setup'.
10894 If the file does not exist, an error is thrown."
10895 (let* ((file (if (equal path "")
10896 buffer-file-name
10897 (substitute-in-file-name (expand-file-name path))))
10898 (file-apps (append org-file-apps (org-default-apps)))
10899 (apps (org-remove-if
10900 'org-file-apps-entry-match-against-dlink-p file-apps))
10901 (apps-dlink (org-remove-if-not
10902 'org-file-apps-entry-match-against-dlink-p file-apps))
10903 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10904 (dirp (if remp nil (file-directory-p file)))
10905 (file (if (and dirp org-open-directory-means-index-dot-org)
10906 (concat (file-name-as-directory file) "index.org")
10907 file))
10908 (a-m-a-p (assq 'auto-mode apps))
10909 (dfile (downcase file))
10910 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10911 (link (cond ((and (eq line nil)
10912 (eq search nil))
10913 file)
10914 (line
10915 (concat file "::" (number-to-string line)))
10916 (search
10917 (concat file "::" search))))
10918 (dlink (downcase link))
10919 (old-buffer (current-buffer))
10920 (old-pos (point))
10921 (old-mode major-mode)
10922 ext cmd link-match-data)
10923 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10924 (setq ext (match-string 1 dfile))
10925 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10926 (setq ext (match-string 1 dfile))))
10927 (cond
10928 ((member in-emacs '((16) system))
10929 (setq cmd (cdr (assoc 'system apps))))
10930 (in-emacs (setq cmd 'emacs))
10932 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10933 (and dirp (cdr (assoc 'directory apps)))
10934 ; first, try matching against apps-dlink
10935 ; if we get a match here, store the match data for later
10936 (let ((match (assoc-default dlink apps-dlink
10937 'string-match)))
10938 (if match
10939 (progn (setq link-match-data (match-data))
10940 match)
10941 (progn (setq in-emacs (or in-emacs line search))
10942 nil))) ; if we have no match in apps-dlink,
10943 ; always open the file in emacs if line or search
10944 ; is given (for backwards compatibility)
10945 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10946 'string-match)
10947 (cdr (assoc ext apps))
10948 (cdr (assoc t apps))))))
10949 (when (eq cmd 'system)
10950 (setq cmd (cdr (assoc 'system apps))))
10951 (when (eq cmd 'default)
10952 (setq cmd (cdr (assoc t apps))))
10953 (when (eq cmd 'mailcap)
10954 (require 'mailcap)
10955 (mailcap-parse-mailcaps)
10956 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10957 (command (mailcap-mime-info mime-type)))
10958 (if (stringp command)
10959 (setq cmd command)
10960 (setq cmd 'emacs))))
10961 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10962 (not (file-exists-p file))
10963 (not org-open-non-existing-files))
10964 (error "No such file: %s" file))
10965 (cond
10966 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10967 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10968 (while (string-match "['\"]%s['\"]" cmd)
10969 (setq cmd (replace-match "%s" t t cmd)))
10970 (while (string-match "%s" cmd)
10971 (setq cmd (replace-match
10972 (save-match-data
10973 (shell-quote-argument
10974 (convert-standard-filename file)))
10975 t t cmd)))
10977 ;; Replace "%1", "%2" etc. in command with group matches from regex
10978 (save-match-data
10979 (let ((match-index 1)
10980 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10981 (set-match-data link-match-data)
10982 (while (<= match-index number-of-groups)
10983 (let ((regex (concat "%" (number-to-string match-index)))
10984 (replace-with (match-string match-index dlink)))
10985 (while (string-match regex cmd)
10986 (setq cmd (replace-match replace-with t t cmd))))
10987 (setq match-index (+ match-index 1)))))
10989 (save-window-excursion
10990 (message "Running %s...done" cmd)
10991 (start-process-shell-command cmd nil cmd)
10992 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10993 ((or (stringp cmd)
10994 (eq cmd 'emacs))
10995 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10996 (widen)
10997 (if line (org-goto-line line)
10998 (if search (org-link-search search))))
10999 ((consp cmd)
11000 (let ((file (convert-standard-filename file)))
11001 (save-match-data
11002 (set-match-data link-match-data)
11003 (eval cmd))))
11004 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11005 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11006 (or (not (equal old-buffer (current-buffer)))
11007 (not (equal old-pos (point))))
11008 (org-mark-ring-push old-pos old-buffer))))
11010 (defun org-file-apps-entry-match-against-dlink-p (entry)
11011 "This function returns non-nil if `entry' uses a regular
11012 expression which should be matched against the whole link by
11013 org-open-file.
11015 It assumes that is the case when the entry uses a regular
11016 expression which has at least one grouping construct and the
11017 action is either a lisp form or a command string containing
11018 '%1', i.e. using at least one subexpression match as a
11019 parameter."
11020 (let ((selector (car entry))
11021 (action (cdr entry)))
11022 (if (stringp selector)
11023 (and (> (regexp-opt-depth selector) 0)
11024 (or (and (stringp action)
11025 (string-match "%[0-9]" action))
11026 (consp action)))
11027 nil)))
11029 (defun org-default-apps ()
11030 "Return the default applications for this operating system."
11031 (cond
11032 ((eq system-type 'darwin)
11033 org-file-apps-defaults-macosx)
11034 ((eq system-type 'windows-nt)
11035 org-file-apps-defaults-windowsnt)
11036 (t org-file-apps-defaults-gnu)))
11038 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11039 "Convert extensions to regular expressions in the cars of LIST.
11040 Also, weed out any non-string entries, because the return value is used
11041 only for regexp matching.
11042 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11043 point to the symbol `emacs', indicating that the file should
11044 be opened in Emacs."
11045 (append
11046 (delq nil
11047 (mapcar (lambda (x)
11048 (if (not (stringp (car x)))
11050 (if (string-match "\\W" (car x))
11052 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11053 list))
11054 (if add-auto-mode
11055 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11057 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11058 (defun org-file-remote-p (file)
11059 "Test whether FILE specifies a location on a remote system.
11060 Return non-nil if the location is indeed remote.
11062 For example, the filename \"/user@host:/foo\" specifies a location
11063 on the system \"/user@host:\"."
11064 (cond ((fboundp 'file-remote-p)
11065 (file-remote-p file))
11066 ((fboundp 'tramp-handle-file-remote-p)
11067 (tramp-handle-file-remote-p file))
11068 ((and (boundp 'ange-ftp-name-format)
11069 (string-match (car ange-ftp-name-format) file))
11070 t)))
11073 ;;;; Refiling
11075 (defun org-get-org-file ()
11076 "Read a filename, with default directory `org-directory'."
11077 (let ((default (or org-default-notes-file remember-data-file)))
11078 (read-file-name (format "File name [%s]: " default)
11079 (file-name-as-directory org-directory)
11080 default)))
11082 (defun org-notes-order-reversed-p ()
11083 "Check if the current file should receive notes in reversed order."
11084 (cond
11085 ((not org-reverse-note-order) nil)
11086 ((eq t org-reverse-note-order) t)
11087 ((not (listp org-reverse-note-order)) nil)
11088 (t (catch 'exit
11089 (let ((all org-reverse-note-order)
11090 entry)
11091 (while (setq entry (pop all))
11092 (if (string-match (car entry) buffer-file-name)
11093 (throw 'exit (cdr entry))))
11094 nil)))))
11096 (defvar org-refile-target-table nil
11097 "The list of refile targets, created by `org-refile'.")
11099 (defvar org-agenda-new-buffers nil
11100 "Buffers created to visit agenda files.")
11102 (defvar org-refile-cache nil
11103 "Cache for refile targets.")
11105 (defvar org-refile-markers nil
11106 "All the markers used for caching refile locations.")
11108 (defun org-refile-marker (pos)
11109 "Get a new refile marker, but only if caching is in use."
11110 (if (not org-refile-use-cache)
11112 (let ((m (make-marker)))
11113 (move-marker m pos)
11114 (push m org-refile-markers)
11115 m)))
11117 (defun org-refile-cache-clear ()
11118 "Clear the refile cache and disable all the markers."
11119 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11120 (setq org-refile-markers nil)
11121 (setq org-refile-cache nil)
11122 (message "Refile cache has been cleared"))
11124 (defun org-refile-cache-check-set (set)
11125 "Check if all the markers in the cache still have live buffers."
11126 (let (marker)
11127 (catch 'exit
11128 (while (and set (setq marker (nth 3 (pop set))))
11129 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11130 (when (and marker (null (marker-buffer marker)))
11131 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11132 (sit-for 3)
11133 (throw 'exit nil)))
11134 t)))
11136 (defun org-refile-cache-put (set &rest identifiers)
11137 "Push the refile targets SET into the cache, under IDENTIFIERS."
11138 (let* ((key (sha1 (prin1-to-string identifiers)))
11139 (entry (assoc key org-refile-cache)))
11140 (if entry
11141 (setcdr entry set)
11142 (push (cons key set) org-refile-cache))))
11144 (defun org-refile-cache-get (&rest identifiers)
11145 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11146 (cond
11147 ((not org-refile-cache) nil)
11148 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11150 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11151 org-refile-cache))))
11152 (and set (org-refile-cache-check-set set) set)))))
11154 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11155 "Produce a table with refile targets."
11156 (let ((case-fold-search nil)
11157 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11158 (entries (or org-refile-targets '((nil . (:level . 1)))))
11159 targets tgs txt re files f desc descre fast-path-p level pos0)
11160 (message "Getting targets...")
11161 (with-current-buffer (or default-buffer (current-buffer))
11162 (while (setq entry (pop entries))
11163 (setq files (car entry) desc (cdr entry))
11164 (setq fast-path-p nil)
11165 (cond
11166 ((null files) (setq files (list (current-buffer))))
11167 ((eq files 'org-agenda-files)
11168 (setq files (org-agenda-files 'unrestricted)))
11169 ((and (symbolp files) (fboundp files))
11170 (setq files (funcall files)))
11171 ((and (symbolp files) (boundp files))
11172 (setq files (symbol-value files))))
11173 (if (stringp files) (setq files (list files)))
11174 (cond
11175 ((eq (car desc) :tag)
11176 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11177 ((eq (car desc) :todo)
11178 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11179 ((eq (car desc) :regexp)
11180 (setq descre (cdr desc)))
11181 ((eq (car desc) :level)
11182 (setq descre (concat "^\\*\\{" (number-to-string
11183 (if org-odd-levels-only
11184 (1- (* 2 (cdr desc)))
11185 (cdr desc)))
11186 "\\}[ \t]")))
11187 ((eq (car desc) :maxlevel)
11188 (setq fast-path-p t)
11189 (setq descre (concat "^\\*\\{1," (number-to-string
11190 (if org-odd-levels-only
11191 (1- (* 2 (cdr desc)))
11192 (cdr desc)))
11193 "\\}[ \t]")))
11194 (t (error "Bad refiling target description %s" desc)))
11195 (while (setq f (pop files))
11196 (with-current-buffer
11197 (if (bufferp f) f (org-get-agenda-file-buffer f))
11199 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11200 (progn
11201 (if (bufferp f) (setq f (buffer-file-name
11202 (buffer-base-buffer f))))
11203 (setq f (and f (expand-file-name f)))
11204 (if (eq org-refile-use-outline-path 'file)
11205 (push (list (file-name-nondirectory f) f nil nil) tgs))
11206 (save-excursion
11207 (save-restriction
11208 (widen)
11209 (goto-char (point-min))
11210 (while (re-search-forward descre nil t)
11211 (goto-char (setq pos0 (point-at-bol)))
11212 (catch 'next
11213 (when org-refile-target-verify-function
11214 (save-match-data
11215 (or (funcall org-refile-target-verify-function)
11216 (throw 'next t))))
11217 (when (and (looking-at org-complex-heading-regexp)
11218 (not (member (match-string 4) excluded-entries))
11219 (match-string 4))
11220 (setq level (org-reduced-level
11221 (- (match-end 1) (match-beginning 1)))
11222 txt (org-link-display-format (match-string 4))
11223 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11224 re (format org-complex-heading-regexp-format
11225 (regexp-quote (match-string 4))))
11226 (when org-refile-use-outline-path
11227 (setq txt (mapconcat
11228 'org-protect-slash
11229 (append
11230 (if (eq org-refile-use-outline-path
11231 'file)
11232 (list (file-name-nondirectory
11233 (buffer-file-name
11234 (buffer-base-buffer))))
11235 (if (eq org-refile-use-outline-path
11236 'full-file-path)
11237 (list (buffer-file-name
11238 (buffer-base-buffer)))))
11239 (org-get-outline-path fast-path-p
11240 level txt)
11241 (list txt))
11242 "/")))
11243 (push (list txt f re (org-refile-marker (point)))
11244 tgs)))
11245 (when (= (point) pos0)
11246 ;; verification function has not moved point
11247 (goto-char (point-at-eol))))))))
11248 (when org-refile-use-cache
11249 (org-refile-cache-put tgs (buffer-file-name) descre))
11250 (setq targets (append tgs targets))
11251 ))))
11252 (message "Getting targets...done")
11253 (nreverse targets)))
11255 (defun org-protect-slash (s)
11256 (while (string-match "/" s)
11257 (setq s (replace-match "\\" t t s)))
11260 (defvar org-olpa (make-vector 20 nil))
11262 (defun org-get-outline-path (&optional fastp level heading)
11263 "Return the outline path to the current entry, as a list.
11265 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11266 routine which makes outline path derivations for an entire file,
11267 avoiding backtracing. Refile target collection makes use of that."
11268 (if fastp
11269 (progn
11270 (if (> level 19)
11271 (error "Outline path failure, more than 19 levels"))
11272 (loop for i from level upto 19 do
11273 (aset org-olpa i nil))
11274 (prog1
11275 (delq nil (append org-olpa nil))
11276 (aset org-olpa level heading)))
11277 (let (rtn case-fold-search)
11278 (save-excursion
11279 (save-restriction
11280 (widen)
11281 (while (org-up-heading-safe)
11282 (when (looking-at org-complex-heading-regexp)
11283 (push (org-match-string-no-properties 4) rtn)))
11284 rtn)))))
11286 (defun org-format-outline-path (path &optional width prefix separator)
11287 "Format the outline path PATH for display.
11288 WIDTH is the maximum number of characters that is available.
11289 PREFIX is a prefix to be included in the returned string,
11290 such as the file name.
11291 SEPARATOR is inserted between the different parts of the path,
11292 the default is \"/\"."
11293 (setq width (or width 79))
11294 (if prefix (setq width (- width (length prefix))))
11295 (if (not path)
11296 (or prefix "")
11297 (let* ((nsteps (length path))
11298 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11299 (maxwidth (if (<= total-width width)
11300 10000 ;; everything fits
11301 ;; we need to shorten the level headings
11302 (/ (- width nsteps) nsteps)))
11303 (org-odd-levels-only nil)
11304 (n 0)
11305 (total (1+ (length prefix))))
11306 (setq maxwidth (max maxwidth 10))
11307 (concat prefix
11308 (if prefix (or separator "/"))
11309 (mapconcat
11310 (lambda (h)
11311 (setq n (1+ n))
11312 (if (and (= n nsteps) (< maxwidth 10000))
11313 (setq maxwidth (- total-width total)))
11314 (if (< (length h) maxwidth)
11315 (progn (setq total (+ total (length h) 1)) h)
11316 (setq h (substring h 0 (- maxwidth 2))
11317 total (+ total maxwidth 1))
11318 (if (string-match "[ \t]+\\'" h)
11319 (setq h (substring h 0 (match-beginning 0))))
11320 (setq h (concat h "..")))
11321 (org-add-props h nil 'face
11322 (nth (% (1- n) org-n-level-faces)
11323 org-level-faces))
11325 path (or separator "/"))))))
11327 (defun org-display-outline-path (&optional file current separator just-return-string)
11328 "Display the current outline path in the echo area.
11330 If FILE is non-nil, prepend the output with the file name.
11331 If CURRENT is non-nil, append the current heading to the output.
11332 SEPARATOR is passed through to `org-format-outline-path'. It separates
11333 the different parts of the path and defaults to \"/\".
11334 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11335 (interactive "P")
11336 (let* (case-fold-search
11337 message-log-max ; Don't populate the *Messages* buffer
11338 (bfn (buffer-file-name (buffer-base-buffer)))
11339 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11340 res)
11341 (if current (setq path (append path
11342 (save-excursion
11343 (org-back-to-heading t)
11344 (if (looking-at org-complex-heading-regexp)
11345 (list (match-string 4)))))))
11346 (setq res
11347 (org-format-outline-path
11348 path
11349 (1- (frame-width))
11350 (and file bfn (concat (file-name-nondirectory bfn) separator))
11351 separator))
11352 (if just-return-string
11353 (org-no-properties res)
11354 (message "%s" res))))
11356 (defvar org-refile-history nil
11357 "History for refiling operations.")
11359 (defvar org-after-refile-insert-hook nil
11360 "Hook run after `org-refile' has inserted its stuff at the new location.
11361 Note that this is still *before* the stuff will be removed from
11362 the *old* location.")
11364 (defvar org-capture-last-stored-marker)
11365 (defvar org-refile-keep nil
11366 "Non-nil means `org-refile' will copy instead of refile.")
11368 (defun org-copy ()
11369 "Like `org-refile', but copy."
11370 (interactive)
11371 (let ((org-refile-keep t))
11372 (funcall 'org-refile nil nil nil "Copy")))
11374 (defun org-refile (&optional goto default-buffer rfloc msg)
11375 "Move the entry or entries at point to another heading.
11376 The list of target headings is compiled using the information in
11377 `org-refile-targets', which see.
11379 At the target location, the entry is filed as a subitem of the target
11380 heading. Depending on `org-reverse-note-order', the new subitem will
11381 either be the first or the last subitem.
11383 If there is an active region, all entries in that region will be moved.
11384 However, the region must fulfill the requirement that the first heading
11385 is the first one sets the top-level of the moved text - at most siblings
11386 below it are allowed.
11388 With prefix arg GOTO, the command will only visit the target location
11389 and not actually move anything.
11391 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11392 go to the location where the last refiling operation has put the subtree.
11393 With a prefix argument of `2', refile to the running clock.
11395 RFLOC can be a refile location obtained in a different way.
11397 MSG is a string to replace \"Refile\" in the default prompt with
11398 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11400 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11402 If you are using target caching (see `org-refile-use-cache'),
11403 you have to clear the target cache in order to find new targets.
11404 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11405 prefix argument (`C-u C-u C-u C-c C-w')."
11407 (interactive "P")
11408 (if (member goto '(0 (64)))
11409 (org-refile-cache-clear)
11410 (let* ((actionmsg (or msg "Refile"))
11411 (cbuf (current-buffer))
11412 (regionp (org-region-active-p))
11413 (region-start (and regionp (region-beginning)))
11414 (region-end (and regionp (region-end)))
11415 (region-length (and regionp (- region-end region-start)))
11416 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11417 pos it nbuf file re level reversed)
11418 (setq last-command nil)
11419 (when regionp
11420 (goto-char region-start)
11421 (or (bolp) (goto-char (point-at-bol)))
11422 (setq region-start (point))
11423 (unless (or (org-kill-is-subtree-p
11424 (buffer-substring region-start region-end))
11425 (prog1 org-refile-active-region-within-subtree
11426 (org-toggle-heading)))
11427 (error "The region is not a (sequence of) subtree(s)")))
11428 (if (equal goto '(16))
11429 (org-refile-goto-last-stored)
11430 (when (or
11431 (and (equal goto 2)
11432 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11433 (prog1
11434 (setq it (list (or org-clock-heading "running clock")
11435 (buffer-file-name
11436 (marker-buffer org-clock-hd-marker))
11438 (marker-position org-clock-hd-marker)))
11439 (setq goto nil)))
11440 (setq it (or rfloc
11441 (let (heading-text)
11442 (save-excursion
11443 (unless goto
11444 (org-back-to-heading t)
11445 (setq heading-text
11446 (nth 4 (org-heading-components))))
11448 (org-refile-get-location
11449 (cond (goto "Goto")
11450 (regionp (concat actionmsg " region to"))
11451 (t (concat actionmsg " subtree \""
11452 heading-text "\" to")))
11453 default-buffer
11454 (and (not (equal '(4) goto))
11455 org-refile-allow-creating-parent-nodes)
11456 goto))))))
11457 (setq file (nth 1 it)
11458 re (nth 2 it)
11459 pos (nth 3 it))
11460 (if (and (not goto)
11462 (equal (buffer-file-name) file)
11463 (if regionp
11464 (and (>= pos region-start)
11465 (<= pos region-end))
11466 (and (>= pos (point))
11467 (< pos (save-excursion
11468 (org-end-of-subtree t t))))))
11469 (error "Cannot refile to position inside the tree or region"))
11471 (setq nbuf (or (find-buffer-visiting file)
11472 (find-file-noselect file)))
11473 (if goto
11474 (progn
11475 (org-pop-to-buffer-same-window nbuf)
11476 (goto-char pos)
11477 (org-show-context 'org-goto))
11478 (if regionp
11479 (progn
11480 (org-kill-new (buffer-substring region-start region-end))
11481 (org-save-markers-in-region region-start region-end))
11482 (org-copy-subtree 1 nil t))
11483 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11484 (find-file-noselect file)))
11485 (setq reversed (org-notes-order-reversed-p))
11486 (save-excursion
11487 (save-restriction
11488 (widen)
11489 (if pos
11490 (progn
11491 (goto-char pos)
11492 (looking-at org-outline-regexp)
11493 (setq level (org-get-valid-level (funcall outline-level) 1))
11494 (goto-char
11495 (if reversed
11496 (or (outline-next-heading) (point-max))
11497 (or (save-excursion (org-get-next-sibling))
11498 (org-end-of-subtree t t)
11499 (point-max)))))
11500 (setq level 1)
11501 (if (not reversed)
11502 (goto-char (point-max))
11503 (goto-char (point-min))
11504 (or (outline-next-heading) (goto-char (point-max)))))
11505 (if (not (bolp)) (newline))
11506 (org-paste-subtree level)
11507 (when org-log-refile
11508 (org-add-log-setup 'refile nil nil 'findpos
11509 org-log-refile)
11510 (unless (eq org-log-refile 'note)
11511 (save-excursion (org-add-log-note))))
11512 (and org-auto-align-tags
11513 (let ((org-loop-over-headlines-in-active-region nil))
11514 (org-set-tags nil t)))
11515 (with-demoted-errors
11516 (bookmark-set "org-refile-last-stored"))
11517 ;; If we are refiling for capture, make sure that the
11518 ;; last-capture pointers point here
11519 (when (org-bound-and-true-p org-refile-for-capture)
11520 (with-demoted-errors
11521 (bookmark-set "org-capture-last-stored-marker"))
11522 (move-marker org-capture-last-stored-marker (point)))
11523 (if (fboundp 'deactivate-mark) (deactivate-mark))
11524 (run-hooks 'org-after-refile-insert-hook))))
11525 (unless org-refile-keep
11526 (if regionp
11527 (delete-region (point) (+ (point) region-length))
11528 (org-cut-subtree)))
11529 (when (featurep 'org-inlinetask)
11530 (org-inlinetask-remove-END-maybe))
11531 (setq org-markers-to-move nil)
11532 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11534 (defun org-refile-goto-last-stored ()
11535 "Go to the location where the last refile was stored."
11536 (interactive)
11537 (bookmark-jump "org-refile-last-stored")
11538 (message "This is the location of the last refile"))
11540 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11541 no-exclude)
11542 "Prompt the user for a refile location, using PROMPT.
11543 PROMPT should not be suffixed with a colon and a space, because
11544 this function appends the default value from
11545 `org-refile-history' automatically, if that is not empty.
11546 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11547 this is used for the GOTO interface."
11548 (let ((org-refile-targets org-refile-targets)
11549 (org-refile-use-outline-path org-refile-use-outline-path)
11550 excluded-entries)
11551 (when (and (derived-mode-p 'org-mode)
11552 (not org-refile-use-cache)
11553 (not no-exclude))
11554 (org-map-tree
11555 (lambda()
11556 (setq excluded-entries
11557 (append excluded-entries (list (org-get-heading t t)))))))
11558 (setq org-refile-target-table
11559 (org-refile-get-targets default-buffer excluded-entries)))
11560 (unless org-refile-target-table
11561 (error "No refile targets"))
11562 (let* ((cbuf (current-buffer))
11563 (partial-completion-mode nil)
11564 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11565 (cfunc (if (and org-refile-use-outline-path
11566 org-outline-path-complete-in-steps)
11567 'org-olpath-completing-read
11568 'org-icompleting-read))
11569 (extra (if org-refile-use-outline-path "/" ""))
11570 (cbnex (concat (buffer-name) extra))
11571 (filename (and cfn (expand-file-name cfn)))
11572 (tbl (mapcar
11573 (lambda (x)
11574 (if (and (not (member org-refile-use-outline-path
11575 '(file full-file-path)))
11576 (not (equal filename (nth 1 x))))
11577 (cons (concat (car x) extra " ("
11578 (file-name-nondirectory (nth 1 x)) ")")
11579 (cdr x))
11580 (cons (concat (car x) extra) (cdr x))))
11581 org-refile-target-table))
11582 (completion-ignore-case t)
11583 cdef
11584 (prompt (concat prompt
11585 (or (and (car org-refile-history)
11586 (concat " (default " (car org-refile-history) ")"))
11587 (and (assoc cbnex tbl) (setq cdef cbnex)
11588 (concat " (default " cbnex ")"))) ": "))
11589 pa answ parent-target child parent old-hist)
11590 (setq old-hist org-refile-history)
11591 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11592 nil 'org-refile-history (or cdef (car org-refile-history))))
11593 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11594 (org-refile-check-position pa)
11595 (if pa
11596 (progn
11597 (when (or (not org-refile-history)
11598 (not (eq old-hist org-refile-history))
11599 (not (equal (car pa) (car org-refile-history))))
11600 (setq org-refile-history
11601 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11602 org-refile-history
11603 (cdr org-refile-history))))
11604 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11605 (pop org-refile-history)))
11607 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11608 (progn
11609 (setq parent (match-string 1 answ)
11610 child (match-string 2 answ))
11611 (setq parent-target (or (assoc parent tbl)
11612 (assoc (concat parent "/") tbl)))
11613 (when (and parent-target
11614 (or (eq new-nodes t)
11615 (and (eq new-nodes 'confirm)
11616 (y-or-n-p (format "Create new node \"%s\"? "
11617 child)))))
11618 (org-refile-new-child parent-target child)))
11619 (error "Invalid target location")))))
11621 (declare-function org-string-nw-p "org-macs" (s))
11622 (defun org-refile-check-position (refile-pointer)
11623 "Check if the refile pointer matches the headline to which it points."
11624 (let* ((file (nth 1 refile-pointer))
11625 (re (nth 2 refile-pointer))
11626 (pos (nth 3 refile-pointer))
11627 buffer)
11628 (if (and (not (markerp pos)) (not file))
11629 (error "Please save the buffer to a file before refiling")
11630 (when (org-string-nw-p re)
11631 (setq buffer (if (markerp pos)
11632 (marker-buffer pos)
11633 (or (find-buffer-visiting file)
11634 (find-file-noselect file))))
11635 (with-current-buffer buffer
11636 (save-excursion
11637 (save-restriction
11638 (widen)
11639 (goto-char pos)
11640 (beginning-of-line 1)
11641 (unless (org-looking-at-p re)
11642 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11644 (defun org-refile-new-child (parent-target child)
11645 "Use refile target PARENT-TARGET to add new CHILD below it."
11646 (unless parent-target
11647 (error "Cannot find parent for new node"))
11648 (let ((file (nth 1 parent-target))
11649 (pos (nth 3 parent-target))
11650 level)
11651 (with-current-buffer (or (find-buffer-visiting file)
11652 (find-file-noselect file))
11653 (save-excursion
11654 (save-restriction
11655 (widen)
11656 (if pos
11657 (goto-char pos)
11658 (goto-char (point-max))
11659 (if (not (bolp)) (newline)))
11660 (when (looking-at org-outline-regexp)
11661 (setq level (funcall outline-level))
11662 (org-end-of-subtree t t))
11663 (org-back-over-empty-lines)
11664 (insert "\n" (make-string
11665 (if pos (org-get-valid-level level 1) 1) ?*)
11666 " " child "\n")
11667 (beginning-of-line 0)
11668 (list (concat (car parent-target) "/" child) file "" (point)))))))
11670 (defun org-olpath-completing-read (prompt collection &rest args)
11671 "Read an outline path like a file name."
11672 (let ((thetable collection)
11673 (org-completion-use-ido nil) ; does not work with ido.
11674 (org-completion-use-iswitchb nil)) ; or iswitchb
11675 (apply
11676 'org-icompleting-read prompt
11677 (lambda (string predicate &optional flag)
11678 (let (rtn r f (l (length string)))
11679 (cond
11680 ((eq flag nil)
11681 ;; try completion
11682 (try-completion string thetable))
11683 ((eq flag t)
11684 ;; all-completions
11685 (setq rtn (all-completions string thetable predicate))
11686 (mapcar
11687 (lambda (x)
11688 (setq r (substring x l))
11689 (if (string-match " ([^)]*)$" x)
11690 (setq f (match-string 0 x))
11691 (setq f ""))
11692 (if (string-match "/" r)
11693 (concat string (substring r 0 (match-end 0)) f)
11695 rtn))
11696 ((eq flag 'lambda)
11697 ;; exact match?
11698 (assoc string thetable)))))
11699 args)))
11701 ;;;; Dynamic blocks
11703 (defun org-find-dblock (name)
11704 "Find the first dynamic block with name NAME in the buffer.
11705 If not found, stay at current position and return nil."
11706 (let ((case-fold-search t) pos)
11707 (save-excursion
11708 (goto-char (point-min))
11709 (setq pos (and (re-search-forward
11710 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11711 (match-beginning 0))))
11712 (if pos (goto-char pos))
11713 pos))
11715 (defconst org-dblock-start-re
11716 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11717 "Matches the start line of a dynamic block, with parameters.")
11719 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11720 "Matches the end of a dynamic block.")
11722 (defun org-create-dblock (plist)
11723 "Create a dynamic block section, with parameters taken from PLIST.
11724 PLIST must contain a :name entry which is used as name of the block."
11725 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11726 (end-of-line 1)
11727 (newline))
11728 (let ((col (current-column))
11729 (name (plist-get plist :name)))
11730 (insert "#+BEGIN: " name)
11731 (while plist
11732 (if (eq (car plist) :name)
11733 (setq plist (cddr plist))
11734 (insert " " (prin1-to-string (pop plist)))))
11735 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11736 (beginning-of-line -2)))
11738 (defun org-prepare-dblock ()
11739 "Prepare dynamic block for refresh.
11740 This empties the block, puts the cursor at the insert position and returns
11741 the property list including an extra property :name with the block name."
11742 (unless (looking-at org-dblock-start-re)
11743 (error "Not at a dynamic block"))
11744 (let* ((begdel (1+ (match-end 0)))
11745 (name (org-no-properties (match-string 1)))
11746 (params (append (list :name name)
11747 (read (concat "(" (match-string 3) ")")))))
11748 (save-excursion
11749 (beginning-of-line 1)
11750 (skip-chars-forward " \t")
11751 (setq params (plist-put params :indentation-column (current-column))))
11752 (unless (re-search-forward org-dblock-end-re nil t)
11753 (error "Dynamic block not terminated"))
11754 (setq params
11755 (append params
11756 (list :content (buffer-substring
11757 begdel (match-beginning 0)))))
11758 (delete-region begdel (match-beginning 0))
11759 (goto-char begdel)
11760 (open-line 1)
11761 params))
11763 (defun org-map-dblocks (&optional command)
11764 "Apply COMMAND to all dynamic blocks in the current buffer.
11765 If COMMAND is not given, use `org-update-dblock'."
11766 (let ((cmd (or command 'org-update-dblock)))
11767 (save-excursion
11768 (goto-char (point-min))
11769 (while (re-search-forward org-dblock-start-re nil t)
11770 (goto-char (match-beginning 0))
11771 (save-excursion
11772 (condition-case nil
11773 (funcall cmd)
11774 (error (message "Error during update of dynamic block"))))
11775 (unless (re-search-forward org-dblock-end-re nil t)
11776 (error "Dynamic block not terminated"))))))
11778 (defun org-dblock-update (&optional arg)
11779 "User command for updating dynamic blocks.
11780 Update the dynamic block at point. With prefix ARG, update all dynamic
11781 blocks in the buffer."
11782 (interactive "P")
11783 (if arg
11784 (org-update-all-dblocks)
11785 (or (looking-at org-dblock-start-re)
11786 (org-beginning-of-dblock))
11787 (org-update-dblock)))
11789 (defun org-update-dblock ()
11790 "Update the dynamic block at point.
11791 This means to empty the block, parse for parameters and then call
11792 the correct writing function."
11793 (interactive)
11794 (save-window-excursion
11795 (let* ((pos (point))
11796 (line (org-current-line))
11797 (params (org-prepare-dblock))
11798 (name (plist-get params :name))
11799 (indent (plist-get params :indentation-column))
11800 (cmd (intern (concat "org-dblock-write:" name))))
11801 (message "Updating dynamic block `%s' at line %d..." name line)
11802 (funcall cmd params)
11803 (message "Updating dynamic block `%s' at line %d...done" name line)
11804 (goto-char pos)
11805 (when (and indent (> indent 0))
11806 (setq indent (make-string indent ?\ ))
11807 (save-excursion
11808 (org-beginning-of-dblock)
11809 (forward-line 1)
11810 (while (not (looking-at org-dblock-end-re))
11811 (insert indent)
11812 (beginning-of-line 2))
11813 (when (looking-at org-dblock-end-re)
11814 (and (looking-at "[ \t]+")
11815 (replace-match ""))
11816 (insert indent)))))))
11818 (defun org-beginning-of-dblock ()
11819 "Find the beginning of the dynamic block at point.
11820 Error if there is no such block at point."
11821 (let ((pos (point))
11822 beg)
11823 (end-of-line 1)
11824 (if (and (re-search-backward org-dblock-start-re nil t)
11825 (setq beg (match-beginning 0))
11826 (re-search-forward org-dblock-end-re nil t)
11827 (> (match-end 0) pos))
11828 (goto-char beg)
11829 (goto-char pos)
11830 (error "Not in a dynamic block"))))
11832 (defun org-update-all-dblocks ()
11833 "Update all dynamic blocks in the buffer.
11834 This function can be used in a hook."
11835 (interactive)
11836 (when (derived-mode-p 'org-mode)
11837 (org-map-dblocks 'org-update-dblock)))
11840 ;;;; Completion
11842 (defun org-get-export-keywords ()
11843 "Return a list of all currently understood export keywords.
11844 Export keywords include options, block names, attributes and
11845 keywords relative to each registered export back-end."
11846 (delq nil
11847 (let (keywords)
11848 (mapc
11849 (lambda (back-end)
11850 (let ((props (cdr back-end)))
11851 ;; Back-end name (for keywords, like #+LATEX:)
11852 (push (upcase (symbol-name (car back-end))) keywords)
11853 ;; Back-end options.
11854 (mapc (lambda (option) (push (cadr option) keywords))
11855 (plist-get (cdr back-end) :options-alist))))
11856 (org-bound-and-true-p org-export-registered-backends))
11857 keywords)))
11859 (defconst org-options-keywords
11860 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11861 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11862 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11863 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11864 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11866 (defcustom org-structure-template-alist
11867 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11868 "<src lang=\"?\">\n\n</src>")
11869 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11870 "<example>\n?\n</example>")
11871 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11872 "<quote>\n?\n</quote>")
11873 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11874 "<verse>\n?\n</verse>")
11875 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11876 "<verbatim>\n?\n</verbatim>")
11877 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11878 "<center>\n?\n</center>")
11879 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11880 "<literal style=\"latex\">\n?\n</literal>")
11881 ("L" "#+LaTeX: "
11882 "<literal style=\"latex\">?</literal>")
11883 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11884 "<literal style=\"html\">\n?\n</literal>")
11885 ("H" "#+HTML: "
11886 "<literal style=\"html\">?</literal>")
11887 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11888 ("A" "#+ASCII: ")
11889 ("i" "#+INDEX: ?"
11890 "#+INDEX: ?")
11891 ("I" "#+INCLUDE: %file ?"
11892 "<include file=%file markup=\"?\">"))
11893 "Structure completion elements.
11894 This is a list of abbreviation keys and values. The value gets inserted
11895 if you type `<' followed by the key and then press the completion key,
11896 usually `M-TAB'. %file will be replaced by a file name after prompting
11897 for the file using completion. The cursor will be placed at the position
11898 of the `?` in the template.
11899 There are two templates for each key, the first uses the original Org syntax,
11900 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11901 the default when the /org-mtags.el/ module has been loaded. See also the
11902 variable `org-mtags-prefer-muse-templates'."
11903 :group 'org-completion
11904 :type '(repeat
11905 (string :tag "Key")
11906 (string :tag "Template")
11907 (string :tag "Muse Template")))
11909 (defun org-try-structure-completion ()
11910 "Try to complete a structure template before point.
11911 This looks for strings like \"<e\" on an otherwise empty line and
11912 expands them."
11913 (let ((l (buffer-substring (point-at-bol) (point)))
11915 (when (and (looking-at "[ \t]*$")
11916 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11917 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11918 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11919 (match-beginning 1)) a)
11920 t)))
11922 (defun org-complete-expand-structure-template (start cell)
11923 "Expand a structure template."
11924 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11925 (rpl (nth (if musep 2 1) cell))
11926 (ind ""))
11927 (delete-region start (point))
11928 (when (string-match "\\`#\\+" rpl)
11929 (cond
11930 ((bolp))
11931 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11932 (setq ind (buffer-substring (point-at-bol) (point))))
11933 (t (newline))))
11934 (setq start (point))
11935 (if (string-match "%file" rpl)
11936 (setq rpl (replace-match
11937 (concat
11938 "\""
11939 (save-match-data
11940 (abbreviate-file-name (read-file-name "Include file: ")))
11941 "\"")
11942 t t rpl)))
11943 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11944 (concat "\n" ind)))
11945 (insert rpl)
11946 (if (re-search-backward "\\?" start t) (delete-char 1))))
11948 ;;;; TODO, DEADLINE, Comments
11950 (defun org-toggle-comment ()
11951 "Change the COMMENT state of an entry."
11952 (interactive)
11953 (save-excursion
11954 (org-back-to-heading)
11955 (let (case-fold-search)
11956 (cond
11957 ((looking-at (format org-heading-keyword-regexp-format
11958 org-comment-string))
11959 (goto-char (match-end 1))
11960 (looking-at (concat " +" org-comment-string))
11961 (replace-match "" t t)
11962 (when (eolp) (insert " ")))
11963 ((looking-at org-outline-regexp)
11964 (goto-char (match-end 0))
11965 (insert org-comment-string " "))))))
11967 (defvar org-last-todo-state-is-todo nil
11968 "This is non-nil when the last TODO state change led to a TODO state.
11969 If the last change removed the TODO tag or switched to DONE, then
11970 this is nil.")
11972 (defvar org-setting-tags nil) ; dynamically skipped
11974 (defvar org-todo-setup-filter-hook nil
11975 "Hook for functions that pre-filter todo specs.
11976 Each function takes a todo spec and returns either nil or the spec
11977 transformed into canonical form." )
11979 (defvar org-todo-get-default-hook nil
11980 "Hook for functions that get a default item for todo.
11981 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11982 nil or a string to be used for the todo mark." )
11984 (defvar org-agenda-headline-snapshot-before-repeat)
11986 (defun org-current-effective-time ()
11987 "Return current time adjusted for `org-extend-today-until' variable."
11988 (let* ((ct (org-current-time))
11989 (dct (decode-time ct))
11990 (ct1
11991 (cond
11992 (org-use-last-clock-out-time-as-effective-time
11993 (or (org-clock-get-last-clock-out-time) ct))
11994 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11995 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11996 (t ct))))
11997 ct1))
11999 (defun org-todo-yesterday (&optional arg)
12000 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12001 (interactive "P")
12002 (if (eq major-mode 'org-agenda-mode)
12003 (apply 'org-agenda-todo-yesterday arg)
12004 (let* ((hour (third (decode-time
12005 (org-current-time))))
12006 (org-extend-today-until (1+ hour)))
12007 (org-todo arg))))
12009 (defvar org-block-entry-blocking ""
12010 "First entry preventing the TODO state change.")
12012 (defun org-todo (&optional arg)
12013 "Change the TODO state of an item.
12014 The state of an item is given by a keyword at the start of the heading,
12015 like
12016 *** TODO Write paper
12017 *** DONE Call mom
12019 The different keywords are specified in the variable `org-todo-keywords'.
12020 By default the available states are \"TODO\" and \"DONE\".
12021 So for this example: when the item starts with TODO, it is changed to DONE.
12022 When it starts with DONE, the DONE is removed. And when neither TODO nor
12023 DONE are present, add TODO at the beginning of the heading.
12025 With \\[universal-argument] prefix arg, use completion to determine the new \
12026 state.
12027 With numeric prefix arg, switch to that state.
12028 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12029 keywords (nextset).
12030 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12031 With a numeric prefix arg of 0, inhibit note taking for the change.
12033 For calling through lisp, arg is also interpreted in the following way:
12034 'none -> empty state
12035 \"\"(empty string) -> switch to empty state
12036 'done -> switch to DONE
12037 'nextset -> switch to the next set of keywords
12038 'previousset -> switch to the previous set of keywords
12039 \"WAITING\" -> switch to the specified keyword, but only if it
12040 really is a member of `org-todo-keywords'."
12041 (interactive "P")
12042 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12043 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12044 'region-start-level 'region))
12045 org-loop-over-headlines-in-active-region)
12046 (org-map-entries
12047 `(org-todo ,arg)
12048 org-loop-over-headlines-in-active-region
12049 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12050 (if (equal arg '(16)) (setq arg 'nextset))
12051 (let ((org-blocker-hook org-blocker-hook)
12052 commentp
12053 case-fold-search)
12054 (when (equal arg '(64))
12055 (setq arg nil org-blocker-hook nil))
12056 (when (and org-blocker-hook
12057 (or org-inhibit-blocking
12058 (org-entry-get nil "NOBLOCKING")))
12059 (setq org-blocker-hook nil))
12060 (save-excursion
12061 (catch 'exit
12062 (org-back-to-heading t)
12063 (when (looking-at (concat "^\\*+ " org-comment-string))
12064 (org-toggle-comment)
12065 (setq commentp t))
12066 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12067 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12068 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12069 (let* ((match-data (match-data))
12070 (startpos (point-at-bol))
12071 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12072 (org-log-done org-log-done)
12073 (org-log-repeat org-log-repeat)
12074 (org-todo-log-states org-todo-log-states)
12075 (org-inhibit-logging
12076 (if (equal arg 0)
12077 (progn (setq arg nil) 'note) org-inhibit-logging))
12078 (this (match-string 1))
12079 (hl-pos (match-beginning 0))
12080 (head (org-get-todo-sequence-head this))
12081 (ass (assoc head org-todo-kwd-alist))
12082 (interpret (nth 1 ass))
12083 (done-word (nth 3 ass))
12084 (final-done-word (nth 4 ass))
12085 (org-last-state (or this ""))
12086 (completion-ignore-case t)
12087 (member (member this org-todo-keywords-1))
12088 (tail (cdr member))
12089 (org-state (cond
12090 ((and org-todo-key-trigger
12091 (or (and (equal arg '(4))
12092 (eq org-use-fast-todo-selection 'prefix))
12093 (and (not arg) org-use-fast-todo-selection
12094 (not (eq org-use-fast-todo-selection
12095 'prefix)))))
12096 ;; Use fast selection
12097 (org-fast-todo-selection))
12098 ((and (equal arg '(4))
12099 (or (not org-use-fast-todo-selection)
12100 (not org-todo-key-trigger)))
12101 ;; Read a state with completion
12102 (org-icompleting-read
12103 "State: " (mapcar 'list org-todo-keywords-1)
12104 nil t))
12105 ((eq arg 'right)
12106 (if this
12107 (if tail (car tail) nil)
12108 (car org-todo-keywords-1)))
12109 ((eq arg 'left)
12110 (if (equal member org-todo-keywords-1)
12112 (if this
12113 (nth (- (length org-todo-keywords-1)
12114 (length tail) 2)
12115 org-todo-keywords-1)
12116 (org-last org-todo-keywords-1))))
12117 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12118 (setq arg nil))) ; hack to fall back to cycling
12119 (arg
12120 ;; user or caller requests a specific state
12121 (cond
12122 ((equal arg "") nil)
12123 ((eq arg 'none) nil)
12124 ((eq arg 'done) (or done-word (car org-done-keywords)))
12125 ((eq arg 'nextset)
12126 (or (car (cdr (member head org-todo-heads)))
12127 (car org-todo-heads)))
12128 ((eq arg 'previousset)
12129 (let ((org-todo-heads (reverse org-todo-heads)))
12130 (or (car (cdr (member head org-todo-heads)))
12131 (car org-todo-heads))))
12132 ((car (member arg org-todo-keywords-1)))
12133 ((stringp arg)
12134 (error "State `%s' not valid in this file" arg))
12135 ((nth (1- (prefix-numeric-value arg))
12136 org-todo-keywords-1))))
12137 ((null member) (or head (car org-todo-keywords-1)))
12138 ((equal this final-done-word) nil) ;; -> make empty
12139 ((null tail) nil) ;; -> first entry
12140 ((memq interpret '(type priority))
12141 (if (eq this-command last-command)
12142 (car tail)
12143 (if (> (length tail) 0)
12144 (or done-word (car org-done-keywords))
12145 nil)))
12147 (car tail))))
12148 (org-state (or
12149 (run-hook-with-args-until-success
12150 'org-todo-get-default-hook org-state org-last-state)
12151 org-state))
12152 (next (if org-state (concat " " org-state " ") " "))
12153 (change-plist (list :type 'todo-state-change :from this :to org-state
12154 :position startpos))
12155 dolog now-done-p)
12156 (when org-blocker-hook
12157 (setq org-last-todo-state-is-todo
12158 (not (member this org-done-keywords)))
12159 (unless (save-excursion
12160 (save-match-data
12161 (org-with-wide-buffer
12162 (run-hook-with-args-until-failure
12163 'org-blocker-hook change-plist))))
12164 (if (org-called-interactively-p 'interactive)
12165 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12166 this org-state org-block-entry-blocking)
12167 ;; fail silently
12168 (message "TODO state change from %s to %s blocked (by \"%s\")"
12169 this org-state org-block-entry-blocking)
12170 (throw 'exit nil))))
12171 (store-match-data match-data)
12172 (replace-match next t t)
12173 (unless (pos-visible-in-window-p hl-pos)
12174 (message "TODO state changed to %s" (org-trim next)))
12175 (unless head
12176 (setq head (org-get-todo-sequence-head org-state)
12177 ass (assoc head org-todo-kwd-alist)
12178 interpret (nth 1 ass)
12179 done-word (nth 3 ass)
12180 final-done-word (nth 4 ass)))
12181 (when (memq arg '(nextset previousset))
12182 (message "Keyword-Set %d/%d: %s"
12183 (- (length org-todo-sets) -1
12184 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12185 (length org-todo-sets)
12186 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12187 (setq org-last-todo-state-is-todo
12188 (not (member org-state org-done-keywords)))
12189 (setq now-done-p (and (member org-state org-done-keywords)
12190 (not (member this org-done-keywords))))
12191 (and logging (org-local-logging logging))
12192 (when (and (or org-todo-log-states org-log-done)
12193 (not (eq org-inhibit-logging t))
12194 (not (memq arg '(nextset previousset))))
12195 ;; we need to look at recording a time and note
12196 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12197 (nth 2 (assoc this org-todo-log-states))))
12198 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12199 (setq dolog 'time))
12200 (when (and org-state
12201 (member org-state org-not-done-keywords)
12202 (not (member this org-not-done-keywords)))
12203 ;; This is now a todo state and was not one before
12204 ;; If there was a CLOSED time stamp, get rid of it.
12205 (org-add-planning-info nil nil 'closed))
12206 (when (and now-done-p org-log-done)
12207 ;; It is now done, and it was not done before
12208 (org-add-planning-info 'closed (org-current-effective-time))
12209 (if (and (not dolog) (eq 'note org-log-done))
12210 (org-add-log-setup 'done org-state this 'findpos 'note)))
12211 (when (and org-state dolog)
12212 ;; This is a non-nil state, and we need to log it
12213 (org-add-log-setup 'state org-state this 'findpos dolog)))
12214 ;; Fixup tag positioning
12215 (org-todo-trigger-tag-changes org-state)
12216 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12217 (when org-provide-todo-statistics
12218 (org-update-parent-todo-statistics))
12219 (run-hooks 'org-after-todo-state-change-hook)
12220 (if (and arg (not (member org-state org-done-keywords)))
12221 (setq head (org-get-todo-sequence-head org-state)))
12222 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12223 ;; Do we need to trigger a repeat?
12224 (when now-done-p
12225 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12226 ;; This is for the agenda, take a snapshot of the headline.
12227 (save-match-data
12228 (setq org-agenda-headline-snapshot-before-repeat
12229 (org-get-heading))))
12230 (org-auto-repeat-maybe org-state))
12231 ;; Fixup cursor location if close to the keyword
12232 (if (and (outline-on-heading-p)
12233 (not (bolp))
12234 (save-excursion (beginning-of-line 1)
12235 (looking-at org-todo-line-regexp))
12236 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12237 (progn
12238 (goto-char (or (match-end 2) (match-end 1)))
12239 (and (looking-at " ") (just-one-space))))
12240 (when org-trigger-hook
12241 (save-excursion
12242 (run-hook-with-args 'org-trigger-hook change-plist)))
12243 (when commentp (org-toggle-comment))))))))
12245 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12246 "Block turning an entry into a TODO, using the hierarchy.
12247 This checks whether the current task should be blocked from state
12248 changes. Such blocking occurs when:
12250 1. The task has children which are not all in a completed state.
12252 2. A task has a parent with the property :ORDERED:, and there
12253 are siblings prior to the current task with incomplete
12254 status.
12256 3. The parent of the task is blocked because it has siblings that should
12257 be done first, or is child of a block grandparent TODO entry."
12259 (if (not org-enforce-todo-dependencies)
12260 t ; if locally turned off don't block
12261 (catch 'dont-block
12262 ;; If this is not a todo state change, or if this entry is already DONE,
12263 ;; do not block
12264 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12265 (member (plist-get change-plist :from)
12266 (cons 'done org-done-keywords))
12267 (member (plist-get change-plist :to)
12268 (cons 'todo org-not-done-keywords))
12269 (not (plist-get change-plist :to)))
12270 (throw 'dont-block t))
12271 ;; If this task has children, and any are undone, it's blocked
12272 (save-excursion
12273 (org-back-to-heading t)
12274 (let ((this-level (funcall outline-level)))
12275 (outline-next-heading)
12276 (let ((child-level (funcall outline-level)))
12277 (while (and (not (eobp))
12278 (> child-level this-level))
12279 ;; this todo has children, check whether they are all
12280 ;; completed
12281 (if (and (not (org-entry-is-done-p))
12282 (org-entry-is-todo-p))
12283 (progn (setq org-block-entry-blocking (org-get-heading))
12284 (throw 'dont-block nil)))
12285 (outline-next-heading)
12286 (setq child-level (funcall outline-level))))))
12287 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12288 ;; any previous siblings are undone, it's blocked
12289 (save-excursion
12290 (org-back-to-heading t)
12291 (let* ((pos (point))
12292 (parent-pos (and (org-up-heading-safe) (point))))
12293 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12294 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12295 (forward-line 1)
12296 (re-search-forward org-not-done-heading-regexp pos t))
12297 (setq org-block-entry-blocking (match-string 0))
12298 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12299 ;; Search further up the hierarchy, to see if an ancestor is blocked
12300 (while t
12301 (goto-char parent-pos)
12302 (if (not (looking-at org-not-done-heading-regexp))
12303 (throw 'dont-block t)) ; do not block, parent is not a TODO
12304 (setq pos (point))
12305 (setq parent-pos (and (org-up-heading-safe) (point)))
12306 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12307 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12308 (forward-line 1)
12309 (re-search-forward org-not-done-heading-regexp pos t)
12310 (setq org-block-entry-blocking (org-get-heading)))
12311 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12313 (defcustom org-track-ordered-property-with-tag nil
12314 "Should the ORDERED property also be shown as a tag?
12315 The ORDERED property decides if an entry should require subtasks to be
12316 completed in sequence. Since a property is not very visible, setting
12317 this option means that toggling the ORDERED property with the command
12318 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12319 not relevant for the behavior, but it makes things more visible.
12321 Note that toggling the tag with tags commands will not change the property
12322 and therefore not influence behavior!
12324 This can be t, meaning the tag ORDERED should be used, It can also be a
12325 string to select a different tag for this task."
12326 :group 'org-todo
12327 :type '(choice
12328 (const :tag "No tracking" nil)
12329 (const :tag "Track with ORDERED tag" t)
12330 (string :tag "Use other tag")))
12332 (defun org-toggle-ordered-property ()
12333 "Toggle the ORDERED property of the current entry.
12334 For better visibility, you can track the value of this property with a tag.
12335 See variable `org-track-ordered-property-with-tag'."
12336 (interactive)
12337 (let* ((t1 org-track-ordered-property-with-tag)
12338 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12339 (save-excursion
12340 (org-back-to-heading)
12341 (if (org-entry-get nil "ORDERED")
12342 (progn
12343 (org-delete-property "ORDERED" "PROPERTIES")
12344 (and tag (org-toggle-tag tag 'off))
12345 (message "Subtasks can be completed in arbitrary order"))
12346 (org-entry-put nil "ORDERED" "t")
12347 (and tag (org-toggle-tag tag 'on))
12348 (message "Subtasks must be completed in sequence")))))
12350 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12351 (defun org-block-todo-from-checkboxes (change-plist)
12352 "Block turning an entry into a TODO, using checkboxes.
12353 This checks whether the current task should be blocked from state
12354 changes because there are unchecked boxes in this entry."
12355 (if (not org-enforce-todo-checkbox-dependencies)
12356 t ; if locally turned off don't block
12357 (catch 'dont-block
12358 ;; If this is not a todo state change, or if this entry is already DONE,
12359 ;; do not block
12360 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12361 (member (plist-get change-plist :from)
12362 (cons 'done org-done-keywords))
12363 (member (plist-get change-plist :to)
12364 (cons 'todo org-not-done-keywords))
12365 (not (plist-get change-plist :to)))
12366 (throw 'dont-block t))
12367 ;; If this task has checkboxes that are not checked, it's blocked
12368 (save-excursion
12369 (org-back-to-heading t)
12370 (let ((beg (point)) end)
12371 (outline-next-heading)
12372 (setq end (point))
12373 (goto-char beg)
12374 (if (org-list-search-forward
12375 (concat (org-item-beginning-re)
12376 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12377 "\\[[- ]\\]")
12378 end t)
12379 (progn
12380 (if (boundp 'org-blocked-by-checkboxes)
12381 (setq org-blocked-by-checkboxes t))
12382 (throw 'dont-block nil)))))
12383 t))) ; do not block
12385 (defun org-entry-blocked-p ()
12386 "Is the current entry blocked?"
12387 (org-with-silent-modifications
12388 (if (org-entry-get nil "NOBLOCKING")
12389 nil ;; Never block this entry
12390 (not (run-hook-with-args-until-failure
12391 'org-blocker-hook
12392 (list :type 'todo-state-change
12393 :position (point)
12394 :from 'todo
12395 :to 'done))))))
12397 (defun org-update-statistics-cookies (all)
12398 "Update the statistics cookie, either from TODO or from checkboxes.
12399 This should be called with the cursor in a line with a statistics cookie."
12400 (interactive "P")
12401 (if all
12402 (progn
12403 (org-update-checkbox-count 'all)
12404 (org-map-entries 'org-update-parent-todo-statistics))
12405 (if (not (org-at-heading-p))
12406 (org-update-checkbox-count)
12407 (let ((pos (point-marker))
12408 end l1 l2)
12409 (ignore-errors (org-back-to-heading t))
12410 (if (not (org-at-heading-p))
12411 (org-update-checkbox-count)
12412 (setq l1 (org-outline-level))
12413 (setq end (save-excursion
12414 (outline-next-heading)
12415 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12416 (point)))
12417 (if (and (save-excursion
12418 (re-search-forward
12419 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12420 (not (save-excursion (re-search-forward
12421 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12422 (org-update-checkbox-count)
12423 (if (and l2 (> l2 l1))
12424 (progn
12425 (goto-char end)
12426 (org-update-parent-todo-statistics))
12427 (goto-char pos)
12428 (beginning-of-line 1)
12429 (while (re-search-forward
12430 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12431 (point-at-eol) t)
12432 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12433 (goto-char pos)
12434 (move-marker pos nil)))))
12436 (defvar org-entry-property-inherited-from) ;; defined below
12437 (defun org-update-parent-todo-statistics ()
12438 "Update any statistics cookie in the parent of the current headline.
12439 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12440 the entire subtree and this will travel up the hierarchy and update
12441 statistics everywhere."
12442 (let* ((prop (save-excursion (org-up-heading-safe)
12443 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12444 (recursive (or (not org-hierarchical-todo-statistics)
12445 (and prop (string-match "\\<recursive\\>" prop))))
12446 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12448 (first t)
12449 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12450 level ltoggle l1 new ndel
12451 (cnt-all 0) (cnt-done 0) is-percent kwd
12452 checkbox-beg ov ovs ove cookie-present)
12453 (catch 'exit
12454 (save-excursion
12455 (beginning-of-line 1)
12456 (setq ltoggle (funcall outline-level))
12457 ;; Three situations are to consider:
12459 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12460 ;; to the top-level ancestor on the headline;
12462 ;; 2. If parent has "recursive" property, repeat up to the
12463 ;; headline setting that property, taking inheritance into
12464 ;; account;
12466 ;; 3. Else, move up to direct parent and proceed only once.
12467 (while (and (setq level (org-up-heading-safe))
12468 (or recursive first)
12469 (>= (point) lim))
12470 (setq first nil cookie-present nil)
12471 (unless (and level
12472 (not (string-match
12473 "\\<checkbox\\>"
12474 (downcase (or (org-entry-get nil "COOKIE_DATA")
12475 "")))))
12476 (throw 'exit nil))
12477 (while (re-search-forward box-re (point-at-eol) t)
12478 (setq cnt-all 0 cnt-done 0 cookie-present t)
12479 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12480 (save-match-data
12481 (unless (outline-next-heading) (throw 'exit nil))
12482 (while (and (looking-at org-complex-heading-regexp)
12483 (> (setq l1 (length (match-string 1))) level))
12484 (setq kwd (and (or recursive (= l1 ltoggle))
12485 (match-string 2)))
12486 (if (or (eq org-provide-todo-statistics 'all-headlines)
12487 (and (listp org-provide-todo-statistics)
12488 (or (member kwd org-provide-todo-statistics)
12489 (member kwd org-done-keywords))))
12490 (setq cnt-all (1+ cnt-all))
12491 (if (eq org-provide-todo-statistics t)
12492 (and kwd (setq cnt-all (1+ cnt-all)))))
12493 (and (member kwd org-done-keywords)
12494 (setq cnt-done (1+ cnt-done)))
12495 (outline-next-heading)))
12496 (setq new
12497 (if is-percent
12498 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12499 (format "[%d/%d]" cnt-done cnt-all))
12500 ndel (- (match-end 0) checkbox-beg))
12501 ;; handle overlays when updating cookie from column view
12502 (when (setq ov (car (overlays-at checkbox-beg)))
12503 (setq ovs (overlay-start ov) ove (overlay-end ov))
12504 (delete-overlay ov))
12505 (goto-char checkbox-beg)
12506 (insert new)
12507 (delete-region (point) (+ (point) ndel))
12508 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12509 (when ov (move-overlay ov ovs ove)))
12510 (when cookie-present
12511 (run-hook-with-args 'org-after-todo-statistics-hook
12512 cnt-done (- cnt-all cnt-done))))))
12513 (run-hooks 'org-todo-statistics-hook)))
12515 (defvar org-after-todo-statistics-hook nil
12516 "Hook that is called after a TODO statistics cookie has been updated.
12517 Each function is called with two arguments: the number of not-done entries
12518 and the number of done entries.
12520 For example, the following function, when added to this hook, will switch
12521 an entry to DONE when all children are done, and back to TODO when new
12522 entries are set to a TODO status. Note that this hook is only called
12523 when there is a statistics cookie in the headline!
12525 (defun org-summary-todo (n-done n-not-done)
12526 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12527 (let (org-log-done org-log-states) ; turn off logging
12528 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12531 (defvar org-todo-statistics-hook nil
12532 "Hook that is run whenever Org thinks TODO statistics should be updated.
12533 This hook runs even if there is no statistics cookie present, in which case
12534 `org-after-todo-statistics-hook' would not run.")
12536 (defun org-todo-trigger-tag-changes (state)
12537 "Apply the changes defined in `org-todo-state-tags-triggers'."
12538 (let ((l org-todo-state-tags-triggers)
12539 changes)
12540 (when (or (not state) (equal state ""))
12541 (setq changes (append changes (cdr (assoc "" l)))))
12542 (when (and (stringp state) (> (length state) 0))
12543 (setq changes (append changes (cdr (assoc state l)))))
12544 (when (member state org-not-done-keywords)
12545 (setq changes (append changes (cdr (assoc 'todo l)))))
12546 (when (member state org-done-keywords)
12547 (setq changes (append changes (cdr (assoc 'done l)))))
12548 (dolist (c changes)
12549 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12551 (defun org-local-logging (value)
12552 "Get logging settings from a property VALUE."
12553 (let* (words w a)
12554 ;; directly set the variables, they are already local.
12555 (setq org-log-done nil
12556 org-log-repeat nil
12557 org-todo-log-states nil)
12558 (setq words (org-split-string value))
12559 (while (setq w (pop words))
12560 (cond
12561 ((setq a (assoc w org-startup-options))
12562 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12563 (set (nth 1 a) (nth 2 a))))
12564 ((setq a (org-extract-log-state-settings w))
12565 (and (member (car a) org-todo-keywords-1)
12566 (push a org-todo-log-states)))))))
12568 (defun org-get-todo-sequence-head (kwd)
12569 "Return the head of the TODO sequence to which KWD belongs.
12570 If KWD is not set, check if there is a text property remembering the
12571 right sequence."
12572 (let (p)
12573 (cond
12574 ((not kwd)
12575 (or (get-text-property (point-at-bol) 'org-todo-head)
12576 (progn
12577 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12578 nil (point-at-eol)))
12579 (get-text-property p 'org-todo-head))))
12580 ((not (member kwd org-todo-keywords-1))
12581 (car org-todo-keywords-1))
12582 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12584 (defun org-fast-todo-selection ()
12585 "Fast TODO keyword selection with single keys.
12586 Returns the new TODO keyword, or nil if no state change should occur."
12587 (let* ((fulltable org-todo-key-alist)
12588 (done-keywords org-done-keywords) ;; needed for the faces.
12589 (maxlen (apply 'max (mapcar
12590 (lambda (x)
12591 (if (stringp (car x)) (string-width (car x)) 0))
12592 fulltable)))
12593 (expert nil)
12594 (fwidth (+ maxlen 3 1 3))
12595 (ncol (/ (- (window-width) 4) fwidth))
12596 tg cnt e c tbl
12597 groups ingroup)
12598 (save-excursion
12599 (save-window-excursion
12600 (if expert
12601 (set-buffer (get-buffer-create " *Org todo*"))
12602 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12603 (erase-buffer)
12604 (org-set-local 'org-done-keywords done-keywords)
12605 (setq tbl fulltable cnt 0)
12606 (while (setq e (pop tbl))
12607 (cond
12608 ((equal e '(:startgroup))
12609 (push '() groups) (setq ingroup t)
12610 (when (not (= cnt 0))
12611 (setq cnt 0)
12612 (insert "\n"))
12613 (insert "{ "))
12614 ((equal e '(:endgroup))
12615 (setq ingroup nil cnt 0)
12616 (insert "}\n"))
12617 ((equal e '(:newline))
12618 (when (not (= cnt 0))
12619 (setq cnt 0)
12620 (insert "\n")
12621 (setq e (car tbl))
12622 (while (equal (car tbl) '(:newline))
12623 (insert "\n")
12624 (setq tbl (cdr tbl)))))
12626 (setq tg (car e) c (cdr e))
12627 (if ingroup (push tg (car groups)))
12628 (setq tg (org-add-props tg nil 'face
12629 (org-get-todo-face tg)))
12630 (if (and (= cnt 0) (not ingroup)) (insert " "))
12631 (insert "[" c "] " tg (make-string
12632 (- fwidth 4 (length tg)) ?\ ))
12633 (when (= (setq cnt (1+ cnt)) ncol)
12634 (insert "\n")
12635 (if ingroup (insert " "))
12636 (setq cnt 0)))))
12637 (insert "\n")
12638 (goto-char (point-min))
12639 (if (not expert) (org-fit-window-to-buffer))
12640 (message "[a-z..]:Set [SPC]:clear")
12641 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12642 (cond
12643 ((or (= c ?\C-g)
12644 (and (= c ?q) (not (rassoc c fulltable))))
12645 (setq quit-flag t))
12646 ((= c ?\ ) nil)
12647 ((setq e (rassoc c fulltable) tg (car e))
12649 (t (setq quit-flag t)))))))
12651 (defun org-entry-is-todo-p ()
12652 (member (org-get-todo-state) org-not-done-keywords))
12654 (defun org-entry-is-done-p ()
12655 (member (org-get-todo-state) org-done-keywords))
12657 (defun org-get-todo-state ()
12658 (save-excursion
12659 (org-back-to-heading t)
12660 (and (looking-at org-todo-line-regexp)
12661 (match-end 2)
12662 (match-string 2))))
12664 (defun org-at-date-range-p (&optional inactive-ok)
12665 "Is the cursor inside a date range?"
12666 (interactive)
12667 (save-excursion
12668 (catch 'exit
12669 (let ((pos (point)))
12670 (skip-chars-backward "^[<\r\n")
12671 (skip-chars-backward "<[")
12672 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12673 (>= (match-end 0) pos)
12674 (throw 'exit t))
12675 (skip-chars-backward "^<[\r\n")
12676 (skip-chars-backward "<[")
12677 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12678 (>= (match-end 0) pos)
12679 (throw 'exit t)))
12680 nil)))
12682 (defun org-get-repeat (&optional tagline)
12683 "Check if there is a deadline/schedule with repeater in this entry."
12684 (save-match-data
12685 (save-excursion
12686 (org-back-to-heading t)
12687 (and (re-search-forward (if tagline
12688 (concat tagline "\\s-*" org-repeat-re)
12689 org-repeat-re)
12690 (org-entry-end-position) t)
12691 (match-string-no-properties 1)))))
12693 (defvar org-last-changed-timestamp)
12694 (defvar org-last-inserted-timestamp)
12695 (defvar org-log-post-message)
12696 (defvar org-log-note-purpose)
12697 (defvar org-log-note-how)
12698 (defvar org-log-note-extra)
12699 (defun org-auto-repeat-maybe (done-word)
12700 "Check if the current headline contains a repeated deadline/schedule.
12701 If yes, set TODO state back to what it was and change the base date
12702 of repeating deadline/scheduled time stamps to new date.
12703 This function is run automatically after each state change to a DONE state."
12704 ;; last-state is dynamically scoped into this function
12705 (let* ((repeat (org-get-repeat))
12706 (aa (assoc org-last-state org-todo-kwd-alist))
12707 (interpret (nth 1 aa))
12708 (head (nth 2 aa))
12709 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12710 (msg "Entry repeats: ")
12711 (org-log-done nil)
12712 (org-todo-log-states nil)
12713 re type n what ts time to-state)
12714 (when repeat
12715 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12716 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12717 org-todo-repeat-to-state))
12718 (unless (and to-state (member to-state org-todo-keywords-1))
12719 (setq to-state (if (eq interpret 'type) org-last-state head)))
12720 (org-todo to-state)
12721 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12722 (org-entry-put nil "LAST_REPEAT" (format-time-string
12723 (org-time-stamp-format t t))))
12724 (when org-log-repeat
12725 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12726 (memq 'org-add-log-note post-command-hook))
12727 ;; OK, we are already setup for some record
12728 (if (eq org-log-repeat 'note)
12729 ;; make sure we take a note, not only a time stamp
12730 (setq org-log-note-how 'note))
12731 ;; Set up for taking a record
12732 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12733 org-last-state
12734 'findpos org-log-repeat)))
12735 (org-back-to-heading t)
12736 (org-add-planning-info nil nil 'closed)
12737 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12738 org-deadline-time-regexp "\\)\\|\\("
12739 org-ts-regexp "\\)"))
12740 (while (re-search-forward
12741 re (save-excursion (outline-next-heading) (point)) t)
12742 (setq type (if (match-end 1) org-scheduled-string
12743 (if (match-end 3) org-deadline-string "Plain:"))
12744 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12745 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12746 (setq n (string-to-number (match-string 2 ts))
12747 what (match-string 3 ts))
12748 (if (equal what "w") (setq n (* n 7) what "d"))
12749 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12750 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12751 ;; Preparation, see if we need to modify the start date for the change
12752 (when (match-end 1)
12753 (setq time (save-match-data (org-time-string-to-time ts)))
12754 (cond
12755 ((equal (match-string 1 ts) ".")
12756 ;; Shift starting date to today
12757 (org-timestamp-change
12758 (- (org-today) (time-to-days time))
12759 'day))
12760 ((equal (match-string 1 ts) "+")
12761 (let ((nshiftmax 10) (nshift 0))
12762 (while (or (= nshift 0)
12763 (<= (time-to-days time)
12764 (time-to-days (current-time))))
12765 (when (= (incf nshift) nshiftmax)
12766 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12767 (error "Abort")))
12768 (org-timestamp-change n (cdr (assoc what whata)))
12769 (org-at-timestamp-p t)
12770 (setq ts (match-string 1))
12771 (setq time (save-match-data (org-time-string-to-time ts)))))
12772 (org-timestamp-change (- n) (cdr (assoc what whata)))
12773 ;; rematch, so that we have everything in place for the real shift
12774 (org-at-timestamp-p t)
12775 (setq ts (match-string 1))
12776 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12777 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12778 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12779 (setq org-log-post-message msg)
12780 (message "%s" msg))))
12782 (defun org-show-todo-tree (arg)
12783 "Make a compact tree which shows all headlines marked with TODO.
12784 The tree will show the lines where the regexp matches, and all higher
12785 headlines above the match.
12786 With a \\[universal-argument] prefix, prompt for a regexp to match.
12787 With a numeric prefix N, construct a sparse tree for the Nth element
12788 of `org-todo-keywords-1'."
12789 (interactive "P")
12790 (let ((case-fold-search nil)
12791 (kwd-re
12792 (cond ((null arg) org-not-done-regexp)
12793 ((equal arg '(4))
12794 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12795 (mapcar 'list org-todo-keywords-1))))
12796 (concat "\\("
12797 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12798 "\\)\\>")))
12799 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12800 (regexp-quote (nth (1- (prefix-numeric-value arg))
12801 org-todo-keywords-1)))
12802 (t (error "Invalid prefix argument: %s" arg)))))
12803 (message "%d TODO entries found"
12804 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12806 (defun org-deadline (arg &optional time)
12807 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12808 With one universal prefix argument, remove any deadline from the item.
12809 With two universal prefix arguments, prompt for a warning delay.
12810 With argument TIME, set the deadline at the corresponding date. TIME
12811 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12812 (interactive "P")
12813 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12814 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12815 'region-start-level 'region))
12816 org-loop-over-headlines-in-active-region)
12817 (org-map-entries
12818 `(org-deadline ',arg ,time)
12819 org-loop-over-headlines-in-active-region
12820 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12821 (let* ((old-date (org-entry-get nil "DEADLINE"))
12822 (old-date-time (if old-date (org-time-string-to-time old-date)))
12823 (repeater (and old-date
12824 (string-match
12825 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12826 old-date)
12827 (match-string 1 old-date))))
12828 (cond
12829 ((equal arg '(4))
12830 (when (and old-date org-log-redeadline)
12831 (org-add-log-setup 'deldeadline nil old-date 'findpos
12832 org-log-redeadline))
12833 (org-remove-timestamp-with-keyword org-deadline-string)
12834 (message "Item no longer has a deadline."))
12835 ((equal arg '(16))
12836 (save-excursion
12837 (if (re-search-forward
12838 org-deadline-time-regexp
12839 (save-excursion (outline-next-heading) (point)) t)
12840 (let* ((rpl0 (match-string 1))
12841 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12842 (replace-match
12843 (concat org-deadline-string
12844 " <" rpl
12845 (format " -%dd"
12846 (abs
12847 (- (time-to-days
12848 (save-match-data
12849 (org-read-date nil t nil "Warn starting from" old-date-time)))
12850 (time-to-days old-date-time))))
12851 ">") t t))
12852 (user-error "No deadline information to update"))))
12854 (org-add-planning-info 'deadline time 'closed)
12855 (when (and old-date org-log-redeadline
12856 (not (equal old-date
12857 (substring org-last-inserted-timestamp 1 -1))))
12858 (org-add-log-setup 'redeadline nil old-date 'findpos
12859 org-log-redeadline))
12860 (when repeater
12861 (save-excursion
12862 (org-back-to-heading t)
12863 (when (re-search-forward (concat org-deadline-string " "
12864 org-last-inserted-timestamp)
12865 (save-excursion
12866 (outline-next-heading) (point)) t)
12867 (goto-char (1- (match-end 0)))
12868 (insert " " repeater)
12869 (setq org-last-inserted-timestamp
12870 (concat (substring org-last-inserted-timestamp 0 -1)
12871 " " repeater
12872 (substring org-last-inserted-timestamp -1))))))
12873 (message "Deadline on %s" org-last-inserted-timestamp))))))
12875 (defun org-schedule (arg &optional time)
12876 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12877 With one universal prefix argument, remove any scheduling date from the item.
12878 With two universal prefix arguments, prompt for a delay cookie.
12879 With argument TIME, scheduled at the corresponding date. TIME can
12880 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12881 (interactive "P")
12882 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12883 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12884 'region-start-level 'region))
12885 org-loop-over-headlines-in-active-region)
12886 (org-map-entries
12887 `(org-schedule ',arg ,time)
12888 org-loop-over-headlines-in-active-region
12889 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12890 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12891 (old-date-time (if old-date (org-time-string-to-time old-date)))
12892 (repeater (and old-date
12893 (string-match
12894 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12895 old-date)
12896 (match-string 1 old-date))))
12897 (cond
12898 ((equal arg '(4))
12899 (progn
12900 (when (and old-date org-log-reschedule)
12901 (org-add-log-setup 'delschedule nil old-date 'findpos
12902 org-log-reschedule))
12903 (org-remove-timestamp-with-keyword org-scheduled-string)
12904 (message "Item is no longer scheduled.")))
12905 ((equal arg '(16))
12906 (save-excursion
12907 (if (re-search-forward
12908 org-scheduled-time-regexp
12909 (save-excursion (outline-next-heading) (point)) t)
12910 (let* ((rpl0 (match-string 1))
12911 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12912 (replace-match
12913 (concat org-scheduled-string
12914 " <" rpl
12915 (format " -%dd"
12916 (abs
12917 (- (time-to-days
12918 (save-match-data
12919 (org-read-date nil t nil "Delay until" old-date-time)))
12920 (time-to-days old-date-time))))
12921 ">") t t))
12922 (user-error "No scheduled information to update"))))
12924 (org-add-planning-info 'scheduled time 'closed)
12925 (when (and old-date org-log-reschedule
12926 (not (equal old-date
12927 (substring org-last-inserted-timestamp 1 -1))))
12928 (org-add-log-setup 'reschedule nil old-date 'findpos
12929 org-log-reschedule))
12930 (when repeater
12931 (save-excursion
12932 (org-back-to-heading t)
12933 (when (re-search-forward (concat org-scheduled-string " "
12934 org-last-inserted-timestamp)
12935 (save-excursion
12936 (outline-next-heading) (point)) t)
12937 (goto-char (1- (match-end 0)))
12938 (insert " " repeater)
12939 (setq org-last-inserted-timestamp
12940 (concat (substring org-last-inserted-timestamp 0 -1)
12941 " " repeater
12942 (substring org-last-inserted-timestamp -1))))))
12943 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12945 (defun org-get-scheduled-time (pom &optional inherit)
12946 "Get the scheduled time as a time tuple, of a format suitable
12947 for calling org-schedule with, or if there is no scheduling,
12948 returns nil."
12949 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12950 (when time
12951 (apply 'encode-time (org-parse-time-string time)))))
12953 (defun org-get-deadline-time (pom &optional inherit)
12954 "Get the deadline as a time tuple, of a format suitable for
12955 calling org-deadline with, or if there is no scheduling, returns
12956 nil."
12957 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12958 (when time
12959 (apply 'encode-time (org-parse-time-string time)))))
12961 (defun org-remove-timestamp-with-keyword (keyword)
12962 "Remove all time stamps with KEYWORD in the current entry."
12963 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12964 beg)
12965 (save-excursion
12966 (org-back-to-heading t)
12967 (setq beg (point))
12968 (outline-next-heading)
12969 (while (re-search-backward re beg t)
12970 (replace-match "")
12971 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12972 (equal (char-before) ?\ ))
12973 (backward-delete-char 1)
12974 (if (string-match "^[ \t]*$" (buffer-substring
12975 (point-at-bol) (point-at-eol)))
12976 (delete-region (point-at-bol)
12977 (min (point-max) (1+ (point-at-eol))))))))))
12979 (defun org-add-planning-info (what &optional time &rest remove)
12980 "Insert new timestamp with keyword in the line directly after the headline.
12981 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12982 If non is given, the user is prompted for a date.
12983 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12984 be removed."
12985 (interactive)
12986 (let (org-time-was-given org-end-time-was-given ts
12987 end default-time default-input)
12989 (catch 'exit
12990 (when (and (memq what '(scheduled deadline))
12991 (or (not time)
12992 (and (stringp time)
12993 (string-match "^[-+]+[0-9]" time))))
12994 ;; Try to get a default date/time from existing timestamp
12995 (save-excursion
12996 (org-back-to-heading t)
12997 (setq end (save-excursion (outline-next-heading) (point)))
12998 (when (re-search-forward (if (eq what 'scheduled)
12999 org-scheduled-time-regexp
13000 org-deadline-time-regexp)
13001 end t)
13002 (setq ts (match-string 1)
13003 default-time
13004 (apply 'encode-time (org-parse-time-string ts))
13005 default-input (and ts (org-get-compact-tod ts))))))
13006 (when what
13007 (setq time
13008 (if (stringp time)
13009 ;; This is a string (relative or absolute), set proper date
13010 (apply 'encode-time
13011 (org-read-date-analyze
13012 time default-time (decode-time default-time)))
13013 ;; If necessary, get the time from the user
13014 (or time (org-read-date nil 'to-time nil nil
13015 default-time default-input)))))
13017 (when (and org-insert-labeled-timestamps-at-point
13018 (member what '(scheduled deadline)))
13019 (insert
13020 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13021 (org-insert-time-stamp time org-time-was-given
13022 nil nil nil (list org-end-time-was-given))
13023 (setq what nil))
13024 (save-excursion
13025 (save-restriction
13026 (let (col list elt ts buffer-invisibility-spec)
13027 (org-back-to-heading t)
13028 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13029 (goto-char (match-end 1))
13030 (setq col (current-column))
13031 (goto-char (match-end 0))
13032 (if (eobp) (insert "\n") (forward-char 1))
13033 (when (and (not what)
13034 (not (looking-at
13035 (concat "[ \t]*"
13036 org-keyword-time-not-clock-regexp))))
13037 ;; Nothing to add, nothing to remove...... :-)
13038 (throw 'exit nil))
13039 (if (and (not (looking-at org-outline-regexp))
13040 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13041 "[^\r\n]*"))
13042 (not (equal (match-string 1) org-clock-string)))
13043 (narrow-to-region (match-beginning 0) (match-end 0))
13044 (insert-before-markers "\n")
13045 (backward-char 1)
13046 (narrow-to-region (point) (point))
13047 (and org-adapt-indentation (org-indent-to-column col)))
13048 ;; Check if we have to remove something.
13049 (setq list (cons what remove))
13050 (while list
13051 (setq elt (pop list))
13052 (when (or (and (eq elt 'scheduled)
13053 (re-search-forward org-scheduled-time-regexp nil t))
13054 (and (eq elt 'deadline)
13055 (re-search-forward org-deadline-time-regexp nil t))
13056 (and (eq elt 'closed)
13057 (re-search-forward org-closed-time-regexp nil t)))
13058 (replace-match "")
13059 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13060 (and (looking-at "[ \t]+") (replace-match ""))
13061 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13062 (when what
13063 (insert
13064 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13065 (cond ((eq what 'scheduled) org-scheduled-string)
13066 ((eq what 'deadline) org-deadline-string)
13067 ((eq what 'closed) org-closed-string))
13068 " ")
13069 (setq ts (org-insert-time-stamp
13070 time
13071 (or org-time-was-given
13072 (and (eq what 'closed) org-log-done-with-time))
13073 (eq what 'closed)
13074 nil nil (list org-end-time-was-given)))
13075 (insert
13076 (if (not (or (bolp) (eq (char-before) ?\ )
13077 (memq (char-after) '(32 10))
13078 (eobp))) " " ""))
13079 (end-of-line 1))
13080 (goto-char (point-min))
13081 (widen)
13082 (if (and (looking-at "[ \t]*\n")
13083 (equal (char-before) ?\n))
13084 (delete-region (1- (point)) (point-at-eol)))
13085 ts))))))
13087 (defvar org-log-note-marker (make-marker))
13088 (defvar org-log-note-purpose nil)
13089 (defvar org-log-note-state nil)
13090 (defvar org-log-note-previous-state nil)
13091 (defvar org-log-note-how nil)
13092 (defvar org-log-note-extra nil)
13093 (defvar org-log-note-window-configuration nil)
13094 (defvar org-log-note-return-to (make-marker))
13095 (defvar org-log-note-effective-time nil
13096 "Remembered current time so that dynamically scoped
13097 `org-extend-today-until' affects tha timestamps in state change
13098 log")
13100 (defvar org-log-post-message nil
13101 "Message to be displayed after a log note has been stored.
13102 The auto-repeater uses this.")
13104 (defun org-add-note ()
13105 "Add a note to the current entry.
13106 This is done in the same way as adding a state change note."
13107 (interactive)
13108 (org-add-log-setup 'note nil nil 'findpos nil))
13110 (defvar org-property-end-re)
13111 (defun org-add-log-setup (&optional purpose state prev-state
13112 findpos how extra)
13113 "Set up the post command hook to take a note.
13114 If this is about to TODO state change, the new state is expected in STATE.
13115 When FINDPOS is non-nil, find the correct position for the note in
13116 the current entry. If not, assume that it can be inserted at point.
13117 HOW is an indicator what kind of note should be created.
13118 EXTRA is additional text that will be inserted into the notes buffer."
13119 (let* ((org-log-into-drawer (org-log-into-drawer))
13120 (drawer (cond ((stringp org-log-into-drawer)
13121 org-log-into-drawer)
13122 (org-log-into-drawer "LOGBOOK"))))
13123 (save-restriction
13124 (save-excursion
13125 (when findpos
13126 (org-back-to-heading t)
13127 (narrow-to-region (point) (save-excursion
13128 (outline-next-heading) (point)))
13129 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13130 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13131 "[^\r\n]*\\)?"))
13132 (goto-char (match-end 0))
13133 (cond
13134 (drawer
13135 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13136 nil t)
13137 (progn
13138 (goto-char (match-end 0))
13139 (or org-log-states-order-reversed
13140 (and (re-search-forward org-property-end-re nil t)
13141 (goto-char (1- (match-beginning 0))))))
13142 (insert "\n:" drawer ":\n:END:")
13143 (beginning-of-line 0)
13144 (org-indent-line)
13145 (beginning-of-line 2)
13146 (org-indent-line)
13147 (end-of-line 0)))
13148 ((and org-log-state-notes-insert-after-drawers
13149 (save-excursion
13150 (forward-line) (looking-at org-drawer-regexp)))
13151 (forward-line)
13152 (while (looking-at org-drawer-regexp)
13153 (goto-char (match-end 0))
13154 (re-search-forward org-property-end-re (point-max) t)
13155 (forward-line))
13156 (forward-line -1)))
13157 (unless org-log-states-order-reversed
13158 (and (= (char-after) ?\n) (forward-char 1))
13159 (org-skip-over-state-notes)
13160 (skip-chars-backward " \t\n\r")))
13161 (move-marker org-log-note-marker (point))
13162 (setq org-log-note-purpose purpose
13163 org-log-note-state state
13164 org-log-note-previous-state prev-state
13165 org-log-note-how how
13166 org-log-note-extra extra
13167 org-log-note-effective-time (org-current-effective-time))
13168 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13170 (defun org-skip-over-state-notes ()
13171 "Skip past the list of State notes in an entry."
13172 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13173 (when (ignore-errors (goto-char (org-in-item-p)))
13174 (let* ((struct (org-list-struct))
13175 (prevs (org-list-prevs-alist struct)))
13176 (while (looking-at "[ \t]*- State")
13177 (goto-char (or (org-list-get-next-item (point) struct prevs)
13178 (org-list-get-item-end (point) struct)))))))
13180 (defun org-add-log-note (&optional purpose)
13181 "Pop up a window for taking a note, and add this note later at point."
13182 (remove-hook 'post-command-hook 'org-add-log-note)
13183 (setq org-log-note-window-configuration (current-window-configuration))
13184 (delete-other-windows)
13185 (move-marker org-log-note-return-to (point))
13186 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13187 (goto-char org-log-note-marker)
13188 (org-switch-to-buffer-other-window "*Org Note*")
13189 (erase-buffer)
13190 (if (memq org-log-note-how '(time state))
13191 (let (current-prefix-arg) (org-store-log-note))
13192 (let ((org-inhibit-startup t)) (org-mode))
13193 (insert (format "# Insert note for %s.
13194 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13195 (cond
13196 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13197 ((eq org-log-note-purpose 'done) "closed todo item")
13198 ((eq org-log-note-purpose 'state)
13199 (format "state change from \"%s\" to \"%s\""
13200 (or org-log-note-previous-state "")
13201 (or org-log-note-state "")))
13202 ((eq org-log-note-purpose 'reschedule)
13203 "rescheduling")
13204 ((eq org-log-note-purpose 'delschedule)
13205 "no longer scheduled")
13206 ((eq org-log-note-purpose 'redeadline)
13207 "changing deadline")
13208 ((eq org-log-note-purpose 'deldeadline)
13209 "removing deadline")
13210 ((eq org-log-note-purpose 'refile)
13211 "refiling")
13212 ((eq org-log-note-purpose 'note)
13213 "this entry")
13214 (t (error "This should not happen")))))
13215 (if org-log-note-extra (insert org-log-note-extra))
13216 (org-set-local 'org-finish-function 'org-store-log-note)
13217 (run-hooks 'org-log-buffer-setup-hook)))
13219 (defvar org-note-abort nil) ; dynamically scoped
13220 (defun org-store-log-note ()
13221 "Finish taking a log note, and insert it to where it belongs."
13222 (let ((txt (buffer-string)))
13223 (kill-buffer (current-buffer))
13224 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13225 lines ind bul)
13226 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13227 (setq txt (replace-match "" t t txt)))
13228 (if (string-match "\\s-+\\'" txt)
13229 (setq txt (replace-match "" t t txt)))
13230 (setq lines (org-split-string txt "\n"))
13231 (when (and note (string-match "\\S-" note))
13232 (setq note
13233 (org-replace-escapes
13234 note
13235 (list (cons "%u" (user-login-name))
13236 (cons "%U" user-full-name)
13237 (cons "%t" (format-time-string
13238 (org-time-stamp-format 'long 'inactive)
13239 org-log-note-effective-time))
13240 (cons "%T" (format-time-string
13241 (org-time-stamp-format 'long nil)
13242 org-log-note-effective-time))
13243 (cons "%d" (format-time-string
13244 (org-time-stamp-format nil 'inactive)
13245 org-log-note-effective-time))
13246 (cons "%D" (format-time-string
13247 (org-time-stamp-format nil nil)
13248 org-log-note-effective-time))
13249 (cons "%s" (if org-log-note-state
13250 (concat "\"" org-log-note-state "\"")
13251 ""))
13252 (cons "%S" (if org-log-note-previous-state
13253 (concat "\"" org-log-note-previous-state "\"")
13254 "\"\"")))))
13255 (if lines (setq note (concat note " \\\\")))
13256 (push note lines))
13257 (when (or current-prefix-arg org-note-abort)
13258 (when org-log-into-drawer
13259 (org-remove-empty-drawer-at
13260 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13261 org-log-note-marker))
13262 (setq lines nil))
13263 (when lines
13264 (with-current-buffer (marker-buffer org-log-note-marker)
13265 (save-excursion
13266 (goto-char org-log-note-marker)
13267 (move-marker org-log-note-marker nil)
13268 (end-of-line 1)
13269 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13270 (setq ind (save-excursion
13271 (if (ignore-errors (goto-char (org-in-item-p)))
13272 (let ((struct (org-list-struct)))
13273 (org-list-get-ind
13274 (org-list-get-top-point struct) struct))
13275 (skip-chars-backward " \r\t\n")
13276 (cond
13277 ((and (org-at-heading-p)
13278 org-adapt-indentation)
13279 (1+ (org-current-level)))
13280 ((org-at-heading-p) 0)
13281 (t (org-get-indentation))))))
13282 (setq bul (org-list-bullet-string "-"))
13283 (org-indent-line-to ind)
13284 (insert bul (pop lines))
13285 (let ((ind-body (+ (length bul) ind)))
13286 (while lines
13287 (insert "\n")
13288 (org-indent-line-to ind-body)
13289 (insert (pop lines))))
13290 (message "Note stored")
13291 (org-back-to-heading t)
13292 (org-cycle-hide-drawers 'children))))))
13293 (set-window-configuration org-log-note-window-configuration)
13294 (with-current-buffer (marker-buffer org-log-note-return-to)
13295 (goto-char org-log-note-return-to))
13296 (move-marker org-log-note-return-to nil)
13297 (and org-log-post-message (message "%s" org-log-post-message)))
13299 (defun org-remove-empty-drawer-at (drawer pos)
13300 "Remove an empty drawer DRAWER at position POS.
13301 POS may also be a marker."
13302 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13303 (save-excursion
13304 (save-restriction
13305 (widen)
13306 (goto-char pos)
13307 (if (org-in-regexp
13308 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13309 (replace-match ""))))))
13311 (defvar org-ts-type nil)
13312 (defun org-sparse-tree (&optional arg type)
13313 "Create a sparse tree, prompt for the details.
13314 This command can create sparse trees. You first need to select the type
13315 of match used to create the tree:
13317 t Show all TODO entries.
13318 T Show entries with a specific TODO keyword.
13319 m Show entries selected by a tags/property match.
13320 p Enter a property name and its value (both with completion on existing
13321 names/values) and show entries with that property.
13322 r Show entries matching a regular expression (`/' can be used as well).
13323 b Show deadlines and scheduled items before a date.
13324 a Show deadlines and scheduled items after a date.
13325 d Show deadlines due within `org-deadline-warning-days'.
13326 D Show deadlines and scheduled items between a date range."
13327 (interactive "P")
13328 (let (ans kwd value ts-type)
13329 (setq type (or type org-sparse-tree-default-date-type))
13330 (setq org-ts-type type)
13331 (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"
13332 (cond ((eq type 'all) "all timestamps")
13333 ((eq type 'scheduled) "only scheduled")
13334 ((eq type 'deadline) "only deadline")
13335 ((eq type 'active) "only active timestamps")
13336 ((eq type 'inactive) "only inactive timestamps")
13337 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13338 (t "scheduled/deadline")))
13339 (setq ans (read-char-exclusive))
13340 (cond
13341 ((equal ans ?c)
13342 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13343 ((equal ans ?d)
13344 (call-interactively 'org-check-deadlines))
13345 ((equal ans ?b)
13346 (call-interactively 'org-check-before-date))
13347 ((equal ans ?a)
13348 (call-interactively 'org-check-after-date))
13349 ((equal ans ?D)
13350 (call-interactively 'org-check-dates-range))
13351 ((equal ans ?t)
13352 (call-interactively 'org-show-todo-tree))
13353 ((equal ans ?T)
13354 (org-show-todo-tree '(4)))
13355 ((member ans '(?T ?m))
13356 (call-interactively 'org-match-sparse-tree))
13357 ((member ans '(?p ?P))
13358 (setq kwd (org-icompleting-read "Property: "
13359 (mapcar 'list (org-buffer-property-keys))))
13360 (setq value (org-icompleting-read "Value: "
13361 (mapcar 'list (org-property-values kwd))))
13362 (unless (string-match "\\`{.*}\\'" value)
13363 (setq value (concat "\"" value "\"")))
13364 (org-match-sparse-tree arg (concat kwd "=" value)))
13365 ((member ans '(?r ?R ?/))
13366 (call-interactively 'org-occur))
13367 (t (error "No such sparse tree command \"%c\"" ans)))))
13369 (defvar org-occur-highlights nil
13370 "List of overlays used for occur matches.")
13371 (make-variable-buffer-local 'org-occur-highlights)
13372 (defvar org-occur-parameters nil
13373 "Parameters of the active org-occur calls.
13374 This is a list, each call to org-occur pushes as cons cell,
13375 containing the regular expression and the callback, onto the list.
13376 The list can contain several entries if `org-occur' has been called
13377 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13378 will only contain one set of parameters. When the highlights are
13379 removed (for example with `C-c C-c', or with the next edit (depending
13380 on `org-remove-highlights-with-change'), this variable is emptied
13381 as well.")
13382 (make-variable-buffer-local 'org-occur-parameters)
13384 (defun org-occur (regexp &optional keep-previous callback)
13385 "Make a compact tree which shows all matches of REGEXP.
13386 The tree will show the lines where the regexp matches, and all higher
13387 headlines above the match. It will also show the heading after the match,
13388 to make sure editing the matching entry is easy.
13389 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13390 call to `org-occur' will be kept, to allow stacking of calls to this
13391 command.
13392 If CALLBACK is non-nil, it is a function which is called to confirm
13393 that the match should indeed be shown."
13394 (interactive "sRegexp: \nP")
13395 (when (equal regexp "")
13396 (error "Regexp cannot be empty"))
13397 (unless keep-previous
13398 (org-remove-occur-highlights nil nil t))
13399 (push (cons regexp callback) org-occur-parameters)
13400 (let ((cnt 0))
13401 (save-excursion
13402 (goto-char (point-min))
13403 (if (or (not keep-previous) ; do not want to keep
13404 (not org-occur-highlights)) ; no previous matches
13405 ;; hide everything
13406 (org-overview))
13407 (while (re-search-forward regexp nil t)
13408 (when (or (not callback)
13409 (save-match-data (funcall callback)))
13410 (setq cnt (1+ cnt))
13411 (when org-highlight-sparse-tree-matches
13412 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13413 (org-show-context 'occur-tree))))
13414 (when org-remove-highlights-with-change
13415 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13416 nil 'local))
13417 (unless org-sparse-tree-open-archived-trees
13418 (org-hide-archived-subtrees (point-min) (point-max)))
13419 (run-hooks 'org-occur-hook)
13420 (if (org-called-interactively-p 'interactive)
13421 (message "%d match(es) for regexp %s" cnt regexp))
13422 cnt))
13424 (defun org-occur-next-match (&optional n reset)
13425 "Function for `next-error-function' to find sparse tree matches.
13426 N is the number of matches to move, when negative move backwards.
13427 RESET is entirely ignored - this function always goes back to the
13428 starting point when no match is found."
13429 (let* ((limit (if (< n 0) (point-min) (point-max)))
13430 (search-func (if (< n 0)
13431 'previous-single-char-property-change
13432 'next-single-char-property-change))
13433 (n (abs n))
13434 (pos (point))
13436 (catch 'exit
13437 (while (setq p1 (funcall search-func (point) 'org-type))
13438 (when (equal p1 limit)
13439 (goto-char pos)
13440 (error "No more matches"))
13441 (when (equal (get-char-property p1 'org-type) 'org-occur)
13442 (setq n (1- n))
13443 (when (= n 0)
13444 (goto-char p1)
13445 (throw 'exit (point))))
13446 (goto-char p1))
13447 (goto-char p1)
13448 (error "No more matches"))))
13450 (defun org-show-context (&optional key)
13451 "Make sure point and context are visible.
13452 How much context is shown depends upon the variables
13453 `org-show-hierarchy-above', `org-show-following-heading',
13454 `org-show-entry-below' and `org-show-siblings'."
13455 (let ((heading-p (org-at-heading-p t))
13456 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13457 (following-p (org-get-alist-option org-show-following-heading key))
13458 (entry-p (org-get-alist-option org-show-entry-below key))
13459 (siblings-p (org-get-alist-option org-show-siblings key)))
13460 ;; Show heading or entry text
13461 (if (and heading-p (not entry-p))
13462 (org-flag-heading nil) ; only show the heading
13463 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13464 (org-show-hidden-entry))) ; show entire entry
13465 (when following-p
13466 ;; Show next sibling, or heading below text
13467 (save-excursion
13468 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13469 (org-flag-heading nil))))
13470 (when siblings-p (org-show-siblings))
13471 (when hierarchy-p
13472 ;; show all higher headings, possibly with siblings
13473 (save-excursion
13474 (while (and (condition-case nil
13475 (progn (org-up-heading-all 1) t)
13476 (error nil))
13477 (not (bobp)))
13478 (org-flag-heading nil)
13479 (when siblings-p (org-show-siblings)))))
13480 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13482 (defvar org-reveal-start-hook nil
13483 "Hook run before revealing a location.")
13485 (defun org-reveal (&optional siblings)
13486 "Show current entry, hierarchy above it, and the following headline.
13487 This can be used to show a consistent set of context around locations
13488 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13489 not t for the search context.
13491 With optional argument SIBLINGS, on each level of the hierarchy all
13492 siblings are shown. This repairs the tree structure to what it would
13493 look like when opened with hierarchical calls to `org-cycle'.
13494 With double optional argument \\[universal-argument] \\[universal-argument], \
13495 go to the parent and show the
13496 entire tree."
13497 (interactive "P")
13498 (run-hooks 'org-reveal-start-hook)
13499 (let ((org-show-hierarchy-above t)
13500 (org-show-following-heading t)
13501 (org-show-siblings (if siblings t org-show-siblings)))
13502 (org-show-context nil))
13503 (when (equal siblings '(16))
13504 (save-excursion
13505 (when (org-up-heading-safe)
13506 (org-show-subtree)
13507 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13509 (defun org-highlight-new-match (beg end)
13510 "Highlight from BEG to END and mark the highlight is an occur headline."
13511 (let ((ov (make-overlay beg end)))
13512 (overlay-put ov 'face 'secondary-selection)
13513 (overlay-put ov 'org-type 'org-occur)
13514 (push ov org-occur-highlights)))
13516 (defun org-remove-occur-highlights (&optional beg end noremove)
13517 "Remove the occur highlights from the buffer.
13518 BEG and END are ignored. If NOREMOVE is nil, remove this function
13519 from the `before-change-functions' in the current buffer."
13520 (interactive)
13521 (unless org-inhibit-highlight-removal
13522 (mapc 'delete-overlay org-occur-highlights)
13523 (setq org-occur-highlights nil)
13524 (setq org-occur-parameters nil)
13525 (unless noremove
13526 (remove-hook 'before-change-functions
13527 'org-remove-occur-highlights 'local))))
13529 ;;;; Priorities
13531 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13532 "Regular expression matching the priority indicator.")
13534 (defvar org-remove-priority-next-time nil)
13536 (defun org-priority-up ()
13537 "Increase the priority of the current item."
13538 (interactive)
13539 (org-priority 'up))
13541 (defun org-priority-down ()
13542 "Decrease the priority of the current item."
13543 (interactive)
13544 (org-priority 'down))
13546 (defun org-priority (&optional action show)
13547 "Change the priority of an item.
13548 ACTION can be `set', `up', `down', or a character."
13549 (interactive "P")
13550 (if (equal action '(4))
13551 (org-show-priority)
13552 (unless org-enable-priority-commands
13553 (error "Priority commands are disabled"))
13554 (setq action (or action 'set))
13555 (let (current new news have remove)
13556 (save-excursion
13557 (org-back-to-heading t)
13558 (if (looking-at org-priority-regexp)
13559 (setq current (string-to-char (match-string 2))
13560 have t))
13561 (cond
13562 ((eq action 'remove)
13563 (setq remove t new ?\ ))
13564 ((or (eq action 'set)
13565 (if (featurep 'xemacs) (characterp action) (integerp action)))
13566 (if (not (eq action 'set))
13567 (setq new action)
13568 (message "Priority %c-%c, SPC to remove: "
13569 org-highest-priority org-lowest-priority)
13570 (save-match-data
13571 (setq new (read-char-exclusive))))
13572 (if (and (= (upcase org-highest-priority) org-highest-priority)
13573 (= (upcase org-lowest-priority) org-lowest-priority))
13574 (setq new (upcase new)))
13575 (cond ((equal new ?\ ) (setq remove t))
13576 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13577 (error "Priority must be between `%c' and `%c'"
13578 org-highest-priority org-lowest-priority))))
13579 ((eq action 'up)
13580 (setq new (if have
13581 (1- current) ; normal cycling
13582 ;; last priority was empty
13583 (if (eq last-command this-command)
13584 org-lowest-priority ; wrap around empty to lowest
13585 ;; default
13586 (if org-priority-start-cycle-with-default
13587 org-default-priority
13588 (1- org-default-priority))))))
13589 ((eq action 'down)
13590 (setq new (if have
13591 (1+ current) ; normal cycling
13592 ;; last priority was empty
13593 (if (eq last-command this-command)
13594 org-highest-priority ; wrap around empty to highest
13595 ;; default
13596 (if org-priority-start-cycle-with-default
13597 org-default-priority
13598 (1+ org-default-priority))))))
13599 (t (error "Invalid action")))
13600 (if (or (< (upcase new) org-highest-priority)
13601 (> (upcase new) org-lowest-priority))
13602 (if (and (memq action '(up down))
13603 (not have) (not (eq last-command this-command)))
13604 ;; `new' is from default priority
13605 (error
13606 "The default can not be set, see `org-default-priority' why")
13607 ;; normal cycling: `new' is beyond highest/lowest priority
13608 ;; and is wrapped around to the empty priority
13609 (setq remove t)))
13610 (setq news (format "%c" new))
13611 (if have
13612 (if remove
13613 (replace-match "" t t nil 1)
13614 (replace-match news t t nil 2))
13615 (if remove
13616 (error "No priority cookie found in line")
13617 (let ((case-fold-search nil))
13618 (looking-at org-todo-line-regexp))
13619 (if (match-end 2)
13620 (progn
13621 (goto-char (match-end 2))
13622 (insert " [#" news "]"))
13623 (goto-char (match-beginning 3))
13624 (insert "[#" news "] "))))
13625 (org-preserve-lc (org-set-tags nil 'align)))
13626 (if remove
13627 (message "Priority removed")
13628 (message "Priority of current item set to %s" news)))))
13630 (defun org-show-priority ()
13631 "Show the priority of the current item.
13632 This priority is composed of the main priority given with the [#A] cookies,
13633 and by additional input from the age of a schedules or deadline entry."
13634 (interactive)
13635 (let ((pri (if (eq major-mode 'org-agenda-mode)
13636 (org-get-at-bol 'priority)
13637 (save-excursion
13638 (save-match-data
13639 (beginning-of-line)
13640 (and (looking-at org-heading-regexp)
13641 (org-get-priority (match-string 0))))))))
13642 (message "Priority is %d" (if pri pri -1000))))
13644 (defun org-get-priority (s)
13645 "Find priority cookie and return priority."
13646 (save-match-data
13647 (if (functionp org-get-priority-function)
13648 (funcall org-get-priority-function)
13649 (if (not (string-match org-priority-regexp s))
13650 (* 1000 (- org-lowest-priority org-default-priority))
13651 (* 1000 (- org-lowest-priority
13652 (string-to-char (match-string 2 s))))))))
13654 ;;;; Tags
13656 (defvar org-agenda-archives-mode)
13657 (defvar org-map-continue-from nil
13658 "Position from where mapping should continue.
13659 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13661 (defvar org-scanner-tags nil
13662 "The current tag list while the tags scanner is running.")
13663 (defvar org-trust-scanner-tags nil
13664 "Should `org-get-tags-at' use the tags for the scanner.
13665 This is for internal dynamical scoping only.
13666 When this is non-nil, the function `org-get-tags-at' will return the value
13667 of `org-scanner-tags' instead of building the list by itself. This
13668 can lead to large speed-ups when the tags scanner is used in a file with
13669 many entries, and when the list of tags is retrieved, for example to
13670 obtain a list of properties. Building the tags list for each entry in such
13671 a file becomes an N^2 operation - but with this variable set, it scales
13672 as N.")
13674 (defun org-scan-tags (action matcher todo-only &optional start-level)
13675 "Sca headline tags with inheritance and produce output ACTION.
13677 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13678 or `agenda' to produce an entry list for an agenda view. It can also be
13679 a Lisp form or a function that should be called at each matched headline, in
13680 this case the return value is a list of all return values from these calls.
13682 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13683 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13684 only lines with a not-done TODO keyword are included in the output.
13685 This should be the same variable that was scoped into
13686 and set by `org-make-tags-matcher' when it constructed MATCHER.
13688 START-LEVEL can be a string with asterisks, reducing the scope to
13689 headlines matching this string."
13690 (require 'org-agenda)
13691 (let* ((re (concat "^"
13692 (if start-level
13693 ;; Get the correct level to match
13694 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13695 org-outline-regexp)
13696 " *\\(\\<\\("
13697 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13698 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13699 (props (list 'face 'default
13700 'done-face 'org-agenda-done
13701 'undone-face 'default
13702 'mouse-face 'highlight
13703 'org-not-done-regexp org-not-done-regexp
13704 'org-todo-regexp org-todo-regexp
13705 'org-complex-heading-regexp org-complex-heading-regexp
13706 'help-echo
13707 (format "mouse-2 or RET jump to org file %s"
13708 (abbreviate-file-name
13709 (or (buffer-file-name (buffer-base-buffer))
13710 (buffer-name (buffer-base-buffer)))))))
13711 (case-fold-search nil)
13712 (org-map-continue-from nil)
13713 lspos tags tags-list
13714 (tags-alist (list (cons 0 org-file-tags)))
13715 (llast 0) rtn rtn1 level category i txt
13716 todo marker entry priority)
13717 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13718 (setq action (list 'lambda nil action)))
13719 (save-excursion
13720 (goto-char (point-min))
13721 (when (eq action 'sparse-tree)
13722 (org-overview)
13723 (org-remove-occur-highlights))
13724 (while (re-search-forward re nil t)
13725 (setq org-map-continue-from nil)
13726 (catch :skip
13727 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13728 tags (if (match-end 4) (org-match-string-no-properties 4)))
13729 (goto-char (setq lspos (match-beginning 0)))
13730 (setq level (org-reduced-level (org-outline-level))
13731 category (org-get-category))
13732 (setq i llast llast level)
13733 ;; remove tag lists from same and sublevels
13734 (while (>= i level)
13735 (when (setq entry (assoc i tags-alist))
13736 (setq tags-alist (delete entry tags-alist)))
13737 (setq i (1- i)))
13738 ;; add the next tags
13739 (when tags
13740 (setq tags (org-split-string tags ":")
13741 tags-alist
13742 (cons (cons level tags) tags-alist)))
13743 ;; compile tags for current headline
13744 (setq tags-list
13745 (if org-use-tag-inheritance
13746 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13747 tags)
13748 org-scanner-tags tags-list)
13749 (when org-use-tag-inheritance
13750 (setcdr (car tags-alist)
13751 (mapcar (lambda (x)
13752 (setq x (copy-sequence x))
13753 (org-add-prop-inherited x))
13754 (cdar tags-alist))))
13755 (when (and tags org-use-tag-inheritance
13756 (or (not (eq t org-use-tag-inheritance))
13757 org-tags-exclude-from-inheritance))
13758 ;; selective inheritance, remove uninherited ones
13759 (setcdr (car tags-alist)
13760 (org-remove-uninherited-tags (cdar tags-alist))))
13761 (when (and
13763 ;; eval matcher only when the todo condition is OK
13764 (and (or (not todo-only) (member todo org-not-done-keywords))
13765 (let ((case-fold-search t) (org-trust-scanner-tags t))
13766 (eval matcher)))
13768 ;; Call the skipper, but return t if it does not skip,
13769 ;; so that the `and' form continues evaluating
13770 (progn
13771 (unless (eq action 'sparse-tree) (org-agenda-skip))
13774 ;; Check if timestamps are deselecting this entry
13775 (or (not todo-only)
13776 (and (member todo org-not-done-keywords)
13777 (or (not org-agenda-tags-todo-honor-ignore-options)
13778 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13780 ;; select this headline
13781 (cond
13782 ((eq action 'sparse-tree)
13783 (and org-highlight-sparse-tree-matches
13784 (org-get-heading) (match-end 0)
13785 (org-highlight-new-match
13786 (match-beginning 1) (match-end 1)))
13787 (org-show-context 'tags-tree))
13788 ((eq action 'agenda)
13789 (setq txt (org-agenda-format-item
13791 (concat
13792 (if (eq org-tags-match-list-sublevels 'indented)
13793 (make-string (1- level) ?.) "")
13794 (org-get-heading))
13795 level category
13796 tags-list)
13797 priority (org-get-priority txt))
13798 (goto-char lspos)
13799 (setq marker (org-agenda-new-marker))
13800 (org-add-props txt props
13801 'org-marker marker 'org-hd-marker marker 'org-category category
13802 'todo-state todo
13803 'priority priority 'type "tagsmatch")
13804 (push txt rtn))
13805 ((functionp action)
13806 (setq org-map-continue-from nil)
13807 (save-excursion
13808 (setq rtn1 (funcall action))
13809 (push rtn1 rtn)))
13810 (t (error "Invalid action")))
13812 ;; if we are to skip sublevels, jump to end of subtree
13813 (unless org-tags-match-list-sublevels
13814 (org-end-of-subtree t)
13815 (backward-char 1))))
13816 ;; Get the correct position from where to continue
13817 (if org-map-continue-from
13818 (goto-char org-map-continue-from)
13819 (and (= (point) lspos) (end-of-line 1)))))
13820 (when (and (eq action 'sparse-tree)
13821 (not org-sparse-tree-open-archived-trees))
13822 (org-hide-archived-subtrees (point-min) (point-max)))
13823 (nreverse rtn)))
13825 (defun org-remove-uninherited-tags (tags)
13826 "Remove all tags that are not inherited from the list TAGS."
13827 (cond
13828 ((eq org-use-tag-inheritance t)
13829 (if org-tags-exclude-from-inheritance
13830 (org-delete-all org-tags-exclude-from-inheritance tags)
13831 tags))
13832 ((not org-use-tag-inheritance) nil)
13833 ((stringp org-use-tag-inheritance)
13834 (delq nil (mapcar
13835 (lambda (x)
13836 (if (and (string-match org-use-tag-inheritance x)
13837 (not (member x org-tags-exclude-from-inheritance)))
13838 x nil))
13839 tags)))
13840 ((listp org-use-tag-inheritance)
13841 (delq nil (mapcar
13842 (lambda (x)
13843 (if (member x org-use-tag-inheritance) x nil))
13844 tags)))))
13846 (defun org-match-sparse-tree (&optional todo-only match)
13847 "Create a sparse tree according to tags string MATCH.
13848 MATCH can contain positive and negative selection of tags, like
13849 \"+WORK+URGENT-WITHBOSS\".
13850 If optional argument TODO-ONLY is non-nil, only select lines that are
13851 also TODO lines."
13852 (interactive "P")
13853 (org-agenda-prepare-buffers (list (current-buffer)))
13854 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13856 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13858 (defvar org-cached-props nil)
13859 (defun org-cached-entry-get (pom property)
13860 (if (or (eq t org-use-property-inheritance)
13861 (and (stringp org-use-property-inheritance)
13862 (string-match org-use-property-inheritance property))
13863 (and (listp org-use-property-inheritance)
13864 (member property org-use-property-inheritance)))
13865 ;; Caching is not possible, check it directly
13866 (org-entry-get pom property 'inherit)
13867 ;; Get all properties, so that we can do complicated checks easily
13868 (cdr (assoc property (or org-cached-props
13869 (setq org-cached-props
13870 (org-entry-properties pom)))))))
13872 (defun org-global-tags-completion-table (&optional files)
13873 "Return the list of all tags in all agenda buffer/files.
13874 Optional FILES argument is a list of files which can be used
13875 instead of the agenda files."
13876 (save-excursion
13877 (org-uniquify
13878 (delq nil
13879 (apply 'append
13880 (mapcar
13881 (lambda (file)
13882 (set-buffer (find-file-noselect file))
13883 (append (org-get-buffer-tags)
13884 (mapcar (lambda (x) (if (stringp (car-safe x))
13885 (list (car-safe x)) nil))
13886 org-tag-alist)))
13887 (if (and files (car files))
13888 files
13889 (org-agenda-files))))))))
13891 (defun org-make-tags-matcher (match)
13892 "Create the TAGS/TODO matcher form for the selection string MATCH.
13894 The variable `todo-only' is scoped dynamically into this function.
13895 It will be set to t if the matcher restricts matching to TODO entries,
13896 otherwise will not be touched.
13898 Returns a cons of the selection string MATCH and the constructed
13899 lisp form implementing the matcher. The matcher is to be evaluated
13900 at an Org entry, with point on the headline, and returns t if the
13901 entry matches the selection string MATCH. The returned lisp form
13902 references two variables with information about the entry, which
13903 must be bound around the form's evaluation: todo, the TODO keyword
13904 at the entry (or nil of none); and tags-list, the list of all tags
13905 at the entry including inherited ones. Additionally, the category
13906 of the entry (if any) must be specified as the text property
13907 'org-category on the headline.
13909 See also `org-scan-tags'.
13911 (declare (special todo-only))
13912 (unless (boundp 'todo-only)
13913 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13914 (unless match
13915 ;; Get a new match request, with completion
13916 (let ((org-last-tags-completion-table
13917 (org-global-tags-completion-table)))
13918 (setq match (org-completing-read-no-i
13919 "Match: " 'org-tags-completion-function nil nil nil
13920 'org-tags-history))))
13922 ;; Parse the string and create a lisp form
13923 (let ((match0 match)
13924 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13925 minus tag mm
13926 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13927 orterms term orlist re-p str-p level-p level-op time-p
13928 prop-p pn pv po gv rest)
13929 ;; Expand group tags
13930 (setq match (org-tags-expand match))
13931 (if (string-match "/+" match)
13932 ;; match contains also a todo-matching request
13933 (progn
13934 (setq tagsmatch (substring match 0 (match-beginning 0))
13935 todomatch (substring match (match-end 0)))
13936 (if (string-match "^!" todomatch)
13937 (setq todo-only t todomatch (substring todomatch 1)))
13938 (if (string-match "^\\s-*$" todomatch)
13939 (setq todomatch nil)))
13940 ;; only matching tags
13941 (setq tagsmatch match todomatch nil))
13943 ;; Make the tags matcher
13944 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13945 (setq tagsmatcher t)
13946 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13947 (while (setq term (pop orterms))
13948 (while (and (equal (substring term -1) "\\") orterms)
13949 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13950 (while (string-match re term)
13951 (setq rest (substring term (match-end 0))
13952 minus (and (match-end 1)
13953 (equal (match-string 1 term) "-"))
13954 tag (save-match-data (replace-regexp-in-string
13955 "\\\\-" "-"
13956 (match-string 2 term)))
13957 re-p (equal (string-to-char tag) ?{)
13958 level-p (match-end 4)
13959 prop-p (match-end 5)
13960 mm (cond
13961 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13962 (level-p
13963 (setq level-op (org-op-to-function (match-string 3 term)))
13964 `(,level-op level ,(string-to-number
13965 (match-string 4 term))))
13966 (prop-p
13967 (setq pn (match-string 5 term)
13968 po (match-string 6 term)
13969 pv (match-string 7 term)
13970 re-p (equal (string-to-char pv) ?{)
13971 str-p (equal (string-to-char pv) ?\")
13972 time-p (save-match-data
13973 (string-match "^\"[[<].*[]>]\"$" pv))
13974 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13975 (if time-p (setq pv (org-matcher-time pv)))
13976 (setq po (org-op-to-function po (if time-p 'time str-p)))
13977 (cond
13978 ((equal pn "CATEGORY")
13979 (setq gv '(get-text-property (point) 'org-category)))
13980 ((equal pn "TODO")
13981 (setq gv 'todo))
13983 (setq gv `(org-cached-entry-get nil ,pn))))
13984 (if re-p
13985 (if (eq po 'org<>)
13986 `(not (string-match ,pv (or ,gv "")))
13987 `(string-match ,pv (or ,gv "")))
13988 (if str-p
13989 `(,po (or ,gv "") ,pv)
13990 `(,po (string-to-number (or ,gv ""))
13991 ,(string-to-number pv) ))))
13992 (t `(member ,tag tags-list)))
13993 mm (if minus (list 'not mm) mm)
13994 term rest)
13995 (push mm tagsmatcher))
13996 (push (if (> (length tagsmatcher) 1)
13997 (cons 'and tagsmatcher)
13998 (car tagsmatcher))
13999 orlist)
14000 (setq tagsmatcher nil))
14001 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14002 (setq tagsmatcher
14003 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14004 ;; Make the todo matcher
14005 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14006 (setq todomatcher t)
14007 (setq orterms (org-split-string todomatch "|") orlist nil)
14008 (while (setq term (pop orterms))
14009 (while (string-match re term)
14010 (setq minus (and (match-end 1)
14011 (equal (match-string 1 term) "-"))
14012 kwd (match-string 2 term)
14013 re-p (equal (string-to-char kwd) ?{)
14014 term (substring term (match-end 0))
14015 mm (if re-p
14016 `(string-match ,(substring kwd 1 -1) todo)
14017 (list 'equal 'todo kwd))
14018 mm (if minus (list 'not mm) mm))
14019 (push mm todomatcher))
14020 (push (if (> (length todomatcher) 1)
14021 (cons 'and todomatcher)
14022 (car todomatcher))
14023 orlist)
14024 (setq todomatcher nil))
14025 (setq todomatcher (if (> (length orlist) 1)
14026 (cons 'or orlist) (car orlist))))
14028 ;; Return the string and lisp forms of the matcher
14029 (setq matcher (if todomatcher
14030 (list 'and tagsmatcher todomatcher)
14031 tagsmatcher))
14032 (when todo-only
14033 (setq matcher (list 'and '(member todo org-not-done-keywords)
14034 matcher)))
14035 (cons match0 matcher)))
14037 (defun org-tags-expand (match &optional single-as-list downcased)
14038 "Expand group tags in MATCH.
14040 This replaces every group tag in MATCH with a regexp tag search.
14041 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14042 will be replaced like this:
14044 Work => {\(?:Work\|Lab\|Conf\}
14045 +Work => +{\(?:Work\|Lab\|Conf\}
14046 -Work => -{\(?:Work\|Lab\|Conf\}
14048 Replacing by a regexp preserves the structure of the match.
14049 E.g., this expansion
14051 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14053 will match anything tagged with \"Lab\" and \"Home\", or tagged
14054 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14056 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14057 assumed to be a single group tag, and the function will return
14058 the list of tags in this group.
14060 When DOWNCASE is non-nil, expand downcased TAGS."
14061 (if org-group-tags
14062 (let* ((case-fold-search t)
14063 (stable org-mode-syntax-table)
14064 (tal (or org-tag-groups-alist-for-agenda
14065 org-tag-groups-alist))
14066 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14067 (tml (mapcar 'car tal))
14068 (rtnmatch match) rpl)
14069 ;; @ and _ are allowed as word-components in tags
14070 (modify-syntax-entry ?@ "w" stable)
14071 (modify-syntax-entry ?_ "w" stable)
14072 (while (and tml (string-match
14073 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14074 rtnmatch))
14075 (let* ((dir (match-string 1 rtnmatch))
14076 (tag (match-string 2 rtnmatch))
14077 (tag (if downcased (downcase tag) tag)))
14078 (setq tml (delete tag tml))
14079 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14080 (setq rtnmatch
14081 (replace-match
14082 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14083 (if single-as-list
14084 (or (reverse rpl) (list rtnmatch))
14085 rtnmatch))
14086 (if single-as-list (list (if downcased (downcase match) match))
14087 match)))
14089 (defun org-op-to-function (op &optional stringp)
14090 "Turn an operator into the appropriate function."
14091 (setq op
14092 (cond
14093 ((equal op "<" ) '(< string< org-time<))
14094 ((equal op ">" ) '(> org-string> org-time>))
14095 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14096 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14097 ((member op '("=" "==")) '(= string= org-time=))
14098 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14099 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14101 (defun org<> (a b) (not (= a b)))
14102 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14103 (defun org-string>= (a b) (not (string< a b)))
14104 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14105 (defun org-string<> (a b) (not (string= a b)))
14106 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14107 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14108 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14109 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14110 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14111 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14112 (defun org-2ft (s)
14113 "Convert S to a floating point time.
14114 If S is already a number, just return it. If it is a string, parse
14115 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14116 (cond
14117 ((numberp s) s)
14118 ((stringp s)
14119 (condition-case nil
14120 (float-time (apply 'encode-time (org-parse-time-string s)))
14121 (error 0.)))
14122 (t 0.)))
14124 (defun org-time-today ()
14125 "Time in seconds today at 0:00.
14126 Returns the float number of seconds since the beginning of the
14127 epoch to the beginning of today (00:00)."
14128 (float-time (apply 'encode-time
14129 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14131 (defun org-matcher-time (s)
14132 "Interpret a time comparison value."
14133 (save-match-data
14134 (cond
14135 ((string= s "<now>") (float-time))
14136 ((string= s "<today>") (org-time-today))
14137 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14138 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14139 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14140 (+ (org-time-today)
14141 (* (string-to-number (match-string 1 s))
14142 (cdr (assoc (match-string 2 s)
14143 '(("d" . 86400.0) ("w" . 604800.0)
14144 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14145 (t (org-2ft s)))))
14147 (defun org-match-any-p (re list)
14148 "Does re match any element of list?"
14149 (setq list (mapcar (lambda (x) (string-match re x)) list))
14150 (delq nil list))
14152 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14153 (defvar org-tags-overlay (make-overlay 1 1))
14154 (org-detach-overlay org-tags-overlay)
14156 (defun org-get-local-tags-at (&optional pos)
14157 "Get a list of tags defined in the current headline."
14158 (org-get-tags-at pos 'local))
14160 (defun org-get-local-tags ()
14161 "Get a list of tags defined in the current headline."
14162 (org-get-tags-at nil 'local))
14164 (defun org-get-tags-at (&optional pos local)
14165 "Get a list of all headline tags applicable at POS.
14166 POS defaults to point. If tags are inherited, the list contains
14167 the targets in the same sequence as the headlines appear, i.e.
14168 the tags of the current headline come last.
14169 When LOCAL is non-nil, only return tags from the current headline,
14170 ignore inherited ones."
14171 (interactive)
14172 (if (and org-trust-scanner-tags
14173 (or (not pos) (equal pos (point)))
14174 (not local))
14175 org-scanner-tags
14176 (let (tags ltags lastpos parent)
14177 (save-excursion
14178 (save-restriction
14179 (widen)
14180 (goto-char (or pos (point)))
14181 (save-match-data
14182 (catch 'done
14183 (condition-case nil
14184 (progn
14185 (org-back-to-heading t)
14186 (while (not (equal lastpos (point)))
14187 (setq lastpos (point))
14188 (when (looking-at
14189 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14190 (setq ltags (org-split-string
14191 (org-match-string-no-properties 1) ":"))
14192 (when parent
14193 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14194 (setq tags (append
14195 (if parent
14196 (org-remove-uninherited-tags ltags)
14197 ltags)
14198 tags)))
14199 (or org-use-tag-inheritance (throw 'done t))
14200 (if local (throw 'done t))
14201 (or (org-up-heading-safe) (error nil))
14202 (setq parent t)))
14203 (error nil)))))
14204 (if local
14205 tags
14206 (reverse (delete-dups
14207 (reverse (append
14208 (org-remove-uninherited-tags
14209 org-file-tags) tags)))))))))
14211 (defun org-add-prop-inherited (s)
14212 (add-text-properties 0 (length s) '(inherited t) s)
14215 (defun org-toggle-tag (tag &optional onoff)
14216 "Toggle the tag TAG for the current line.
14217 If ONOFF is `on' or `off', don't toggle but set to this state."
14218 (let (res current)
14219 (save-excursion
14220 (org-back-to-heading t)
14221 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14222 (point-at-eol) t)
14223 (progn
14224 (setq current (match-string 1))
14225 (replace-match ""))
14226 (setq current ""))
14227 (setq current (nreverse (org-split-string current ":")))
14228 (cond
14229 ((eq onoff 'on)
14230 (setq res t)
14231 (or (member tag current) (push tag current)))
14232 ((eq onoff 'off)
14233 (or (not (member tag current)) (setq current (delete tag current))))
14234 (t (if (member tag current)
14235 (setq current (delete tag current))
14236 (setq res t)
14237 (push tag current))))
14238 (end-of-line 1)
14239 (if current
14240 (progn
14241 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14242 (org-set-tags nil t))
14243 (delete-horizontal-space))
14244 (run-hooks 'org-after-tags-change-hook))
14245 res))
14247 (defun org-align-tags-here (to-col)
14248 ;; Assumes that this is a headline
14249 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14250 (beginning-of-line 1)
14251 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14252 (< pos (match-beginning 2)))
14253 (progn
14254 (setq tags-l (- (match-end 2) (match-beginning 2)))
14255 (goto-char (match-beginning 1))
14256 (insert " ")
14257 (delete-region (point) (1+ (match-beginning 2)))
14258 (setq ncol (max (current-column)
14259 (1+ col)
14260 (if (> to-col 0)
14261 to-col
14262 (- (abs to-col) tags-l))))
14263 (setq p (point))
14264 (insert (make-string (- ncol (current-column)) ?\ ))
14265 (setq ncol (current-column))
14266 (when indent-tabs-mode (tabify p (point-at-eol)))
14267 (org-move-to-column (min ncol col) t))
14268 (goto-char pos))))
14270 (defun org-set-tags-command (&optional arg just-align)
14271 "Call the set-tags command for the current entry."
14272 (interactive "P")
14273 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14274 (org-set-tags arg just-align)
14275 (save-excursion
14276 (unless (and (org-region-active-p)
14277 org-loop-over-headlines-in-active-region)
14278 (org-back-to-heading t))
14279 (org-set-tags arg just-align))))
14281 (defun org-set-tags-to (data)
14282 "Set the tags of the current entry to DATA, replacing the current tags.
14283 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14284 If DATA is nil or the empty string, any tags will be removed."
14285 (interactive "sTags: ")
14286 (setq data
14287 (cond
14288 ((eq data nil) "")
14289 ((equal data "") "")
14290 ((stringp data)
14291 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14292 ":"))
14293 ((listp data)
14294 (concat ":" (mapconcat 'identity data ":") ":"))))
14295 (when data
14296 (save-excursion
14297 (org-back-to-heading t)
14298 (when (looking-at org-complex-heading-regexp)
14299 (if (match-end 5)
14300 (progn
14301 (goto-char (match-beginning 5))
14302 (insert data)
14303 (delete-region (point) (point-at-eol))
14304 (org-set-tags nil 'align))
14305 (goto-char (point-at-eol))
14306 (insert " " data)
14307 (org-set-tags nil 'align)))
14308 (beginning-of-line 1)
14309 (if (looking-at ".*?\\([ \t]+\\)$")
14310 (delete-region (match-beginning 1) (match-end 1))))))
14312 (defun org-align-all-tags ()
14313 "Align the tags i all headings."
14314 (interactive)
14315 (save-excursion
14316 (or (ignore-errors (org-back-to-heading t))
14317 (outline-next-heading))
14318 (if (org-at-heading-p)
14319 (org-set-tags t)
14320 (message "No headings"))))
14322 (defvar org-indent-indentation-per-level)
14323 (defun org-set-tags (&optional arg just-align)
14324 "Set the tags for the current headline.
14325 With prefix ARG, realign all tags in headings in the current buffer."
14326 (interactive "P")
14327 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14328 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14329 'region-start-level 'region))
14330 org-loop-over-headlines-in-active-region)
14331 (org-map-entries
14332 ;; We don't use ARG and JUST-ALIGN here these args are not
14333 ;; useful when looping over headlines
14334 `(org-set-tags)
14335 org-loop-over-headlines-in-active-region
14336 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14337 (let* ((re org-outline-regexp-bol)
14338 (current (unless arg (org-get-tags-string)))
14339 (col (current-column))
14340 (org-setting-tags t)
14341 table current-tags inherited-tags ; computed below when needed
14342 tags p0 c0 c1 rpl di tc level)
14343 (if arg
14344 (save-excursion
14345 (goto-char (point-min))
14346 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14347 (while (re-search-forward re nil t)
14348 (org-set-tags nil t)
14349 (end-of-line 1)))
14350 (message "All tags realigned to column %d" org-tags-column))
14351 (if just-align
14352 (setq tags current)
14353 ;; Get a new set of tags from the user
14354 (save-excursion
14355 (setq table (append org-tag-persistent-alist
14356 (or org-tag-alist (org-get-buffer-tags))
14357 (and
14358 org-complete-tags-always-offer-all-agenda-tags
14359 (org-global-tags-completion-table
14360 (org-agenda-files))))
14361 org-last-tags-completion-table table
14362 current-tags (org-split-string current ":")
14363 inherited-tags (nreverse
14364 (nthcdr (length current-tags)
14365 (nreverse (org-get-tags-at))))
14366 tags
14367 (if (or (eq t org-use-fast-tag-selection)
14368 (and org-use-fast-tag-selection
14369 (delq nil (mapcar 'cdr table))))
14370 (org-fast-tag-selection
14371 current-tags inherited-tags table
14372 (if org-fast-tag-selection-include-todo
14373 org-todo-key-alist))
14374 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14375 (org-trim
14376 (org-icompleting-read "Tags: "
14377 'org-tags-completion-function
14378 nil nil current 'org-tags-history))))))
14379 (while (string-match "[-+&]+" tags)
14380 ;; No boolean logic, just a list
14381 (setq tags (replace-match ":" t t tags))))
14383 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14385 (if org-tags-sort-function
14386 (setq tags (mapconcat 'identity
14387 (sort (org-split-string
14388 tags (org-re "[^[:alnum:]_@#%]+"))
14389 org-tags-sort-function) ":")))
14391 (if (string-match "\\`[\t ]*\\'" tags)
14392 (setq tags "")
14393 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14394 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14396 ;; Insert new tags at the correct column
14397 (beginning-of-line 1)
14398 (setq level (or (and (looking-at org-outline-regexp)
14399 (- (match-end 0) (point) 1))
14401 (cond
14402 ((and (equal current "") (equal tags "")))
14403 ((re-search-forward
14404 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14405 (point-at-eol) t)
14406 (if (equal tags "")
14407 (setq rpl "")
14408 (goto-char (match-beginning 0))
14409 (setq c0 (current-column)
14410 ;; compute offset for the case of org-indent-mode active
14411 di (if org-indent-mode
14412 (* (1- org-indent-indentation-per-level) (1- level))
14414 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14415 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14416 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14417 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14418 (replace-match rpl t t)
14419 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14420 tags)
14421 (t (error "Tags alignment failed")))
14422 (org-move-to-column col)
14423 (unless just-align
14424 (run-hooks 'org-after-tags-change-hook))))))
14426 (defun org-change-tag-in-region (beg end tag off)
14427 "Add or remove TAG for each entry in the region.
14428 This works in the agenda, and also in an org-mode buffer."
14429 (interactive
14430 (list (region-beginning) (region-end)
14431 (let ((org-last-tags-completion-table
14432 (if (derived-mode-p 'org-mode)
14433 (org-get-buffer-tags)
14434 (org-global-tags-completion-table))))
14435 (org-icompleting-read
14436 "Tag: " 'org-tags-completion-function nil nil nil
14437 'org-tags-history))
14438 (progn
14439 (message "[s]et or [r]emove? ")
14440 (equal (read-char-exclusive) ?r))))
14441 (if (fboundp 'deactivate-mark) (deactivate-mark))
14442 (let ((agendap (equal major-mode 'org-agenda-mode))
14443 l1 l2 m buf pos newhead (cnt 0))
14444 (goto-char end)
14445 (setq l2 (1- (org-current-line)))
14446 (goto-char beg)
14447 (setq l1 (org-current-line))
14448 (loop for l from l1 to l2 do
14449 (org-goto-line l)
14450 (setq m (get-text-property (point) 'org-hd-marker))
14451 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14452 (and agendap m))
14453 (setq buf (if agendap (marker-buffer m) (current-buffer))
14454 pos (if agendap m (point)))
14455 (with-current-buffer buf
14456 (save-excursion
14457 (save-restriction
14458 (goto-char pos)
14459 (setq cnt (1+ cnt))
14460 (org-toggle-tag tag (if off 'off 'on))
14461 (setq newhead (org-get-heading)))))
14462 (and agendap (org-agenda-change-all-lines newhead m))))
14463 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14465 (defun org-tags-completion-function (string predicate &optional flag)
14466 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14467 (confirm (lambda (x) (stringp (car x)))))
14468 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14469 (setq s1 (match-string 1 string)
14470 s2 (match-string 2 string))
14471 (setq s1 "" s2 string))
14472 (cond
14473 ((eq flag nil)
14474 ;; try completion
14475 (setq rtn (try-completion s2 ctable confirm))
14476 (if (stringp rtn)
14477 (setq rtn
14478 (concat s1 s2 (substring rtn (length s2))
14479 (if (and org-add-colon-after-tag-completion
14480 (assoc rtn ctable))
14481 ":" ""))))
14482 rtn)
14483 ((eq flag t)
14484 ;; all-completions
14485 (all-completions s2 ctable confirm))
14486 ((eq flag 'lambda)
14487 ;; exact match?
14488 (assoc s2 ctable)))))
14490 (defun org-fast-tag-insert (kwd tags face &optional end)
14491 "Insert KDW, and the TAGS, the latter with face FACE.
14492 Also insert END."
14493 (insert (format "%-12s" (concat kwd ":"))
14494 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14495 (or end "")))
14497 (defun org-fast-tag-show-exit (flag)
14498 (save-excursion
14499 (org-goto-line 3)
14500 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14501 (replace-match ""))
14502 (when flag
14503 (end-of-line 1)
14504 (org-move-to-column (- (window-width) 19) t)
14505 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14507 (defun org-set-current-tags-overlay (current prefix)
14508 "Add an overlay to CURRENT tag with PREFIX."
14509 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14510 (if (featurep 'xemacs)
14511 (org-overlay-display org-tags-overlay (concat prefix s)
14512 'secondary-selection)
14513 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14514 (org-overlay-display org-tags-overlay (concat prefix s)))))
14516 (defvar org-last-tag-selection-key nil)
14517 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14518 "Fast tag selection with single keys.
14519 CURRENT is the current list of tags in the headline, INHERITED is the
14520 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14521 possibly with grouping information. TODO-TABLE is a similar table with
14522 TODO keywords, should these have keys assigned to them.
14523 If the keys are nil, a-z are automatically assigned.
14524 Returns the new tags string, or nil to not change the current settings."
14525 (let* ((fulltable (append table todo-table))
14526 (maxlen (apply 'max (mapcar
14527 (lambda (x)
14528 (if (stringp (car x)) (string-width (car x)) 0))
14529 fulltable)))
14530 (buf (current-buffer))
14531 (expert (eq org-fast-tag-selection-single-key 'expert))
14532 (buffer-tags nil)
14533 (fwidth (+ maxlen 3 1 3))
14534 (ncol (/ (- (window-width) 4) fwidth))
14535 (i-face 'org-done)
14536 (c-face 'org-todo)
14537 tg cnt e c char c1 c2 ntable tbl rtn
14538 ov-start ov-end ov-prefix
14539 (exit-after-next org-fast-tag-selection-single-key)
14540 (done-keywords org-done-keywords)
14541 groups ingroup)
14542 (save-excursion
14543 (beginning-of-line 1)
14544 (if (looking-at
14545 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14546 (setq ov-start (match-beginning 1)
14547 ov-end (match-end 1)
14548 ov-prefix "")
14549 (setq ov-start (1- (point-at-eol))
14550 ov-end (1+ ov-start))
14551 (skip-chars-forward "^\n\r")
14552 (setq ov-prefix
14553 (concat
14554 (buffer-substring (1- (point)) (point))
14555 (if (> (current-column) org-tags-column)
14557 (make-string (- org-tags-column (current-column)) ?\ ))))))
14558 (move-overlay org-tags-overlay ov-start ov-end)
14559 (save-window-excursion
14560 (if expert
14561 (set-buffer (get-buffer-create " *Org tags*"))
14562 (delete-other-windows)
14563 (split-window-vertically)
14564 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14565 (erase-buffer)
14566 (org-set-local 'org-done-keywords done-keywords)
14567 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14568 (org-fast-tag-insert "Current" current c-face "\n\n")
14569 (org-fast-tag-show-exit exit-after-next)
14570 (org-set-current-tags-overlay current ov-prefix)
14571 (setq tbl fulltable char ?a cnt 0)
14572 (while (setq e (pop tbl))
14573 (cond
14574 ((equal (car e) :startgroup)
14575 (push '() groups) (setq ingroup t)
14576 (when (not (= cnt 0))
14577 (setq cnt 0)
14578 (insert "\n"))
14579 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14580 ((equal (car e) :endgroup)
14581 (setq ingroup nil cnt 0)
14582 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14583 ((equal e '(:newline))
14584 (when (not (= cnt 0))
14585 (setq cnt 0)
14586 (insert "\n")
14587 (setq e (car tbl))
14588 (while (equal (car tbl) '(:newline))
14589 (insert "\n")
14590 (setq tbl (cdr tbl)))))
14591 ((equal e '(:grouptags)) nil)
14593 (setq tg (copy-sequence (car e)) c2 nil)
14594 (if (cdr e)
14595 (setq c (cdr e))
14596 ;; automatically assign a character.
14597 (setq c1 (string-to-char
14598 (downcase (substring
14599 tg (if (= (string-to-char tg) ?@) 1 0)))))
14600 (if (or (rassoc c1 ntable) (rassoc c1 table))
14601 (while (or (rassoc char ntable) (rassoc char table))
14602 (setq char (1+ char)))
14603 (setq c2 c1))
14604 (setq c (or c2 char)))
14605 (if ingroup (push tg (car groups)))
14606 (setq tg (org-add-props tg nil 'face
14607 (cond
14608 ((not (assoc tg table))
14609 (org-get-todo-face tg))
14610 ((member tg current) c-face)
14611 ((member tg inherited) i-face))))
14612 (if (equal (caar tbl) :grouptags)
14613 (org-add-props tg nil 'face 'org-tag-group))
14614 (if (and (= cnt 0) (not ingroup)) (insert " "))
14615 (insert "[" c "] " tg (make-string
14616 (- fwidth 4 (length tg)) ?\ ))
14617 (push (cons tg c) ntable)
14618 (when (= (setq cnt (1+ cnt)) ncol)
14619 (insert "\n")
14620 (if ingroup (insert " "))
14621 (setq cnt 0)))))
14622 (setq ntable (nreverse ntable))
14623 (insert "\n")
14624 (goto-char (point-min))
14625 (if (not expert) (org-fit-window-to-buffer))
14626 (setq rtn
14627 (catch 'exit
14628 (while t
14629 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14630 (if (not groups) "no " "")
14631 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14632 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14633 (setq org-last-tag-selection-key c)
14634 (cond
14635 ((= c ?\r) (throw 'exit t))
14636 ((= c ?!)
14637 (setq groups (not groups))
14638 (goto-char (point-min))
14639 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14640 ((= c ?\C-c)
14641 (if (not expert)
14642 (org-fast-tag-show-exit
14643 (setq exit-after-next (not exit-after-next)))
14644 (setq expert nil)
14645 (delete-other-windows)
14646 (set-window-buffer (split-window-vertically) " *Org tags*")
14647 (org-switch-to-buffer-other-window " *Org tags*")
14648 (org-fit-window-to-buffer)))
14649 ((or (= c ?\C-g)
14650 (and (= c ?q) (not (rassoc c ntable))))
14651 (org-detach-overlay org-tags-overlay)
14652 (setq quit-flag t))
14653 ((= c ?\ )
14654 (setq current nil)
14655 (if exit-after-next (setq exit-after-next 'now)))
14656 ((= c ?\t)
14657 (condition-case nil
14658 (setq tg (org-icompleting-read
14659 "Tag: "
14660 (or buffer-tags
14661 (with-current-buffer buf
14662 (org-get-buffer-tags)))))
14663 (quit (setq tg "")))
14664 (when (string-match "\\S-" tg)
14665 (add-to-list 'buffer-tags (list tg))
14666 (if (member tg current)
14667 (setq current (delete tg current))
14668 (push tg current)))
14669 (if exit-after-next (setq exit-after-next 'now)))
14670 ((setq e (rassoc c todo-table) tg (car e))
14671 (with-current-buffer buf
14672 (save-excursion (org-todo tg)))
14673 (if exit-after-next (setq exit-after-next 'now)))
14674 ((setq e (rassoc c ntable) tg (car e))
14675 (if (member tg current)
14676 (setq current (delete tg current))
14677 (loop for g in groups do
14678 (if (member tg g)
14679 (mapc (lambda (x)
14680 (setq current (delete x current)))
14681 g)))
14682 (push tg current))
14683 (if exit-after-next (setq exit-after-next 'now))))
14685 ;; Create a sorted list
14686 (setq current
14687 (sort current
14688 (lambda (a b)
14689 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14690 (if (eq exit-after-next 'now) (throw 'exit t))
14691 (goto-char (point-min))
14692 (beginning-of-line 2)
14693 (delete-region (point) (point-at-eol))
14694 (org-fast-tag-insert "Current" current c-face)
14695 (org-set-current-tags-overlay current ov-prefix)
14696 (while (re-search-forward
14697 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14698 (setq tg (match-string 1))
14699 (add-text-properties
14700 (match-beginning 1) (match-end 1)
14701 (list 'face
14702 (cond
14703 ((member tg current) c-face)
14704 ((member tg inherited) i-face)
14705 (t (get-text-property (match-beginning 1) 'face))))))
14706 (goto-char (point-min)))))
14707 (org-detach-overlay org-tags-overlay)
14708 (if rtn
14709 (mapconcat 'identity current ":")
14710 nil))))
14712 (defun org-get-tags-string ()
14713 "Get the TAGS string in the current headline."
14714 (unless (org-at-heading-p t)
14715 (error "Not on a heading"))
14716 (save-excursion
14717 (beginning-of-line 1)
14718 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14719 (org-match-string-no-properties 1)
14720 "")))
14722 (defun org-get-tags ()
14723 "Get the list of tags specified in the current headline."
14724 (org-split-string (org-get-tags-string) ":"))
14726 (defun org-get-buffer-tags ()
14727 "Get a table of all tags used in the buffer, for completion."
14728 (let (tags)
14729 (save-excursion
14730 (goto-char (point-min))
14731 (while (re-search-forward
14732 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14733 (when (equal (char-after (point-at-bol 0)) ?*)
14734 (mapc (lambda (x) (add-to-list 'tags x))
14735 (org-split-string (org-match-string-no-properties 1) ":")))))
14736 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14737 (mapcar 'list tags)))
14739 ;;;; The mapping API
14741 (defun org-map-entries (func &optional match scope &rest skip)
14742 "Call FUNC at each headline selected by MATCH in SCOPE.
14744 FUNC is a function or a lisp form. The function will be called without
14745 arguments, with the cursor positioned at the beginning of the headline.
14746 The return values of all calls to the function will be collected and
14747 returned as a list.
14749 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14750 does not need to preserve point. After evaluation, the cursor will be
14751 moved to the end of the line (presumably of the headline of the
14752 processed entry) and search continues from there. Under some
14753 circumstances, this may not produce the wanted results. For example,
14754 if you have removed (e.g. archived) the current (sub)tree it could
14755 mean that the next entry will be skipped entirely. In such cases, you
14756 can specify the position from where search should continue by making
14757 FUNC set the variable `org-map-continue-from' to the desired buffer
14758 position.
14760 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14761 Only headlines that are matched by this query will be considered during
14762 the iteration. When MATCH is nil or t, all headlines will be
14763 visited by the iteration.
14765 SCOPE determines the scope of this command. It can be any of:
14767 nil The current buffer, respecting the restriction if any
14768 tree The subtree started with the entry at point
14769 region The entries within the active region, if any
14770 region-start-level
14771 The entries within the active region, but only those at
14772 the same level than the first one.
14773 file The current buffer, without restriction
14774 file-with-archives
14775 The current buffer, and any archives associated with it
14776 agenda All agenda files
14777 agenda-with-archives
14778 All agenda files with any archive files associated with them
14779 \(file1 file2 ...)
14780 If this is a list, all files in the list will be scanned
14782 The remaining args are treated as settings for the skipping facilities of
14783 the scanner. The following items can be given here:
14785 archive skip trees with the archive tag
14786 comment skip trees with the COMMENT keyword
14787 function or Emacs Lisp form:
14788 will be used as value for `org-agenda-skip-function', so
14789 whenever the function returns a position, FUNC will not be
14790 called for that entry and search will continue from the
14791 position returned
14793 If your function needs to retrieve the tags including inherited tags
14794 at the *current* entry, you can use the value of the variable
14795 `org-scanner-tags' which will be much faster than getting the value
14796 with `org-get-tags-at'. If your function gets properties with
14797 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14798 to t around the call to `org-entry-properties' to get the same speedup.
14799 Note that if your function moves around to retrieve tags and properties at
14800 a *different* entry, you cannot use these techniques."
14801 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14802 (not (org-region-active-p)))
14803 (let* ((org-agenda-archives-mode nil) ; just to make sure
14804 (org-agenda-skip-archived-trees (memq 'archive skip))
14805 (org-agenda-skip-comment-trees (memq 'comment skip))
14806 (org-agenda-skip-function
14807 (car (org-delete-all '(comment archive) skip)))
14808 (org-tags-match-list-sublevels t)
14809 (start-level (eq scope 'region-start-level))
14810 matcher file res
14811 org-todo-keywords-for-agenda
14812 org-done-keywords-for-agenda
14813 org-todo-keyword-alist-for-agenda
14814 org-drawers-for-agenda
14815 org-tag-alist-for-agenda
14816 todo-only)
14818 (cond
14819 ((eq match t) (setq matcher t))
14820 ((eq match nil) (setq matcher t))
14821 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14823 (save-window-excursion
14824 (save-restriction
14825 (cond ((eq scope 'tree)
14826 (org-back-to-heading t)
14827 (org-narrow-to-subtree)
14828 (setq scope nil))
14829 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14830 (org-region-active-p))
14831 ;; If needed, set start-level to a string like "2"
14832 (when start-level
14833 (save-excursion
14834 (goto-char (region-beginning))
14835 (unless (org-at-heading-p) (outline-next-heading))
14836 (setq start-level (org-current-level))))
14837 (narrow-to-region (region-beginning)
14838 (save-excursion
14839 (goto-char (region-end))
14840 (unless (and (bolp) (org-at-heading-p))
14841 (outline-next-heading))
14842 (point)))
14843 (setq scope nil)))
14845 (if (not scope)
14846 (progn
14847 (org-agenda-prepare-buffers
14848 (list (buffer-file-name (current-buffer))))
14849 (setq res (org-scan-tags func matcher todo-only start-level)))
14850 ;; Get the right scope
14851 (cond
14852 ((and scope (listp scope) (symbolp (car scope)))
14853 (setq scope (eval scope)))
14854 ((eq scope 'agenda)
14855 (setq scope (org-agenda-files t)))
14856 ((eq scope 'agenda-with-archives)
14857 (setq scope (org-agenda-files t))
14858 (setq scope (org-add-archive-files scope)))
14859 ((eq scope 'file)
14860 (setq scope (list (buffer-file-name))))
14861 ((eq scope 'file-with-archives)
14862 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14863 (org-agenda-prepare-buffers scope)
14864 (while (setq file (pop scope))
14865 (with-current-buffer (org-find-base-buffer-visiting file)
14866 (save-excursion
14867 (save-restriction
14868 (widen)
14869 (goto-char (point-min))
14870 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14871 res)))
14873 ;;;; Properties
14875 ;;; Setting and retrieving properties
14877 (defconst org-special-properties
14878 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14879 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14880 "The special properties valid in Org-mode.
14882 These are properties that are not defined in the property drawer,
14883 but in some other way.")
14885 (defconst org-default-properties
14886 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14887 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14888 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14889 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14890 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14891 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14892 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14893 "Some properties that are used by Org-mode for various purposes.
14894 Being in this list makes sure that they are offered for completion.")
14896 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14897 "Regular expression matching the first line of a property drawer.")
14899 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14900 "Regular expression matching the last line of a property drawer.")
14902 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14903 "Regular expression matching the first line of a property drawer.")
14905 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14906 "Regular expression matching the first line of a property drawer.")
14908 (defconst org-property-drawer-re
14909 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14910 org-property-end-re "\\)\n?")
14911 "Matches an entire property drawer.")
14913 (defconst org-clock-drawer-re
14914 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14915 org-property-end-re "\\)\n?")
14916 "Matches an entire clock drawer.")
14918 (defsubst org-re-property (property)
14919 "Return a regexp matching a PROPERTY line.
14920 Match group 1 will be set to the value."
14921 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14923 (defsubst org-re-property-keyword (property)
14924 "Return a regexp matching a PROPERTY line, possibly with no
14925 value for the property."
14926 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14928 (defun org-property-action ()
14929 "Do an action on properties."
14930 (interactive)
14931 (let (c)
14932 (org-at-property-p)
14933 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14934 (setq c (read-char-exclusive))
14935 (cond
14936 ((equal c ?s)
14937 (call-interactively 'org-set-property))
14938 ((equal c ?d)
14939 (call-interactively 'org-delete-property))
14940 ((equal c ?D)
14941 (call-interactively 'org-delete-property-globally))
14942 ((equal c ?c)
14943 (call-interactively 'org-compute-property-at-point))
14944 (t (error "No such property action %c" c)))))
14946 (defun org-inc-effort ()
14947 "Increment the value of the effort property in the current entry."
14948 (interactive)
14949 (org-set-effort nil t))
14951 (defvar org-clock-effort) ;; Defined in org-clock.el
14952 (defvar org-clock-current-task) ;; Defined in org-clock.el
14953 (defun org-set-effort (&optional value increment)
14954 "Set the effort property of the current entry.
14955 With numerical prefix arg, use the nth allowed value, 0 stands for the
14956 10th allowed value.
14958 When INCREMENT is non-nil, set the property to the next allowed value."
14959 (interactive "P")
14960 (if (equal value 0) (setq value 10))
14961 (let* ((completion-ignore-case t)
14962 (prop org-effort-property)
14963 (cur (org-entry-get nil prop))
14964 (allowed (org-property-get-allowed-values nil prop 'table))
14965 (existing (mapcar 'list (org-property-values prop)))
14966 (heading (nth 4 (org-heading-components)))
14968 (val (cond
14969 ((stringp value) value)
14970 ((and allowed (integerp value))
14971 (or (car (nth (1- value) allowed))
14972 (car (org-last allowed))))
14973 ((and allowed increment)
14974 (or (caadr (member (list cur) allowed))
14975 (error "Allowed effort values are not set")))
14976 (allowed
14977 (message "Select 1-9,0, [RET%s]: %s"
14978 (if cur (concat "=" cur) "")
14979 (mapconcat 'car allowed " "))
14980 (setq rpl (read-char-exclusive))
14981 (if (equal rpl ?\r)
14983 (setq rpl (- rpl ?0))
14984 (if (equal rpl 0) (setq rpl 10))
14985 (if (and (> rpl 0) (<= rpl (length allowed)))
14986 (car (nth (1- rpl) allowed))
14987 (org-completing-read "Effort: " allowed nil))))
14989 (let (org-completion-use-ido org-completion-use-iswitchb)
14990 (org-completing-read
14991 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14992 (concat "[" cur "]") "")
14993 ": ")
14994 existing nil nil "" nil cur))))))
14995 (unless (equal (org-entry-get nil prop) val)
14996 (org-entry-put nil prop val))
14997 (save-excursion
14998 (org-back-to-heading t)
14999 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15000 (when (string= heading org-clock-current-task)
15001 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15002 (org-clock-update-mode-line))
15003 (message "%s is now %s" prop val)))
15005 (defun org-at-property-p ()
15006 "Is cursor inside a property drawer?"
15007 (save-excursion
15008 (beginning-of-line 1)
15009 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15010 (save-match-data ;; Used by calling procedures
15011 (let ((p (point))
15012 (range (unless (org-before-first-heading-p)
15013 (org-get-property-block))))
15014 (and range (<= (car range) p) (< p (cdr range))))))))
15016 (defun org-get-property-block (&optional beg end force)
15017 "Return the (beg . end) range of the body of the property drawer.
15018 BEG and END are the beginning and end of the current subtree, or of
15019 the part before the first headline. If they are not given, they will
15020 be found. If the drawer does not exist and FORCE is non-nil, create
15021 the drawer."
15022 (catch 'exit
15023 (save-excursion
15024 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15025 (progn (org-back-to-heading t) (point))))
15026 (end (or end (and (not (outline-next-heading)) (point-max))
15027 (point))))
15028 (goto-char beg)
15029 (if (re-search-forward org-property-start-re end t)
15030 (setq beg (1+ (match-end 0)))
15031 (if force
15032 (save-excursion
15033 (org-insert-property-drawer)
15034 (setq end (progn (outline-next-heading) (point))))
15035 (throw 'exit nil))
15036 (goto-char beg)
15037 (if (re-search-forward org-property-start-re end t)
15038 (setq beg (1+ (match-end 0)))))
15039 (if (re-search-forward org-property-end-re end t)
15040 (setq end (match-beginning 0))
15041 (or force (throw 'exit nil))
15042 (goto-char beg)
15043 (setq end beg)
15044 (org-indent-line)
15045 (insert ":END:\n"))
15046 (cons beg end)))))
15048 (defun org-entry-properties (&optional pom which specific)
15049 "Get all properties of the entry at point-or-marker POM.
15050 This includes the TODO keyword, the tags, time strings for deadline,
15051 scheduled, and clocking, and any additional properties defined in the
15052 entry. The return value is an alist, keys may occur multiple times
15053 if the property key was used several times.
15054 POM may also be nil, in which case the current entry is used.
15055 If WHICH is nil or `all', get all properties. If WHICH is
15056 `special' or `standard', only get that subclass. If WHICH
15057 is a string only get exactly this property. SPECIFIC can be a string, the
15058 specific property we are interested in. Specifying it can speed
15059 things up because then unnecessary parsing is avoided."
15060 (setq which (or which 'all))
15061 (org-with-point-at pom
15062 (let ((clockstr (substring org-clock-string 0 -1))
15063 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15064 (case-fold-search nil)
15065 beg end range props sum-props key key1 value string clocksum clocksumt)
15066 (save-excursion
15067 (when (condition-case nil
15068 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15069 (error nil))
15070 (setq beg (point))
15071 (setq sum-props (get-text-property (point) 'org-summaries))
15072 (setq clocksum (get-text-property (point) :org-clock-minutes)
15073 clocksumt (get-text-property (point) :org-clock-minutes-today))
15074 (outline-next-heading)
15075 (setq end (point))
15076 (when (memq which '(all special))
15077 ;; Get the special properties, like TODO and tags
15078 (goto-char beg)
15079 (when (and (or (not specific) (string= specific "TODO"))
15080 (looking-at org-todo-line-regexp) (match-end 2))
15081 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15082 (when (and (or (not specific) (string= specific "PRIORITY"))
15083 (looking-at org-priority-regexp))
15084 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15085 (when (or (not specific) (string= specific "FILE"))
15086 (push (cons "FILE" buffer-file-name) props))
15087 (when (and (or (not specific) (string= specific "TAGS"))
15088 (setq value (org-get-tags-string))
15089 (string-match "\\S-" value))
15090 (push (cons "TAGS" value) props))
15091 (when (and (or (not specific) (string= specific "ALLTAGS"))
15092 (setq value (org-get-tags-at)))
15093 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15094 ":"))
15095 props))
15096 (when (or (not specific) (string= specific "BLOCKED"))
15097 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15098 (when (or (not specific)
15099 (member specific
15100 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15101 "TIMESTAMP" "TIMESTAMP_IA")))
15102 (catch 'match
15103 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15104 (setq key (if (match-end 1)
15105 (substring (org-match-string-no-properties 1)
15106 0 -1))
15107 string (if (equal key clockstr)
15108 (org-trim
15109 (buffer-substring-no-properties
15110 (match-beginning 3) (goto-char
15111 (point-at-eol))))
15112 (substring (org-match-string-no-properties 3)
15113 1 -1)))
15114 ;; Get the correct property name from the key. This is
15115 ;; necessary if the user has configured time keywords.
15116 (setq key1 (concat key ":"))
15117 (cond
15118 ((not key)
15119 (setq key
15120 (if (= (char-after (match-beginning 3)) ?\[)
15121 "TIMESTAMP_IA" "TIMESTAMP")))
15122 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15123 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15124 ((equal key1 org-closed-string) (setq key "CLOSED"))
15125 ((equal key1 org-clock-string) (setq key "CLOCK")))
15126 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15127 (progn
15128 (push (cons key string) props)
15129 ;; no need to search further if match is found
15130 (throw 'match t))
15131 (when (or (equal key "CLOCK") (not (assoc key props)))
15132 (push (cons key string) props)))))))
15134 (when (memq which '(all standard))
15135 ;; Get the standard properties, like :PROP: ...
15136 (setq range (org-get-property-block beg end))
15137 (when range
15138 (goto-char (car range))
15139 (while (re-search-forward
15140 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15141 (cdr range) t)
15142 (setq key (org-match-string-no-properties 1)
15143 value (org-trim (or (org-match-string-no-properties 2) "")))
15144 (unless (member key excluded)
15145 (push (cons key (or value "")) props)))))
15146 (if clocksum
15147 (push (cons "CLOCKSUM"
15148 (org-columns-number-to-string (/ (float clocksum) 60.)
15149 'add_times))
15150 props))
15151 (if clocksumt
15152 (push (cons "CLOCKSUM_T"
15153 (org-columns-number-to-string (/ (float clocksumt) 60.)
15154 'add_times))
15155 props))
15156 (unless (assoc "CATEGORY" props)
15157 (push (cons "CATEGORY" (org-get-category)) props))
15158 (append sum-props (nreverse props)))))))
15160 (defun org-entry-get (pom property &optional inherit literal-nil)
15161 "Get value of PROPERTY for entry or content at point-or-marker POM.
15162 If INHERIT is non-nil and the entry does not have the property,
15163 then also check higher levels of the hierarchy.
15164 If INHERIT is the symbol `selective', use inheritance only if the setting
15165 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15166 If the property is present but empty, the return value is the empty string.
15167 If the property is not present at all, nil is returned.
15169 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15170 do not interpret it as the list atom nil. This is used for inheritance
15171 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15172 (org-with-point-at pom
15173 (if (and inherit (if (eq inherit 'selective)
15174 (org-property-inherit-p property)
15176 (org-entry-get-with-inheritance property literal-nil)
15177 (if (member property org-special-properties)
15178 ;; We need a special property. Use `org-entry-properties' to
15179 ;; retrieve it, but specify the wanted property
15180 (cdr (assoc property (org-entry-properties nil 'special property)))
15181 (let ((range (org-get-property-block)))
15182 (when (and range (not (eq (car range) (cdr range))))
15183 (let* ((props (list (or (assoc property org-file-properties)
15184 (assoc property org-global-properties)
15185 (assoc property org-global-properties-fixed))))
15186 (ap (lambda (key)
15187 (when (re-search-forward
15188 (org-re-property key) (cdr range) t)
15189 (setq props
15190 (org-update-property-plist
15192 (if (match-end 1)
15193 (org-match-string-no-properties 1) "")
15194 props)))))
15195 val)
15196 (goto-char (car range))
15197 (funcall ap property)
15198 (goto-char (car range))
15199 (while (funcall ap (concat property "+")))
15200 (setq val (cdr (assoc property props)))
15201 (when val (if literal-nil val (org-not-nil val))))))))))
15203 (defun org-property-or-variable-value (var &optional inherit)
15204 "Check if there is a property fixing the value of VAR.
15205 If yes, return this value. If not, return the current value of the variable."
15206 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15207 (if (and prop (stringp prop) (string-match "\\S-" prop))
15208 (read prop)
15209 (symbol-value var))))
15211 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15212 "Delete the property PROPERTY from entry at point-or-marker POM.
15213 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15214 an empty drawer to delete."
15215 (org-with-point-at pom
15216 (if (member property org-special-properties)
15217 nil ; cannot delete these properties.
15218 (let ((range (org-get-property-block)))
15219 (if (and range
15220 (goto-char (car range))
15221 (re-search-forward
15222 (org-re-property property)
15223 (cdr range) t))
15224 (progn
15225 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15226 (and delete-empty-drawer
15227 (org-remove-empty-drawer-at
15228 delete-empty-drawer (car range)))
15230 nil)))))
15232 ;; Multi-values properties are properties that contain multiple values
15233 ;; These values are assumed to be single words, separated by whitespace.
15234 (defun org-entry-add-to-multivalued-property (pom property value)
15235 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15236 (let* ((old (org-entry-get pom property))
15237 (values (and old (org-split-string old "[ \t]"))))
15238 (setq value (org-entry-protect-space value))
15239 (unless (member value values)
15240 (setq values (append values (list value)))
15241 (org-entry-put pom property
15242 (mapconcat 'identity values " ")))))
15244 (defun org-entry-remove-from-multivalued-property (pom property value)
15245 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15246 (let* ((old (org-entry-get pom property))
15247 (values (and old (org-split-string old "[ \t]"))))
15248 (setq value (org-entry-protect-space value))
15249 (when (member value values)
15250 (setq values (delete value values))
15251 (org-entry-put pom property
15252 (mapconcat 'identity values " ")))))
15254 (defun org-entry-member-in-multivalued-property (pom property value)
15255 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15256 (let* ((old (org-entry-get pom property))
15257 (values (and old (org-split-string old "[ \t]"))))
15258 (setq value (org-entry-protect-space value))
15259 (member value values)))
15261 (defun org-entry-get-multivalued-property (pom property)
15262 "Return a list of values in a multivalued property."
15263 (let* ((value (org-entry-get pom property))
15264 (values (and value (org-split-string value "[ \t]"))))
15265 (mapcar 'org-entry-restore-space values)))
15267 (defun org-entry-put-multivalued-property (pom property &rest values)
15268 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15269 VALUES should be a list of strings. Spaces will be protected."
15270 (org-entry-put pom property
15271 (mapconcat 'org-entry-protect-space values " "))
15272 (let* ((value (org-entry-get pom property))
15273 (values (and value (org-split-string value "[ \t]"))))
15274 (mapcar 'org-entry-restore-space values)))
15276 (defun org-entry-protect-space (s)
15277 "Protect spaces and newline in string S."
15278 (while (string-match " " s)
15279 (setq s (replace-match "%20" t t s)))
15280 (while (string-match "\n" s)
15281 (setq s (replace-match "%0A" t t s)))
15284 (defun org-entry-restore-space (s)
15285 "Restore spaces and newline in string S."
15286 (while (string-match "%20" s)
15287 (setq s (replace-match " " t t s)))
15288 (while (string-match "%0A" s)
15289 (setq s (replace-match "\n" t t s)))
15292 (defvar org-entry-property-inherited-from (make-marker)
15293 "Marker pointing to the entry from where a property was inherited.
15294 Each call to `org-entry-get-with-inheritance' will set this marker to the
15295 location of the entry where the inheritance search matched. If there was
15296 no match, the marker will point nowhere.
15297 Note that also `org-entry-get' calls this function, if the INHERIT flag
15298 is set.")
15300 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15301 "Get PROPERTY of entry or content at point, search higher levels if needed.
15302 The search will stop at the first ancestor which has the property defined.
15303 If the value found is \"nil\", return nil to show that the property
15304 should be considered as undefined (this is the meaning of nil here).
15305 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15306 (move-marker org-entry-property-inherited-from nil)
15307 (let (tmp)
15308 (save-excursion
15309 (save-restriction
15310 (widen)
15311 (catch 'ex
15312 (while t
15313 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15314 (or (ignore-errors (org-back-to-heading t))
15315 (goto-char (point-min)))
15316 (move-marker org-entry-property-inherited-from (point))
15317 (throw 'ex tmp))
15318 (or (ignore-errors (org-up-heading-safe))
15319 (throw 'ex nil))))))
15320 (setq tmp (or tmp
15321 (cdr (assoc property org-file-properties))
15322 (cdr (assoc property org-global-properties))
15323 (cdr (assoc property org-global-properties-fixed))))
15324 (if literal-nil tmp (org-not-nil tmp))))
15326 (defvar org-property-changed-functions nil
15327 "Hook called when the value of a property has changed.
15328 Each hook function should accept two arguments, the name of the property
15329 and the new value.")
15331 (defun org-entry-put (pom property value)
15332 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15333 (org-with-point-at pom
15334 (org-back-to-heading t)
15335 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15336 range)
15337 (cond
15338 ((equal property "TODO")
15339 (when (and (stringp value) (string-match "\\S-" value)
15340 (not (member value org-todo-keywords-1)))
15341 (error "\"%s\" is not a valid TODO state" value))
15342 (if (or (not value)
15343 (not (string-match "\\S-" value)))
15344 (setq value 'none))
15345 (org-todo value)
15346 (org-set-tags nil 'align))
15347 ((equal property "PRIORITY")
15348 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15349 (string-to-char value) ?\ ))
15350 (org-set-tags nil 'align))
15351 ((equal property "CLOCKSUM")
15352 (if (not (re-search-forward
15353 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15354 (error "Cannot find a clock log")
15355 (goto-char (- (match-end 1) 2))
15356 (cond
15357 ((eq value 'earlier) (org-timestamp-down))
15358 ((eq value 'later) (org-timestamp-up)))
15359 (org-clock-sum-current-item)))
15360 ((equal property "SCHEDULED")
15361 (if (re-search-forward org-scheduled-time-regexp end t)
15362 (cond
15363 ((eq value 'earlier) (org-timestamp-change -1 'day))
15364 ((eq value 'later) (org-timestamp-change 1 'day))
15365 (t (call-interactively 'org-schedule)))
15366 (call-interactively 'org-schedule)))
15367 ((equal property "DEADLINE")
15368 (if (re-search-forward org-deadline-time-regexp end t)
15369 (cond
15370 ((eq value 'earlier) (org-timestamp-change -1 'day))
15371 ((eq value 'later) (org-timestamp-change 1 'day))
15372 (t (call-interactively 'org-deadline)))
15373 (call-interactively 'org-deadline)))
15374 ((member property org-special-properties)
15375 (error "The %s property can not yet be set with `org-entry-put'"
15376 property))
15377 (t ; a non-special property
15378 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15379 (setq range (org-get-property-block beg end 'force))
15380 (goto-char (car range))
15381 (if (re-search-forward
15382 (org-re-property-keyword property) (cdr range) t)
15383 (progn
15384 (delete-region (match-beginning 0) (match-end 0))
15385 (goto-char (match-beginning 0)))
15386 (goto-char (cdr range))
15387 (insert "\n")
15388 (backward-char 1)
15389 (org-indent-line))
15390 (insert ":" property ":")
15391 (and value (insert " " value))
15392 (org-indent-line)))))
15393 (run-hook-with-args 'org-property-changed-functions property value)))
15395 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15396 "Get all property keys in the current buffer.
15397 With INCLUDE-SPECIALS, also list the special properties that reflect things
15398 like tags and TODO state.
15399 With INCLUDE-DEFAULTS, also include properties that has special meaning
15400 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15401 and others.
15402 With INCLUDE-COLUMNS, also include property names given in COLUMN
15403 formats in the current buffer."
15404 (let (rtn range cfmt s p)
15405 (save-excursion
15406 (save-restriction
15407 (widen)
15408 (goto-char (point-min))
15409 (while (re-search-forward org-property-start-re nil t)
15410 (setq range (org-get-property-block))
15411 (goto-char (car range))
15412 (while (re-search-forward
15413 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15414 (cdr range) t)
15415 (add-to-list 'rtn (org-match-string-no-properties 1)))
15416 (outline-next-heading))))
15418 (when include-specials
15419 (setq rtn (append org-special-properties rtn)))
15421 (when include-defaults
15422 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15423 (add-to-list 'rtn org-effort-property))
15425 (when include-columns
15426 (save-excursion
15427 (save-restriction
15428 (widen)
15429 (goto-char (point-min))
15430 (while (re-search-forward
15431 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15432 nil t)
15433 (setq cfmt (match-string 2) s 0)
15434 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15435 cfmt s)
15436 (setq s (match-end 0)
15437 p (match-string 1 cfmt))
15438 (unless (or (equal p "ITEM")
15439 (member p org-special-properties))
15440 (add-to-list 'rtn (match-string 1 cfmt))))))))
15442 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15444 (defun org-property-values (key)
15445 "Return a list of all values of property KEY in the current buffer."
15446 (save-excursion
15447 (save-restriction
15448 (widen)
15449 (goto-char (point-min))
15450 (let ((re (org-re-property key))
15451 values)
15452 (while (re-search-forward re nil t)
15453 (add-to-list 'values (org-trim (match-string 1))))
15454 (delete "" values)))))
15456 (defun org-insert-property-drawer ()
15457 "Insert a property drawer into the current entry."
15458 (org-back-to-heading t)
15459 (looking-at org-outline-regexp)
15460 (let ((indent (if org-adapt-indentation
15461 (- (match-end 0) (match-beginning 0))
15463 (beg (point))
15464 (re (concat "^[ \t]*" org-keyword-time-regexp))
15465 end hiddenp)
15466 (outline-next-heading)
15467 (setq end (point))
15468 (goto-char beg)
15469 (while (re-search-forward re end t))
15470 (setq hiddenp (outline-invisible-p))
15471 (end-of-line 1)
15472 (and (equal (char-after) ?\n) (forward-char 1))
15473 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15474 (if (member (match-string 1) '("CLOCK:" ":END:"))
15475 ;; just skip this line
15476 (beginning-of-line 2)
15477 ;; Drawer start, find the end
15478 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15479 (beginning-of-line 1)))
15480 (org-skip-over-state-notes)
15481 (skip-chars-backward " \t\n\r")
15482 (if (eq (char-before) ?*) (forward-char 1))
15483 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15484 (beginning-of-line 0)
15485 (org-indent-to-column indent)
15486 (beginning-of-line 2)
15487 (org-indent-to-column indent)
15488 (beginning-of-line 0)
15489 (if hiddenp
15490 (save-excursion
15491 (org-back-to-heading t)
15492 (hide-entry))
15493 (org-flag-drawer t))))
15495 (defun org-insert-drawer (&optional arg drawer)
15496 "Insert a drawer at point.
15498 Optional argument DRAWER, when non-nil, is a string representing
15499 drawer's name. Otherwise, the user is prompted for a name.
15501 If a region is active, insert the drawer around that region
15502 instead.
15504 Point is left between drawer's boundaries."
15505 (interactive "P")
15506 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15507 "LOGBOOK"))
15508 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15509 ;; internally by Org. They are meant to be inserted
15510 ;; automatically.
15511 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15512 ;; Remove system drawers from list. Note: For some reason,
15513 ;; `org-completing-read' ignores the predicate while
15514 ;; `completing-read' handles it fine.
15515 (drawer (if arg "PROPERTIES"
15516 (or drawer
15517 (completing-read
15518 "Drawer: " org-drawers
15519 (lambda (d) (not (member d system-drawers))))))))
15520 (cond
15521 ;; With C-u, fall back on `org-insert-property-drawer'
15522 (arg (org-insert-property-drawer))
15523 ;; With an active region, insert a drawer at point.
15524 ((not (org-region-active-p))
15525 (progn
15526 (unless (bolp) (insert "\n"))
15527 (insert (format ":%s:\n\n:END:\n" drawer))
15528 (forward-line -2)))
15529 ;; Otherwise, insert the drawer at point
15531 (let ((rbeg (region-beginning))
15532 (rend (copy-marker (region-end))))
15533 (unwind-protect
15534 (progn
15535 (goto-char rbeg)
15536 (beginning-of-line)
15537 (when (save-excursion
15538 (re-search-forward org-outline-regexp-bol rend t))
15539 (error "Drawers cannot contain headlines"))
15540 ;; Position point at the beginning of the first
15541 ;; non-blank line in region. Insert drawer's opening
15542 ;; there, then indent it.
15543 (org-skip-whitespace)
15544 (beginning-of-line)
15545 (insert ":" drawer ":\n")
15546 (forward-line -1)
15547 (indent-for-tab-command)
15548 ;; Move point to the beginning of the first blank line
15549 ;; after the last non-blank line in region. Insert
15550 ;; drawer's closing, then indent it.
15551 (goto-char rend)
15552 (skip-chars-backward " \r\t\n")
15553 (insert "\n:END:")
15554 (deactivate-mark t)
15555 (indent-for-tab-command)
15556 (unless (eolp) (insert "\n")))
15557 ;; Clear marker, whatever the outcome of insertion is.
15558 (set-marker rend nil)))))))
15560 (defvar org-property-set-functions-alist nil
15561 "Property set function alist.
15562 Each entry should have the following format:
15564 (PROPERTY . READ-FUNCTION)
15566 The read function will be called with the same argument as
15567 `org-completing-read'.")
15569 (defun org-set-property-function (property)
15570 "Get the function that should be used to set PROPERTY.
15571 This is computed according to `org-property-set-functions-alist'."
15572 (or (cdr (assoc property org-property-set-functions-alist))
15573 'org-completing-read))
15575 (defun org-read-property-value (property)
15576 "Read PROPERTY value from user."
15577 (let* ((completion-ignore-case t)
15578 (allowed (org-property-get-allowed-values nil property 'table))
15579 (cur (org-entry-get nil property))
15580 (prompt (concat property " value"
15581 (if (and cur (string-match "\\S-" cur))
15582 (concat " [" cur "]") "") ": "))
15583 (set-function (org-set-property-function property))
15584 (val (if allowed
15585 (funcall set-function prompt allowed nil
15586 (not (get-text-property 0 'org-unrestricted
15587 (caar allowed))))
15588 (let (org-completion-use-ido org-completion-use-iswitchb)
15589 (funcall set-function prompt
15590 (mapcar 'list (org-property-values property))
15591 nil nil "" nil cur)))))
15592 (if (equal val "")
15594 val)))
15596 (defvar org-last-set-property nil)
15597 (defvar org-last-set-property-value nil)
15598 (defun org-read-property-name ()
15599 "Read a property name."
15600 (let* ((completion-ignore-case t)
15601 (keys (org-buffer-property-keys nil t t))
15602 (default-prop (or (save-excursion
15603 (save-match-data
15604 (beginning-of-line)
15605 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15606 (null (string= (match-string 1) "END"))
15607 (match-string 1))))
15608 org-last-set-property))
15609 (property (org-icompleting-read
15610 (concat "Property"
15611 (if default-prop (concat " [" default-prop "]") "")
15612 ": ")
15613 (mapcar 'list keys)
15614 nil nil nil nil
15615 default-prop)))
15616 (if (member property keys)
15617 property
15618 (or (cdr (assoc (downcase property)
15619 (mapcar (lambda (x) (cons (downcase x) x))
15620 keys)))
15621 property))))
15623 (defun org-set-property-and-value (use-last)
15624 "Allow to set [PROPERTY]: [value] direction from prompt.
15625 When use-default, don't even ask, just use the last
15626 \"[PROPERTY]: [value]\" string from the history."
15627 (interactive "P")
15628 (let* ((completion-ignore-case t)
15629 (pv (or (and use-last org-last-set-property-value)
15630 (org-completing-read
15631 "Enter a \"[Property]: [value]\" pair: "
15632 nil nil nil nil nil
15633 org-last-set-property-value)))
15634 prop val)
15635 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15636 (setq prop (match-string 1 pv)
15637 val (match-string 2 pv))
15638 (org-set-property prop val))))
15640 (defun org-set-property (property value)
15641 "In the current entry, set PROPERTY to VALUE.
15642 When called interactively, this will prompt for a property name, offering
15643 completion on existing and default properties. And then it will prompt
15644 for a value, offering completion either on allowed values (via an inherited
15645 xxx_ALL property) or on existing values in other instances of this property
15646 in the current file."
15647 (interactive (list nil nil))
15648 (let* ((property (or property (org-read-property-name)))
15649 (value (or value (org-read-property-value property)))
15650 (fn (cdr (assoc property org-properties-postprocess-alist))))
15651 (setq org-last-set-property property)
15652 (setq org-last-set-property-value (concat property ": " value))
15653 ;; Possibly postprocess the inserted value:
15654 (when fn (setq value (funcall fn value)))
15655 (unless (equal (org-entry-get nil property) value)
15656 (org-entry-put nil property value))))
15658 (defun org-delete-property (property &optional delete-empty-drawer)
15659 "In the current entry, delete PROPERTY.
15660 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15661 an empty drawer to delete."
15662 (interactive
15663 (let* ((completion-ignore-case t)
15664 (prop (org-icompleting-read "Property: "
15665 (org-entry-properties nil 'standard))))
15666 (list prop)))
15667 (message "Property %s %s" property
15668 (if (org-entry-delete nil property delete-empty-drawer)
15669 "deleted"
15670 "was not present in the entry")))
15672 (defun org-delete-property-globally (property)
15673 "Remove PROPERTY globally, from all entries."
15674 (interactive
15675 (let* ((completion-ignore-case t)
15676 (prop (org-icompleting-read
15677 "Globally remove property: "
15678 (mapcar 'list (org-buffer-property-keys)))))
15679 (list prop)))
15680 (save-excursion
15681 (save-restriction
15682 (widen)
15683 (goto-char (point-min))
15684 (let ((cnt 0))
15685 (while (re-search-forward
15686 (org-re-property property)
15687 nil t)
15688 (setq cnt (1+ cnt))
15689 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15690 (message "Property \"%s\" removed from %d entries" property cnt)))))
15692 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15694 (defun org-compute-property-at-point ()
15695 "Compute the property at point.
15696 This looks for an enclosing column format, extracts the operator and
15697 then applies it to the property in the column format's scope."
15698 (interactive)
15699 (unless (org-at-property-p)
15700 (error "Not at a property"))
15701 (let ((prop (org-match-string-no-properties 2)))
15702 (org-columns-get-format-and-top-level)
15703 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15704 (error "No operator defined for property %s" prop))
15705 (org-columns-compute prop)))
15707 (defvar org-property-allowed-value-functions nil
15708 "Hook for functions supplying allowed values for a specific property.
15709 The functions must take a single argument, the name of the property, and
15710 return a flat list of allowed values. If \":ETC\" is one of
15711 the values, this means that these values are intended as defaults for
15712 completion, but that other values should be allowed too.
15713 The functions must return nil if they are not responsible for this
15714 property.")
15716 (defun org-property-get-allowed-values (pom property &optional table)
15717 "Get allowed values for the property PROPERTY.
15718 When TABLE is non-nil, return an alist that can directly be used for
15719 completion."
15720 (let (vals)
15721 (cond
15722 ((equal property "TODO")
15723 (setq vals (org-with-point-at pom
15724 (append org-todo-keywords-1 '("")))))
15725 ((equal property "PRIORITY")
15726 (let ((n org-lowest-priority))
15727 (while (>= n org-highest-priority)
15728 (push (char-to-string n) vals)
15729 (setq n (1- n)))))
15730 ((member property org-special-properties))
15731 ((setq vals (run-hook-with-args-until-success
15732 'org-property-allowed-value-functions property)))
15734 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15735 (when (and vals (string-match "\\S-" vals))
15736 (setq vals (car (read-from-string (concat "(" vals ")"))))
15737 (setq vals (mapcar (lambda (x)
15738 (cond ((stringp x) x)
15739 ((numberp x) (number-to-string x))
15740 ((symbolp x) (symbol-name x))
15741 (t "???")))
15742 vals)))))
15743 (when (member ":ETC" vals)
15744 (setq vals (remove ":ETC" vals))
15745 (org-add-props (car vals) '(org-unrestricted t)))
15746 (if table (mapcar 'list vals) vals)))
15748 (defun org-property-previous-allowed-value (&optional previous)
15749 "Switch to the next allowed value for this property."
15750 (interactive)
15751 (org-property-next-allowed-value t))
15753 (defun org-property-next-allowed-value (&optional previous)
15754 "Switch to the next allowed value for this property."
15755 (interactive)
15756 (unless (org-at-property-p)
15757 (error "Not at a property"))
15758 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15759 (key (match-string 2))
15760 (value (match-string 3))
15761 (allowed (or (org-property-get-allowed-values (point) key)
15762 (and (member value '("[ ]" "[-]" "[X]"))
15763 '("[ ]" "[X]"))))
15764 (heading (save-match-data (nth 4 (org-heading-components))))
15765 nval)
15766 (unless allowed
15767 (error "Allowed values for this property have not been defined"))
15768 (if previous (setq allowed (reverse allowed)))
15769 (if (member value allowed)
15770 (setq nval (car (cdr (member value allowed)))))
15771 (setq nval (or nval (car allowed)))
15772 (if (equal nval value)
15773 (error "Only one allowed value for this property"))
15774 (org-at-property-p)
15775 (replace-match (concat " :" key ": " nval) t t)
15776 (org-indent-line)
15777 (beginning-of-line 1)
15778 (skip-chars-forward " \t")
15779 (when (equal prop org-effort-property)
15780 (save-excursion
15781 (org-back-to-heading t)
15782 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15783 (when (string= org-clock-current-task heading)
15784 (setq org-clock-effort nval)
15785 (org-clock-update-mode-line)))
15786 (run-hook-with-args 'org-property-changed-functions key nval)))
15788 (defun org-find-olp (path &optional this-buffer)
15789 "Return a marker pointing to the entry at outline path OLP.
15790 If anything goes wrong, throw an error.
15791 You can wrap this call to catch the error like this:
15793 (condition-case msg
15794 (org-mobile-locate-entry (match-string 4))
15795 (error (nth 1 msg)))
15797 The return value will then be either a string with the error message,
15798 or a marker if everything is OK.
15800 If THIS-BUFFER is set, the outline path does not contain a file,
15801 only headings."
15802 (let* ((file (if this-buffer buffer-file-name (pop path)))
15803 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15804 (level 1)
15805 (lmin 1)
15806 (lmax 1)
15807 limit re end found pos heading cnt flevel)
15808 (unless buffer (error "File not found :%s" file))
15809 (with-current-buffer buffer
15810 (save-excursion
15811 (save-restriction
15812 (widen)
15813 (setq limit (point-max))
15814 (goto-char (point-min))
15815 (while (setq heading (pop path))
15816 (setq re (format org-complex-heading-regexp-format
15817 (regexp-quote heading)))
15818 (setq cnt 0 pos (point))
15819 (while (re-search-forward re end t)
15820 (setq level (- (match-end 1) (match-beginning 1)))
15821 (if (and (>= level lmin) (<= level lmax))
15822 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15823 (when (= cnt 0) (error "Heading not found on level %d: %s"
15824 lmax heading))
15825 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15826 lmax heading))
15827 (goto-char found)
15828 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15829 (setq end (save-excursion (org-end-of-subtree t t))))
15830 (when (org-at-heading-p)
15831 (point-marker)))))))
15833 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15834 "Find node HEADING in BUFFER.
15835 Return a marker to the heading if it was found, or nil if not.
15836 If POS-ONLY is set, return just the position instead of a marker.
15838 The heading text must match exact, but it may have a TODO keyword,
15839 a priority cookie and tags in the standard locations."
15840 (with-current-buffer (or buffer (current-buffer))
15841 (save-excursion
15842 (save-restriction
15843 (widen)
15844 (goto-char (point-min))
15845 (let (case-fold-search)
15846 (if (re-search-forward
15847 (format org-complex-heading-regexp-format
15848 (regexp-quote heading)) nil t)
15849 (if pos-only
15850 (match-beginning 0)
15851 (move-marker (make-marker) (match-beginning 0)))))))))
15853 (defun org-find-exact-heading-in-directory (heading &optional dir)
15854 "Find Org node headline HEADING in all .org files in directory DIR.
15855 When the target headline is found, return a marker to this location."
15856 (let ((files (directory-files (or dir default-directory)
15857 nil "\\`[^.#].*\\.org\\'"))
15858 file visiting m buffer)
15859 (catch 'found
15860 (while (setq file (pop files))
15861 (message "trying %s" file)
15862 (setq visiting (org-find-base-buffer-visiting file))
15863 (setq buffer (or visiting (find-file-noselect file)))
15864 (setq m (org-find-exact-headline-in-buffer
15865 heading buffer))
15866 (when (and (not m) (not visiting)) (kill-buffer buffer))
15867 (and m (throw 'found m))))))
15869 (defun org-find-entry-with-id (ident)
15870 "Locate the entry that contains the ID property with exact value IDENT.
15871 IDENT can be a string, a symbol or a number, this function will search for
15872 the string representation of it.
15873 Return the position where this entry starts, or nil if there is no such entry."
15874 (interactive "sID: ")
15875 (let ((id (cond
15876 ((stringp ident) ident)
15877 ((symbol-name ident) (symbol-name ident))
15878 ((numberp ident) (number-to-string ident))
15879 (t (error "IDENT %s must be a string, symbol or number" ident))))
15880 (case-fold-search nil))
15881 (save-excursion
15882 (save-restriction
15883 (widen)
15884 (goto-char (point-min))
15885 (when (re-search-forward
15886 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15887 nil t)
15888 (org-back-to-heading t)
15889 (point))))))
15891 ;;;; Timestamps
15893 (defvar org-last-changed-timestamp nil)
15894 (defvar org-last-inserted-timestamp nil
15895 "The last time stamp inserted with `org-insert-time-stamp'.")
15896 (defvar org-time-was-given) ; dynamically scoped parameter
15897 (defvar org-end-time-was-given) ; dynamically scoped parameter
15898 (defvar org-ts-what) ; dynamically scoped parameter
15900 (defun org-time-stamp (arg &optional inactive)
15901 "Prompt for a date/time and insert a time stamp.
15902 If the user specifies a time like HH:MM or if this command is
15903 called with at least one prefix argument, the time stamp contains
15904 the date and the time. Otherwise, only the date is be included.
15906 All parts of a date not specified by the user is filled in from
15907 the current date/time. So if you just press return without
15908 typing anything, the time stamp will represent the current
15909 date/time.
15911 If there is already a timestamp at the cursor, it will be
15912 modified.
15914 With two universal prefix arguments, insert an active timestamp
15915 with the current time without prompting the user."
15916 (interactive "P")
15917 (let* ((ts nil)
15918 (default-time
15919 ;; Default time is either today, or, when entering a range,
15920 ;; the range start.
15921 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15922 (save-excursion
15923 (re-search-backward
15924 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15925 (- (point) 20) t)))
15926 (apply 'encode-time (org-parse-time-string (match-string 1)))
15927 (current-time)))
15928 (default-input (and ts (org-get-compact-tod ts)))
15929 (repeater (save-excursion
15930 (save-match-data
15931 (beginning-of-line)
15932 (when (re-search-forward
15933 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15934 (save-excursion (progn (end-of-line) (point))) t)
15935 (match-string 0)))))
15936 org-time-was-given org-end-time-was-given time)
15937 (cond
15938 ((and (org-at-timestamp-p t)
15939 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15940 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15941 (insert "--")
15942 (setq time (let ((this-command this-command))
15943 (org-read-date arg 'totime nil nil
15944 default-time default-input inactive)))
15945 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15946 ((org-at-timestamp-p t)
15947 (setq time (let ((this-command this-command))
15948 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15949 (when (org-at-timestamp-p t) ; just to get the match data
15950 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15951 (replace-match "")
15952 (setq org-last-changed-timestamp
15953 (org-insert-time-stamp
15954 time (or org-time-was-given arg)
15955 inactive nil nil (list org-end-time-was-given)))
15956 (when repeater (goto-char (1- (point))) (insert " " repeater)
15957 (setq org-last-changed-timestamp
15958 (concat (substring org-last-inserted-timestamp 0 -1)
15959 " " repeater ">"))))
15960 (message "Timestamp updated"))
15961 ((equal arg '(16))
15962 (org-insert-time-stamp (current-time) t))
15964 (setq time (let ((this-command this-command))
15965 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15966 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15967 nil nil (list org-end-time-was-given))))))
15969 ;; FIXME: can we use this for something else, like computing time differences?
15970 (defun org-get-compact-tod (s)
15971 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15972 (let* ((t1 (match-string 1 s))
15973 (h1 (string-to-number (match-string 2 s)))
15974 (m1 (string-to-number (match-string 3 s)))
15975 (t2 (and (match-end 4) (match-string 5 s)))
15976 (h2 (and t2 (string-to-number (match-string 6 s))))
15977 (m2 (and t2 (string-to-number (match-string 7 s))))
15978 dh dm)
15979 (if (not t2)
15981 (setq dh (- h2 h1) dm (- m2 m1))
15982 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15983 (concat t1 "+" (number-to-string dh)
15984 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15986 (defun org-time-stamp-inactive (&optional arg)
15987 "Insert an inactive time stamp.
15988 An inactive time stamp is enclosed in square brackets instead of angle
15989 brackets. It is inactive in the sense that it does not trigger agenda entries,
15990 does not link to the calendar and cannot be changed with the S-cursor keys.
15991 So these are more for recording a certain time/date."
15992 (interactive "P")
15993 (org-time-stamp arg 'inactive))
15995 (defvar org-date-ovl (make-overlay 1 1))
15996 (overlay-put org-date-ovl 'face 'org-date-selected)
15997 (org-detach-overlay org-date-ovl)
15999 (defvar org-ans1) ; dynamically scoped parameter
16000 (defvar org-ans2) ; dynamically scoped parameter
16002 (defvar org-plain-time-of-day-regexp) ; defined below
16004 (defvar org-overriding-default-time nil) ; dynamically scoped
16005 (defvar org-read-date-overlay nil)
16006 (defvar org-dcst nil) ; dynamically scoped
16007 (defvar org-read-date-history nil)
16008 (defvar org-read-date-final-answer nil)
16009 (defvar org-read-date-analyze-futurep nil)
16010 (defvar org-read-date-analyze-forced-year nil)
16011 (defvar org-read-date-inactive)
16013 (defvar org-read-date-minibuffer-local-map
16014 (let ((map (make-sparse-keymap)))
16015 (set-keymap-parent map minibuffer-local-map)
16016 (org-defkey map (kbd ".")
16017 (lambda () (interactive)
16018 (org-eval-in-calendar '(calendar-goto-today))))
16019 (org-defkey map [(meta shift left)]
16020 (lambda () (interactive)
16021 (org-eval-in-calendar '(calendar-backward-month 1))))
16022 (org-defkey map [(meta shift right)]
16023 (lambda () (interactive)
16024 (org-eval-in-calendar '(calendar-forward-month 1))))
16025 (org-defkey map [(meta shift up)]
16026 (lambda () (interactive)
16027 (org-eval-in-calendar '(calendar-backward-year 1))))
16028 (org-defkey map [(meta shift down)]
16029 (lambda () (interactive)
16030 (org-eval-in-calendar '(calendar-forward-year 1))))
16031 (org-defkey map [?\e (shift left)]
16032 (lambda () (interactive)
16033 (org-eval-in-calendar '(calendar-backward-month 1))))
16034 (org-defkey map [?\e (shift right)]
16035 (lambda () (interactive)
16036 (org-eval-in-calendar '(calendar-forward-month 1))))
16037 (org-defkey map [?\e (shift up)]
16038 (lambda () (interactive)
16039 (org-eval-in-calendar '(calendar-backward-year 1))))
16040 (org-defkey map [?\e (shift down)]
16041 (lambda () (interactive)
16042 (org-eval-in-calendar '(calendar-forward-year 1))))
16043 (org-defkey map [(shift up)]
16044 (lambda () (interactive)
16045 (org-eval-in-calendar '(calendar-backward-week 1))))
16046 (org-defkey map [(shift down)]
16047 (lambda () (interactive)
16048 (org-eval-in-calendar '(calendar-forward-week 1))))
16049 (org-defkey map [(shift left)]
16050 (lambda () (interactive)
16051 (org-eval-in-calendar '(calendar-backward-day 1))))
16052 (org-defkey map [(shift right)]
16053 (lambda () (interactive)
16054 (org-eval-in-calendar '(calendar-forward-day 1))))
16055 (org-defkey map "!"
16056 (lambda () (interactive)
16057 (org-eval-in-calendar '(diary-view-entries))
16058 (message "")))
16059 (org-defkey map ">"
16060 (lambda () (interactive)
16061 (org-eval-in-calendar '(scroll-calendar-left 1))))
16062 (org-defkey map "<"
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(scroll-calendar-right 1))))
16065 (org-defkey map "\C-v"
16066 (lambda () (interactive)
16067 (org-eval-in-calendar
16068 '(calendar-scroll-left-three-months 1))))
16069 (org-defkey map "\M-v"
16070 (lambda () (interactive)
16071 (org-eval-in-calendar
16072 '(calendar-scroll-right-three-months 1))))
16073 map)
16074 "Keymap for minibuffer commands when using `org-read-date'.")
16076 (defun org-read-date (&optional org-with-time to-time from-string prompt
16077 default-time default-input inactive)
16078 "Read a date, possibly a time, and make things smooth for the user.
16079 The prompt will suggest to enter an ISO date, but you can also enter anything
16080 which will at least partially be understood by `parse-time-string'.
16081 Unrecognized parts of the date will default to the current day, month, year,
16082 hour and minute. If this command is called to replace a timestamp at point,
16083 or to enter the second timestamp of a range, the default time is taken
16084 from the existing stamp. Furthermore, the command prefers the future,
16085 so if you are giving a date where the year is not given, and the day-month
16086 combination is already past in the current year, it will assume you
16087 mean next year. For details, see the manual. A few examples:
16089 3-2-5 --> 2003-02-05
16090 feb 15 --> currentyear-02-15
16091 2/15 --> currentyear-02-15
16092 sep 12 9 --> 2009-09-12
16093 12:45 --> today 12:45
16094 22 sept 0:34 --> currentyear-09-22 0:34
16095 12 --> currentyear-currentmonth-12
16096 Fri --> nearest Friday (today or later)
16097 etc.
16099 Furthermore you can specify a relative date by giving, as the *first* thing
16100 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16101 change in days weeks, months, years.
16102 With a single plus or minus, the date is relative to today. With a double
16103 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16104 +4d --> four days from today
16105 +4 --> same as above
16106 +2w --> two weeks from today
16107 ++5 --> five days from default date
16109 The function understands only English month and weekday abbreviations.
16111 While prompting, a calendar is popped up - you can also select the
16112 date with the mouse (button 1). The calendar shows a period of three
16113 months. To scroll it to other months, use the keys `>' and `<'.
16114 If you don't like the calendar, turn it off with
16115 \(setq org-read-date-popup-calendar nil)
16117 With optional argument TO-TIME, the date will immediately be converted
16118 to an internal time.
16119 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16120 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16121 still enter a time, and this function will inform the calling routine
16122 about this change. The calling routine may then choose to change the
16123 format used to insert the time stamp into the buffer to include the time.
16124 With optional argument FROM-STRING, read from this string instead from
16125 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16126 the time/date that is used for everything that is not specified by the
16127 user."
16128 (require 'parse-time)
16129 (let* ((org-time-stamp-rounding-minutes
16130 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16131 (org-dcst org-display-custom-times)
16132 (ct (org-current-time))
16133 (org-def (or org-overriding-default-time default-time ct))
16134 (org-defdecode (decode-time org-def))
16135 (dummy (progn
16136 (when (< (nth 2 org-defdecode) org-extend-today-until)
16137 (setcar (nthcdr 2 org-defdecode) -1)
16138 (setcar (nthcdr 1 org-defdecode) 59)
16139 (setq org-def (apply 'encode-time org-defdecode)
16140 org-defdecode (decode-time org-def)))))
16141 (mouse-autoselect-window nil) ; Don't let the mouse jump
16142 (calendar-frame-setup nil)
16143 (calendar-setup nil)
16144 (calendar-move-hook nil)
16145 (calendar-view-diary-initially-flag nil)
16146 (calendar-view-holidays-initially-flag nil)
16147 (timestr (format-time-string
16148 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16149 (prompt (concat (if prompt (concat prompt " ") "")
16150 (format "Date+time [%s]: " timestr)))
16151 ans (org-ans0 "") org-ans1 org-ans2 final)
16153 (cond
16154 (from-string (setq ans from-string))
16155 (org-read-date-popup-calendar
16156 (save-excursion
16157 (save-window-excursion
16158 (calendar)
16159 (org-eval-in-calendar '(setq cursor-type nil) t)
16160 (unwind-protect
16161 (progn
16162 (calendar-forward-day (- (time-to-days org-def)
16163 (calendar-absolute-from-gregorian
16164 (calendar-current-date))))
16165 (org-eval-in-calendar nil t)
16166 (let* ((old-map (current-local-map))
16167 (map (copy-keymap calendar-mode-map))
16168 (minibuffer-local-map
16169 (copy-keymap org-read-date-minibuffer-local-map)))
16170 (org-defkey map (kbd "RET") 'org-calendar-select)
16171 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16172 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16173 (unwind-protect
16174 (progn
16175 (use-local-map map)
16176 (setq org-read-date-inactive inactive)
16177 (add-hook 'post-command-hook 'org-read-date-display)
16178 (setq org-ans0 (read-string prompt default-input
16179 'org-read-date-history nil))
16180 ;; org-ans0: from prompt
16181 ;; org-ans1: from mouse click
16182 ;; org-ans2: from calendar motion
16183 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16184 (remove-hook 'post-command-hook 'org-read-date-display)
16185 (use-local-map old-map)
16186 (when org-read-date-overlay
16187 (delete-overlay org-read-date-overlay)
16188 (setq org-read-date-overlay nil)))))
16189 (bury-buffer "*Calendar*")))))
16191 (t ; Naked prompt only
16192 (unwind-protect
16193 (setq ans (read-string prompt default-input
16194 'org-read-date-history timestr))
16195 (when org-read-date-overlay
16196 (delete-overlay org-read-date-overlay)
16197 (setq org-read-date-overlay nil)))))
16199 (setq final (org-read-date-analyze ans org-def org-defdecode))
16201 (when org-read-date-analyze-forced-year
16202 (message "Year was forced into %s"
16203 (if org-read-date-force-compatible-dates
16204 "compatible range (1970-2037)"
16205 "range representable on this machine"))
16206 (ding))
16208 ;; One round trip to get rid of 34th of August and stuff like that....
16209 (setq final (decode-time (apply 'encode-time final)))
16211 (setq org-read-date-final-answer ans)
16213 (if to-time
16214 (apply 'encode-time final)
16215 (if (and (boundp 'org-time-was-given) org-time-was-given)
16216 (format "%04d-%02d-%02d %02d:%02d"
16217 (nth 5 final) (nth 4 final) (nth 3 final)
16218 (nth 2 final) (nth 1 final))
16219 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16221 (defvar org-def)
16222 (defvar org-defdecode)
16223 (defvar org-with-time)
16224 (defun org-read-date-display ()
16225 "Display the current date prompt interpretation in the minibuffer."
16226 (when org-read-date-display-live
16227 (when org-read-date-overlay
16228 (delete-overlay org-read-date-overlay))
16229 (when (minibufferp (current-buffer))
16230 (save-excursion
16231 (end-of-line 1)
16232 (while (not (equal (buffer-substring
16233 (max (point-min) (- (point) 4)) (point))
16234 " "))
16235 (insert " ")))
16236 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16237 " " (or org-ans1 org-ans2)))
16238 (org-end-time-was-given nil)
16239 (f (org-read-date-analyze ans org-def org-defdecode))
16240 (fmts (if org-dcst
16241 org-time-stamp-custom-formats
16242 org-time-stamp-formats))
16243 (fmt (if (or org-with-time
16244 (and (boundp 'org-time-was-given) org-time-was-given))
16245 (cdr fmts)
16246 (car fmts)))
16247 (txt (format-time-string fmt (apply 'encode-time f)))
16248 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16249 (txt (concat "=> " txt)))
16250 (when (and org-end-time-was-given
16251 (string-match org-plain-time-of-day-regexp txt))
16252 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16253 org-end-time-was-given
16254 (substring txt (match-end 0)))))
16255 (when org-read-date-analyze-futurep
16256 (setq txt (concat txt " (=>F)")))
16257 (setq org-read-date-overlay
16258 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16259 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16261 (defun org-read-date-analyze (ans org-def org-defdecode)
16262 "Analyze the combined answer of the date prompt."
16263 ;; FIXME: cleanup and comment
16264 (let ((nowdecode (decode-time (current-time)))
16265 delta deltan deltaw deltadef year month day
16266 hour minute second wday pm h2 m2 tl wday1
16267 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16268 (setq org-read-date-analyze-futurep nil
16269 org-read-date-analyze-forced-year nil)
16270 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16271 (setq ans "+0"))
16273 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16274 (setq ans (replace-match "" t t ans)
16275 deltan (car delta)
16276 deltaw (nth 1 delta)
16277 deltadef (nth 2 delta)))
16279 ;; Check if there is an iso week date in there. If yes, store the
16280 ;; info and postpone interpreting it until the rest of the parsing
16281 ;; is done.
16282 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16283 (setq iso-year (if (match-end 1)
16284 (org-small-year-to-year
16285 (string-to-number (match-string 1 ans))))
16286 iso-weekday (if (match-end 3)
16287 (string-to-number (match-string 3 ans)))
16288 iso-week (string-to-number (match-string 2 ans)))
16289 (setq ans (replace-match "" t t ans)))
16291 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16292 (when (string-match
16293 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16294 (setq year (if (match-end 2)
16295 (string-to-number (match-string 2 ans))
16296 (progn (setq kill-year t)
16297 (string-to-number (format-time-string "%Y"))))
16298 month (string-to-number (match-string 3 ans))
16299 day (string-to-number (match-string 4 ans)))
16300 (if (< year 100) (setq year (+ 2000 year)))
16301 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16302 t nil ans)))
16304 ;; Help matching dotted european dates
16305 (when (string-match
16306 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16307 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16308 (setq kill-year t)
16309 (string-to-number (format-time-string "%Y")))
16310 day (string-to-number (match-string 1 ans))
16311 month (string-to-number (match-string 2 ans))
16312 ans (replace-match (format "%04d-%02d-%02d" year month day)
16313 t nil ans)))
16315 ;; Help matching american dates, like 5/30 or 5/30/7
16316 (when (string-match
16317 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16318 (setq year (if (match-end 4)
16319 (string-to-number (match-string 4 ans))
16320 (progn (setq kill-year t)
16321 (string-to-number (format-time-string "%Y"))))
16322 month (string-to-number (match-string 1 ans))
16323 day (string-to-number (match-string 2 ans)))
16324 (if (< year 100) (setq year (+ 2000 year)))
16325 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16326 t nil ans)))
16327 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16328 ;; If there is a time with am/pm, and *no* time without it, we convert
16329 ;; so that matching will be successful.
16330 (loop for i from 1 to 2 do ; twice, for end time as well
16331 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16332 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16333 (setq hour (string-to-number (match-string 1 ans))
16334 minute (if (match-end 3)
16335 (string-to-number (match-string 3 ans))
16337 pm (equal ?p
16338 (string-to-char (downcase (match-string 4 ans)))))
16339 (if (and (= hour 12) (not pm))
16340 (setq hour 0)
16341 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16342 (setq ans (replace-match (format "%02d:%02d" hour minute)
16343 t t ans))))
16345 ;; Check if a time range is given as a duration
16346 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16347 (setq hour (string-to-number (match-string 1 ans))
16348 h2 (+ hour (string-to-number (match-string 3 ans)))
16349 minute (string-to-number (match-string 2 ans))
16350 m2 (+ minute (if (match-end 5) (string-to-number
16351 (match-string 5 ans))0)))
16352 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16353 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16354 t t ans)))
16356 ;; Check if there is a time range
16357 (when (boundp 'org-end-time-was-given)
16358 (setq org-time-was-given nil)
16359 (when (and (string-match org-plain-time-of-day-regexp ans)
16360 (match-end 8))
16361 (setq org-end-time-was-given (match-string 8 ans))
16362 (setq ans (concat (substring ans 0 (match-beginning 7))
16363 (substring ans (match-end 7))))))
16365 (setq tl (parse-time-string ans)
16366 day (or (nth 3 tl) (nth 3 org-defdecode))
16367 month (or (nth 4 tl)
16368 (if (and org-read-date-prefer-future
16369 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16370 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16371 (nth 4 org-defdecode)))
16372 year (or (and (not kill-year) (nth 5 tl))
16373 (if (and org-read-date-prefer-future
16374 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16375 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16376 (nth 5 org-defdecode)))
16377 hour (or (nth 2 tl) (nth 2 org-defdecode))
16378 minute (or (nth 1 tl) (nth 1 org-defdecode))
16379 second (or (nth 0 tl) 0)
16380 wday (nth 6 tl))
16382 (when (and (eq org-read-date-prefer-future 'time)
16383 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16384 (equal day (nth 3 nowdecode))
16385 (equal month (nth 4 nowdecode))
16386 (equal year (nth 5 nowdecode))
16387 (nth 2 tl)
16388 (or (< (nth 2 tl) (nth 2 nowdecode))
16389 (and (= (nth 2 tl) (nth 2 nowdecode))
16390 (nth 1 tl)
16391 (< (nth 1 tl) (nth 1 nowdecode)))))
16392 (setq day (1+ day)
16393 futurep t))
16395 ;; Special date definitions below
16396 (cond
16397 (iso-week
16398 ;; There was an iso week
16399 (require 'cal-iso)
16400 (setq futurep nil)
16401 (setq year (or iso-year year)
16402 day (or iso-weekday wday 1)
16403 wday nil ; to make sure that the trigger below does not match
16404 iso-date (calendar-gregorian-from-absolute
16405 (calendar-absolute-from-iso
16406 (list iso-week day year))))
16407 ; FIXME: Should we also push ISO weeks into the future?
16408 ; (when (and org-read-date-prefer-future
16409 ; (not iso-year)
16410 ; (< (calendar-absolute-from-gregorian iso-date)
16411 ; (time-to-days (current-time))))
16412 ; (setq year (1+ year)
16413 ; iso-date (calendar-gregorian-from-absolute
16414 ; (calendar-absolute-from-iso
16415 ; (list iso-week day year)))))
16416 (setq month (car iso-date)
16417 year (nth 2 iso-date)
16418 day (nth 1 iso-date)))
16419 (deltan
16420 (setq futurep nil)
16421 (unless deltadef
16422 (let ((now (decode-time (current-time))))
16423 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16424 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16425 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16426 ((equal deltaw "m") (setq month (+ month deltan)))
16427 ((equal deltaw "y") (setq year (+ year deltan)))))
16428 ((and wday (not (nth 3 tl)))
16429 ;; Weekday was given, but no day, so pick that day in the week
16430 ;; on or after the derived date.
16431 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16432 (unless (equal wday wday1)
16433 (setq day (+ day (% (- wday wday1 -7) 7))))))
16434 (if (and (boundp 'org-time-was-given)
16435 (nth 2 tl))
16436 (setq org-time-was-given t))
16437 (if (< year 100) (setq year (+ 2000 year)))
16438 ;; Check of the date is representable
16439 (if org-read-date-force-compatible-dates
16440 (progn
16441 (if (< year 1970)
16442 (setq year 1970 org-read-date-analyze-forced-year t))
16443 (if (> year 2037)
16444 (setq year 2037 org-read-date-analyze-forced-year t)))
16445 (condition-case nil
16446 (ignore (encode-time second minute hour day month year))
16447 (error
16448 (setq year (nth 5 org-defdecode))
16449 (setq org-read-date-analyze-forced-year t))))
16450 (setq org-read-date-analyze-futurep futurep)
16451 (list second minute hour day month year)))
16453 (defvar parse-time-weekdays)
16454 (defun org-read-date-get-relative (s today default)
16455 "Check string S for special relative date string.
16456 TODAY and DEFAULT are internal times, for today and for a default.
16457 Return shift list (N what def-flag)
16458 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16459 N is the number of WHATs to shift.
16460 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16461 the DEFAULT date rather than TODAY."
16462 (require 'parse-time)
16463 (when (and
16464 (string-match
16465 (concat
16466 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16467 "\\([0-9]+\\)?"
16468 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16469 "\\([ \t]\\|$\\)") s)
16470 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16471 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16472 (string-to-char (substring (match-string 1 s) -1))
16473 ?+))
16474 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16475 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16476 (what (if (match-end 3) (match-string 3 s) "d"))
16477 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16478 (date (if rel default today))
16479 (wday (nth 6 (decode-time date)))
16480 delta)
16481 (if wday1
16482 (progn
16483 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16484 (if (= dir ?-) (setq delta (- delta 7)))
16485 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16486 (list delta "d" rel))
16487 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16489 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16490 "Turn a user-specified date into the internal representation.
16491 The internal representation needed by the calendar is (month day year).
16492 This is a wrapper to handle the brain-dead convention in calendar that
16493 user function argument order change dependent on argument order."
16494 (if (boundp 'calendar-date-style)
16495 (cond
16496 ((eq calendar-date-style 'american)
16497 (list arg1 arg2 arg3))
16498 ((eq calendar-date-style 'european)
16499 (list arg2 arg1 arg3))
16500 ((eq calendar-date-style 'iso)
16501 (list arg2 arg3 arg1)))
16502 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16503 (if (org-bound-and-true-p european-calendar-style)
16504 (list arg2 arg1 arg3)
16505 (list arg1 arg2 arg3)))))
16507 (defun org-eval-in-calendar (form &optional keepdate)
16508 "Eval FORM in the calendar window and return to current window.
16509 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16510 otherwise stick to the current value of `org-ans2'."
16511 (let ((sf (selected-frame))
16512 (sw (selected-window)))
16513 (select-window (get-buffer-window "*Calendar*" t))
16514 (eval form)
16515 (when (and (not keepdate) (calendar-cursor-to-date))
16516 (let* ((date (calendar-cursor-to-date))
16517 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16518 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16519 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16520 (select-window sw)
16521 (org-select-frame-set-input-focus sf)))
16523 (defun org-calendar-select ()
16524 "Return to `org-read-date' with the date currently selected.
16525 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16526 (interactive)
16527 (when (calendar-cursor-to-date)
16528 (let* ((date (calendar-cursor-to-date))
16529 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16530 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16531 (if (active-minibuffer-window) (exit-minibuffer))))
16533 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16534 "Insert a date stamp for the date given by the internal TIME.
16535 WITH-HM means use the stamp format that includes the time of the day.
16536 INACTIVE means use square brackets instead of angular ones, so that the
16537 stamp will not contribute to the agenda.
16538 PRE and POST are optional strings to be inserted before and after the
16539 stamp.
16540 The command returns the inserted time stamp."
16541 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16542 stamp)
16543 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16544 (insert-before-markers (or pre ""))
16545 (when (listp extra)
16546 (setq extra (car extra))
16547 (if (and (stringp extra)
16548 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16549 (setq extra (format "-%02d:%02d"
16550 (string-to-number (match-string 1 extra))
16551 (string-to-number (match-string 2 extra))))
16552 (setq extra nil)))
16553 (when extra
16554 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16555 (insert-before-markers (setq stamp (format-time-string fmt time)))
16556 (insert-before-markers (or post ""))
16557 (setq org-last-inserted-timestamp stamp)))
16559 (defun org-toggle-time-stamp-overlays ()
16560 "Toggle the use of custom time stamp formats."
16561 (interactive)
16562 (setq org-display-custom-times (not org-display-custom-times))
16563 (unless org-display-custom-times
16564 (let ((p (point-min)) (bmp (buffer-modified-p)))
16565 (while (setq p (next-single-property-change p 'display))
16566 (if (and (get-text-property p 'display)
16567 (eq (get-text-property p 'face) 'org-date))
16568 (remove-text-properties
16569 p (setq p (next-single-property-change p 'display))
16570 '(display t))))
16571 (set-buffer-modified-p bmp)))
16572 (if (featurep 'xemacs)
16573 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16574 (org-restart-font-lock)
16575 (setq org-table-may-need-update t)
16576 (if org-display-custom-times
16577 (message "Time stamps are overlaid with custom format")
16578 (message "Time stamp overlays removed")))
16580 (defun org-display-custom-time (beg end)
16581 "Overlay modified time stamp format over timestamp between BEG and END."
16582 (let* ((ts (buffer-substring beg end))
16583 t1 w1 with-hm tf time str w2 (off 0))
16584 (save-match-data
16585 (setq t1 (org-parse-time-string ts t))
16586 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16587 (setq off (- (match-end 0) (match-beginning 0)))))
16588 (setq end (- end off))
16589 (setq w1 (- end beg)
16590 with-hm (and (nth 1 t1) (nth 2 t1))
16591 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16592 time (org-fix-decoded-time t1)
16593 str (org-add-props
16594 (format-time-string
16595 (substring tf 1 -1) (apply 'encode-time time))
16596 nil 'mouse-face 'highlight)
16597 w2 (length str))
16598 (if (not (= w2 w1))
16599 (add-text-properties (1+ beg) (+ 2 beg)
16600 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16601 (if (featurep 'xemacs)
16602 (progn
16603 (put-text-property beg end 'invisible t)
16604 (put-text-property beg end 'end-glyph (make-glyph str)))
16605 (put-text-property beg end 'display str))))
16607 (defun org-translate-time (string)
16608 "Translate all timestamps in STRING to custom format.
16609 But do this only if the variable `org-display-custom-times' is set."
16610 (when org-display-custom-times
16611 (save-match-data
16612 (let* ((start 0)
16613 (re org-ts-regexp-both)
16614 t1 with-hm inactive tf time str beg end)
16615 (while (setq start (string-match re string start))
16616 (setq beg (match-beginning 0)
16617 end (match-end 0)
16618 t1 (save-match-data
16619 (org-parse-time-string (substring string beg end) t))
16620 with-hm (and (nth 1 t1) (nth 2 t1))
16621 inactive (equal (substring string beg (1+ beg)) "[")
16622 tf (funcall (if with-hm 'cdr 'car)
16623 org-time-stamp-custom-formats)
16624 time (org-fix-decoded-time t1)
16625 str (format-time-string
16626 (concat
16627 (if inactive "[" "<") (substring tf 1 -1)
16628 (if inactive "]" ">"))
16629 (apply 'encode-time time))
16630 string (replace-match str t t string)
16631 start (+ start (length str)))))))
16632 string)
16634 (defun org-fix-decoded-time (time)
16635 "Set 0 instead of nil for the first 6 elements of time.
16636 Don't touch the rest."
16637 (let ((n 0))
16638 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16640 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16642 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16643 "Difference between TIMESTAMP-STRING and now in days.
16644 If SECONDS is non-nil, return the difference in seconds."
16645 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16646 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16647 (funcall fdiff (current-time)))))
16649 (defun org-deadline-close (timestamp-string &optional ndays)
16650 "Is the time in TIMESTAMP-STRING close to the current date?"
16651 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16652 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16653 (not (org-entry-is-done-p))))
16655 (defun org-get-wdays (ts &optional delay zero-delay)
16656 "Get the deadline lead time appropriate for timestring TS.
16657 When DELAY is non-nil, get the delay time for scheduled items
16658 instead of the deadline lead time. When ZERO-DELAY is non-nil
16659 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16660 don't try to find the delay cookie in the scheduled timestamp."
16661 (let ((tv (if delay org-scheduled-delay-days
16662 org-deadline-warning-days)))
16663 (cond
16664 ((or (and delay (< tv 0))
16665 (and delay zero-delay (<= tv 0))
16666 (and (not delay) (<= tv 0)))
16667 ;; Enforce this value no matter what
16668 (- tv))
16669 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16670 ;; lead time is specified.
16671 (floor (* (string-to-number (match-string 1 ts))
16672 (cdr (assoc (match-string 2 ts)
16673 '(("d" . 1) ("w" . 7)
16674 ("m" . 30.4) ("y" . 365.25)
16675 ("h" . 0.041667)))))))
16676 ;; go for the default.
16677 (t tv))))
16679 (defun org-calendar-select-mouse (ev)
16680 "Return to `org-read-date' with the date currently selected.
16681 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16682 (interactive "e")
16683 (mouse-set-point ev)
16684 (when (calendar-cursor-to-date)
16685 (let* ((date (calendar-cursor-to-date))
16686 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16687 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16688 (if (active-minibuffer-window) (exit-minibuffer))))
16690 (defun org-check-deadlines (ndays)
16691 "Check if there are any deadlines due or past due.
16692 A deadline is considered due if it happens within `org-deadline-warning-days'
16693 days from today's date. If the deadline appears in an entry marked DONE,
16694 it is not shown. The prefix arg NDAYS can be used to test that many
16695 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16696 (interactive "P")
16697 (let* ((org-warn-days
16698 (cond
16699 ((equal ndays '(4)) 100000)
16700 (ndays (prefix-numeric-value ndays))
16701 (t (abs org-deadline-warning-days))))
16702 (case-fold-search nil)
16703 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16704 (callback
16705 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16707 (message "%d deadlines past-due or due within %d days"
16708 (org-occur regexp nil callback)
16709 org-warn-days)))
16711 (defsubst org-re-timestamp (type)
16712 "Return a regexp for timestamp TYPE.
16713 Allowed values for TYPE are:
16715 all: all timestamps
16716 active: only active timestamps (<...>)
16717 inactive: only inactive timestamps ([...])
16718 scheduled: only scheduled timestamps
16719 deadline: only deadline timestamps
16721 When TYPE is nil, fall back on returning a regexp that matches
16722 both scheduled and deadline timestamps."
16723 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16724 ((eq type 'active) org-ts-regexp)
16725 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16726 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16727 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16728 ((eq type 'scheduled-or-deadline)
16729 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16731 (defun org-check-before-date (date)
16732 "Check if there are deadlines or scheduled entries before DATE."
16733 (interactive (list (org-read-date)))
16734 (let ((case-fold-search nil)
16735 (regexp (org-re-timestamp org-ts-type))
16736 (callback
16737 (lambda () (time-less-p
16738 (org-time-string-to-time (match-string 1))
16739 (org-time-string-to-time date)))))
16740 (message "%d entries before %s"
16741 (org-occur regexp nil callback) date)))
16743 (defun org-check-after-date (date)
16744 "Check if there are deadlines or scheduled entries after DATE."
16745 (interactive (list (org-read-date)))
16746 (let ((case-fold-search nil)
16747 (regexp (org-re-timestamp org-ts-type))
16748 (callback
16749 (lambda () (not
16750 (time-less-p
16751 (org-time-string-to-time (match-string 1))
16752 (org-time-string-to-time date))))))
16753 (message "%d entries after %s"
16754 (org-occur regexp nil callback) date)))
16756 (defun org-check-dates-range (start-date end-date)
16757 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16758 (interactive (list (org-read-date nil nil nil "Range starts")
16759 (org-read-date nil nil nil "Range end")))
16760 (let ((case-fold-search nil)
16761 (regexp (org-re-timestamp org-ts-type))
16762 (callback
16763 (lambda ()
16764 (let ((match (match-string 1)))
16765 (and
16766 (not (time-less-p
16767 (org-time-string-to-time match)
16768 (org-time-string-to-time start-date)))
16769 (time-less-p
16770 (org-time-string-to-time match)
16771 (org-time-string-to-time end-date)))))))
16772 (message "%d entries between %s and %s"
16773 (org-occur regexp nil callback) start-date end-date)))
16775 (defun org-evaluate-time-range (&optional to-buffer)
16776 "Evaluate a time range by computing the difference between start and end.
16777 Normally the result is just printed in the echo area, but with prefix arg
16778 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16779 If the time range is actually in a table, the result is inserted into the
16780 next column.
16781 For time difference computation, a year is assumed to be exactly 365
16782 days in order to avoid rounding problems."
16783 (interactive "P")
16785 (org-clock-update-time-maybe)
16786 (save-excursion
16787 (unless (org-at-date-range-p t)
16788 (goto-char (point-at-bol))
16789 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16790 (if (not (org-at-date-range-p t))
16791 (error "Not at a time-stamp range, and none found in current line")))
16792 (let* ((ts1 (match-string 1))
16793 (ts2 (match-string 2))
16794 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16795 (match-end (match-end 0))
16796 (time1 (org-time-string-to-time ts1))
16797 (time2 (org-time-string-to-time ts2))
16798 (t1 (org-float-time time1))
16799 (t2 (org-float-time time2))
16800 (diff (abs (- t2 t1)))
16801 (negative (< (- t2 t1) 0))
16802 ;; (ys (floor (* 365 24 60 60)))
16803 (ds (* 24 60 60))
16804 (hs (* 60 60))
16805 (fy "%dy %dd %02d:%02d")
16806 (fy1 "%dy %dd")
16807 (fd "%dd %02d:%02d")
16808 (fd1 "%dd")
16809 (fh "%02d:%02d")
16810 y d h m align)
16811 (if havetime
16812 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16814 d (floor (/ diff ds)) diff (mod diff ds)
16815 h (floor (/ diff hs)) diff (mod diff hs)
16816 m (floor (/ diff 60)))
16817 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16819 d (floor (+ (/ diff ds) 0.5))
16820 h 0 m 0))
16821 (if (not to-buffer)
16822 (message "%s" (org-make-tdiff-string y d h m))
16823 (if (org-at-table-p)
16824 (progn
16825 (goto-char match-end)
16826 (setq align t)
16827 (and (looking-at " *|") (goto-char (match-end 0))))
16828 (goto-char match-end))
16829 (if (looking-at
16830 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16831 (replace-match ""))
16832 (if negative (insert " -"))
16833 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16834 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16835 (insert " " (format fh h m))))
16836 (if align (org-table-align))
16837 (message "Time difference inserted")))))
16839 (defun org-make-tdiff-string (y d h m)
16840 (let ((fmt "")
16841 (l nil))
16842 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16843 l (push y l)))
16844 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16845 l (push d l)))
16846 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16847 l (push h l)))
16848 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16849 l (push m l)))
16850 (apply 'format fmt (nreverse l))))
16852 (defun org-time-string-to-time (s &optional buffer pos)
16853 "Convert a timestamp string into internal time."
16854 (condition-case errdata
16855 (apply 'encode-time (org-parse-time-string s))
16856 (error (error "Bad timestamp `%s'%s\nError was: %s"
16857 s (if (not (and buffer pos))
16859 (format " at %d in buffer `%s'" pos buffer))
16860 (cdr errdata)))))
16862 (defun org-time-string-to-seconds (s)
16863 "Convert a timestamp string to a number of seconds."
16864 (org-float-time (org-time-string-to-time s)))
16866 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16867 "Convert a time stamp to an absolute day number.
16868 If there is a specifier for a cyclic time stamp, get the closest
16869 date to DAYNR.
16870 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16871 The variable `date' is bound by the calendar when this is called."
16872 (cond
16873 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16874 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16875 daynr
16876 (+ daynr 1000)))
16877 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16878 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16879 (time-to-days (current-time))) (match-string 0 s)
16880 prefer show-all))
16881 (t (time-to-days
16882 (condition-case errdata
16883 (apply 'encode-time (org-parse-time-string s))
16884 (error (error "Bad timestamp `%s'%s\nError was: %s"
16885 s (if (not (and buffer pos))
16887 (format " at %d in buffer `%s'" pos buffer))
16888 (cdr errdata))))))))
16890 (defun org-days-to-iso-week (days)
16891 "Return the iso week number."
16892 (require 'cal-iso)
16893 (car (calendar-iso-from-absolute days)))
16895 (defun org-small-year-to-year (year)
16896 "Convert 2-digit years into 4-digit years.
16897 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16898 The year 2000 cannot be abbreviated. Any year larger than 99
16899 is returned unchanged."
16900 (if (< year 38)
16901 (setq year (+ 2000 year))
16902 (if (< year 100)
16903 (setq year (+ 1900 year))))
16904 year)
16906 (defun org-time-from-absolute (d)
16907 "Return the time corresponding to date D.
16908 D may be an absolute day number, or a calendar-type list (month day year)."
16909 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16910 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16912 (defun org-calendar-holiday ()
16913 "List of holidays, for Diary display in Org-mode."
16914 (require 'holidays)
16915 (let ((hl (funcall
16916 (if (fboundp 'calendar-check-holidays)
16917 'calendar-check-holidays 'check-calendar-holidays) date)))
16918 (if hl (mapconcat 'identity hl "; "))))
16920 (defun org-diary-sexp-entry (sexp entry date)
16921 "Process a SEXP diary ENTRY for DATE."
16922 (require 'diary-lib)
16923 (let ((result (if calendar-debug-sexp
16924 (let ((stack-trace-on-error t))
16925 (eval (car (read-from-string sexp))))
16926 (condition-case nil
16927 (eval (car (read-from-string sexp)))
16928 (error
16929 (beep)
16930 (message "Bad sexp at line %d in %s: %s"
16931 (org-current-line)
16932 (buffer-file-name) sexp)
16933 (sleep-for 2))))))
16934 (cond ((stringp result) (split-string result "; "))
16935 ((and (consp result)
16936 (not (consp (cdr result)))
16937 (stringp (cdr result))) (cdr result))
16938 ((and (consp result)
16939 (stringp (car result))) result)
16940 (result entry))))
16942 (defun org-diary-to-ical-string (frombuf)
16943 "Get iCalendar entries from diary entries in buffer FROMBUF.
16944 This uses the icalendar.el library."
16945 (let* ((tmpdir (if (featurep 'xemacs)
16946 (temp-directory)
16947 temporary-file-directory))
16948 (tmpfile (make-temp-name
16949 (expand-file-name "orgics" tmpdir)))
16950 buf rtn b e)
16951 (with-current-buffer frombuf
16952 (icalendar-export-region (point-min) (point-max) tmpfile)
16953 (setq buf (find-buffer-visiting tmpfile))
16954 (set-buffer buf)
16955 (goto-char (point-min))
16956 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16957 (setq b (match-beginning 0)))
16958 (goto-char (point-max))
16959 (if (re-search-backward "^END:VEVENT" nil t)
16960 (setq e (match-end 0)))
16961 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16962 (kill-buffer buf)
16963 (delete-file tmpfile)
16964 rtn))
16966 (defun org-closest-date (start current change prefer show-all)
16967 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16968 When PREFER is `past', return a date that is either CURRENT or past.
16969 When PREFER is `future', return a date that is either CURRENT or future.
16970 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16971 ;; Make the proper lists from the dates
16972 (catch 'exit
16973 (let ((a1 '(("h" . hour)
16974 ("d" . day)
16975 ("w" . week)
16976 ("m" . month)
16977 ("y" . year)))
16978 (shour (nth 2 (org-parse-time-string start)))
16979 dn dw sday cday n1 n2 n0
16980 d m y y1 y2 date1 date2 nmonths nm ny m2)
16982 (setq start (org-date-to-gregorian start)
16983 current (org-date-to-gregorian
16984 (if show-all
16985 current
16986 (time-to-days (current-time))))
16987 sday (calendar-absolute-from-gregorian start)
16988 cday (calendar-absolute-from-gregorian current))
16990 (if (<= cday sday) (throw 'exit sday))
16992 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16993 (setq dn (string-to-number (match-string 1 change))
16994 dw (cdr (assoc (match-string 2 change) a1)))
16995 (error "Invalid change specifier: %s" change))
16996 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16997 (cond
16998 ((eq dw 'hour)
16999 (let ((missing-hours
17000 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17001 dn)))
17002 (setq n1 (if (zerop missing-hours) cday
17003 (- cday (1+ (floor (/ missing-hours 24)))))
17004 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17005 ((eq dw 'day)
17006 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17007 n2 (+ n1 dn)))
17008 ((eq dw 'year)
17009 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17010 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17011 (setq date1 (list m d y1)
17012 n1 (calendar-absolute-from-gregorian date1)
17013 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17014 n2 (calendar-absolute-from-gregorian date2)))
17015 ((eq dw 'month)
17016 ;; approx number of month between the two dates
17017 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17018 ;; How often does dn fit in there?
17019 (setq d (nth 1 start) m (car start) y (nth 2 start)
17020 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17021 m (+ m nm)
17022 ny (floor (/ m 12))
17023 y (+ y ny)
17024 m (- m (* ny 12)))
17025 (while (> m 12) (setq m (- m 12) y (1+ y)))
17026 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17027 (setq m2 (+ m dn) y2 y)
17028 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17029 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17030 (while (<= n2 cday)
17031 (setq n1 n2 m m2 y y2)
17032 (setq m2 (+ m dn) y2 y)
17033 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17034 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17035 ;; Make sure n1 is the earlier date
17036 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17037 (if show-all
17038 (cond
17039 ((eq prefer 'past) (if (= cday n2) n2 n1))
17040 ((eq prefer 'future) (if (= cday n1) n1 n2))
17041 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17042 (cond
17043 ((eq prefer 'past) (if (= cday n2) n2 n1))
17044 ((eq prefer 'future) (if (= cday n1) n1 n2))
17045 (t (if (= cday n1) n1 n2)))))))
17047 (defun org-date-to-gregorian (date)
17048 "Turn any specification of DATE into a Gregorian date for the calendar."
17049 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17050 ((and (listp date) (= (length date) 3)) date)
17051 ((stringp date)
17052 (setq date (org-parse-time-string date))
17053 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17054 ((listp date)
17055 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17057 (defun org-parse-time-string (s &optional nodefault)
17058 "Parse the standard Org-mode time string.
17059 This should be a lot faster than the normal `parse-time-string'.
17060 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17061 hour and minute fields will be nil if not given."
17062 (cond ((string-match org-ts-regexp0 s)
17063 (list 0
17064 (if (or (match-beginning 8) (not nodefault))
17065 (string-to-number (or (match-string 8 s) "0")))
17066 (if (or (match-beginning 7) (not nodefault))
17067 (string-to-number (or (match-string 7 s) "0")))
17068 (string-to-number (match-string 4 s))
17069 (string-to-number (match-string 3 s))
17070 (string-to-number (match-string 2 s))
17071 nil nil nil))
17072 ((string-match "^<[^>]+>$" s)
17073 (decode-time (seconds-to-time (org-matcher-time s))))
17074 (t (error "Not a standard Org-mode time string: %s" s))))
17076 (defun org-timestamp-up (&optional arg)
17077 "Increase the date item at the cursor by one.
17078 If the cursor is on the year, change the year. If it is on the month,
17079 the day or the time, change that.
17080 With prefix ARG, change by that many units."
17081 (interactive "p")
17082 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17084 (defun org-timestamp-down (&optional arg)
17085 "Decrease the date item at the cursor by one.
17086 If the cursor is on the year, change the year. If it is on the month,
17087 the day or the time, change that.
17088 With prefix ARG, change by that many units."
17089 (interactive "p")
17090 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17092 (defun org-timestamp-up-day (&optional arg)
17093 "Increase the date in the time stamp by one day.
17094 With prefix ARG, change that many days."
17095 (interactive "p")
17096 (if (and (not (org-at-timestamp-p t))
17097 (org-at-heading-p))
17098 (org-todo 'up)
17099 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17101 (defun org-timestamp-down-day (&optional arg)
17102 "Decrease the date in the time stamp by one day.
17103 With prefix ARG, change that many days."
17104 (interactive "p")
17105 (if (and (not (org-at-timestamp-p t))
17106 (org-at-heading-p))
17107 (org-todo 'down)
17108 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17110 (defun org-at-timestamp-p (&optional inactive-ok)
17111 "Determine if the cursor is in or at a timestamp."
17112 (interactive)
17113 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17114 (pos (point))
17115 (ans (or (looking-at tsr)
17116 (save-excursion
17117 (skip-chars-backward "^[<\n\r\t")
17118 (if (> (point) (point-min)) (backward-char 1))
17119 (and (looking-at tsr)
17120 (> (- (match-end 0) pos) -1))))))
17121 (and ans
17122 (boundp 'org-ts-what)
17123 (setq org-ts-what
17124 (cond
17125 ((= pos (match-beginning 0)) 'bracket)
17126 ;; Point is considered to be "on the bracket" whether
17127 ;; it's really on it or right after it.
17128 ((= pos (1- (match-end 0))) 'bracket)
17129 ((= pos (match-end 0)) 'after)
17130 ((org-pos-in-match-range pos 2) 'year)
17131 ((org-pos-in-match-range pos 3) 'month)
17132 ((org-pos-in-match-range pos 7) 'hour)
17133 ((org-pos-in-match-range pos 8) 'minute)
17134 ((or (org-pos-in-match-range pos 4)
17135 (org-pos-in-match-range pos 5)) 'day)
17136 ((and (> pos (or (match-end 8) (match-end 5)))
17137 (< pos (match-end 0)))
17138 (- pos (or (match-end 8) (match-end 5))))
17139 (t 'day))))
17140 ans))
17142 (defun org-toggle-timestamp-type ()
17143 "Toggle the type (<active> or [inactive]) of a time stamp."
17144 (interactive)
17145 (when (org-at-timestamp-p t)
17146 (let ((beg (match-beginning 0)) (end (match-end 0))
17147 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17148 (save-excursion
17149 (goto-char beg)
17150 (while (re-search-forward "[][<>]" end t)
17151 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17152 t t)))
17153 (message "Timestamp is now %sactive"
17154 (if (equal (char-after beg) ?<) "" "in")))))
17156 (defun org-at-clock-log-p nil
17157 "Is the cursor on the clock log line?"
17158 (save-excursion
17159 (move-beginning-of-line 1)
17160 (looking-at "^[ \t]*CLOCK:")))
17162 (defvar org-clock-history) ; defined in org-clock.el
17163 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17164 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17165 "Change the date in the time stamp at point.
17166 The date will be changed by N times WHAT. WHAT can be `day', `month',
17167 `year', `minute', `second'. If WHAT is not given, the cursor position
17168 in the timestamp determines what will be changed.
17169 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17170 (let ((origin (point)) origin-cat
17171 with-hm inactive
17172 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17173 org-ts-what
17174 extra rem
17175 ts time time0 fixnext clrgx)
17176 (if (not (org-at-timestamp-p t))
17177 (error "Not at a timestamp"))
17178 (if (and (not what) (eq org-ts-what 'bracket))
17179 (org-toggle-timestamp-type)
17180 ;; Point isn't on brackets. Remember the part of the time-stamp
17181 ;; the point was in. Indeed, size of time-stamps may change,
17182 ;; but point must be kept in the same category nonetheless.
17183 (setq origin-cat org-ts-what)
17184 (if (and (not what) (not (eq org-ts-what 'day))
17185 org-display-custom-times
17186 (get-text-property (point) 'display)
17187 (not (get-text-property (1- (point)) 'display)))
17188 (setq org-ts-what 'day))
17189 (setq org-ts-what (or what org-ts-what)
17190 inactive (= (char-after (match-beginning 0)) ?\[)
17191 ts (match-string 0))
17192 (replace-match "")
17193 (when (string-match
17194 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17196 (setq extra (match-string 1 ts))
17197 (if suppress-tmp-delay
17198 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17199 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17200 (setq with-hm t))
17201 (setq time0 (org-parse-time-string ts))
17202 (when (and updown
17203 (eq org-ts-what 'minute)
17204 (not current-prefix-arg))
17205 ;; This looks like s-up and s-down. Change by one rounding step.
17206 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17207 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17208 (setcar (cdr time0) (+ (nth 1 time0)
17209 (if (> n 0) (- rem) (- dm rem))))))
17210 (setq time
17211 (encode-time (or (car time0) 0)
17212 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17213 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17214 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17215 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17216 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17217 (nthcdr 6 time0)))
17218 (when (and (member org-ts-what '(hour minute))
17219 extra
17220 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17221 (setq extra (org-modify-ts-extra
17222 extra
17223 (if (eq org-ts-what 'hour) 2 5)
17224 n dm)))
17225 (when (integerp org-ts-what)
17226 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17227 (if (eq what 'calendar)
17228 (let ((cal-date (org-get-date-from-calendar)))
17229 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17230 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17231 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17232 (setcar time0 (or (car time0) 0))
17233 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17234 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17235 (setq time (apply 'encode-time time0))))
17236 ;; Insert the new time-stamp, and ensure point stays in the same
17237 ;; category as before (i.e. not after the last position in that
17238 ;; category).
17239 (let ((pos (point)))
17240 ;; Stay before inserted string. `save-excursion' is of no use.
17241 (setq org-last-changed-timestamp
17242 (org-insert-time-stamp time with-hm inactive nil nil extra))
17243 (goto-char pos))
17244 (save-match-data
17245 (looking-at org-ts-regexp3)
17246 (goto-char (cond
17247 ;; `day' category ends before `hour' if any, or at
17248 ;; the end of the day name.
17249 ((eq origin-cat 'day)
17250 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17251 ((eq origin-cat 'hour) (min (match-end 7) origin))
17252 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17253 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17254 ;; `year' and `month' have both fixed size: point
17255 ;; couldn't have moved into another part.
17256 (t origin))))
17257 ;; Update clock if on a CLOCK line.
17258 (org-clock-update-time-maybe)
17259 ;; Maybe adjust the closest clock in `org-clock-history'
17260 (when org-clock-adjust-closest
17261 (if (not (and (org-at-clock-log-p)
17262 (< 1 (length (delq nil (mapcar 'marker-position
17263 org-clock-history))))))
17264 (message "No clock to adjust")
17265 (cond ((save-excursion ; fix previous clock?
17266 (re-search-backward org-ts-regexp0 nil t)
17267 (org-looking-back (concat org-clock-string " \\[")))
17268 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17269 ((save-excursion ; fix next clock?
17270 (re-search-backward org-ts-regexp0 nil t)
17271 (looking-at (concat org-ts-regexp0 "\\] =>")))
17272 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17273 (save-window-excursion
17274 ;; Find closest clock to point, adjust the previous/next one in history
17275 (let* ((p (save-excursion (org-back-to-heading t)))
17276 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17277 (clfixnth
17278 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17279 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17280 (if (not clfixpos)
17281 (message "No clock to adjust")
17282 (save-excursion
17283 (org-goto-marker-or-bmk clfixpos)
17284 (org-show-subtree)
17285 (when (re-search-forward clrgx nil t)
17286 (goto-char (match-beginning 1))
17287 (let (org-clock-adjust-closest)
17288 (org-timestamp-change n org-ts-what updown))
17289 (message "Clock adjusted in %s for heading: %s"
17290 (file-name-nondirectory (buffer-file-name))
17291 (org-get-heading t t)))))))))
17292 ;; Try to recenter the calendar window, if any.
17293 (if (and org-calendar-follow-timestamp-change
17294 (get-buffer-window "*Calendar*" t)
17295 (memq org-ts-what '(day month year)))
17296 (org-recenter-calendar (time-to-days time))))))
17298 (defun org-modify-ts-extra (s pos n dm)
17299 "Change the different parts of the lead-time and repeat fields in timestamp."
17300 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17301 ng h m new rem)
17302 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17303 (cond
17304 ((or (org-pos-in-match-range pos 2)
17305 (org-pos-in-match-range pos 3))
17306 (setq m (string-to-number (match-string 3 s))
17307 h (string-to-number (match-string 2 s)))
17308 (if (org-pos-in-match-range pos 2)
17309 (setq h (+ h n))
17310 (setq n (* dm (org-no-warnings (signum n))))
17311 (when (not (= 0 (setq rem (% m dm))))
17312 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17313 (setq m (+ m n)))
17314 (if (< m 0) (setq m (+ m 60) h (1- h)))
17315 (if (> m 59) (setq m (- m 60) h (1+ h)))
17316 (setq h (min 24 (max 0 h)))
17317 (setq ng 1 new (format "-%02d:%02d" h m)))
17318 ((org-pos-in-match-range pos 6)
17319 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17320 ((org-pos-in-match-range pos 5)
17321 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17323 ((org-pos-in-match-range pos 9)
17324 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17325 ((org-pos-in-match-range pos 8)
17326 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17328 (when ng
17329 (setq s (concat
17330 (substring s 0 (match-beginning ng))
17332 (substring s (match-end ng))))))
17335 (defun org-recenter-calendar (date)
17336 "If the calendar is visible, recenter it to DATE."
17337 (let ((cwin (get-buffer-window "*Calendar*" t)))
17338 (when cwin
17339 (let ((calendar-move-hook nil))
17340 (with-selected-window cwin
17341 (calendar-goto-date (if (listp date) date
17342 (calendar-gregorian-from-absolute date))))))))
17344 (defun org-goto-calendar (&optional arg)
17345 "Go to the Emacs calendar at the current date.
17346 If there is a time stamp in the current line, go to that date.
17347 A prefix ARG can be used to force the current date."
17348 (interactive "P")
17349 (let ((tsr org-ts-regexp) diff
17350 (calendar-move-hook nil)
17351 (calendar-view-holidays-initially-flag nil)
17352 (calendar-view-diary-initially-flag nil))
17353 (if (or (org-at-timestamp-p)
17354 (save-excursion
17355 (beginning-of-line 1)
17356 (looking-at (concat ".*" tsr))))
17357 (let ((d1 (time-to-days (current-time)))
17358 (d2 (time-to-days
17359 (org-time-string-to-time (match-string 1)))))
17360 (setq diff (- d2 d1))))
17361 (calendar)
17362 (calendar-goto-today)
17363 (if (and diff (not arg)) (calendar-forward-day diff))))
17365 (defun org-get-date-from-calendar ()
17366 "Return a list (month day year) of date at point in calendar."
17367 (with-current-buffer "*Calendar*"
17368 (save-match-data
17369 (calendar-cursor-to-date))))
17371 (defun org-date-from-calendar ()
17372 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17373 If there is already a time stamp at the cursor position, update it."
17374 (interactive)
17375 (if (org-at-timestamp-p t)
17376 (org-timestamp-change 0 'calendar)
17377 (let ((cal-date (org-get-date-from-calendar)))
17378 (org-insert-time-stamp
17379 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17381 (defcustom org-effort-durations
17382 `(("h" . 60)
17383 ("d" . ,(* 60 8))
17384 ("w" . ,(* 60 8 5))
17385 ("m" . ,(* 60 8 5 4))
17386 ("y" . ,(* 60 8 5 40)))
17387 "Conversion factor to minutes for an effort modifier.
17389 Each entry has the form (MODIFIER . MINUTES).
17391 In an effort string, a number followed by MODIFIER is multiplied
17392 by the specified number of MINUTES to obtain an effort in
17393 minutes.
17395 For example, if the value of this variable is ((\"hours\" . 60)), then an
17396 effort string \"2hours\" is equivalent to 120 minutes."
17397 :group 'org-agenda
17398 :version "24.1"
17399 :type '(alist :key-type (string :tag "Modifier")
17400 :value-type (number :tag "Minutes")))
17402 (defun org-minutes-to-clocksum-string (m)
17403 "Format number of minutes as a clocksum string.
17404 The format is determined by `org-time-clocksum-format',
17405 `org-time-clocksum-use-fractional' and
17406 `org-time-clocksum-fractional-format' and
17407 `org-time-clocksum-use-effort-durations'."
17408 (let ((clocksum "") h d w mo y fmt n)
17409 (setq h (if org-time-clocksum-use-effort-durations
17410 (cdr (assoc "h" org-effort-durations)) 60)
17411 d (if org-time-clocksum-use-effort-durations
17412 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17413 w (if org-time-clocksum-use-effort-durations
17414 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17415 mo (if org-time-clocksum-use-effort-durations
17416 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17417 y (if org-time-clocksum-use-effort-durations
17418 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17419 ;; fractional format
17420 (if org-time-clocksum-use-fractional
17421 (cond
17422 ;; single format string
17423 ((stringp org-time-clocksum-fractional-format)
17424 (format org-time-clocksum-fractional-format (/ m (float h))))
17425 ;; choice of fractional formats for different time units
17426 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17427 (> (/ (truncate m) (* y d h)) 0))
17428 (format fmt (/ m (* y d (float h)))))
17429 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17430 (> (/ (truncate m) (* mo d h)) 0))
17431 (format fmt (/ m (* mo d (float h)))))
17432 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17433 (> (/ (truncate m) (* w d h)) 0))
17434 (format fmt (/ m (* w d (float h)))))
17435 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17436 (> (/ (truncate m) (* d h)) 0))
17437 (format fmt (/ m (* d (float h)))))
17438 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17439 (> (/ (truncate m) h) 0))
17440 (format fmt (/ m (float h))))
17441 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17442 (format fmt m))
17443 ;; fall back to smallest time unit with a format
17444 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17445 (format fmt (/ m (float h))))
17446 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17447 (format fmt (/ m (* d (float h)))))
17448 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17449 (format fmt (/ m (* w d (float h)))))
17450 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17451 (format fmt (/ m (* mo d (float h)))))
17452 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17453 (format fmt (/ m (* y d (float h))))))
17454 ;; standard (non-fractional) format, with single format string
17455 (if (stringp org-time-clocksum-format)
17456 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17457 ;; separate formats components
17458 (and (setq fmt (plist-get org-time-clocksum-format :years))
17459 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17460 (plist-get org-time-clocksum-format :require-years))
17461 (setq clocksum (concat clocksum (format fmt n))
17462 m (- m (* n y d h))))
17463 (and (setq fmt (plist-get org-time-clocksum-format :months))
17464 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17465 (plist-get org-time-clocksum-format :require-months))
17466 (setq clocksum (concat clocksum (format fmt n))
17467 m (- m (* n mo d h))))
17468 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17469 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17470 (plist-get org-time-clocksum-format :require-weeks))
17471 (setq clocksum (concat clocksum (format fmt n))
17472 m (- m (* n w d h))))
17473 (and (setq fmt (plist-get org-time-clocksum-format :days))
17474 (or (> (setq n (/ (truncate m) (* d h))) 0)
17475 (plist-get org-time-clocksum-format :require-days))
17476 (setq clocksum (concat clocksum (format fmt n))
17477 m (- m (* n d h))))
17478 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17479 (or (> (setq n (/ (truncate m) h)) 0)
17480 (plist-get org-time-clocksum-format :require-hours))
17481 (setq clocksum (concat clocksum (format fmt n))
17482 m (- m (* n h))))
17483 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17484 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17485 (setq clocksum (concat clocksum (format fmt m))))
17486 ;; return formatted time duration
17487 clocksum))))
17489 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17490 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17491 "Org mode version 8.0")
17493 (defun org-hours-to-clocksum-string (n)
17494 (org-minutes-to-clocksum-string (* n 60)))
17496 (defun org-hh:mm-string-to-minutes (s)
17497 "Convert a string H:MM to a number of minutes.
17498 If the string is just a number, interpret it as minutes.
17499 In fact, the first hh:mm or number in the string will be taken,
17500 there can be extra stuff in the string.
17501 If no number is found, the return value is 0."
17502 (cond
17503 ((integerp s) s)
17504 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17505 (+ (* (string-to-number (match-string 1 s)) 60)
17506 (string-to-number (match-string 2 s))))
17507 ((string-match "\\([0-9]+\\)" s)
17508 (string-to-number (match-string 1 s)))
17509 (t 0)))
17511 (defcustom org-image-actual-width t
17512 "Should we use the actual width of images when inlining them?
17514 When set to `t', always use the image width.
17516 When set to a number, use imagemagick (when available) to set
17517 the image's width to this value.
17519 When set to a number in a list, try to get the width from any
17520 #+ATTR.* keyword if it matches a width specification like
17522 #+ATTR_HTML: :width 300px
17524 and fall back on that number if none is found.
17526 When set to nil, try to get the width from an #+ATTR.* keyword
17527 and fall back on the original width if none is found.
17529 This requires Emacs >= 24.1, build with imagemagick support."
17530 :group 'org-appearance
17531 :version "24.4"
17532 :package-version '(Org . "8.0")
17533 :type '(choice
17534 (const :tag "Use the image width" t)
17535 (integer :tag "Use a number of pixels")
17536 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17537 (const :tag "Use #+ATTR* or don't resize" nil)))
17539 (defcustom org-agenda-inhibit-startup nil
17540 "Inhibit startup when preparing agenda buffers.
17541 When this variable is `t' (the default), the initialization of
17542 the Org agenda buffers is inhibited: e.g. the visibility state
17543 is not set, the tables are not re-aligned, etc."
17544 :type 'boolean
17545 :version "24.3"
17546 :group 'org-agenda)
17548 (defun org-duration-string-to-minutes (s &optional output-to-string)
17549 "Convert a duration string S to minutes.
17551 A bare number is interpreted as minutes, modifiers can be set by
17552 customizing `org-effort-durations' (which see).
17554 Entries containing a colon are interpreted as H:MM by
17555 `org-hh:mm-string-to-minutes'."
17556 (let ((result 0)
17557 (re (concat "\\([0-9.]+\\) *\\("
17558 (regexp-opt (mapcar 'car org-effort-durations))
17559 "\\)")))
17560 (while (string-match re s)
17561 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17562 (string-to-number (match-string 1 s))))
17563 (setq s (replace-match "" nil t s)))
17564 (setq result (floor result))
17565 (incf result (org-hh:mm-string-to-minutes s))
17566 (if output-to-string (number-to-string result) result)))
17568 ;;;; Files
17570 (defun org-save-all-org-buffers ()
17571 "Save all Org-mode buffers without user confirmation."
17572 (interactive)
17573 (message "Saving all Org-mode buffers...")
17574 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17575 (when (featurep 'org-id) (org-id-locations-save))
17576 (message "Saving all Org-mode buffers... done"))
17578 (defun org-revert-all-org-buffers ()
17579 "Revert all Org-mode buffers.
17580 Prompt for confirmation when there are unsaved changes.
17581 Be sure you know what you are doing before letting this function
17582 overwrite your changes.
17584 This function is useful in a setup where one tracks org files
17585 with a version control system, to revert on one machine after pulling
17586 changes from another. I believe the procedure must be like this:
17588 1. M-x org-save-all-org-buffers
17589 2. Pull changes from the other machine, resolve conflicts
17590 3. M-x org-revert-all-org-buffers"
17591 (interactive)
17592 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17593 (error "Abort"))
17594 (save-excursion
17595 (save-window-excursion
17596 (mapc
17597 (lambda (b)
17598 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17599 (with-current-buffer b buffer-file-name))
17600 (org-pop-to-buffer-same-window b)
17601 (revert-buffer t 'no-confirm)))
17602 (buffer-list))
17603 (when (and (featurep 'org-id) org-id-track-globally)
17604 (org-id-locations-load)))))
17606 ;;;; Agenda files
17608 ;;;###autoload
17609 (defun org-switchb (&optional arg)
17610 "Switch between Org buffers.
17611 With one prefix argument, restrict available buffers to files.
17612 With two prefix arguments, restrict available buffers to agenda files.
17614 Defaults to `iswitchb' for buffer name completion.
17615 Set `org-completion-use-ido' to make it use ido instead."
17616 (interactive "P")
17617 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17618 ((equal arg '(16)) (org-buffer-list 'agenda))
17619 (t (org-buffer-list))))
17620 (org-completion-use-iswitchb org-completion-use-iswitchb)
17621 (org-completion-use-ido org-completion-use-ido))
17622 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17623 (setq org-completion-use-iswitchb t))
17624 (org-pop-to-buffer-same-window
17625 (org-icompleting-read "Org buffer: "
17626 (mapcar 'list (mapcar 'buffer-name blist))
17627 nil t))))
17629 ;;; Define some older names previously used for this functionality
17630 ;;;###autoload
17631 (defalias 'org-ido-switchb 'org-switchb)
17632 ;;;###autoload
17633 (defalias 'org-iswitchb 'org-switchb)
17635 (defun org-buffer-list (&optional predicate exclude-tmp)
17636 "Return a list of Org buffers.
17637 PREDICATE can be `export', `files' or `agenda'.
17639 export restrict the list to Export buffers.
17640 files restrict the list to buffers visiting Org files.
17641 agenda restrict the list to buffers visiting agenda files.
17643 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17644 (let* ((bfn nil)
17645 (agenda-files (and (eq predicate 'agenda)
17646 (mapcar 'file-truename (org-agenda-files t))))
17647 (filter
17648 (cond
17649 ((eq predicate 'files)
17650 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17651 ((eq predicate 'export)
17652 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17653 ((eq predicate 'agenda)
17654 (lambda (b)
17655 (with-current-buffer b
17656 (and (derived-mode-p 'org-mode)
17657 (setq bfn (buffer-file-name b))
17658 (member (file-truename bfn) agenda-files)))))
17659 (t (lambda (b) (with-current-buffer b
17660 (or (derived-mode-p 'org-mode)
17661 (string-match "\*Org .*Export"
17662 (buffer-name b)))))))))
17663 (delq nil
17664 (mapcar
17665 (lambda(b)
17666 (if (and (funcall filter b)
17667 (or (not exclude-tmp)
17668 (not (string-match "tmp" (buffer-name b)))))
17670 nil))
17671 (buffer-list)))))
17673 (defun org-agenda-files (&optional unrestricted archives)
17674 "Get the list of agenda files.
17675 Optional UNRESTRICTED means return the full list even if a restriction
17676 is currently in place.
17677 When ARCHIVES is t, include all archive files that are really being
17678 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17679 `org-agenda-archives-mode' is t."
17680 (let ((files
17681 (cond
17682 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17683 ((stringp org-agenda-files) (org-read-agenda-file-list))
17684 ((listp org-agenda-files) org-agenda-files)
17685 (t (error "Invalid value of `org-agenda-files'")))))
17686 (setq files (apply 'append
17687 (mapcar (lambda (f)
17688 (if (file-directory-p f)
17689 (directory-files
17690 f t org-agenda-file-regexp)
17691 (list f)))
17692 files)))
17693 (when org-agenda-skip-unavailable-files
17694 (setq files (delq nil
17695 (mapcar (function
17696 (lambda (file)
17697 (and (file-readable-p file) file)))
17698 files))))
17699 (when (or (eq archives t)
17700 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17701 (setq files (org-add-archive-files files)))
17702 files))
17704 (defun org-agenda-file-p (&optional file)
17705 "Return non-nil, if FILE is an agenda file.
17706 If FILE is omitted, use the file associated with the current
17707 buffer."
17708 (member (or file (buffer-file-name))
17709 (org-agenda-files t)))
17711 (defun org-edit-agenda-file-list ()
17712 "Edit the list of agenda files.
17713 Depending on setup, this either uses customize to edit the variable
17714 `org-agenda-files', or it visits the file that is holding the list. In the
17715 latter case, the buffer is set up in a way that saving it automatically kills
17716 the buffer and restores the previous window configuration."
17717 (interactive)
17718 (if (stringp org-agenda-files)
17719 (let ((cw (current-window-configuration)))
17720 (find-file org-agenda-files)
17721 (org-set-local 'org-window-configuration cw)
17722 (org-add-hook 'after-save-hook
17723 (lambda ()
17724 (set-window-configuration
17725 (prog1 org-window-configuration
17726 (kill-buffer (current-buffer))))
17727 (org-install-agenda-files-menu)
17728 (message "New agenda file list installed"))
17729 nil 'local)
17730 (message "%s" (substitute-command-keys
17731 "Edit list and finish with \\[save-buffer]")))
17732 (customize-variable 'org-agenda-files)))
17734 (defun org-store-new-agenda-file-list (list)
17735 "Set new value for the agenda file list and save it correctly."
17736 (if (stringp org-agenda-files)
17737 (let ((fe (org-read-agenda-file-list t)) b u)
17738 (while (setq b (find-buffer-visiting org-agenda-files))
17739 (kill-buffer b))
17740 (with-temp-file org-agenda-files
17741 (insert
17742 (mapconcat
17743 (lambda (f) ;; Keep un-expanded entries.
17744 (if (setq u (assoc f fe))
17745 (cdr u)
17747 list "\n")
17748 "\n")))
17749 (let ((org-mode-hook nil) (org-inhibit-startup t)
17750 (org-insert-mode-line-in-empty-file nil))
17751 (setq org-agenda-files list)
17752 (customize-save-variable 'org-agenda-files org-agenda-files))))
17754 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17755 "Read the list of agenda files from a file.
17756 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17757 filenames, used by `org-store-new-agenda-file-list' to write back
17758 un-expanded file names."
17759 (when (file-directory-p org-agenda-files)
17760 (error "`org-agenda-files' cannot be a single directory"))
17761 (when (stringp org-agenda-files)
17762 (with-temp-buffer
17763 (insert-file-contents org-agenda-files)
17764 (mapcar
17765 (lambda (f)
17766 (let ((e (expand-file-name (substitute-in-file-name f)
17767 org-directory)))
17768 (if pair-with-expansion
17769 (cons e f)
17770 e)))
17771 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17773 ;;;###autoload
17774 (defun org-cycle-agenda-files ()
17775 "Cycle through the files in `org-agenda-files'.
17776 If the current buffer visits an agenda file, find the next one in the list.
17777 If the current buffer does not, find the first agenda file."
17778 (interactive)
17779 (let* ((fs (org-agenda-files t))
17780 (files (append fs (list (car fs))))
17781 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17782 file)
17783 (unless files (error "No agenda files"))
17784 (catch 'exit
17785 (while (setq file (pop files))
17786 (if (equal (file-truename file) tcf)
17787 (when (car files)
17788 (find-file (car files))
17789 (throw 'exit t))))
17790 (find-file (car fs)))
17791 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17793 (defun org-agenda-file-to-front (&optional to-end)
17794 "Move/add the current file to the top of the agenda file list.
17795 If the file is not present in the list, it is added to the front. If it is
17796 present, it is moved there. With optional argument TO-END, add/move to the
17797 end of the list."
17798 (interactive "P")
17799 (let ((org-agenda-skip-unavailable-files nil)
17800 (file-alist (mapcar (lambda (x)
17801 (cons (file-truename x) x))
17802 (org-agenda-files t)))
17803 (ctf (file-truename
17804 (or buffer-file-name
17805 (error "Please save the current buffer to a file"))))
17806 x had)
17807 (setq x (assoc ctf file-alist) had x)
17809 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17810 (if to-end
17811 (setq file-alist (append (delq x file-alist) (list x)))
17812 (setq file-alist (cons x (delq x file-alist))))
17813 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17814 (org-install-agenda-files-menu)
17815 (message "File %s to %s of agenda file list"
17816 (if had "moved" "added") (if to-end "end" "front"))))
17818 (defun org-remove-file (&optional file)
17819 "Remove current file from the list of files in variable `org-agenda-files'.
17820 These are the files which are being checked for agenda entries.
17821 Optional argument FILE means use this file instead of the current."
17822 (interactive)
17823 (let* ((org-agenda-skip-unavailable-files nil)
17824 (file (or file buffer-file-name
17825 (error "Current buffer does not visit a file")))
17826 (true-file (file-truename file))
17827 (afile (abbreviate-file-name file))
17828 (files (delq nil (mapcar
17829 (lambda (x)
17830 (if (equal true-file
17831 (file-truename x))
17832 nil x))
17833 (org-agenda-files t)))))
17834 (if (not (= (length files) (length (org-agenda-files t))))
17835 (progn
17836 (org-store-new-agenda-file-list files)
17837 (org-install-agenda-files-menu)
17838 (message "Removed file: %s" afile))
17839 (message "File was not in list: %s (not removed)" afile))))
17841 (defun org-file-menu-entry (file)
17842 (vector file (list 'find-file file) t))
17844 (defun org-check-agenda-file (file)
17845 "Make sure FILE exists. If not, ask user what to do."
17846 (when (not (file-exists-p file))
17847 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17848 (abbreviate-file-name file))
17849 (let ((r (downcase (read-char-exclusive))))
17850 (cond
17851 ((equal r ?r)
17852 (org-remove-file file)
17853 (throw 'nextfile t))
17854 (t (error "Abort"))))))
17856 (defun org-get-agenda-file-buffer (file)
17857 "Get a buffer visiting FILE. If the buffer needs to be created, add
17858 it to the list of buffers which might be released later."
17859 (let ((buf (org-find-base-buffer-visiting file)))
17860 (if buf
17861 buf ; just return it
17862 ;; Make a new buffer and remember it
17863 (setq buf (find-file-noselect file))
17864 (if buf (push buf org-agenda-new-buffers))
17865 buf)))
17867 (defun org-release-buffers (blist)
17868 "Release all buffers in list, asking the user for confirmation when needed.
17869 When a buffer is unmodified, it is just killed. When modified, it is saved
17870 \(if the user agrees) and then killed."
17871 (let (buf file)
17872 (while (setq buf (pop blist))
17873 (setq file (buffer-file-name buf))
17874 (when (and (buffer-modified-p buf)
17875 file
17876 (y-or-n-p (format "Save file %s? " file)))
17877 (with-current-buffer buf (save-buffer)))
17878 (kill-buffer buf))))
17880 (defun org-agenda-prepare-buffers (files)
17881 "Create buffers for all agenda files, protect archived trees and comments."
17882 (interactive)
17883 (let ((pa '(:org-archived t))
17884 (pc '(:org-comment t))
17885 (pall '(:org-archived t :org-comment t))
17886 (inhibit-read-only t)
17887 (org-inhibit-startup org-agenda-inhibit-startup)
17888 (rea (concat ":" org-archive-tag ":"))
17889 file re org-tag-alist)
17890 (setq org-tag-alist-for-agenda nil
17891 org-tag-groups-alist-for-agenda nil)
17892 (save-excursion
17893 (save-restriction
17894 (while (setq file (pop files))
17895 (catch 'nextfile
17896 (if (bufferp file)
17897 (set-buffer file)
17898 (org-check-agenda-file file)
17899 (set-buffer (org-get-agenda-file-buffer file)))
17900 (widen)
17901 (org-set-regexps-and-options-for-tags)
17902 (org-refresh-category-properties)
17903 (org-refresh-properties org-effort-property 'org-effort)
17904 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17905 (setq org-todo-keywords-for-agenda
17906 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17907 (setq org-done-keywords-for-agenda
17908 (append org-done-keywords-for-agenda org-done-keywords))
17909 (setq org-todo-keyword-alist-for-agenda
17910 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17911 (setq org-drawers-for-agenda
17912 (append org-drawers-for-agenda org-drawers))
17913 (setq org-tag-alist-for-agenda
17914 (append org-tag-alist-for-agenda org-tag-alist))
17915 (if org-group-tags
17916 (setq org-tag-groups-alist-for-agenda
17917 (org-uniquify-alist
17918 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17919 (org-with-silent-modifications
17920 (save-excursion
17921 (remove-text-properties (point-min) (point-max) pall)
17922 (when org-agenda-skip-archived-trees
17923 (goto-char (point-min))
17924 (while (re-search-forward rea nil t)
17925 (if (org-at-heading-p t)
17926 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17927 (goto-char (point-min))
17928 (setq re (format org-heading-keyword-regexp-format
17929 org-comment-string))
17930 (while (re-search-forward re nil t)
17931 (add-text-properties
17932 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17933 (setq org-todo-keywords-for-agenda
17934 (org-uniquify org-todo-keywords-for-agenda))
17935 (setq org-todo-keyword-alist-for-agenda
17936 (org-uniquify org-todo-keyword-alist-for-agenda))))
17939 ;;;; CDLaTeX minor mode
17941 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17942 "Keymap for the minor `org-cdlatex-mode'.")
17944 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17945 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17946 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17947 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17948 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17950 (defvar org-cdlatex-texmathp-advice-is-done nil
17951 "Flag remembering if we have applied the advice to texmathp already.")
17953 (define-minor-mode org-cdlatex-mode
17954 "Toggle the minor `org-cdlatex-mode'.
17955 This mode supports entering LaTeX environment and math in LaTeX fragments
17956 in Org-mode.
17957 \\{org-cdlatex-mode-map}"
17958 nil " OCDL" nil
17959 (when org-cdlatex-mode
17960 (require 'cdlatex)
17961 (run-hooks 'cdlatex-mode-hook)
17962 (cdlatex-compute-tables))
17963 (unless org-cdlatex-texmathp-advice-is-done
17964 (setq org-cdlatex-texmathp-advice-is-done t)
17965 (defadvice texmathp (around org-math-always-on activate)
17966 "Always return t in org-mode buffers.
17967 This is because we want to insert math symbols without dollars even outside
17968 the LaTeX math segments. If Orgmode thinks that point is actually inside
17969 an embedded LaTeX fragment, let texmathp do its job.
17970 \\[org-cdlatex-mode-map]"
17971 (interactive)
17972 (let (p)
17973 (cond
17974 ((not (derived-mode-p 'org-mode)) ad-do-it)
17975 ((eq this-command 'cdlatex-math-symbol)
17976 (setq ad-return-value t
17977 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17979 (let ((p (org-inside-LaTeX-fragment-p)))
17980 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17981 (setq ad-return-value t
17982 texmathp-why '("Org-mode embedded math" . 0))
17983 (if p ad-do-it)))))))))
17985 (defun turn-on-org-cdlatex ()
17986 "Unconditionally turn on `org-cdlatex-mode'."
17987 (org-cdlatex-mode 1))
17989 (defun org-try-cdlatex-tab ()
17990 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17991 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17992 - inside a LaTeX fragment, or
17993 - after the first word in a line, where an abbreviation expansion could
17994 insert a LaTeX environment."
17995 (when org-cdlatex-mode
17996 (cond
17997 ;; Before any word on the line: No expansion possible.
17998 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17999 ;; Just after first word on the line: Expand it. Make sure it
18000 ;; cannot happen on headlines, though.
18001 ((save-excursion
18002 (skip-chars-backward "a-zA-Z0-9*")
18003 (skip-chars-backward " \t")
18004 (and (bolp) (not (org-at-heading-p))))
18005 (cdlatex-tab) t)
18006 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18008 (defun org-cdlatex-underscore-caret (&optional arg)
18009 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18010 Revert to the normal definition outside of these fragments."
18011 (interactive "P")
18012 (if (org-inside-LaTeX-fragment-p)
18013 (call-interactively 'cdlatex-sub-superscript)
18014 (let (org-cdlatex-mode)
18015 (call-interactively (key-binding (vector last-input-event))))))
18017 (defun org-cdlatex-math-modify (&optional arg)
18018 "Execute `cdlatex-math-modify' in LaTeX fragments.
18019 Revert to the normal definition outside of these fragments."
18020 (interactive "P")
18021 (if (org-inside-LaTeX-fragment-p)
18022 (call-interactively 'cdlatex-math-modify)
18023 (let (org-cdlatex-mode)
18024 (call-interactively (key-binding (vector last-input-event))))))
18028 ;;;; LaTeX fragments
18030 (defvar org-latex-regexps
18031 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18032 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18033 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18034 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18035 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18036 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18037 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18038 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18039 "Regular expressions for matching embedded LaTeX.")
18041 (defun org-inside-LaTeX-fragment-p ()
18042 "Test if point is inside a LaTeX fragment.
18043 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18044 sequence appearing also before point.
18045 Even though the matchers for math are configurable, this function assumes
18046 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18047 delimiters are skipped when they have been removed by customization.
18048 The return value is nil, or a cons cell with the delimiter and the
18049 position of this delimiter.
18051 This function does a reasonably good job, but can locally be fooled by
18052 for example currency specifications. For example it will assume being in
18053 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18054 fragments that are properly closed, but during editing, we have to live
18055 with the uncertainty caused by missing closing delimiters. This function
18056 looks only before point, not after."
18057 (catch 'exit
18058 (let ((pos (point))
18059 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18060 (lim (progn
18061 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18062 (point)))
18063 dd-on str (start 0) m re)
18064 (goto-char pos)
18065 (when dodollar
18066 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18067 re (nth 1 (assoc "$" org-latex-regexps)))
18068 (while (string-match re str start)
18069 (cond
18070 ((= (match-end 0) (length str))
18071 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18072 ((= (match-end 0) (- (length str) 5))
18073 (throw 'exit nil))
18074 (t (setq start (match-end 0))))))
18075 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18076 (goto-char pos)
18077 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18078 (and (match-beginning 2) (throw 'exit nil))
18079 ;; count $$
18080 (while (re-search-backward "\\$\\$" lim t)
18081 (setq dd-on (not dd-on)))
18082 (goto-char pos)
18083 (if dd-on (cons "$$" m))))))
18085 (defun org-inside-latex-macro-p ()
18086 "Is point inside a LaTeX macro or its arguments?"
18087 (save-match-data
18088 (org-in-regexp
18089 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18091 (defvar org-latex-fragment-image-overlays nil
18092 "List of overlays carrying the images of latex fragments.")
18093 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18095 (defun org-remove-latex-fragment-image-overlays ()
18096 "Remove all overlays with LaTeX fragment images in current buffer."
18097 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18098 (setq org-latex-fragment-image-overlays nil))
18100 (defun org-preview-latex-fragment (&optional subtree)
18101 "Preview the LaTeX fragment at point, or all locally or globally.
18102 If the cursor is in a LaTeX fragment, create the image and overlay
18103 it over the source code. If there is no fragment at point, display
18104 all fragments in the current text, from one headline to the next. With
18105 prefix SUBTREE, display all fragments in the current subtree. With a
18106 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18107 the cursor is before the first headline,
18108 display all fragments in the buffer.
18109 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18110 (interactive "P")
18111 (unless buffer-file-name
18112 (error "Can't preview LaTeX fragment in a non-file buffer"))
18113 (org-remove-latex-fragment-image-overlays)
18114 (save-excursion
18115 (save-restriction
18116 (let (beg end at msg)
18117 (cond
18118 ((or (equal subtree '(16))
18119 (not (save-excursion
18120 (re-search-backward org-outline-regexp-bol nil t))))
18121 (setq beg (point-min) end (point-max)
18122 msg "Creating images for buffer...%s"))
18123 ((equal subtree '(4))
18124 (org-back-to-heading)
18125 (setq beg (point) end (org-end-of-subtree t)
18126 msg "Creating images for subtree...%s"))
18128 (if (setq at (org-inside-LaTeX-fragment-p))
18129 (goto-char (max (point-min) (- (cdr at) 2)))
18130 (org-back-to-heading))
18131 (setq beg (point) end (progn (outline-next-heading) (point))
18132 msg (if at "Creating image...%s"
18133 "Creating images for entry...%s"))))
18134 (message msg "")
18135 (narrow-to-region beg end)
18136 (goto-char beg)
18137 (org-format-latex
18138 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18139 (file-name-nondirectory
18140 buffer-file-name)))
18141 default-directory 'overlays msg at 'forbuffer
18142 org-latex-create-formula-image-program)
18143 (message msg "done. Use `C-c C-c' to remove images.")))))
18145 (defun org-format-latex (prefix &optional dir overlays msg at
18146 forbuffer processing-type)
18147 "Replace LaTeX fragments with links to an image, and produce images.
18148 Some of the options can be changed using the variable
18149 `org-format-latex-options'."
18150 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18151 (let* ((prefixnodir (file-name-nondirectory prefix))
18152 (absprefix (expand-file-name prefix dir))
18153 (todir (file-name-directory absprefix))
18154 (opt org-format-latex-options)
18155 (optnew org-format-latex-options)
18156 (matchers (plist-get opt :matchers))
18157 (re-list org-latex-regexps)
18158 (cnt 0) txt hash link beg end re e checkdir
18159 string
18160 m n block-type block linkfile movefile ov)
18161 ;; Check the different regular expressions
18162 (while (setq e (pop re-list))
18163 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18164 block (if block-type "\n\n" ""))
18165 (when (member m matchers)
18166 (goto-char (point-min))
18167 (while (re-search-forward re nil t)
18168 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18169 (or (not overlays)
18170 (not (eq (get-char-property (match-beginning n)
18171 'org-overlay-type)
18172 'org-latex-overlay))))
18173 (cond
18174 ((eq processing-type 'verbatim))
18175 ((eq processing-type 'mathjax)
18176 ;; Prepare for MathJax processing.
18177 (setq string (match-string n))
18178 (when (member m '("$" "$1"))
18179 (save-excursion
18180 (delete-region (match-beginning n) (match-end n))
18181 (goto-char (match-beginning n))
18182 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18183 ((or (eq processing-type 'dvipng)
18184 (eq processing-type 'imagemagick))
18185 ;; Process to an image.
18186 (setq txt (match-string n)
18187 beg (match-beginning n) end (match-end n)
18188 cnt (1+ cnt))
18189 (let ((face (face-at-point))
18190 (fg (plist-get opt :foreground))
18191 (bg (plist-get opt :background))
18192 ;; Ensure full list is printed.
18193 print-length print-level)
18194 (when forbuffer
18195 ;; Get the colors from the face at point.
18196 (goto-char beg)
18197 (when (eq fg 'auto)
18198 (setq fg (face-attribute face :foreground nil 'default)))
18199 (when (eq bg 'auto)
18200 (setq bg (face-attribute face :background nil 'default)))
18201 (setq optnew (copy-sequence opt))
18202 (plist-put optnew :foreground fg)
18203 (plist-put optnew :background bg))
18204 (setq hash (sha1 (prin1-to-string
18205 (list org-format-latex-header
18206 org-latex-default-packages-alist
18207 org-latex-packages-alist
18208 org-format-latex-options
18209 forbuffer txt fg bg)))
18210 linkfile (format "%s_%s.png" prefix hash)
18211 movefile (format "%s_%s.png" absprefix hash)))
18212 (setq link (concat block "[[file:" linkfile "]]" block))
18213 (if msg (message msg cnt))
18214 (goto-char beg)
18215 (unless checkdir ; Ensure the directory exists.
18216 (setq checkdir t)
18217 (or (file-directory-p todir) (make-directory todir t)))
18218 (unless (file-exists-p movefile)
18219 (org-create-formula-image
18220 txt movefile optnew forbuffer processing-type))
18221 (if overlays
18222 (progn
18223 (mapc (lambda (o)
18224 (if (eq (overlay-get o 'org-overlay-type)
18225 'org-latex-overlay)
18226 (delete-overlay o)))
18227 (overlays-in beg end))
18228 (setq ov (make-overlay beg end))
18229 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18230 (if (featurep 'xemacs)
18231 (progn
18232 (overlay-put ov 'invisible t)
18233 (overlay-put
18234 ov 'end-glyph
18235 (make-glyph (vector 'png :file movefile))))
18236 (overlay-put
18237 ov 'display
18238 (list 'image :type 'png :file movefile :ascent 'center)))
18239 (push ov org-latex-fragment-image-overlays)
18240 (goto-char end))
18241 (delete-region beg end)
18242 (insert (org-add-props link
18243 (list 'org-latex-src
18244 (replace-regexp-in-string
18245 "\"" "" txt)
18246 'org-latex-src-embed-type
18247 (if block-type 'paragraph 'character))))))
18248 ((eq processing-type 'mathml)
18249 ;; Process to MathML
18250 (unless (save-match-data (org-format-latex-mathml-available-p))
18251 (error "LaTeX to MathML converter not configured"))
18252 (setq txt (match-string n)
18253 beg (match-beginning n) end (match-end n)
18254 cnt (1+ cnt))
18255 (if msg (message msg cnt))
18256 (goto-char beg)
18257 (delete-region beg end)
18258 (insert (org-format-latex-as-mathml
18259 txt block-type prefix dir)))
18261 (error "Unknown conversion type %s for latex fragments"
18262 processing-type)))))))))
18264 (defun org-create-math-formula (latex-frag &optional mathml-file)
18265 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18266 Use `org-latex-to-mathml-convert-command'. If the conversion is
18267 sucessful, return the portion between \"<math...> </math>\"
18268 elements otherwise return nil. When MATHML-FILE is specified,
18269 write the results in to that file. When invoked as an
18270 interactive command, prompt for LATEX-FRAG, with initial value
18271 set to the current active region and echo the results for user
18272 inspection."
18273 (interactive (list (let ((frag (when (org-region-active-p)
18274 (buffer-substring-no-properties
18275 (region-beginning) (region-end)))))
18276 (read-string "LaTeX Fragment: " frag nil frag))))
18277 (unless latex-frag (error "Invalid latex-frag"))
18278 (let* ((tmp-in-file (file-relative-name
18279 (make-temp-name (expand-file-name "ltxmathml-in"))))
18280 (ignore (write-region latex-frag nil tmp-in-file))
18281 (tmp-out-file (file-relative-name
18282 (make-temp-name (expand-file-name "ltxmathml-out"))))
18283 (cmd (format-spec
18284 org-latex-to-mathml-convert-command
18285 `((?j . ,(shell-quote-argument
18286 (expand-file-name org-latex-to-mathml-jar-file)))
18287 (?I . ,(shell-quote-argument tmp-in-file))
18288 (?o . ,(shell-quote-argument tmp-out-file)))))
18289 mathml shell-command-output)
18290 (when (org-called-interactively-p 'any)
18291 (unless (org-format-latex-mathml-available-p)
18292 (error "LaTeX to MathML converter not configured")))
18293 (message "Running %s" cmd)
18294 (setq shell-command-output (shell-command-to-string cmd))
18295 (setq mathml
18296 (when (file-readable-p tmp-out-file)
18297 (with-current-buffer (find-file-noselect tmp-out-file t)
18298 (goto-char (point-min))
18299 (when (re-search-forward
18300 (concat
18301 (regexp-quote
18302 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18303 "\\(.\\|\n\\)*"
18304 (regexp-quote "</math>")) nil t)
18305 (prog1 (match-string 0) (kill-buffer))))))
18306 (cond
18307 (mathml
18308 (setq mathml
18309 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18310 (when mathml-file
18311 (write-region mathml nil mathml-file))
18312 (when (org-called-interactively-p 'any)
18313 (message mathml)))
18314 ((message "LaTeX to MathML conversion failed")
18315 (message shell-command-output)))
18316 (delete-file tmp-in-file)
18317 (when (file-exists-p tmp-out-file)
18318 (delete-file tmp-out-file))
18319 mathml))
18321 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18322 prefix &optional dir)
18323 "Use `org-create-math-formula' but check local cache first."
18324 (let* ((absprefix (expand-file-name prefix dir))
18325 (print-length nil) (print-level nil)
18326 (formula-id (concat
18327 "formula-"
18328 (sha1
18329 (prin1-to-string
18330 (list latex-frag
18331 org-latex-to-mathml-convert-command)))))
18332 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18333 (formula-cache-dir (file-name-directory formula-cache)))
18335 (unless (file-directory-p formula-cache-dir)
18336 (make-directory formula-cache-dir t))
18338 (unless (file-exists-p formula-cache)
18339 (org-create-math-formula latex-frag formula-cache))
18341 (if (file-exists-p formula-cache)
18342 ;; Successful conversion. Return the link to MathML file.
18343 (org-add-props
18344 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18345 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18346 'org-latex-src-embed-type (if latex-frag-type
18347 'paragraph 'character)))
18348 ;; Failed conversion. Return the LaTeX fragment verbatim
18349 latex-frag)))
18351 (defun org-create-formula-image (string tofile options buffer &optional type)
18352 "Create an image from LaTeX source using dvipng or convert.
18353 This function calls either `org-create-formula-image-with-dvipng'
18354 or `org-create-formula-image-with-imagemagick' depending on the
18355 value of `org-latex-create-formula-image-program' or on the value
18356 of the optional TYPE variable.
18358 Note: ultimately these two function should be combined as they
18359 share a good deal of logic."
18360 (org-check-external-command
18361 "latex" "needed to convert LaTeX fragments to images")
18362 (funcall
18363 (case (or type org-latex-create-formula-image-program)
18364 ('dvipng
18365 (org-check-external-command
18366 "dvipng" "needed to convert LaTeX fragments to images")
18367 #'org-create-formula-image-with-dvipng)
18368 ('imagemagick
18369 (org-check-external-command
18370 "convert" "you need to install imagemagick")
18371 #'org-create-formula-image-with-imagemagick)
18372 (t (error
18373 "invalid value of `org-latex-create-formula-image-program'")))
18374 string tofile options buffer))
18376 (declare-function org-export--get-global-options "ox" (&optional backend))
18377 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18378 (defun org-create-formula--latex-header ()
18379 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18380 (org-latex-guess-inputenc
18381 (org-splice-latex-header
18382 org-format-latex-header
18383 org-latex-default-packages-alist
18384 org-latex-packages-alist t
18385 (plist-get
18386 (org-combine-plists
18387 (org-export--get-global-options 'latex)
18388 (org-export--get-inbuffer-options 'latex))
18389 :latex-header))))
18391 ;; This function borrows from Ganesh Swami's latex2png.el
18392 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18393 "This calls dvipng."
18394 (require 'ox-latex)
18395 (let* ((tmpdir (if (featurep 'xemacs)
18396 (temp-directory)
18397 temporary-file-directory))
18398 (texfilebase (make-temp-name
18399 (expand-file-name "orgtex" tmpdir)))
18400 (texfile (concat texfilebase ".tex"))
18401 (dvifile (concat texfilebase ".dvi"))
18402 (pngfile (concat texfilebase ".png"))
18403 (fnh (if (featurep 'xemacs)
18404 (font-height (face-font 'default))
18405 (face-attribute 'default :height nil)))
18406 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18407 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18408 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18409 "Black"))
18410 (bg (or (plist-get options (if buffer :background :html-background))
18411 "Transparent")))
18412 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18413 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18414 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18415 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18416 (let ((latex-header (org-create-formula--latex-header)))
18417 (with-temp-file texfile
18418 (insert latex-header)
18419 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18420 (let ((dir default-directory))
18421 (condition-case nil
18422 (progn
18423 (cd tmpdir)
18424 (call-process "latex" nil nil nil texfile))
18425 (error nil))
18426 (cd dir))
18427 (if (not (file-exists-p dvifile))
18428 (progn (message "Failed to create dvi file from %s" texfile) nil)
18429 (condition-case nil
18430 (if (featurep 'xemacs)
18431 (call-process "dvipng" nil nil nil
18432 "-fg" fg "-bg" bg
18433 "-T" "tight"
18434 "-o" pngfile
18435 dvifile)
18436 (call-process "dvipng" nil nil nil
18437 "-fg" fg "-bg" bg
18438 "-D" dpi
18439 ;;"-x" scale "-y" scale
18440 "-T" "tight"
18441 "-o" pngfile
18442 dvifile))
18443 (error nil))
18444 (if (not (file-exists-p pngfile))
18445 (if org-format-latex-signal-error
18446 (error "Failed to create png file from %s" texfile)
18447 (message "Failed to create png file from %s" texfile)
18448 nil)
18449 ;; Use the requested file name and clean up
18450 (copy-file pngfile tofile 'replace)
18451 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18452 (if (file-exists-p (concat texfilebase e))
18453 (delete-file (concat texfilebase e))))
18454 pngfile))))
18456 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18457 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18458 "This calls convert, which is included into imagemagick."
18459 (require 'ox-latex)
18460 (let* ((tmpdir (if (featurep 'xemacs)
18461 (temp-directory)
18462 temporary-file-directory))
18463 (texfilebase (make-temp-name
18464 (expand-file-name "orgtex" tmpdir)))
18465 (texfile (concat texfilebase ".tex"))
18466 (pdffile (concat texfilebase ".pdf"))
18467 (pngfile (concat texfilebase ".png"))
18468 (fnh (if (featurep 'xemacs)
18469 (font-height (face-font 'default))
18470 (face-attribute 'default :height nil)))
18471 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18472 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18473 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18474 "black"))
18475 (bg (or (plist-get options (if buffer :background :html-background))
18476 "white")))
18477 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18478 (setq fg (org-latex-color-format fg)))
18479 (if (eq bg 'default) (setq bg (org-latex-color :background))
18480 (setq bg (org-latex-color-format
18481 (if (string= bg "Transparent") "white" bg))))
18482 (let ((latex-header (org-create-formula--latex-header)))
18483 (with-temp-file texfile
18484 (insert latex-header)
18485 (insert "\n\\begin{document}\n"
18486 "\\definecolor{fg}{rgb}{" fg "}\n"
18487 "\\definecolor{bg}{rgb}{" bg "}\n"
18488 "\n\\pagecolor{bg}\n"
18489 "\n{\\color{fg}\n"
18490 string
18491 "\n}\n"
18492 "\n\\end{document}\n")))
18493 (org-latex-compile texfile t)
18494 (if (not (file-exists-p pdffile))
18495 (progn (message "Failed to create pdf file from %s" texfile) nil)
18496 (condition-case nil
18497 (if (featurep 'xemacs)
18498 (call-process "convert" nil nil nil
18499 "-density" "96"
18500 "-trim"
18501 "-antialias"
18502 pdffile
18503 "-quality" "100"
18504 ;; "-sharpen" "0x1.0"
18505 pngfile)
18506 (call-process "convert" nil nil nil
18507 "-density" dpi
18508 "-trim"
18509 "-antialias"
18510 pdffile
18511 "-quality" "100"
18512 ;; "-sharpen" "0x1.0"
18513 pngfile))
18514 (error nil))
18515 (if (not (file-exists-p pngfile))
18516 (if org-format-latex-signal-error
18517 (error "Failed to create png file from %s" texfile)
18518 (message "Failed to create png file from %s" texfile)
18519 nil)
18520 ;; Use the requested file name and clean up
18521 (copy-file pngfile tofile 'replace)
18522 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18523 (if (file-exists-p (concat texfilebase e))
18524 (delete-file (concat texfilebase e))))
18525 pngfile))))
18527 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18528 "Fill a LaTeX header template TPL.
18529 In the template, the following place holders will be recognized:
18531 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18532 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18533 [PACKAGES] \\usepackage statements for PKG
18534 [NO-PACKAGES] do not include PKG
18535 [EXTRA] the string EXTRA
18536 [NO-EXTRA] do not include EXTRA
18538 For backward compatibility, if both the positive and the negative place
18539 holder is missing, the positive one (without the \"NO-\") will be
18540 assumed to be present at the end of the template.
18541 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18542 EXTRA is a string.
18543 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18544 (let (rpl (end ""))
18545 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18546 (setq rpl (if (or (match-end 1) (not def-pkg))
18547 "" (org-latex-packages-to-string def-pkg snippets-p t))
18548 tpl (replace-match rpl t t tpl))
18549 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18551 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18552 (setq rpl (if (or (match-end 1) (not pkg))
18553 "" (org-latex-packages-to-string pkg snippets-p t))
18554 tpl (replace-match rpl t t tpl))
18555 (if pkg (setq end
18556 (concat end "\n"
18557 (org-latex-packages-to-string pkg snippets-p)))))
18559 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18560 (setq rpl (if (or (match-end 1) (not extra))
18561 "" (concat extra "\n"))
18562 tpl (replace-match rpl t t tpl))
18563 (if (and extra (string-match "\\S-" extra))
18564 (setq end (concat end "\n" extra))))
18566 (if (string-match "\\S-" end)
18567 (concat tpl "\n" end)
18568 tpl)))
18570 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18571 "Turn an alist of packages into a string with the \\usepackage macros."
18572 (setq pkg (mapconcat (lambda(p)
18573 (cond
18574 ((stringp p) p)
18575 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18576 (format "%% Package %s omitted" (cadr p)))
18577 ((equal "" (car p))
18578 (format "\\usepackage{%s}" (cadr p)))
18580 (format "\\usepackage[%s]{%s}"
18581 (car p) (cadr p)))))
18583 "\n"))
18584 (if newline (concat pkg "\n") pkg))
18586 (defun org-dvipng-color (attr)
18587 "Return a RGB color specification for dvipng."
18588 (apply 'format "rgb %s %s %s"
18589 (mapcar 'org-normalize-color
18590 (if (featurep 'xemacs)
18591 (color-rgb-components
18592 (face-property 'default
18593 (cond ((eq attr :foreground) 'foreground)
18594 ((eq attr :background) 'background))))
18595 (color-values (face-attribute 'default attr nil))))))
18597 (defun org-dvipng-color-format (color-name)
18598 "Convert COLOR-NAME to a RGB color value for dvipng."
18599 (apply 'format "rgb %s %s %s"
18600 (mapcar 'org-normalize-color
18601 (color-values color-name))))
18603 (defun org-latex-color (attr)
18604 "Return a RGB color for the LaTeX color package."
18605 (apply 'format "%s,%s,%s"
18606 (mapcar 'org-normalize-color
18607 (if (featurep 'xemacs)
18608 (color-rgb-components
18609 (face-property 'default
18610 (cond ((eq attr :foreground) 'foreground)
18611 ((eq attr :background) 'background))))
18612 (color-values (face-attribute 'default attr nil))))))
18614 (defun org-latex-color-format (color-name)
18615 "Convert COLOR-NAME to a RGB color value."
18616 (apply 'format "%s,%s,%s"
18617 (mapcar 'org-normalize-color
18618 (color-values color-name))))
18620 (defun org-normalize-color (value)
18621 "Return string to be used as color value for an RGB component."
18622 (format "%g" (/ value 65535.0)))
18626 ;; Image display
18628 (defvar org-inline-image-overlays nil)
18629 (make-variable-buffer-local 'org-inline-image-overlays)
18631 (defun org-toggle-inline-images (&optional include-linked)
18632 "Toggle the display of inline images.
18633 INCLUDE-LINKED is passed to `org-display-inline-images'."
18634 (interactive "P")
18635 (if org-inline-image-overlays
18636 (progn
18637 (org-remove-inline-images)
18638 (message "Inline image display turned off"))
18639 (org-display-inline-images include-linked)
18640 (if (and (org-called-interactively-p)
18641 org-inline-image-overlays)
18642 (message "%d images displayed inline"
18643 (length org-inline-image-overlays))
18644 (message "No images to display inline"))))
18646 (defun org-redisplay-inline-images ()
18647 "Refresh the display of inline images."
18648 (interactive)
18649 (if (not org-inline-image-overlays)
18650 (org-toggle-inline-images)
18651 (org-toggle-inline-images)
18652 (org-toggle-inline-images)))
18654 (defun org-display-inline-images (&optional include-linked refresh beg end)
18655 "Display inline images.
18656 Normally only links without a description part are inlined, because this
18657 is how it will work for export. When INCLUDE-LINKED is set, also links
18658 with a description part will be inlined. This can be nice for a quick
18659 look at those images, but it does not reflect what exported files will look
18660 like.
18661 When REFRESH is set, refresh existing images between BEG and END.
18662 This will create new image displays only if necessary.
18663 BEG and END default to the buffer boundaries."
18664 (interactive "P")
18665 (unless refresh
18666 (org-remove-inline-images)
18667 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18668 (save-excursion
18669 (save-restriction
18670 (widen)
18671 (setq beg (or beg (point-min)) end (or end (point-max)))
18672 (goto-char beg)
18673 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18674 (substring (org-image-file-name-regexp) 0 -2)
18675 "\\)\\]" (if include-linked "" "\\]")))
18676 (case-fold-search t)
18677 old file ov img type attrwidth width)
18678 (while (re-search-forward re end t)
18679 (setq old (get-char-property-and-overlay (match-beginning 1)
18680 'org-image-overlay)
18681 file (expand-file-name
18682 (concat (or (match-string 3) "") (match-string 4))))
18683 (when (image-type-available-p 'imagemagick)
18684 (setq attrwidth (if (or (listp org-image-actual-width)
18685 (null org-image-actual-width))
18686 (save-excursion
18687 (save-match-data
18688 (when (re-search-backward
18689 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18690 (save-excursion
18691 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18692 (string-to-number (match-string 1))))))
18693 width (cond ((eq org-image-actual-width t) nil)
18694 ((null org-image-actual-width) attrwidth)
18695 ((numberp org-image-actual-width)
18696 org-image-actual-width)
18697 ((listp org-image-actual-width)
18698 (or attrwidth (car org-image-actual-width))))
18699 type (if width 'imagemagick)))
18700 (when (file-exists-p file)
18701 (if (and (car-safe old) refresh)
18702 (image-refresh (overlay-get (cdr old) 'display))
18703 (setq img (save-match-data (create-image file type nil :width width)))
18704 (when img
18705 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18706 (overlay-put ov 'display img)
18707 (overlay-put ov 'face 'default)
18708 (overlay-put ov 'org-image-overlay t)
18709 (overlay-put ov 'modification-hooks
18710 (list 'org-display-inline-remove-overlay))
18711 (push ov org-inline-image-overlays)))))))))
18713 (define-obsolete-function-alias
18714 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18716 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18717 "Remove inline-display overlay if a corresponding region is modified."
18718 (let ((inhibit-modification-hooks t))
18719 (when (and ov after)
18720 (delete ov org-inline-image-overlays)
18721 (delete-overlay ov))))
18723 (defun org-remove-inline-images ()
18724 "Remove inline display of images."
18725 (interactive)
18726 (mapc 'delete-overlay org-inline-image-overlays)
18727 (setq org-inline-image-overlays nil))
18729 ;;;; Key bindings
18731 ;; Outline functions from `outline-mode-prefix-map'
18732 ;; that can be remapped in Org:
18733 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18734 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18735 (define-key org-mode-map [remap outline-forward-same-level]
18736 'org-forward-heading-same-level)
18737 (define-key org-mode-map [remap outline-backward-same-level]
18738 'org-backward-heading-same-level)
18739 (define-key org-mode-map [remap show-branches]
18740 'org-kill-note-or-show-branches)
18741 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18742 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18743 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18745 ;; Outline functions from `outline-mode-prefix-map' that can not
18746 ;; be remapped in Org:
18748 ;; - the column "key binding" shows whether the Outline function is still
18749 ;; available in Org mode on the same key that it has been bound to in
18750 ;; Outline mode:
18751 ;; - "overridden": key used for a different functionality in Org mode
18752 ;; - else: key still bound to the same Outline function in Org mode
18754 ;; | Outline function | key binding | Org replacement |
18755 ;; |------------------------------------+-------------+-----------------------|
18756 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18757 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18758 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18759 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18760 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18761 ;; | `show-entry' | overridden | no replacement |
18762 ;; | `show-children' | `C-c C-i' | visibility cycling |
18763 ;; | `show-branches' | `C-c C-k' | still same function |
18764 ;; | `show-subtree' | overridden | visibility cycling |
18765 ;; | `show-all' | overridden | no replacement |
18766 ;; | `hide-subtree' | overridden | visibility cycling |
18767 ;; | `hide-body' | overridden | no replacement |
18768 ;; | `hide-entry' | overridden | visibility cycling |
18769 ;; | `hide-leaves' | overridden | no replacement |
18770 ;; | `hide-sublevels' | overridden | no replacement |
18771 ;; | `hide-other' | overridden | no replacement |
18773 ;; Make `C-c C-x' a prefix key
18774 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18776 ;; TAB key with modifiers
18777 (org-defkey org-mode-map "\C-i" 'org-cycle)
18778 (org-defkey org-mode-map [(tab)] 'org-cycle)
18779 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18780 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18781 ;; The following line is necessary under Suse GNU/Linux
18782 (unless (featurep 'xemacs)
18783 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18784 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18785 (define-key org-mode-map [backtab] 'org-shifttab)
18787 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18788 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18789 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18791 ;; Cursor keys with modifiers
18792 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18793 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18794 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18795 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18797 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18798 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18799 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18800 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18802 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18803 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18804 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18805 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18807 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18808 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18809 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18810 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18812 ;; Babel keys
18813 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18814 (mapc (lambda (pair)
18815 (define-key org-babel-map (car pair) (cdr pair)))
18816 org-babel-key-bindings)
18818 ;;; Extra keys for tty access.
18819 ;; We only set them when really needed because otherwise the
18820 ;; menus don't show the simple keys
18822 (when (or org-use-extra-keys
18823 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18824 (not window-system))
18825 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18826 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18827 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18828 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18829 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18830 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18831 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18832 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18833 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18834 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18835 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18836 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18837 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18838 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18839 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18840 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18841 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18842 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18843 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18844 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18845 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18846 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18847 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18848 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18849 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18850 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18851 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18852 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18854 ;; All the other keys
18856 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18857 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18858 (if (boundp 'narrow-map)
18859 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18860 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18861 (if (boundp 'narrow-map)
18862 (org-defkey narrow-map "b" 'org-narrow-to-block)
18863 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18864 (if (boundp 'narrow-map)
18865 (org-defkey narrow-map "e" 'org-narrow-to-element)
18866 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18867 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18868 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18869 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18870 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18871 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18872 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18873 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18874 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18875 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18876 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18877 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18878 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18879 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18880 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18881 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18882 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18883 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18884 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18885 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18886 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18887 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18888 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18889 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18890 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18891 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18892 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18893 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18894 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18895 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18896 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18897 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18898 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18899 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18900 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18901 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18902 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18903 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18904 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18905 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18906 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18907 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18908 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18909 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18910 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18911 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18912 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18913 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18914 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18915 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18916 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18917 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18918 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18919 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18920 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18921 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18922 (org-defkey org-mode-map "\C-c^" 'org-sort)
18923 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18924 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18925 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18926 (org-defkey org-mode-map "\C-m" 'org-return)
18927 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18928 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18929 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18930 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18931 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18932 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18933 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18934 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18935 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18936 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18937 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18938 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18939 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18940 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18941 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18942 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18943 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18944 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18945 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18946 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18947 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18948 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18949 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18951 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18952 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18953 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18955 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18956 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18957 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18958 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18959 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18960 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18961 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18962 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18963 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18964 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18965 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18966 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18967 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18968 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18969 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18970 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18971 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18972 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18973 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18974 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18975 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18976 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18977 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18979 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18980 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18981 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18982 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18983 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18985 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18987 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18989 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18990 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18992 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18995 (when (featurep 'xemacs)
18996 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18999 (defconst org-speed-commands-default
19001 ("Outline Navigation")
19002 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19003 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19004 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19005 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19006 ("F" . org-next-block)
19007 ("B" . org-previous-block)
19008 ("u" . (org-speed-move-safe 'outline-up-heading))
19009 ("j" . org-goto)
19010 ("g" . (org-refile t))
19011 ("Outline Visibility")
19012 ("c" . org-cycle)
19013 ("C" . org-shifttab)
19014 (" " . org-display-outline-path)
19015 ("=" . org-columns)
19016 ("Outline Structure Editing")
19017 ("U" . org-shiftmetaup)
19018 ("D" . org-shiftmetadown)
19019 ("r" . org-metaright)
19020 ("l" . org-metaleft)
19021 ("R" . org-shiftmetaright)
19022 ("L" . org-shiftmetaleft)
19023 ("i" . (progn (forward-char 1) (call-interactively
19024 'org-insert-heading-respect-content)))
19025 ("^" . org-sort)
19026 ("w" . org-refile)
19027 ("a" . org-archive-subtree-default-with-confirmation)
19028 ("@" . org-mark-subtree)
19029 ("#" . org-toggle-comment)
19030 ("Clock Commands")
19031 ("I" . org-clock-in)
19032 ("O" . org-clock-out)
19033 ("Meta Data Editing")
19034 ("t" . org-todo)
19035 ("," . (org-priority))
19036 ("0" . (org-priority ?\ ))
19037 ("1" . (org-priority ?A))
19038 ("2" . (org-priority ?B))
19039 ("3" . (org-priority ?C))
19040 (":" . org-set-tags-command)
19041 ("e" . org-set-effort)
19042 ("E" . org-inc-effort)
19043 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19044 (org-entry-put (point) "APPT_WARNTIME" m)))
19045 ("Agenda Views etc")
19046 ("v" . org-agenda)
19047 ("/" . org-sparse-tree)
19048 ("Misc")
19049 ("o" . org-open-at-point)
19050 ("?" . org-speed-command-help)
19051 ("<" . (org-agenda-set-restriction-lock 'subtree))
19052 (">" . (org-agenda-remove-restriction-lock))
19054 "The default speed commands.")
19056 (defun org-print-speed-command (e)
19057 (if (> (length (car e)) 1)
19058 (progn
19059 (princ "\n")
19060 (princ (car e))
19061 (princ "\n")
19062 (princ (make-string (length (car e)) ?-))
19063 (princ "\n"))
19064 (princ (car e))
19065 (princ " ")
19066 (if (symbolp (cdr e))
19067 (princ (symbol-name (cdr e)))
19068 (prin1 (cdr e)))
19069 (princ "\n")))
19071 (defun org-speed-command-help ()
19072 "Show the available speed commands."
19073 (interactive)
19074 (if (not org-use-speed-commands)
19075 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19076 (with-output-to-temp-buffer "*Help*"
19077 (princ "User-defined Speed commands\n===========================\n")
19078 (mapc 'org-print-speed-command org-speed-commands-user)
19079 (princ "\n")
19080 (princ "Built-in Speed commands\n=======================\n")
19081 (mapc 'org-print-speed-command org-speed-commands-default))
19082 (with-current-buffer "*Help*"
19083 (setq truncate-lines t))))
19085 (defun org-speed-move-safe (cmd)
19086 "Execute CMD, but make sure that the cursor always ends up in a headline.
19087 If not, return to the original position and throw an error."
19088 (interactive)
19089 (let ((pos (point)))
19090 (call-interactively cmd)
19091 (unless (and (bolp) (org-at-heading-p))
19092 (goto-char pos)
19093 (error "Boundary reached while executing %s" cmd))))
19095 (defvar org-self-insert-command-undo-counter 0)
19097 (defvar org-table-auto-blank-field) ; defined in org-table.el
19098 (defvar org-speed-command nil)
19100 (define-obsolete-function-alias
19101 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19103 (defun org-speed-command-activate (keys)
19104 "Hook for activating single-letter speed commands.
19105 `org-speed-commands-default' specifies a minimal command set.
19106 Use `org-speed-commands-user' for further customization."
19107 (when (or (and (bolp) (looking-at org-outline-regexp))
19108 (and (functionp org-use-speed-commands)
19109 (funcall org-use-speed-commands)))
19110 (cdr (assoc keys (append org-speed-commands-user
19111 org-speed-commands-default)))))
19113 (define-obsolete-function-alias
19114 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19116 (defun org-babel-speed-command-activate (keys)
19117 "Hook for activating single-letter code block commands."
19118 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19119 (cdr (assoc keys org-babel-key-bindings))))
19121 (defcustom org-speed-command-hook
19122 '(org-speed-command-default-hook org-babel-speed-command-hook)
19123 "Hook for activating speed commands at strategic locations.
19124 Hook functions are called in sequence until a valid handler is
19125 found.
19127 Each hook takes a single argument, a user-pressed command key
19128 which is also a `self-insert-command' from the global map.
19130 Within the hook, examine the cursor position and the command key
19131 and return nil or a valid handler as appropriate. Handler could
19132 be one of an interactive command, a function, or a form.
19134 Set `org-use-speed-commands' to non-nil value to enable this
19135 hook. The default setting is `org-speed-command-activate'."
19136 :group 'org-structure
19137 :version "24.1"
19138 :type 'hook)
19140 (defun org-self-insert-command (N)
19141 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19142 If the cursor is in a table looking at whitespace, the whitespace is
19143 overwritten, and the table is not marked as requiring realignment."
19144 (interactive "p")
19145 (org-check-before-invisible-edit 'insert)
19146 (cond
19147 ((and org-use-speed-commands
19148 (setq org-speed-command
19149 (run-hook-with-args-until-success
19150 'org-speed-command-hook (this-command-keys))))
19151 (cond
19152 ((commandp org-speed-command)
19153 (setq this-command org-speed-command)
19154 (call-interactively org-speed-command))
19155 ((functionp org-speed-command)
19156 (funcall org-speed-command))
19157 ((and org-speed-command (listp org-speed-command))
19158 (eval org-speed-command))
19159 (t (let (org-use-speed-commands)
19160 (call-interactively 'org-self-insert-command)))))
19161 ((and
19162 (org-table-p)
19163 (progn
19164 ;; check if we blank the field, and if that triggers align
19165 (and (featurep 'org-table) org-table-auto-blank-field
19166 (member last-command
19167 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19168 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19169 ;; got extra space, this field does not determine column width
19170 (let (org-table-may-need-update) (org-table-blank-field))
19171 ;; no extra space, this field may determine column width
19172 (org-table-blank-field)))
19174 (eq N 1)
19175 (looking-at "[^|\n]* |"))
19176 (let (org-table-may-need-update)
19177 (goto-char (1- (match-end 0)))
19178 (backward-delete-char 1)
19179 (goto-char (match-beginning 0))
19180 (self-insert-command N)))
19182 (setq org-table-may-need-update t)
19183 (self-insert-command N)
19184 (org-fix-tags-on-the-fly)
19185 (if org-self-insert-cluster-for-undo
19186 (if (not (eq last-command 'org-self-insert-command))
19187 (setq org-self-insert-command-undo-counter 1)
19188 (if (>= org-self-insert-command-undo-counter 20)
19189 (setq org-self-insert-command-undo-counter 1)
19190 (and (> org-self-insert-command-undo-counter 0)
19191 buffer-undo-list (listp buffer-undo-list)
19192 (not (cadr buffer-undo-list)) ; remove nil entry
19193 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19194 (setq org-self-insert-command-undo-counter
19195 (1+ org-self-insert-command-undo-counter))))))))
19197 (defun org-check-before-invisible-edit (kind)
19198 "Check is editing if kind KIND would be dangerous with invisible text around.
19199 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19200 ;; First, try to get out of here as quickly as possible, to reduce overhead
19201 (if (and org-catch-invisible-edits
19202 (or (not (boundp 'visible-mode)) (not visible-mode))
19203 (or (get-char-property (point) 'invisible)
19204 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19205 ;; OK, we need to take a closer look
19206 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19207 (invisible-before-point (if (bobp) nil (get-char-property
19208 (1- (point)) 'invisible)))
19209 (border-and-ok-direction
19211 ;; Check if we are acting predictably before invisible text
19212 (and invisible-at-point (not invisible-before-point)
19213 (memq kind '(insert delete-backward)))
19214 ;; Check if we are acting predictably after invisible text
19215 ;; This works not well, and I have turned it off. It seems
19216 ;; better to always show and stop after invisible text.
19217 ;; (and (not invisible-at-point) invisible-before-point
19218 ;; (memq kind '(insert delete)))
19220 (when (or (memq invisible-at-point '(outline org-hide-block t))
19221 (memq invisible-before-point '(outline org-hide-block t)))
19222 (if (eq org-catch-invisible-edits 'error)
19223 (error "Editing in invisible areas is prohibited - make visible first"))
19224 (if (and org-custom-properties-overlays
19225 (y-or-n-p "Display invisible properties in this buffer? "))
19226 (org-toggle-custom-properties-visibility)
19227 ;; Make the area visible
19228 (save-excursion
19229 (if invisible-before-point
19230 (goto-char (previous-single-char-property-change
19231 (point) 'invisible)))
19232 (org-cycle))
19233 (cond
19234 ((eq org-catch-invisible-edits 'show)
19235 ;; That's it, we do the edit after showing
19236 (message
19237 "Unfolding invisible region around point before editing")
19238 (sit-for 1))
19239 ((and (eq org-catch-invisible-edits 'smart)
19240 border-and-ok-direction)
19241 (message "Unfolding invisible region around point before editing"))
19243 ;; Don't do the edit, make the user repeat it in full visibility
19244 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19246 (defun org-fix-tags-on-the-fly ()
19247 (when (and (equal (char-after (point-at-bol)) ?*)
19248 (org-at-heading-p))
19249 (org-align-tags-here org-tags-column)))
19251 (defun org-delete-backward-char (N)
19252 "Like `delete-backward-char', insert whitespace at field end in tables.
19253 When deleting backwards, in tables this function will insert whitespace in
19254 front of the next \"|\" separator, to keep the table aligned. The table will
19255 still be marked for re-alignment if the field did fill the entire column,
19256 because, in this case the deletion might narrow the column."
19257 (interactive "p")
19258 (save-match-data
19259 (org-check-before-invisible-edit 'delete-backward)
19260 (if (and (org-table-p)
19261 (eq N 1)
19262 (string-match "|" (buffer-substring (point-at-bol) (point)))
19263 (looking-at ".*?|"))
19264 (let ((pos (point))
19265 (noalign (looking-at "[^|\n\r]* |"))
19266 (c org-table-may-need-update))
19267 (backward-delete-char N)
19268 (if (not overwrite-mode)
19269 (progn
19270 (skip-chars-forward "^|")
19271 (insert " ")
19272 (goto-char (1- pos))))
19273 ;; noalign: if there were two spaces at the end, this field
19274 ;; does not determine the width of the column.
19275 (if noalign (setq org-table-may-need-update c)))
19276 (backward-delete-char N)
19277 (org-fix-tags-on-the-fly))))
19279 (defun org-delete-char (N)
19280 "Like `delete-char', but insert whitespace at field end in tables.
19281 When deleting characters, in tables this function will insert whitespace in
19282 front of the next \"|\" separator, to keep the table aligned. The table will
19283 still be marked for re-alignment if the field did fill the entire column,
19284 because, in this case the deletion might narrow the column."
19285 (interactive "p")
19286 (save-match-data
19287 (org-check-before-invisible-edit 'delete)
19288 (if (and (org-table-p)
19289 (not (bolp))
19290 (not (= (char-after) ?|))
19291 (eq N 1))
19292 (if (looking-at ".*?|")
19293 (let ((pos (point))
19294 (noalign (looking-at "[^|\n\r]* |"))
19295 (c org-table-may-need-update))
19296 (replace-match
19297 (concat (substring (match-string 0) 1 -1) " |") nil t)
19298 (goto-char pos)
19299 ;; noalign: if there were two spaces at the end, this field
19300 ;; does not determine the width of the column.
19301 (if noalign (setq org-table-may-need-update c)))
19302 (delete-char N))
19303 (delete-char N)
19304 (org-fix-tags-on-the-fly))))
19306 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19307 (put 'org-self-insert-command 'delete-selection t)
19308 (put 'orgtbl-self-insert-command 'delete-selection t)
19309 (put 'org-delete-char 'delete-selection 'supersede)
19310 (put 'org-delete-backward-char 'delete-selection 'supersede)
19311 (put 'org-yank 'delete-selection 'yank)
19313 ;; Make `flyspell-mode' delay after some commands
19314 (put 'org-self-insert-command 'flyspell-delayed t)
19315 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19316 (put 'org-delete-char 'flyspell-delayed t)
19317 (put 'org-delete-backward-char 'flyspell-delayed t)
19319 ;; Make pabbrev-mode expand after org-mode commands
19320 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19321 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19323 ;; How to do this: Measure non-white length of current string
19324 ;; If equal to column width, we should realign.
19326 (defun org-remap (map &rest commands)
19327 "In MAP, remap the functions given in COMMANDS.
19328 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19329 (let (new old)
19330 (while commands
19331 (setq old (pop commands) new (pop commands))
19332 (if (fboundp 'command-remapping)
19333 (org-defkey map (vector 'remap old) new)
19334 (substitute-key-definition old new map global-map)))))
19336 (defun org-transpose-words ()
19337 "Transpose words for Org.
19338 This uses the `org-mode-transpose-word-syntax-table' syntax
19339 table, which interprets characters in `org-emphasis-alist' as
19340 word constituants."
19341 (interactive)
19342 (with-syntax-table org-mode-transpose-word-syntax-table
19343 (call-interactively 'transpose-words)))
19344 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19346 (when (eq org-enable-table-editor 'optimized)
19347 ;; If the user wants maximum table support, we need to hijack
19348 ;; some standard editing functions
19349 (org-remap org-mode-map
19350 'self-insert-command 'org-self-insert-command
19351 'delete-char 'org-delete-char
19352 'delete-backward-char 'org-delete-backward-char)
19353 (org-defkey org-mode-map "|" 'org-force-self-insert))
19355 (defvar org-ctrl-c-ctrl-c-hook nil
19356 "Hook for functions attaching themselves to `C-c C-c'.
19358 This can be used to add additional functionality to the C-c C-c
19359 key which executes context-dependent commands. This hook is run
19360 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19361 run after the last test.
19363 Each function will be called with no arguments. The function
19364 must check if the context is appropriate for it to act. If yes,
19365 it should do its thing and then return a non-nil value. If the
19366 context is wrong, just do nothing and return nil.")
19368 (defvar org-ctrl-c-ctrl-c-final-hook nil
19369 "Hook for functions attaching themselves to `C-c C-c'.
19371 This can be used to add additional functionality to the C-c C-c
19372 key which executes context-dependent commands. This hook is run
19373 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19374 before the first test.
19376 Each function will be called with no arguments. The function
19377 must check if the context is appropriate for it to act. If yes,
19378 it should do its thing and then return a non-nil value. If the
19379 context is wrong, just do nothing and return nil.")
19381 (defvar org-tab-first-hook nil
19382 "Hook for functions to attach themselves to TAB.
19383 See `org-ctrl-c-ctrl-c-hook' for more information.
19384 This hook runs as the first action when TAB is pressed, even before
19385 `org-cycle' messes around with the `outline-regexp' to cater for
19386 inline tasks and plain list item folding.
19387 If any function in this hook returns t, any other actions that
19388 would have been caused by TAB (such as table field motion or visibility
19389 cycling) will not occur.")
19391 (defvar org-tab-after-check-for-table-hook nil
19392 "Hook for functions to attach themselves to TAB.
19393 See `org-ctrl-c-ctrl-c-hook' for more information.
19394 This hook runs after it has been established that the cursor is not in a
19395 table, but before checking if the cursor is in a headline or if global cycling
19396 should be done.
19397 If any function in this hook returns t, not other actions like visibility
19398 cycling will be done.")
19400 (defvar org-tab-after-check-for-cycling-hook nil
19401 "Hook for functions to attach themselves to TAB.
19402 See `org-ctrl-c-ctrl-c-hook' for more information.
19403 This hook runs after it has been established that not table field motion and
19404 not visibility should be done because of current context. This is probably
19405 the place where a package like yasnippets can hook in.")
19407 (defvar org-tab-before-tab-emulation-hook nil
19408 "Hook for functions to attach themselves to TAB.
19409 See `org-ctrl-c-ctrl-c-hook' for more information.
19410 This hook runs after every other options for TAB have been exhausted, but
19411 before indentation and \t insertion takes place.")
19413 (defvar org-metaleft-hook nil
19414 "Hook for functions attaching themselves to `M-left'.
19415 See `org-ctrl-c-ctrl-c-hook' for more information.")
19416 (defvar org-metaright-hook nil
19417 "Hook for functions attaching themselves to `M-right'.
19418 See `org-ctrl-c-ctrl-c-hook' for more information.")
19419 (defvar org-metaup-hook nil
19420 "Hook for functions attaching themselves to `M-up'.
19421 See `org-ctrl-c-ctrl-c-hook' for more information.")
19422 (defvar org-metadown-hook nil
19423 "Hook for functions attaching themselves to `M-down'.
19424 See `org-ctrl-c-ctrl-c-hook' for more information.")
19425 (defvar org-shiftmetaleft-hook nil
19426 "Hook for functions attaching themselves to `M-S-left'.
19427 See `org-ctrl-c-ctrl-c-hook' for more information.")
19428 (defvar org-shiftmetaright-hook nil
19429 "Hook for functions attaching themselves to `M-S-right'.
19430 See `org-ctrl-c-ctrl-c-hook' for more information.")
19431 (defvar org-shiftmetaup-hook nil
19432 "Hook for functions attaching themselves to `M-S-up'.
19433 See `org-ctrl-c-ctrl-c-hook' for more information.")
19434 (defvar org-shiftmetadown-hook nil
19435 "Hook for functions attaching themselves to `M-S-down'.
19436 See `org-ctrl-c-ctrl-c-hook' for more information.")
19437 (defvar org-metareturn-hook nil
19438 "Hook for functions attaching themselves to `M-RET'.
19439 See `org-ctrl-c-ctrl-c-hook' for more information.")
19440 (defvar org-shiftup-hook nil
19441 "Hook for functions attaching themselves to `S-up'.
19442 See `org-ctrl-c-ctrl-c-hook' for more information.")
19443 (defvar org-shiftup-final-hook nil
19444 "Hook for functions attaching themselves to `S-up'.
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-shiftdown-hook nil
19448 "Hook for functions attaching themselves to `S-down'.
19449 See `org-ctrl-c-ctrl-c-hook' for more information.")
19450 (defvar org-shiftdown-final-hook nil
19451 "Hook for functions attaching themselves to `S-down'.
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.")
19454 (defvar org-shiftleft-hook nil
19455 "Hook for functions attaching themselves to `S-left'.
19456 See `org-ctrl-c-ctrl-c-hook' for more information.")
19457 (defvar org-shiftleft-final-hook nil
19458 "Hook for functions attaching themselves to `S-left'.
19459 This one runs after all other options except shift-select have been excluded.
19460 See `org-ctrl-c-ctrl-c-hook' for more information.")
19461 (defvar org-shiftright-hook nil
19462 "Hook for functions attaching themselves to `S-right'.
19463 See `org-ctrl-c-ctrl-c-hook' for more information.")
19464 (defvar org-shiftright-final-hook nil
19465 "Hook for functions attaching themselves to `S-right'.
19466 This one runs after all other options except shift-select have been excluded.
19467 See `org-ctrl-c-ctrl-c-hook' for more information.")
19469 (defun org-modifier-cursor-error ()
19470 "Throw an error, a modified cursor command was applied in wrong context."
19471 (error "This command is active in special context like tables, headlines or items"))
19473 (defun org-shiftselect-error ()
19474 "Throw an error because Shift-Cursor command was applied in wrong context."
19475 (if (and (boundp 'shift-select-mode) shift-select-mode)
19476 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19477 (error "This command works only in special context like headlines or timestamps")))
19479 (defun org-call-for-shift-select (cmd)
19480 (let ((this-command-keys-shift-translated t))
19481 (call-interactively cmd)))
19483 (defun org-shifttab (&optional arg)
19484 "Global visibility cycling or move to previous table field.
19485 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19486 on context.
19487 See the individual commands for more information."
19488 (interactive "P")
19489 (cond
19490 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19491 ((integerp arg)
19492 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19493 (message "Content view to level: %d" arg)
19494 (org-content (prefix-numeric-value arg2))
19495 (setq org-cycle-global-status 'overview)))
19496 (t (call-interactively 'org-global-cycle))))
19498 (defun org-shiftmetaleft ()
19499 "Promote subtree or delete table column.
19500 Calls `org-promote-subtree', `org-outdent-item-tree', or
19501 `org-table-delete-column', depending on context. See the
19502 individual commands for more information."
19503 (interactive)
19504 (cond
19505 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19506 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19507 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19508 ((if (not (org-region-active-p)) (org-at-item-p)
19509 (save-excursion (goto-char (region-beginning))
19510 (org-at-item-p)))
19511 (call-interactively 'org-outdent-item-tree))
19512 (t (org-modifier-cursor-error))))
19514 (defun org-shiftmetaright ()
19515 "Demote subtree or insert table column.
19516 Calls `org-demote-subtree', `org-indent-item-tree', or
19517 `org-table-insert-column', depending on context. See the
19518 individual commands for more information."
19519 (interactive)
19520 (cond
19521 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19522 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19523 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19524 ((if (not (org-region-active-p)) (org-at-item-p)
19525 (save-excursion (goto-char (region-beginning))
19526 (org-at-item-p)))
19527 (call-interactively 'org-indent-item-tree))
19528 (t (org-modifier-cursor-error))))
19530 (defun org-shiftmetaup (&optional arg)
19531 "Move subtree up or kill table row.
19532 Calls `org-move-subtree-up' or `org-table-kill-row' or
19533 `org-move-item-up' or `org-timestamp-up', depending on context.
19534 See the individual commands for more information."
19535 (interactive "P")
19536 (cond
19537 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19538 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19539 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19540 ((org-at-item-p) (call-interactively 'org-move-item-up))
19541 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19542 (call-interactively 'org-timestamp-up)))
19543 (t (call-interactively 'org-drag-line-backward))))
19545 (defun org-shiftmetadown (&optional arg)
19546 "Move subtree down or insert table row.
19547 Calls `org-move-subtree-down' or `org-table-insert-row' or
19548 `org-move-item-down' or `org-timestamp-up', depending on context.
19549 See the individual commands for more information."
19550 (interactive "P")
19551 (cond
19552 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19553 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19554 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19555 ((org-at-item-p) (call-interactively 'org-move-item-down))
19556 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19557 (call-interactively 'org-timestamp-down)))
19558 (t (call-interactively 'org-drag-line-forward))))
19560 (defsubst org-hidden-tree-error ()
19561 (error
19562 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19564 (defun org-metaleft (&optional arg)
19565 "Promote heading or move table column to left.
19566 Calls `org-do-promote' or `org-table-move-column', depending on context.
19567 With no specific context, calls the Emacs default `backward-word'.
19568 See the individual commands for more information."
19569 (interactive "P")
19570 (cond
19571 ((run-hook-with-args-until-success 'org-metaleft-hook))
19572 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19573 ((org-with-limited-levels
19574 (or (org-at-heading-p)
19575 (and (org-region-active-p)
19576 (save-excursion
19577 (goto-char (region-beginning))
19578 (org-at-heading-p)))))
19579 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19580 (call-interactively 'org-do-promote))
19581 ;; At an inline task.
19582 ((org-at-heading-p)
19583 (call-interactively 'org-inlinetask-promote))
19584 ((or (org-at-item-p)
19585 (and (org-region-active-p)
19586 (save-excursion
19587 (goto-char (region-beginning))
19588 (org-at-item-p))))
19589 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19590 (call-interactively 'org-outdent-item))
19591 (t (call-interactively 'backward-word))))
19593 (defun org-metaright (&optional arg)
19594 "Demote a subtree, a list item or move table column to right.
19595 In front of a drawer or a block keyword, indent it correctly.
19596 With no specific context, calls the Emacs default `forward-word'.
19597 See the individual commands for more information."
19598 (interactive "P")
19599 (cond
19600 ((run-hook-with-args-until-success 'org-metaright-hook))
19601 ((org-at-table-p) (call-interactively 'org-table-move-column))
19602 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19603 ((org-at-block-p) (call-interactively 'org-indent-block))
19604 ((org-with-limited-levels
19605 (or (org-at-heading-p)
19606 (and (org-region-active-p)
19607 (save-excursion
19608 (goto-char (region-beginning))
19609 (org-at-heading-p)))))
19610 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19611 (call-interactively 'org-do-demote))
19612 ;; At an inline task.
19613 ((org-at-heading-p)
19614 (call-interactively 'org-inlinetask-demote))
19615 ((or (org-at-item-p)
19616 (and (org-region-active-p)
19617 (save-excursion
19618 (goto-char (region-beginning))
19619 (org-at-item-p))))
19620 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19621 (call-interactively 'org-indent-item))
19622 (t (call-interactively 'forward-word))))
19624 (defun org-check-for-hidden (what)
19625 "Check if there are hidden headlines/items in the current visual line.
19626 WHAT can be either `headlines' or `items'. If the current line is
19627 an outline or item heading and it has a folded subtree below it,
19628 this function returns t, nil otherwise."
19629 (let ((re (cond
19630 ((eq what 'headlines) org-outline-regexp-bol)
19631 ((eq what 'items) (org-item-beginning-re))
19632 (t (error "This should not happen"))))
19633 beg end)
19634 (save-excursion
19635 (catch 'exit
19636 (unless (org-region-active-p)
19637 (setq beg (point-at-bol))
19638 (beginning-of-line 2)
19639 (while (and (not (eobp)) ;; this is like `next-line'
19640 (get-char-property (1- (point)) 'invisible))
19641 (beginning-of-line 2))
19642 (setq end (point))
19643 (goto-char beg)
19644 (goto-char (point-at-eol))
19645 (setq end (max end (point)))
19646 (while (re-search-forward re end t)
19647 (if (get-char-property (match-beginning 0) 'invisible)
19648 (throw 'exit t))))
19649 nil))))
19651 (defun org-metaup (&optional arg)
19652 "Move subtree up or move table row up.
19653 Calls `org-move-subtree-up' or `org-table-move-row' or
19654 `org-move-item-up', depending on context. See the individual commands
19655 for more information."
19656 (interactive "P")
19657 (cond
19658 ((run-hook-with-args-until-success 'org-metaup-hook))
19659 ((org-region-active-p)
19660 (let* ((a (min (region-beginning) (region-end)))
19661 (b (1- (max (region-beginning) (region-end))))
19662 (c (save-excursion (goto-char a)
19663 (move-beginning-of-line 0)))
19664 (d (save-excursion (goto-char a)
19665 (move-end-of-line 0) (point))))
19666 (transpose-regions a b c d)
19667 (goto-char c)))
19668 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19669 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19670 ((org-at-item-p) (call-interactively 'org-move-item-up))
19671 (t (org-drag-element-backward))))
19673 (defun org-metadown (&optional arg)
19674 "Move subtree down or move table row down.
19675 Calls `org-move-subtree-down' or `org-table-move-row' or
19676 `org-move-item-down', depending on context. See the individual
19677 commands for more information."
19678 (interactive "P")
19679 (cond
19680 ((run-hook-with-args-until-success 'org-metadown-hook))
19681 ((org-region-active-p)
19682 (let* ((a (min (region-beginning) (region-end)))
19683 (b (max (region-beginning) (region-end)))
19684 (c (save-excursion (goto-char b)
19685 (move-beginning-of-line 1)))
19686 (d (save-excursion (goto-char b)
19687 (move-end-of-line 1) (1+ (point)))))
19688 (transpose-regions a b c d)
19689 (goto-char d)))
19690 ((org-at-table-p) (call-interactively 'org-table-move-row))
19691 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19692 ((org-at-item-p) (call-interactively 'org-move-item-down))
19693 (t (org-drag-element-forward))))
19695 (defun org-shiftup (&optional arg)
19696 "Increase item in timestamp or increase priority of current headline.
19697 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19698 depending on context. See the individual commands for more information."
19699 (interactive "P")
19700 (cond
19701 ((run-hook-with-args-until-success 'org-shiftup-hook))
19702 ((and org-support-shift-select (org-region-active-p))
19703 (org-call-for-shift-select 'previous-line))
19704 ((org-at-timestamp-p t)
19705 (call-interactively (if org-edit-timestamp-down-means-later
19706 'org-timestamp-down 'org-timestamp-up)))
19707 ((and (not (eq org-support-shift-select 'always))
19708 org-enable-priority-commands
19709 (org-at-heading-p))
19710 (call-interactively 'org-priority-up))
19711 ((and (not org-support-shift-select) (org-at-item-p))
19712 (call-interactively 'org-previous-item))
19713 ((org-clocktable-try-shift 'up arg))
19714 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19715 (org-support-shift-select
19716 (org-call-for-shift-select 'previous-line))
19717 (t (org-shiftselect-error))))
19719 (defun org-shiftdown (&optional arg)
19720 "Decrease item in timestamp or decrease priority of current headline.
19721 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19722 depending on context. See the individual commands for more information."
19723 (interactive "P")
19724 (cond
19725 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19726 ((and org-support-shift-select (org-region-active-p))
19727 (org-call-for-shift-select 'next-line))
19728 ((org-at-timestamp-p t)
19729 (call-interactively (if org-edit-timestamp-down-means-later
19730 'org-timestamp-up 'org-timestamp-down)))
19731 ((and (not (eq org-support-shift-select 'always))
19732 org-enable-priority-commands
19733 (org-at-heading-p))
19734 (call-interactively 'org-priority-down))
19735 ((and (not org-support-shift-select) (org-at-item-p))
19736 (call-interactively 'org-next-item))
19737 ((org-clocktable-try-shift 'down arg))
19738 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19739 (org-support-shift-select
19740 (org-call-for-shift-select 'next-line))
19741 (t (org-shiftselect-error))))
19743 (defun org-shiftright (&optional arg)
19744 "Cycle the thing at point or in the current line, depending on context.
19745 Depending on context, this does one of the following:
19747 - switch a timestamp at point one day into the future
19748 - on a headline, switch to the next TODO keyword.
19749 - on an item, switch entire list to the next bullet type
19750 - on a property line, switch to the next allowed value
19751 - on a clocktable definition line, move time block into the future"
19752 (interactive "P")
19753 (cond
19754 ((run-hook-with-args-until-success 'org-shiftright-hook))
19755 ((and org-support-shift-select (org-region-active-p))
19756 (org-call-for-shift-select 'forward-char))
19757 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19758 ((and (not (eq org-support-shift-select 'always))
19759 (org-at-heading-p))
19760 (let ((org-inhibit-logging
19761 (not org-treat-S-cursor-todo-selection-as-state-change))
19762 (org-inhibit-blocking
19763 (not org-treat-S-cursor-todo-selection-as-state-change)))
19764 (org-call-with-arg 'org-todo 'right)))
19765 ((or (and org-support-shift-select
19766 (not (eq org-support-shift-select 'always))
19767 (org-at-item-bullet-p))
19768 (and (not org-support-shift-select) (org-at-item-p)))
19769 (org-call-with-arg 'org-cycle-list-bullet nil))
19770 ((and (not (eq org-support-shift-select 'always))
19771 (org-at-property-p))
19772 (call-interactively 'org-property-next-allowed-value))
19773 ((org-clocktable-try-shift 'right arg))
19774 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19775 (org-support-shift-select
19776 (org-call-for-shift-select 'forward-char))
19777 (t (org-shiftselect-error))))
19779 (defun org-shiftleft (&optional arg)
19780 "Cycle the thing at point or in the current line, depending on context.
19781 Depending on context, this does one of the following:
19783 - switch a timestamp at point one day into the past
19784 - on a headline, switch to the previous TODO keyword.
19785 - on an item, switch entire list to the previous bullet type
19786 - on a property line, switch to the previous allowed value
19787 - on a clocktable definition line, move time block into the past"
19788 (interactive "P")
19789 (cond
19790 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19791 ((and org-support-shift-select (org-region-active-p))
19792 (org-call-for-shift-select 'backward-char))
19793 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19794 ((and (not (eq org-support-shift-select 'always))
19795 (org-at-heading-p))
19796 (let ((org-inhibit-logging
19797 (not org-treat-S-cursor-todo-selection-as-state-change))
19798 (org-inhibit-blocking
19799 (not org-treat-S-cursor-todo-selection-as-state-change)))
19800 (org-call-with-arg 'org-todo 'left)))
19801 ((or (and org-support-shift-select
19802 (not (eq org-support-shift-select 'always))
19803 (org-at-item-bullet-p))
19804 (and (not org-support-shift-select) (org-at-item-p)))
19805 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19806 ((and (not (eq org-support-shift-select 'always))
19807 (org-at-property-p))
19808 (call-interactively 'org-property-previous-allowed-value))
19809 ((org-clocktable-try-shift 'left arg))
19810 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19811 (org-support-shift-select
19812 (org-call-for-shift-select 'backward-char))
19813 (t (org-shiftselect-error))))
19815 (defun org-shiftcontrolright ()
19816 "Switch to next TODO set."
19817 (interactive)
19818 (cond
19819 ((and org-support-shift-select (org-region-active-p))
19820 (org-call-for-shift-select 'forward-word))
19821 ((and (not (eq org-support-shift-select 'always))
19822 (org-at-heading-p))
19823 (org-call-with-arg 'org-todo 'nextset))
19824 (org-support-shift-select
19825 (org-call-for-shift-select 'forward-word))
19826 (t (org-shiftselect-error))))
19828 (defun org-shiftcontrolleft ()
19829 "Switch to previous TODO set."
19830 (interactive)
19831 (cond
19832 ((and org-support-shift-select (org-region-active-p))
19833 (org-call-for-shift-select 'backward-word))
19834 ((and (not (eq org-support-shift-select 'always))
19835 (org-at-heading-p))
19836 (org-call-with-arg 'org-todo 'previousset))
19837 (org-support-shift-select
19838 (org-call-for-shift-select 'backward-word))
19839 (t (org-shiftselect-error))))
19841 (defun org-shiftcontrolup (&optional n)
19842 "Change timestamps synchronously up in CLOCK log lines.
19843 Optional argument N tells to change by that many units."
19844 (interactive "P")
19845 (cond ((and (not org-support-shift-select)
19846 (org-at-clock-log-p)
19847 (org-at-timestamp-p t))
19848 (org-clock-timestamps-up n))
19849 (t (org-shiftselect-error))))
19851 (defun org-shiftcontroldown (&optional n)
19852 "Change timestamps synchronously down in CLOCK log lines.
19853 Optional argument N tells to change by that many units."
19854 (interactive "P")
19855 (cond ((and (not org-support-shift-select)
19856 (org-at-clock-log-p)
19857 (org-at-timestamp-p t))
19858 (org-clock-timestamps-down n))
19859 (t (org-shiftselect-error))))
19861 (defun org-ctrl-c-ret ()
19862 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19863 (interactive)
19864 (cond
19865 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19866 (t (call-interactively 'org-insert-heading))))
19868 (defun org-find-visible ()
19869 (let ((s (point)))
19870 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19871 (get-char-property s 'invisible)))
19873 (defun org-find-invisible ()
19874 (let ((s (point)))
19875 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19876 (not (get-char-property s 'invisible))))
19879 (defun org-copy-visible (beg end)
19880 "Copy the visible parts of the region."
19881 (interactive "r")
19882 (let (snippets s)
19883 (save-excursion
19884 (save-restriction
19885 (narrow-to-region beg end)
19886 (setq s (goto-char (point-min)))
19887 (while (not (= (point) (point-max)))
19888 (goto-char (org-find-invisible))
19889 (push (buffer-substring s (point)) snippets)
19890 (setq s (goto-char (org-find-visible))))))
19891 (kill-new (apply 'concat (nreverse snippets)))))
19893 (defun org-copy-special ()
19894 "Copy region in table or copy current subtree.
19895 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19896 See the individual commands for more information."
19897 (interactive)
19898 (call-interactively
19899 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19901 (defun org-cut-special ()
19902 "Cut region in table or cut current subtree.
19903 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19904 See the individual commands for more information."
19905 (interactive)
19906 (call-interactively
19907 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19909 (defun org-paste-special (arg)
19910 "Paste rectangular region into table, or past subtree relative to level.
19911 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19912 See the individual commands for more information."
19913 (interactive "P")
19914 (if (org-at-table-p)
19915 (org-table-paste-rectangle)
19916 (org-paste-subtree arg)))
19918 (defsubst org-in-fixed-width-region-p ()
19919 "Is point in a fixed-width region?"
19920 (save-match-data
19921 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19923 (defun org-edit-special (&optional arg)
19924 "Call a special editor for the element at point.
19925 When at a table, call the formula editor with `org-table-edit-formulas'.
19926 When in a source code block, call `org-edit-src-code'.
19927 When in a fixed-width region, call `org-edit-fixed-width-region'.
19928 When at an #+INCLUDE keyword, visit the included file.
19929 On a link, call `ffap' to visit the link at point.
19930 Otherwise, return a user error."
19931 (interactive)
19932 (let ((element (org-element-at-point)))
19933 (assert (not buffer-read-only) nil
19934 "Buffer is read-only: %s" (buffer-name))
19935 (case (org-element-type element)
19936 (src-block
19937 (if (not arg) (org-edit-src-code)
19938 (let* ((info (org-babel-get-src-block-info))
19939 (lang (nth 0 info))
19940 (params (nth 2 info))
19941 (session (cdr (assq :session params))))
19942 (if (not session) (org-edit-src-code)
19943 ;; At a src-block with a session and function called with
19944 ;; an ARG: switch to the buffer related to the inferior
19945 ;; process.
19946 (funcall (intern (concat "org-babel-prep-session:" lang))
19947 session params)))))
19948 (keyword
19949 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19950 (find-file
19951 (org-remove-double-quotes
19952 (car (org-split-string (org-element-property :value element)))))
19953 (user-error "No special environment to edit here")))
19954 (table
19955 (if (eq (org-element-property :type element) 'table.el)
19956 (org-edit-src-code)
19957 (call-interactively 'org-table-edit-formulas)))
19958 ;; Only Org tables contain `table-row' type elements.
19959 (table-row (call-interactively 'org-table-edit-formulas))
19960 ((example-block export-block) (org-edit-src-code))
19961 (fixed-width (org-edit-fixed-width-region))
19962 (otherwise
19963 ;; No notable element at point. Though, we may be at a link,
19964 ;; which is an object. Thus, scan deeper.
19965 (if (eq (org-element-type (org-element-context element)) 'link)
19966 (call-interactively 'ffap)
19967 (user-error "No special environment to edit here"))))))
19969 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19970 (defun org-ctrl-c-ctrl-c (&optional arg)
19971 "Set tags in headline, or update according to changed information at point.
19973 This command does many different things, depending on context:
19975 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19976 this is what we do.
19978 - If the cursor is on a statistics cookie, update it.
19980 - If the cursor is in a headline, prompt for tags and insert them
19981 into the current line, aligned to `org-tags-column'. When called
19982 with prefix arg, realign all tags in the current buffer.
19984 - If the cursor is in one of the special #+KEYWORD lines, this
19985 triggers scanning the buffer for these lines and updating the
19986 information.
19988 - If the cursor is inside a table, realign the table. This command
19989 works even if the automatic table editor has been turned off.
19991 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19992 the entire table.
19994 - If the cursor is at a footnote reference or definition, jump to
19995 the corresponding definition or references, respectively.
19997 - If the cursor is a the beginning of a dynamic block, update it.
19999 - If the current buffer is a capture buffer, close note and file it.
20001 - If the cursor is on a <<<target>>>, update radio targets and
20002 corresponding links in this buffer.
20004 - If the cursor is on a numbered item in a plain list, renumber the
20005 ordered list.
20007 - If the cursor is on a checkbox, toggle it.
20009 - If the cursor is on a code block, evaluate it. The variable
20010 `org-confirm-babel-evaluate' can be used to control prompting
20011 before code block evaluation, by default every code block
20012 evaluation requires confirmation. Code block evaluation can be
20013 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20014 (interactive "P")
20015 (cond
20016 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20017 org-occur-highlights
20018 org-latex-fragment-image-overlays)
20019 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20020 (org-remove-occur-highlights)
20021 (org-remove-latex-fragment-image-overlays)
20022 (message "Temporary highlights/overlays removed from current buffer"))
20023 ((and (local-variable-p 'org-finish-function (current-buffer))
20024 (fboundp org-finish-function))
20025 (funcall org-finish-function))
20026 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20028 (let* ((context (org-element-context)) (type (org-element-type context)))
20029 ;; Test if point is within a blank line.
20030 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20031 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20032 (user-error "C-c C-c can do nothing useful at this location"))
20033 ;; For convenience: at the first line of a paragraph on the
20034 ;; same line as an item, apply function on that item instead.
20035 (when (eq type 'paragraph)
20036 (let ((parent (org-element-property :parent context)))
20037 (when (and (eq (org-element-type parent) 'item)
20038 (= (point-at-bol) (org-element-property :begin parent)))
20039 (setq context parent type 'item))))
20040 ;; Act according to type of element or object at point.
20041 (case type
20042 (clock (org-clock-update-time-maybe))
20043 (dynamic-block
20044 (save-excursion
20045 (goto-char (org-element-property :post-affiliated context))
20046 (org-update-dblock)))
20047 (footnote-definition
20048 (goto-char (org-element-property :post-affiliated context))
20049 (call-interactively 'org-footnote-action))
20050 (footnote-reference (call-interactively 'org-footnote-action))
20051 ((headline inlinetask)
20052 (save-excursion (goto-char (org-element-property :begin context))
20053 (call-interactively 'org-set-tags)))
20054 (item
20055 ;; At an item: a double C-u set checkbox to "[-]"
20056 ;; unconditionally, whereas a single one will toggle its
20057 ;; presence. Without an universal argument, if the item
20058 ;; has a checkbox, toggle it. Otherwise repair the list.
20059 (let* ((box (org-element-property :checkbox context))
20060 (struct (org-element-property :structure context))
20061 (old-struct (copy-tree struct))
20062 (parents (org-list-parents-alist struct))
20063 (prevs (org-list-prevs-alist struct))
20064 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20065 (org-list-set-checkbox
20066 (org-element-property :begin context) struct
20067 (cond ((equal arg '(16)) "[-]")
20068 ((and (not box) (equal arg '(4))) "[ ]")
20069 ((or (not box) (equal arg '(4))) nil)
20070 ((eq box 'on) "[ ]")
20071 (t "[X]")))
20072 ;; Mimic `org-list-write-struct' but with grabbing
20073 ;; a return value from `org-list-struct-fix-box'.
20074 (org-list-struct-fix-ind struct parents 2)
20075 (org-list-struct-fix-item-end struct)
20076 (org-list-struct-fix-bul struct prevs)
20077 (org-list-struct-fix-ind struct parents)
20078 (let ((block-item
20079 (org-list-struct-fix-box struct parents prevs orderedp)))
20080 (if (and box (equal struct old-struct))
20081 (if (equal arg '(16))
20082 (message "Checkboxes already reset")
20083 (user-error "Cannot toggle this checkbox: %s"
20084 (if (eq box 'on)
20085 "all subitems checked"
20086 "unchecked subitems")))
20087 (org-list-struct-apply-struct struct old-struct)
20088 (org-update-checkbox-count-maybe))
20089 (when block-item
20090 (message "Checkboxes were removed due to empty box at line %d"
20091 (org-current-line block-item))))))
20092 (keyword
20093 (let ((org-inhibit-startup-visibility-stuff t)
20094 (org-startup-align-all-tables nil))
20095 (when (boundp 'org-table-coordinate-overlays)
20096 (mapc 'delete-overlay org-table-coordinate-overlays)
20097 (setq org-table-coordinate-overlays nil))
20098 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20099 (message "Local setup has been refreshed"))
20100 (plain-list
20101 ;; At a plain list, with a double C-u argument, set
20102 ;; checkboxes of each item to "[-]", whereas a single one
20103 ;; will toggle their presence according to the state of the
20104 ;; first item in the list. Without an argument, repair the
20105 ;; list.
20106 (let* ((begin (org-element-property :contents-begin context))
20107 (struct (org-element-property :structure context))
20108 (old-struct (copy-tree struct))
20109 (first-box (save-excursion
20110 (goto-char begin)
20111 (looking-at org-list-full-item-re)
20112 (match-string-no-properties 3)))
20113 (new-box (cond ((equal arg '(16)) "[-]")
20114 ((equal arg '(4)) (unless first-box "[ ]"))
20115 ((equal first-box "[X]") "[ ]")
20116 (t "[X]"))))
20117 (cond
20118 (arg
20119 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20120 (org-list-get-all-items
20121 begin struct (org-list-prevs-alist struct))))
20122 ((and first-box (eq (point) begin))
20123 ;; For convenience, when point is at bol on the first
20124 ;; item of the list and no argument is provided, simply
20125 ;; toggle checkbox of that item, if any.
20126 (org-list-set-checkbox begin struct new-box)))
20127 (org-list-write-struct
20128 struct (org-list-parents-alist struct) old-struct)
20129 (org-update-checkbox-count-maybe)
20130 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
20131 ((property-drawer node-property)
20132 (call-interactively 'org-property-action))
20133 ((radio-target target)
20134 (call-interactively 'org-update-radio-target-regexp))
20135 (statistics-cookie
20136 (call-interactively 'org-update-statistics-cookies))
20137 ((table table-cell table-row)
20138 ;; At a table, recalculate every field and align it. Also
20139 ;; send the table if necessary. If the table has
20140 ;; a `table.el' type, just give up. At a table row or
20141 ;; cell, maybe recalculate line but always align table.
20142 (if (eq (org-element-property :type context) 'table.el)
20143 (message "Use C-c ' to edit table.el tables")
20144 (let ((org-enable-table-editor t))
20145 (if (or (eq type 'table)
20146 ;; Check if point is at a TBLFM line.
20147 (and (eq type 'table-row)
20148 (= (point) (org-element-property :end context))))
20149 (save-excursion
20150 (goto-char (org-element-property :contents-begin context))
20151 (org-call-with-arg 'org-table-recalculate (or arg t))
20152 (orgtbl-send-table 'maybe))
20153 (org-table-maybe-eval-formula)
20154 (cond (arg (call-interactively 'org-table-recalculate))
20155 ((org-table-maybe-recalculate-line))
20156 (t (org-table-align)))))))
20157 (timestamp (org-timestamp-change 0 'day))
20158 (otherwise
20159 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20160 (user-error
20161 "C-c C-c can do nothing useful at this location")))))))))
20163 (defun org-mode-restart ()
20164 "Restart Org-mode, to scan again for special lines.
20165 Also updates the keyword regular expressions."
20166 (interactive)
20167 (org-mode)
20168 (message "Org-mode restarted"))
20170 (defun org-kill-note-or-show-branches ()
20171 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20172 (interactive)
20173 (if (not org-finish-function)
20174 (progn
20175 (hide-subtree)
20176 (call-interactively 'show-branches))
20177 (let ((org-note-abort t))
20178 (funcall org-finish-function))))
20180 (defun org-return (&optional indent)
20181 "Goto next table row or insert a newline.
20182 Calls `org-table-next-row' or `newline', depending on context.
20183 See the individual commands for more information."
20184 (interactive)
20185 (let (org-ts-what)
20186 (cond
20187 ((or (bobp) (org-in-src-block-p))
20188 (if indent (newline-and-indent) (newline)))
20189 ((org-at-table-p)
20190 (org-table-justify-field-maybe)
20191 (call-interactively 'org-table-next-row))
20192 ;; when `newline-and-indent' is called within a list, make sure
20193 ;; text moved stays inside the item.
20194 ((and (org-in-item-p) indent)
20195 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20196 (progn
20197 (save-match-data (newline))
20198 (org-indent-line-to (length (match-string 0))))
20199 (let ((ind (org-get-indentation)))
20200 (newline)
20201 (if (org-looking-back org-list-end-re)
20202 (org-indent-line)
20203 (org-indent-line-to ind)))))
20204 ((and org-return-follows-link
20205 (org-at-timestamp-p t)
20206 (not (eq org-ts-what 'after)))
20207 (org-follow-timestamp-link))
20208 ((and org-return-follows-link
20209 (let ((tprop (get-text-property (point) 'face)))
20210 (or (eq tprop 'org-link)
20211 (and (listp tprop) (memq 'org-link tprop)))))
20212 (call-interactively 'org-open-at-point))
20213 ((and (org-at-heading-p)
20214 (looking-at
20215 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20216 (org-show-entry)
20217 (end-of-line 1)
20218 (newline))
20219 (t (if indent (newline-and-indent) (newline))))))
20221 (defun org-return-indent ()
20222 "Goto next table row or insert a newline and indent.
20223 Calls `org-table-next-row' or `newline-and-indent', depending on
20224 context. See the individual commands for more information."
20225 (interactive)
20226 (org-return t))
20228 (defun org-ctrl-c-star ()
20229 "Compute table, or change heading status of lines.
20230 Calls `org-table-recalculate' or `org-toggle-heading',
20231 depending on context."
20232 (interactive)
20233 (cond
20234 ((org-at-table-p)
20235 (call-interactively 'org-table-recalculate))
20237 ;; Convert all lines in region to list items
20238 (call-interactively 'org-toggle-heading))))
20240 (defun org-ctrl-c-minus ()
20241 "Insert separator line in table or modify bullet status of line.
20242 Also turns a plain line or a region of lines into list items.
20243 Calls `org-table-insert-hline', `org-toggle-item', or
20244 `org-cycle-list-bullet', depending on context."
20245 (interactive)
20246 (cond
20247 ((org-at-table-p)
20248 (call-interactively 'org-table-insert-hline))
20249 ((org-region-active-p)
20250 (call-interactively 'org-toggle-item))
20251 ((org-in-item-p)
20252 (call-interactively 'org-cycle-list-bullet))
20254 (call-interactively 'org-toggle-item))))
20256 (defun org-toggle-item (arg)
20257 "Convert headings or normal lines to items, items to normal lines.
20258 If there is no active region, only the current line is considered.
20260 If the first non blank line in the region is a headline, convert
20261 all headlines to items, shifting text accordingly.
20263 If it is an item, convert all items to normal lines.
20265 If it is normal text, change region into a list of items.
20266 With a prefix argument ARG, change the region in a single item."
20267 (interactive "P")
20268 (let ((shift-text
20269 (function
20270 ;; Shift text in current section to IND, from point to END.
20271 ;; The function leaves point to END line.
20272 (lambda (ind end)
20273 (let ((min-i 1000) (end (copy-marker end)))
20274 ;; First determine the minimum indentation (MIN-I) of
20275 ;; the text.
20276 (save-excursion
20277 (catch 'exit
20278 (while (< (point) end)
20279 (let ((i (org-get-indentation)))
20280 (cond
20281 ;; Skip blank lines and inline tasks.
20282 ((looking-at "^[ \t]*$"))
20283 ((looking-at org-outline-regexp-bol))
20284 ;; We can't find less than 0 indentation.
20285 ((zerop i) (throw 'exit (setq min-i 0)))
20286 ((< i min-i) (setq min-i i))))
20287 (forward-line))))
20288 ;; Then indent each line so that a line indented to
20289 ;; MIN-I becomes indented to IND. Ignore blank lines
20290 ;; and inline tasks in the process.
20291 (let ((delta (- ind min-i)))
20292 (while (< (point) end)
20293 (unless (or (looking-at "^[ \t]*$")
20294 (looking-at org-outline-regexp-bol))
20295 (org-indent-line-to (+ (org-get-indentation) delta)))
20296 (forward-line)))))))
20297 (skip-blanks
20298 (function
20299 ;; Return beginning of first non-blank line, starting from
20300 ;; line at POS.
20301 (lambda (pos)
20302 (save-excursion
20303 (goto-char pos)
20304 (skip-chars-forward " \r\t\n")
20305 (point-at-bol)))))
20306 beg end)
20307 ;; Determine boundaries of changes.
20308 (if (org-region-active-p)
20309 (setq beg (funcall skip-blanks (region-beginning))
20310 end (copy-marker (region-end)))
20311 (setq beg (funcall skip-blanks (point-at-bol))
20312 end (copy-marker (point-at-eol))))
20313 ;; Depending on the starting line, choose an action on the text
20314 ;; between BEG and END.
20315 (org-with-limited-levels
20316 (save-excursion
20317 (goto-char beg)
20318 (cond
20319 ;; Case 1. Start at an item: de-itemize. Note that it only
20320 ;; happens when a region is active: `org-ctrl-c-minus'
20321 ;; would call `org-cycle-list-bullet' otherwise.
20322 ((org-at-item-p)
20323 (while (< (point) end)
20324 (when (org-at-item-p)
20325 (skip-chars-forward " \t")
20326 (delete-region (point) (match-end 0)))
20327 (forward-line)))
20328 ;; Case 2. Start at an heading: convert to items.
20329 ((org-at-heading-p)
20330 (let* ((bul (org-list-bullet-string "-"))
20331 (bul-len (length bul))
20332 ;; Indentation of the first heading. It should be
20333 ;; relative to the indentation of its parent, if any.
20334 (start-ind (save-excursion
20335 (cond
20336 ((not org-adapt-indentation) 0)
20337 ((not (outline-previous-heading)) 0)
20338 (t (length (match-string 0))))))
20339 ;; Level of first heading. Further headings will be
20340 ;; compared to it to determine hierarchy in the list.
20341 (ref-level (org-reduced-level (org-outline-level))))
20342 (while (< (point) end)
20343 (let* ((level (org-reduced-level (org-outline-level)))
20344 (delta (max 0 (- level ref-level))))
20345 ;; If current headline is less indented than the first
20346 ;; one, set it as reference, in order to preserve
20347 ;; subtrees.
20348 (when (< level ref-level) (setq ref-level level))
20349 (replace-match bul t t)
20350 (org-indent-line-to (+ start-ind (* delta bul-len)))
20351 ;; Ensure all text down to END (or SECTION-END) belongs
20352 ;; to the newly created item.
20353 (let ((section-end (save-excursion
20354 (or (outline-next-heading) (point)))))
20355 (forward-line)
20356 (funcall shift-text
20357 (+ start-ind (* (1+ delta) bul-len))
20358 (min end section-end)))))))
20359 ;; Case 3. Normal line with ARG: make the first line of region
20360 ;; an item, and shift indentation of others lines to
20361 ;; set them as item's body.
20362 (arg (let* ((bul (org-list-bullet-string "-"))
20363 (bul-len (length bul))
20364 (ref-ind (org-get-indentation)))
20365 (skip-chars-forward " \t")
20366 (insert bul)
20367 (forward-line)
20368 (while (< (point) end)
20369 ;; Ensure that lines less indented than first one
20370 ;; still get included in item body.
20371 (funcall shift-text
20372 (+ ref-ind bul-len)
20373 (min end (save-excursion (or (outline-next-heading)
20374 (point)))))
20375 (forward-line))))
20376 ;; Case 4. Normal line without ARG: turn each non-item line
20377 ;; into an item.
20379 (while (< (point) end)
20380 (unless (or (org-at-heading-p) (org-at-item-p))
20381 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20382 (replace-match
20383 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20384 (forward-line))))))))
20386 (defun org-toggle-heading (&optional nstars)
20387 "Convert headings to normal text, or items or text to headings.
20388 If there is no active region, only convert the current line.
20390 With a \\[universal-argument] prefix, convert the whole list at
20391 point into heading.
20393 In a region:
20395 - If the first non blank line is a headline, remove the stars
20396 from all headlines in the region.
20398 - If it is a normal line, turn each and every normal line (i.e.,
20399 not an heading or an item) in the region into headings. If you
20400 want to convert only the first line of this region, use one
20401 universal prefix argument.
20403 - If it is a plain list item, turn all plain list items into headings.
20405 When converting a line into a heading, the number of stars is chosen
20406 such that the lines become children of the current entry. However,
20407 when a numeric prefix argument is given, its value determines the
20408 number of stars to add."
20409 (interactive "P")
20410 (let ((skip-blanks
20411 (function
20412 ;; Return beginning of first non-blank line, starting from
20413 ;; line at POS.
20414 (lambda (pos)
20415 (save-excursion
20416 (goto-char pos)
20417 (while (org-at-comment-p) (forward-line))
20418 (skip-chars-forward " \r\t\n")
20419 (point-at-bol)))))
20420 beg end toggled)
20421 ;; Determine boundaries of changes. If a universal prefix has
20422 ;; been given, put the list in a region. If region ends at a bol,
20423 ;; do not consider the last line to be in the region.
20425 (when (and current-prefix-arg (org-at-item-p))
20426 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20427 (org-mark-element))
20429 (if (org-region-active-p)
20430 (setq beg (funcall skip-blanks (region-beginning))
20431 end (copy-marker (save-excursion
20432 (goto-char (region-end))
20433 (if (bolp) (point) (point-at-eol)))))
20434 (setq beg (funcall skip-blanks (point-at-bol))
20435 end (copy-marker (point-at-eol))))
20436 ;; Ensure inline tasks don't count as headings.
20437 (org-with-limited-levels
20438 (save-excursion
20439 (goto-char beg)
20440 (cond
20441 ;; Case 1. Started at an heading: de-star headings.
20442 ((org-at-heading-p)
20443 (while (< (point) end)
20444 (when (org-at-heading-p t)
20445 (looking-at org-outline-regexp) (replace-match "")
20446 (setq toggled t))
20447 (forward-line)))
20448 ;; Case 2. Started at an item: change items into headlines.
20449 ;; One star will be added by `org-list-to-subtree'.
20450 ((org-at-item-p)
20451 (let* ((stars (make-string
20452 ;; subtract the star that will be added again by
20453 ;; `org-list-to-subtree'
20454 (if (numberp nstars) (1- nstars)
20455 (or (org-current-level) 0))
20456 ?*))
20457 (add-stars
20458 (cond (nstars "") ; stars from prefix only
20459 ((equal stars "") "") ; before first heading
20460 (org-odd-levels-only "*") ; inside heading, odd
20461 (t "")))) ; inside heading, oddeven
20462 (while (< (point) end)
20463 (when (org-at-item-p)
20464 ;; Pay attention to cases when region ends before list.
20465 (let* ((struct (org-list-struct))
20466 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20467 (save-restriction
20468 (narrow-to-region (point) list-end)
20469 (insert
20470 (org-list-to-subtree
20471 (org-list-parse-list t)
20472 '(:istart (concat stars add-stars (funcall get-stars depth))
20473 :icount (concat stars add-stars (funcall get-stars depth)))))))
20474 (setq toggled t))
20475 (forward-line))))
20476 ;; Case 3. Started at normal text: make every line an heading,
20477 ;; skipping headlines and items.
20478 (t (let* ((stars
20479 (make-string
20480 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20481 (add-stars
20482 (cond (nstars "") ; stars from prefix only
20483 ((equal stars "") "*") ; before first heading
20484 (org-odd-levels-only "**") ; inside heading, odd
20485 (t "*"))) ; inside heading, oddeven
20486 (rpl (concat stars add-stars " "))
20487 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20488 (while (< (point) (if (equal nstars '(4)) lend end))
20489 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20490 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20491 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20492 (forward-line)))))))
20493 (unless toggled (message "Cannot toggle heading from here"))))
20495 (defun org-meta-return (&optional arg)
20496 "Insert a new heading or wrap a region in a table.
20497 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20498 See the individual commands for more information."
20499 (interactive "P")
20500 (cond
20501 ((run-hook-with-args-until-success 'org-metareturn-hook))
20502 ((or (org-at-drawer-p) (org-at-property-p))
20503 (newline-and-indent))
20504 ((org-at-table-p)
20505 (call-interactively 'org-table-wrap-region))
20506 (t (call-interactively 'org-insert-heading))))
20508 ;;; Menu entries
20510 (defsubst org-in-subtree-not-table-p ()
20511 "Are we in a subtree and not in a table?"
20512 (and (not (org-before-first-heading-p))
20513 (not (org-at-table-p))))
20515 ;; Define the Org-mode menus
20516 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20517 '("Tbl"
20518 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20519 ["Next Field" org-cycle (org-at-table-p)]
20520 ["Previous Field" org-shifttab (org-at-table-p)]
20521 ["Next Row" org-return (org-at-table-p)]
20522 "--"
20523 ["Blank Field" org-table-blank-field (org-at-table-p)]
20524 ["Edit Field" org-table-edit-field (org-at-table-p)]
20525 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20526 "--"
20527 ("Column"
20528 ["Move Column Left" org-metaleft (org-at-table-p)]
20529 ["Move Column Right" org-metaright (org-at-table-p)]
20530 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20531 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20532 ("Row"
20533 ["Move Row Up" org-metaup (org-at-table-p)]
20534 ["Move Row Down" org-metadown (org-at-table-p)]
20535 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20536 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20537 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20538 "--"
20539 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20540 ("Rectangle"
20541 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20542 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20543 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20544 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20545 "--"
20546 ("Calculate"
20547 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20548 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20549 ["Edit Formulas" org-edit-special (org-at-table-p)]
20550 "--"
20551 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20552 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20553 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20554 "--"
20555 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20556 "--"
20557 ["Sum Column/Rectangle" org-table-sum
20558 (or (org-at-table-p) (org-region-active-p))]
20559 ["Which Column?" org-table-current-column (org-at-table-p)])
20560 ["Debug Formulas"
20561 org-table-toggle-formula-debugger
20562 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20563 ["Show Col/Row Numbers"
20564 org-table-toggle-coordinate-overlays
20565 :style toggle
20566 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20567 "--"
20568 ["Create" org-table-create (and (not (org-at-table-p))
20569 org-enable-table-editor)]
20570 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20571 ["Import from File" org-table-import (not (org-at-table-p))]
20572 ["Export to File" org-table-export (org-at-table-p)]
20573 "--"
20574 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20576 (easy-menu-define org-org-menu org-mode-map "Org menu"
20577 '("Org"
20578 ("Show/Hide"
20579 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20580 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20581 ["Sparse Tree..." org-sparse-tree t]
20582 ["Reveal Context" org-reveal t]
20583 ["Show All" show-all t]
20584 "--"
20585 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20586 "--"
20587 ["New Heading" org-insert-heading t]
20588 ("Navigate Headings"
20589 ["Up" outline-up-heading t]
20590 ["Next" outline-next-visible-heading t]
20591 ["Previous" outline-previous-visible-heading t]
20592 ["Next Same Level" outline-forward-same-level t]
20593 ["Previous Same Level" outline-backward-same-level t]
20594 "--"
20595 ["Jump" org-goto t])
20596 ("Edit Structure"
20597 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20598 "--"
20599 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20600 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20601 "--"
20602 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20603 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20604 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20605 "--"
20606 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20607 "--"
20608 ["Copy visible text" org-copy-visible t]
20609 "--"
20610 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20611 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20612 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20613 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20614 "--"
20615 ["Sort Region/Children" org-sort t]
20616 "--"
20617 ["Convert to odd levels" org-convert-to-odd-levels t]
20618 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20619 ("Editing"
20620 ["Emphasis..." org-emphasize t]
20621 ["Edit Source Example" org-edit-special t]
20622 "--"
20623 ["Footnote new/jump" org-footnote-action t]
20624 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20625 ("Archive"
20626 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20627 "--"
20628 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20629 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20630 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20632 "--"
20633 ("Hyperlinks"
20634 ["Store Link (Global)" org-store-link t]
20635 ["Find existing link to here" org-occur-link-in-agenda-files t]
20636 ["Insert Link" org-insert-link t]
20637 ["Follow Link" org-open-at-point t]
20638 "--"
20639 ["Next link" org-next-link t]
20640 ["Previous link" org-previous-link t]
20641 "--"
20642 ["Descriptive Links"
20643 org-toggle-link-display
20644 :style radio
20645 :selected org-descriptive-links
20647 ["Literal Links"
20648 org-toggle-link-display
20649 :style radio
20650 :selected (not org-descriptive-links)])
20651 "--"
20652 ("TODO Lists"
20653 ["TODO/DONE/-" org-todo t]
20654 ("Select keyword"
20655 ["Next keyword" org-shiftright (org-at-heading-p)]
20656 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20657 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20658 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20659 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20660 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20661 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20662 "--"
20663 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20664 :selected org-enforce-todo-dependencies :style toggle :active t]
20665 "Settings for tree at point"
20666 ["Do Children sequentially" org-toggle-ordered-property :style radio
20667 :selected (org-entry-get nil "ORDERED")
20668 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20669 ["Do Children parallel" org-toggle-ordered-property :style radio
20670 :selected (not (org-entry-get nil "ORDERED"))
20671 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20672 "--"
20673 ["Set Priority" org-priority t]
20674 ["Priority Up" org-shiftup t]
20675 ["Priority Down" org-shiftdown t]
20676 "--"
20677 ["Get news from all feeds" org-feed-update-all t]
20678 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20679 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20680 ("TAGS and Properties"
20681 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20682 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20683 "--"
20684 ["Set property" org-set-property (not (org-before-first-heading-p))]
20685 ["Column view of properties" org-columns t]
20686 ["Insert Column View DBlock" org-insert-columns-dblock t])
20687 ("Dates and Scheduling"
20688 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20689 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20690 ("Change Date"
20691 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20692 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20693 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20694 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20695 ["Compute Time Range" org-evaluate-time-range t]
20696 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20697 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20698 "--"
20699 ["Custom time format" org-toggle-time-stamp-overlays
20700 :style radio :selected org-display-custom-times]
20701 "--"
20702 ["Goto Calendar" org-goto-calendar t]
20703 ["Date from Calendar" org-date-from-calendar t]
20704 "--"
20705 ["Start/Restart Timer" org-timer-start t]
20706 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20707 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20708 ["Insert Timer String" org-timer t]
20709 ["Insert Timer Item" org-timer-item t])
20710 ("Logging work"
20711 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20712 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20713 ["Clock out" org-clock-out t]
20714 ["Clock cancel" org-clock-cancel t]
20715 "--"
20716 ["Mark as default task" org-clock-mark-default-task t]
20717 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20718 ["Goto running clock" org-clock-goto t]
20719 "--"
20720 ["Display times" org-clock-display t]
20721 ["Create clock table" org-clock-report t]
20722 "--"
20723 ["Record DONE time"
20724 (progn (setq org-log-done (not org-log-done))
20725 (message "Switching to %s will %s record a timestamp"
20726 (car org-done-keywords)
20727 (if org-log-done "automatically" "not")))
20728 :style toggle :selected org-log-done])
20729 "--"
20730 ["Agenda Command..." org-agenda t]
20731 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20732 ("File List for Agenda")
20733 ("Special views current file"
20734 ["TODO Tree" org-show-todo-tree t]
20735 ["Check Deadlines" org-check-deadlines t]
20736 ["Timeline" org-timeline t]
20737 ["Tags/Property tree" org-match-sparse-tree t])
20738 "--"
20739 ["Export/Publish..." org-export-dispatch t]
20740 ("LaTeX"
20741 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20742 :selected org-cdlatex-mode]
20743 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20744 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20745 ["Modify math symbol" org-cdlatex-math-modify
20746 (org-inside-LaTeX-fragment-p)]
20747 ["Insert citation" org-reftex-citation t]
20748 "--"
20749 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20750 "--"
20751 ("MobileOrg"
20752 ["Push Files and Views" org-mobile-push t]
20753 ["Get Captured and Flagged" org-mobile-pull t]
20754 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20755 "--"
20756 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20757 "--"
20758 ("Documentation"
20759 ["Show Version" org-version t]
20760 ["Info Documentation" org-info t])
20761 ("Customize"
20762 ["Browse Org Group" org-customize t]
20763 "--"
20764 ["Expand This Menu" org-create-customize-menu
20765 (fboundp 'customize-menu-create)])
20766 ["Send bug report" org-submit-bug-report t]
20767 "--"
20768 ("Refresh/Reload"
20769 ["Refresh setup current buffer" org-mode-restart t]
20770 ["Reload Org (after update)" org-reload t]
20771 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20774 (defun org-info (&optional node)
20775 "Read documentation for Org-mode in the info system.
20776 With optional NODE, go directly to that node."
20777 (interactive)
20778 (info (format "(org)%s" (or node ""))))
20780 ;;;###autoload
20781 (defun org-submit-bug-report ()
20782 "Submit a bug report on Org-mode via mail.
20784 Don't hesitate to report any problems or inaccurate documentation.
20786 If you don't have setup sending mail from (X)Emacs, please copy the
20787 output buffer into your mail program, as it gives us important
20788 information about your Org-mode version and configuration."
20789 (interactive)
20790 (require 'reporter)
20791 (org-load-modules-maybe)
20792 (org-require-autoloaded-modules)
20793 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20794 (reporter-submit-bug-report
20795 "emacs-orgmode@gnu.org"
20796 (org-version nil 'full)
20797 (let (list)
20798 (save-window-excursion
20799 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20800 (delete-other-windows)
20801 (erase-buffer)
20802 (insert "You are about to submit a bug report to the Org-mode mailing list.
20804 We would like to add your full Org-mode and Outline configuration to the
20805 bug report. This greatly simplifies the work of the maintainer and
20806 other experts on the mailing list.
20808 HOWEVER, some variables you have customized may contain private
20809 information. The names of customers, colleagues, or friends, might
20810 appear in the form of file names, tags, todo states, or search strings.
20811 If you answer yes to the prompt, you might want to check and remove
20812 such private information before sending the email.")
20813 (add-text-properties (point-min) (point-max) '(face org-warning))
20814 (when (yes-or-no-p "Include your Org-mode configuration ")
20815 (mapatoms
20816 (lambda (v)
20817 (and (boundp v)
20818 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20819 (or (and (symbol-value v)
20820 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20821 (and
20822 (get v 'custom-type) (get v 'standard-value)
20823 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20824 (push v list)))))
20825 (kill-buffer (get-buffer "*Warn about privacy*"))
20826 list))
20827 nil nil
20828 "Remember to cover the basics, that is, what you expected to happen and
20829 what in fact did happen. You don't know how to make a good report? See
20831 http://orgmode.org/manual/Feedback.html#Feedback
20833 Your bug report will be posted to the Org-mode mailing list.
20834 ------------------------------------------------------------------------")
20835 (save-excursion
20836 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20837 (replace-match "\\1Bug: \\3 [\\2]")))))
20840 (defun org-install-agenda-files-menu ()
20841 (let ((bl (buffer-list)))
20842 (save-excursion
20843 (while bl
20844 (set-buffer (pop bl))
20845 (if (derived-mode-p 'org-mode) (setq bl nil)))
20846 (when (derived-mode-p 'org-mode)
20847 (easy-menu-change
20848 '("Org") "File List for Agenda"
20849 (append
20850 (list
20851 ["Edit File List" (org-edit-agenda-file-list) t]
20852 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20853 ["Remove Current File from List" org-remove-file t]
20854 ["Cycle through agenda files" org-cycle-agenda-files t]
20855 ["Occur in all agenda files" org-occur-in-agenda-files t]
20856 "--")
20857 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20859 ;;;; Documentation
20861 (defun org-require-autoloaded-modules ()
20862 (interactive)
20863 (mapc 'require
20864 '(org-agenda org-archive org-attach org-clock org-colview org-id
20865 org-remember org-table org-timer)))
20867 ;;;###autoload
20868 (defun org-reload (&optional uncompiled)
20869 "Reload all org lisp files.
20870 With prefix arg UNCOMPILED, load the uncompiled versions."
20871 (interactive "P")
20872 (require 'loadhist)
20873 (let* ((org-dir (org-find-library-dir "org"))
20874 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20875 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20876 (remove-re (mapconcat 'identity
20877 (mapcar (lambda (f) (concat "^" f "$"))
20878 (list (if (featurep 'xemacs)
20879 "org-colview"
20880 "org-colview-xemacs")
20881 "org" "org-loaddefs" "org-version"))
20882 "\\|"))
20883 (feats (delete-dups
20884 (mapcar 'file-name-sans-extension
20885 (mapcar 'file-name-nondirectory
20886 (delq nil
20887 (mapcar 'feature-file
20888 features))))))
20889 (lfeat (append
20890 (sort
20891 (setq feats
20892 (delq nil (mapcar
20893 (lambda (f)
20894 (if (and (string-match feature-re f)
20895 (not (string-match remove-re f)))
20896 f nil))
20897 feats)))
20898 'string-lessp)
20899 (list "org-version" "org")))
20900 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20901 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20902 load-uncore load-misses)
20903 (setq load-misses
20904 (delq 't
20905 (mapcar (lambda (f)
20906 (or (org-load-noerror-mustsuffix (concat org-dir f))
20907 (and (string= org-dir contrib-dir)
20908 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20909 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20910 (add-to-list 'load-uncore f 'append)
20913 lfeat)))
20914 (if load-uncore
20915 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20916 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20917 (if load-misses
20918 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20919 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20920 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20922 ;;;###autoload
20923 (defun org-customize ()
20924 "Call the customize function with org as argument."
20925 (interactive)
20926 (org-load-modules-maybe)
20927 (org-require-autoloaded-modules)
20928 (customize-browse 'org))
20930 (defun org-create-customize-menu ()
20931 "Create a full customization menu for Org-mode, insert it into the menu."
20932 (interactive)
20933 (org-load-modules-maybe)
20934 (org-require-autoloaded-modules)
20935 (if (fboundp 'customize-menu-create)
20936 (progn
20937 (easy-menu-change
20938 '("Org") "Customize"
20939 `(["Browse Org group" org-customize t]
20940 "--"
20941 ,(customize-menu-create 'org)
20942 ["Set" Custom-set t]
20943 ["Save" Custom-save t]
20944 ["Reset to Current" Custom-reset-current t]
20945 ["Reset to Saved" Custom-reset-saved t]
20946 ["Reset to Standard Settings" Custom-reset-standard t]))
20947 (message "\"Org\"-menu now contains full customization menu"))
20948 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20950 ;;;; Miscellaneous stuff
20952 ;;; Generally useful functions
20954 (defun org-get-at-bol (property)
20955 "Get text property PROPERTY at beginning of line."
20956 (get-text-property (point-at-bol) property))
20958 (defun org-find-text-property-in-string (prop s)
20959 "Return the first non-nil value of property PROP in string S."
20960 (or (get-text-property 0 prop s)
20961 (get-text-property (or (next-single-property-change 0 prop s) 0)
20962 prop s)))
20964 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20965 "Display the given MESSAGE as a warning."
20966 (if (fboundp 'display-warning)
20967 (display-warning 'org message
20968 (if (featurep 'xemacs) 'warning :warning))
20969 (let ((buf (get-buffer-create "*Org warnings*")))
20970 (with-current-buffer buf
20971 (goto-char (point-max))
20972 (insert "Warning (Org): " message)
20973 (unless (bolp)
20974 (newline)))
20975 (display-buffer buf)
20976 (sit-for 0))))
20978 (defun org-eval (form)
20979 "Eval FORM and return result."
20980 (condition-case error
20981 (eval form)
20982 (error (format "%%![Error: %s]" error))))
20984 (defun org-in-clocktable-p ()
20985 "Check if the cursor is in a clocktable."
20986 (let ((pos (point)) start)
20987 (save-excursion
20988 (end-of-line 1)
20989 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20990 (setq start (match-beginning 0))
20991 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20992 (>= (match-end 0) pos)
20993 start))))
20995 (defun org-in-commented-line ()
20996 "Is point in a line starting with `#'?"
20997 (equal (char-after (point-at-bol)) ?#))
20999 (defun org-in-indented-comment-line ()
21000 "Is point in a line starting with `#' after some white space?"
21001 (save-excursion
21002 (save-match-data
21003 (goto-char (point-at-bol))
21004 (looking-at "[ \t]*#"))))
21006 (defun org-in-verbatim-emphasis ()
21007 (save-match-data
21008 (and (org-in-regexp org-emph-re 2)
21009 (>= (point) (match-beginning 3))
21010 (<= (point) (match-end 4))
21011 (member (match-string 3) '("=" "~")))))
21013 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21014 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21015 (if (and marker (marker-buffer marker)
21016 (buffer-live-p (marker-buffer marker)))
21017 (progn
21018 (org-pop-to-buffer-same-window (marker-buffer marker))
21019 (if (or (> marker (point-max)) (< marker (point-min)))
21020 (widen))
21021 (goto-char marker)
21022 (org-show-context 'org-goto))
21023 (if bookmark
21024 (bookmark-jump bookmark)
21025 (error "Cannot find location"))))
21027 (defun org-quote-csv-field (s)
21028 "Quote field for inclusion in CSV material."
21029 (if (string-match "[\",]" s)
21030 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21033 (defun org-force-self-insert (N)
21034 "Needed to enforce self-insert under remapping."
21035 (interactive "p")
21036 (self-insert-command N))
21038 (defun org-string-width (s)
21039 "Compute width of string, ignoring invisible characters.
21040 This ignores character with invisibility property `org-link', and also
21041 characters with property `org-cwidth', because these will become invisible
21042 upon the next fontification round."
21043 (let (b l)
21044 (when (or (eq t buffer-invisibility-spec)
21045 (assq 'org-link buffer-invisibility-spec))
21046 (while (setq b (text-property-any 0 (length s)
21047 'invisible 'org-link s))
21048 (setq s (concat (substring s 0 b)
21049 (substring s (or (next-single-property-change
21050 b 'invisible s) (length s)))))))
21051 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21052 (setq s (concat (substring s 0 b)
21053 (substring s (or (next-single-property-change
21054 b 'org-cwidth s) (length s))))))
21055 (setq l (string-width s) b -1)
21056 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21057 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21060 (defun org-shorten-string (s maxlength)
21061 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21062 If the string is shorter or has length MAXLENGTH, just return the
21063 original string. If it is longer, the functions finds a space in the
21064 string, breaks this string off at that locations and adds three dots
21065 as ellipsis. Including the ellipsis, the string will not be longer
21066 than MAXLENGTH. If finding a good breaking point in the string does
21067 not work, the string is just chopped off in the middle of a word
21068 if necessary."
21069 (if (<= (length s) maxlength)
21071 (let* ((n (max (- maxlength 4) 1))
21072 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21073 (if (string-match re s)
21074 (concat (match-string 1 s) "...")
21075 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21077 (defun org-get-indentation (&optional line)
21078 "Get the indentation of the current line, interpreting tabs.
21079 When LINE is given, assume it represents a line and compute its indentation."
21080 (if line
21081 (if (string-match "^ *" (org-remove-tabs line))
21082 (match-end 0))
21083 (save-excursion
21084 (beginning-of-line 1)
21085 (skip-chars-forward " \t")
21086 (current-column))))
21088 (defun org-get-string-indentation (s)
21089 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21090 (let ((n -1) (i 0) (w tab-width) c)
21091 (catch 'exit
21092 (while (< (setq n (1+ n)) (length s))
21093 (setq c (aref s n))
21094 (cond ((= c ?\ ) (setq i (1+ i)))
21095 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21096 (t (throw 'exit t)))))
21099 (defun org-remove-tabs (s &optional width)
21100 "Replace tabulators in S with spaces.
21101 Assumes that s is a single line, starting in column 0."
21102 (setq width (or width tab-width))
21103 (while (string-match "\t" s)
21104 (setq s (replace-match
21105 (make-string
21106 (- (* width (/ (+ (match-beginning 0) width) width))
21107 (match-beginning 0)) ?\ )
21108 t t s)))
21111 (defun org-fix-indentation (line ind)
21112 "Fix indentation in LINE.
21113 IND is a cons cell with target and minimum indentation.
21114 If the current indentation in LINE is smaller than the minimum,
21115 leave it alone. If it is larger than ind, set it to the target."
21116 (let* ((l (org-remove-tabs line))
21117 (i (org-get-indentation l))
21118 (i1 (car ind)) (i2 (cdr ind)))
21119 (if (>= i i2) (setq l (substring line i2)))
21120 (if (> i1 0)
21121 (concat (make-string i1 ?\ ) l)
21122 l)))
21124 (defun org-remove-indentation (code &optional n)
21125 "Remove the maximum common indentation from the lines in CODE.
21126 N may optionally be the number of spaces to remove."
21127 (with-temp-buffer
21128 (insert code)
21129 (org-do-remove-indentation n)
21130 (buffer-string)))
21132 (defun org-do-remove-indentation (&optional n)
21133 "Remove the maximum common indentation from the buffer."
21134 (untabify (point-min) (point-max))
21135 (let ((min 10000) re)
21136 (if n
21137 (setq min n)
21138 (goto-char (point-min))
21139 (while (re-search-forward "^ *[^ \n]" nil t)
21140 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21141 (unless (or (= min 0) (= min 10000))
21142 (setq re (format "^ \\{%d\\}" min))
21143 (goto-char (point-min))
21144 (while (re-search-forward re nil t)
21145 (replace-match "")
21146 (end-of-line 1))
21147 min)))
21149 (defun org-fill-template (template alist)
21150 "Find each %key of ALIST in TEMPLATE and replace it."
21151 (let ((case-fold-search nil)
21152 entry key value)
21153 (setq alist (sort (copy-sequence alist)
21154 (lambda (a b) (< (length (car a)) (length (car b))))))
21155 (while (setq entry (pop alist))
21156 (setq template
21157 (replace-regexp-in-string
21158 (concat "%" (regexp-quote (car entry)))
21159 (or (cdr entry) "") template t t)))
21160 template))
21162 (defun org-base-buffer (buffer)
21163 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21164 (if (not buffer)
21165 buffer
21166 (or (buffer-base-buffer buffer)
21167 buffer)))
21169 (defun org-trim (s)
21170 "Remove whitespace at beginning and end of string."
21171 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21172 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21175 (defun org-wrap (string &optional width lines)
21176 "Wrap string to either a number of lines, or a width in characters.
21177 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21178 that costs. If there is a word longer than WIDTH, the text is actually
21179 wrapped to the length of that word.
21180 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21181 many lines, whatever width that takes.
21182 The return value is a list of lines, without newlines at the end."
21183 (let* ((words (org-split-string string "[ \t\n]+"))
21184 (maxword (apply 'max (mapcar 'org-string-width words)))
21185 w ll)
21186 (cond (width
21187 (org-do-wrap words (max maxword width)))
21188 (lines
21189 (setq w maxword)
21190 (setq ll (org-do-wrap words maxword))
21191 (if (<= (length ll) lines)
21193 (setq ll words)
21194 (while (> (length ll) lines)
21195 (setq w (1+ w))
21196 (setq ll (org-do-wrap words w)))
21197 ll))
21198 (t (error "Cannot wrap this")))))
21200 (defun org-do-wrap (words width)
21201 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21202 (let (lines line)
21203 (while words
21204 (setq line (pop words))
21205 (while (and words (< (+ (length line) (length (car words))) width))
21206 (setq line (concat line " " (pop words))))
21207 (setq lines (push line lines)))
21208 (nreverse lines)))
21210 (defun org-split-string (string &optional separators)
21211 "Splits STRING into substrings at SEPARATORS.
21212 No empty strings are returned if there are matches at the beginning
21213 and end of string."
21214 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21215 (start 0)
21216 notfirst
21217 (list nil))
21218 (while (and (string-match rexp string
21219 (if (and notfirst
21220 (= start (match-beginning 0))
21221 (< start (length string)))
21222 (1+ start) start))
21223 (< (match-beginning 0) (length string)))
21224 (setq notfirst t)
21225 (or (eq (match-beginning 0) 0)
21226 (and (eq (match-beginning 0) (match-end 0))
21227 (eq (match-beginning 0) start))
21228 (setq list
21229 (cons (substring string start (match-beginning 0))
21230 list)))
21231 (setq start (match-end 0)))
21232 (or (eq start (length string))
21233 (setq list
21234 (cons (substring string start)
21235 list)))
21236 (nreverse list)))
21238 (defun org-quote-vert (s)
21239 "Replace \"|\" with \"\\vert\"."
21240 (while (string-match "|" s)
21241 (setq s (replace-match "\\vert" t t s)))
21244 (defun org-uuidgen-p (s)
21245 "Is S an ID created by UUIDGEN?"
21246 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21248 (defun org-in-src-block-p (&optional inside)
21249 "Whether point is in a code source block.
21250 When INSIDE is non-nil, don't consider we are within a src block
21251 when point is at #+BEGIN_SRC or #+END_SRC."
21252 (let ((case-fold-search t) ov)
21253 (or (and (setq ov (overlays-at (point)))
21254 (memq 'org-block-background
21255 (overlay-properties (car ov))))
21256 (and (not inside)
21257 (save-match-data
21258 (save-excursion
21259 (beginning-of-line)
21260 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21262 (defun org-context ()
21263 "Return a list of contexts of the current cursor position.
21264 If several contexts apply, all are returned.
21265 Each context entry is a list with a symbol naming the context, and
21266 two positions indicating start and end of the context. Possible
21267 contexts are:
21269 :headline anywhere in a headline
21270 :headline-stars on the leading stars in a headline
21271 :todo-keyword on a TODO keyword (including DONE) in a headline
21272 :tags on the TAGS in a headline
21273 :priority on the priority cookie in a headline
21274 :item on the first line of a plain list item
21275 :item-bullet on the bullet/number of a plain list item
21276 :checkbox on the checkbox in a plain list item
21277 :table in an org-mode table
21278 :table-special on a special filed in a table
21279 :table-table in a table.el table
21280 :clocktable in a clocktable
21281 :src-block in a source block
21282 :link on a hyperlink
21283 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21284 :target on a <<target>>
21285 :radio-target on a <<<radio-target>>>
21286 :latex-fragment on a LaTeX fragment
21287 :latex-preview on a LaTeX fragment with overlaid preview image
21289 This function expects the position to be visible because it uses font-lock
21290 faces as a help to recognize the following contexts: :table-special, :link,
21291 and :keyword."
21292 (let* ((f (get-text-property (point) 'face))
21293 (faces (if (listp f) f (list f)))
21294 (case-fold-search t)
21295 (p (point)) clist o)
21296 ;; First the large context
21297 (cond
21298 ((org-at-heading-p t)
21299 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21300 (when (progn
21301 (beginning-of-line 1)
21302 (looking-at org-todo-line-tags-regexp))
21303 (push (org-point-in-group p 1 :headline-stars) clist)
21304 (push (org-point-in-group p 2 :todo-keyword) clist)
21305 (push (org-point-in-group p 4 :tags) clist))
21306 (goto-char p)
21307 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21308 (if (looking-at "\\[#[A-Z0-9]\\]")
21309 (push (org-point-in-group p 0 :priority) clist)))
21311 ((org-at-item-p)
21312 (push (org-point-in-group p 2 :item-bullet) clist)
21313 (push (list :item (point-at-bol)
21314 (save-excursion (org-end-of-item) (point)))
21315 clist)
21316 (and (org-at-item-checkbox-p)
21317 (push (org-point-in-group p 0 :checkbox) clist)))
21319 ((org-at-table-p)
21320 (push (list :table (org-table-begin) (org-table-end)) clist)
21321 (if (memq 'org-formula faces)
21322 (push (list :table-special
21323 (previous-single-property-change p 'face)
21324 (next-single-property-change p 'face)) clist)))
21325 ((org-at-table-p 'any)
21326 (push (list :table-table) clist)))
21327 (goto-char p)
21329 (let ((case-fold-search t))
21330 ;; New the "medium" contexts: clocktables, source blocks
21331 (cond ((org-in-clocktable-p)
21332 (push (list :clocktable
21333 (and (or (looking-at "#\\+BEGIN: clocktable")
21334 (search-backward "#+BEGIN: clocktable" nil t))
21335 (match-beginning 0))
21336 (and (re-search-forward "#\\+END:?" nil t)
21337 (match-end 0))) clist))
21338 ((org-in-src-block-p)
21339 (push (list :src-block
21340 (and (or (looking-at "#\\+BEGIN_SRC")
21341 (search-backward "#+BEGIN_SRC" nil t))
21342 (match-beginning 0))
21343 (and (search-forward "#+END_SRC" nil t)
21344 (match-beginning 0))) clist))))
21345 (goto-char p)
21347 ;; Now the small context
21348 (cond
21349 ((org-at-timestamp-p)
21350 (push (org-point-in-group p 0 :timestamp) clist))
21351 ((memq 'org-link faces)
21352 (push (list :link
21353 (previous-single-property-change p 'face)
21354 (next-single-property-change p 'face)) clist))
21355 ((memq 'org-special-keyword faces)
21356 (push (list :keyword
21357 (previous-single-property-change p 'face)
21358 (next-single-property-change p 'face)) clist))
21359 ((org-at-target-p)
21360 (push (org-point-in-group p 0 :target) clist)
21361 (goto-char (1- (match-beginning 0)))
21362 (if (looking-at org-radio-target-regexp)
21363 (push (org-point-in-group p 0 :radio-target) clist))
21364 (goto-char p))
21365 ((setq o (car (delq nil
21366 (mapcar
21367 (lambda (x)
21368 (if (memq x org-latex-fragment-image-overlays) x))
21369 (overlays-at (point))))))
21370 (push (list :latex-fragment
21371 (overlay-start o) (overlay-end o)) clist)
21372 (push (list :latex-preview
21373 (overlay-start o) (overlay-end o)) clist))
21374 ((org-inside-LaTeX-fragment-p)
21375 ;; FIXME: positions wrong.
21376 (push (list :latex-fragment (point) (point)) clist)))
21378 (setq clist (nreverse (delq nil clist)))
21379 clist))
21381 ;; FIXME: Compare with at-regexp-p Do we need both?
21382 (defun org-in-regexp (re &optional nlines visually)
21383 "Check if point is inside a match of regexp.
21384 Normally only the current line is checked, but you can include NLINES extra
21385 lines both before and after point into the search.
21386 If VISUALLY is set, require that the cursor is not after the match but
21387 really on, so that the block visually is on the match."
21388 (catch 'exit
21389 (let ((pos (point))
21390 (eol (point-at-eol (+ 1 (or nlines 0))))
21391 (inc (if visually 1 0)))
21392 (save-excursion
21393 (beginning-of-line (- 1 (or nlines 0)))
21394 (while (re-search-forward re eol t)
21395 (if (and (<= (match-beginning 0) pos)
21396 (>= (+ inc (match-end 0)) pos))
21397 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21399 (defun org-at-regexp-p (regexp)
21400 "Is point inside a match of REGEXP in the current line?"
21401 (catch 'exit
21402 (save-excursion
21403 (let ((pos (point)) (end (point-at-eol)))
21404 (beginning-of-line 1)
21405 (while (re-search-forward regexp end t)
21406 (if (and (<= (match-beginning 0) pos)
21407 (>= (match-end 0) pos))
21408 (throw 'exit t)))
21409 nil))))
21411 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21412 "Non-nil when point is between matches of START-RE and END-RE.
21414 Also return a non-nil value when point is on one of the matches.
21416 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21417 buffer positions. Default values are the positions of headlines
21418 surrounding the point.
21420 The functions returns a cons cell whose car (resp. cdr) is the
21421 position before START-RE (resp. after END-RE)."
21422 (save-match-data
21423 (let ((pos (point))
21424 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21425 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21426 beg end)
21427 (save-excursion
21428 ;; Point is on a block when on START-RE or if START-RE can be
21429 ;; found before it...
21430 (and (or (org-at-regexp-p start-re)
21431 (re-search-backward start-re limit-up t))
21432 (setq beg (match-beginning 0))
21433 ;; ... and END-RE after it...
21434 (goto-char (match-end 0))
21435 (re-search-forward end-re limit-down t)
21436 (> (setq end (match-end 0)) pos)
21437 ;; ... without another START-RE in-between.
21438 (goto-char (match-beginning 0))
21439 (not (re-search-backward start-re (1+ beg) t))
21440 ;; Return value.
21441 (cons beg end))))))
21443 (defun org-in-block-p (names)
21444 "Non-nil when point belongs to a block whose name belongs to NAMES.
21446 NAMES is a list of strings containing names of blocks.
21448 Return first block name matched, or nil. Beware that in case of
21449 nested blocks, the returned name may not belong to the closest
21450 block from point."
21451 (save-match-data
21452 (catch 'exit
21453 (let ((case-fold-search t)
21454 (lim-up (save-excursion (outline-previous-heading)))
21455 (lim-down (save-excursion (outline-next-heading))))
21456 (mapc (lambda (name)
21457 (let ((n (regexp-quote name)))
21458 (when (org-between-regexps-p
21459 (concat "^[ \t]*#\\+begin_" n)
21460 (concat "^[ \t]*#\\+end_" n)
21461 lim-up lim-down)
21462 (throw 'exit n))))
21463 names))
21464 nil)))
21466 (defun org-occur-in-agenda-files (regexp &optional nlines)
21467 "Call `multi-occur' with buffers for all agenda files."
21468 (interactive "sOrg-files matching: \np")
21469 (let* ((files (org-agenda-files))
21470 (tnames (mapcar 'file-truename files))
21471 (extra org-agenda-text-search-extra-files)
21473 (when (eq (car extra) 'agenda-archives)
21474 (setq extra (cdr extra))
21475 (setq files (org-add-archive-files files)))
21476 (while (setq f (pop extra))
21477 (unless (member (file-truename f) tnames)
21478 (add-to-list 'files f 'append)
21479 (add-to-list 'tnames (file-truename f) 'append)))
21480 (multi-occur
21481 (mapcar (lambda (x)
21482 (with-current-buffer
21483 (or (get-file-buffer x) (find-file-noselect x))
21484 (widen)
21485 (current-buffer)))
21486 files)
21487 regexp)))
21489 (if (boundp 'occur-mode-find-occurrence-hook)
21490 ;; Emacs 23
21491 (add-hook 'occur-mode-find-occurrence-hook
21492 (lambda ()
21493 (when (derived-mode-p 'org-mode)
21494 (org-reveal))))
21495 ;; Emacs 22
21496 (defadvice occur-mode-goto-occurrence
21497 (after org-occur-reveal activate)
21498 (and (derived-mode-p 'org-mode) (org-reveal)))
21499 (defadvice occur-mode-goto-occurrence-other-window
21500 (after org-occur-reveal activate)
21501 (and (derived-mode-p 'org-mode) (org-reveal)))
21502 (defadvice occur-mode-display-occurrence
21503 (after org-occur-reveal activate)
21504 (when (derived-mode-p 'org-mode)
21505 (let ((pos (occur-mode-find-occurrence)))
21506 (with-current-buffer (marker-buffer pos)
21507 (save-excursion
21508 (goto-char pos)
21509 (org-reveal)))))))
21511 (defun org-occur-link-in-agenda-files ()
21512 "Create a link and search for it in the agendas.
21513 The link is not stored in `org-stored-links', it is just created
21514 for the search purpose."
21515 (interactive)
21516 (let ((link (condition-case nil
21517 (org-store-link nil)
21518 (error "Unable to create a link to here"))))
21519 (org-occur-in-agenda-files (regexp-quote link))))
21521 (defun org-reverse-string (string)
21522 "Return the reverse of STRING."
21523 (apply 'string (reverse (string-to-list string))))
21525 (defun org-uniquify (list)
21526 "Remove duplicate elements from LIST."
21527 (let (res)
21528 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21529 res))
21531 (defun org-uniquify-alist (alist)
21532 "Merge duplicate elements of an alist.
21534 For example, in this alist:
21536 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21537 => '((a 1 3) (b 2))
21539 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21540 (let (rtn)
21541 (mapc
21542 (lambda (e)
21543 (let (n)
21544 (if (not (assoc (car e) rtn))
21545 (push e rtn)
21546 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21547 (setq rtn (assq-delete-all (car e) rtn))
21548 (push n rtn))))
21549 alist)
21550 rtn))
21552 (defun org-delete-all (elts list)
21553 "Remove all elements in ELTS from LIST."
21554 (while elts
21555 (setq list (delete (pop elts) list)))
21556 list)
21558 (defun org-count (cl-item cl-seq)
21559 "Count the number of occurrences of ITEM in SEQ.
21560 Taken from `count' in cl-seq.el with all keyword arguments removed."
21561 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21562 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21563 (while (< cl-start cl-end)
21564 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21565 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21566 (setq cl-start (1+ cl-start)))
21567 cl-count))
21569 (defun org-remove-if (predicate seq)
21570 "Remove everything from SEQ that fulfills PREDICATE."
21571 (let (res e)
21572 (while seq
21573 (setq e (pop seq))
21574 (if (not (funcall predicate e)) (push e res)))
21575 (nreverse res)))
21577 (defun org-remove-if-not (predicate seq)
21578 "Remove everything from SEQ that does not fulfill PREDICATE."
21579 (let (res e)
21580 (while seq
21581 (setq e (pop seq))
21582 (if (funcall predicate e) (push e res)))
21583 (nreverse res)))
21585 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21586 "Reduce two-argument FUNCTION across SEQ.
21587 Taken from `reduce' in cl-seq.el with all keyword arguments but
21588 \":initial-value\" removed."
21589 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21590 (cadr (memq :initial-value cl-keys)))
21591 (cl-seq (pop cl-seq))
21592 (t (funcall cl-func)))))
21593 (while cl-seq
21594 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21595 cl-accum))
21597 (defun org-back-over-empty-lines ()
21598 "Move backwards over whitespace, to the beginning of the first empty line.
21599 Returns the number of empty lines passed."
21600 (let ((pos (point)))
21601 (if (cdr (assoc 'heading org-blank-before-new-entry))
21602 (skip-chars-backward " \t\n\r")
21603 (unless (eobp)
21604 (forward-line -1)))
21605 (beginning-of-line 2)
21606 (goto-char (min (point) pos))
21607 (count-lines (point) pos)))
21609 (defun org-skip-whitespace ()
21610 (skip-chars-forward " \t\n\r"))
21612 (defun org-point-in-group (point group &optional context)
21613 "Check if POINT is in match-group GROUP.
21614 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21615 match. If the match group does not exist or point is not inside it,
21616 return nil."
21617 (and (match-beginning group)
21618 (>= point (match-beginning group))
21619 (<= point (match-end group))
21620 (if context
21621 (list context (match-beginning group) (match-end group))
21622 t)))
21624 (defun org-switch-to-buffer-other-window (&rest args)
21625 "Switch to buffer in a second window on the current frame.
21626 In particular, do not allow pop-up frames.
21627 Returns the newly created buffer."
21628 (org-no-popups
21629 (apply 'switch-to-buffer-other-window args)))
21631 (defun org-combine-plists (&rest plists)
21632 "Create a single property list from all plists in PLISTS.
21633 The process starts by copying the first list, and then setting properties
21634 from the other lists. Settings in the last list are the most significant
21635 ones and overrule settings in the other lists."
21636 (let ((rtn (copy-sequence (pop plists)))
21637 p v ls)
21638 (while plists
21639 (setq ls (pop plists))
21640 (while ls
21641 (setq p (pop ls) v (pop ls))
21642 (setq rtn (plist-put rtn p v))))
21643 rtn))
21645 (defun org-replace-escapes (string table)
21646 "Replace %-escapes in STRING with values in TABLE.
21647 TABLE is an association list with keys like \"%a\" and string values.
21648 The sequences in STRING may contain normal field width and padding information,
21649 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21650 so values can contain further %-escapes if they are define later in TABLE."
21651 (let ((tbl (copy-alist table))
21652 (case-fold-search nil)
21653 (pchg 0)
21654 e re rpl)
21655 (while (setq e (pop tbl))
21656 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21657 (when (and (cdr e) (string-match re (cdr e)))
21658 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21659 (safe "SREF"))
21660 (add-text-properties 0 3 (list 'sref sref) safe)
21661 (setcdr e (replace-match safe t t (cdr e)))))
21662 (while (string-match re string)
21663 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21664 (cdr e)))
21665 (setq string (replace-match rpl t t string))))
21666 (while (setq pchg (next-property-change pchg string))
21667 (let ((sref (get-text-property pchg 'sref string)))
21668 (when (and sref (string-match "SREF" string pchg))
21669 (setq string (replace-match sref t t string)))))
21670 string))
21672 (defun org-sublist (list start end)
21673 "Return a section of LIST, from START to END.
21674 Counting starts at 1."
21675 (let (rtn (c start))
21676 (setq list (nthcdr (1- start) list))
21677 (while (and list (<= c end))
21678 (push (pop list) rtn)
21679 (setq c (1+ c)))
21680 (nreverse rtn)))
21682 (defun org-find-base-buffer-visiting (file)
21683 "Like `find-buffer-visiting' but always return the base buffer and
21684 not an indirect buffer."
21685 (let ((buf (or (get-file-buffer file)
21686 (find-buffer-visiting file))))
21687 (if buf
21688 (or (buffer-base-buffer buf) buf)
21689 nil)))
21691 (defun org-image-file-name-regexp (&optional extensions)
21692 "Return regexp matching the file names of images.
21693 If EXTENSIONS is given, only match these."
21694 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21695 (image-file-name-regexp)
21696 (let ((image-file-name-extensions
21697 (or extensions
21698 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21699 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21700 (concat "\\."
21701 (regexp-opt (nconc (mapcar 'upcase
21702 image-file-name-extensions)
21703 image-file-name-extensions)
21705 "\\'"))))
21707 (defun org-file-image-p (file &optional extensions)
21708 "Return non-nil if FILE is an image."
21709 (save-match-data
21710 (string-match (org-image-file-name-regexp extensions) file)))
21712 (defun org-get-cursor-date (&optional with-time)
21713 "Return the date at cursor in as a time.
21714 This works in the calendar and in the agenda, anywhere else it just
21715 returns the current time.
21716 If WITH-TIME is non-nil, returns the time of the event at point (in
21717 the agenda) or the current time of the day."
21718 (let (date day defd tp tm hod mod)
21719 (when with-time
21720 (setq tp (get-text-property (point) 'time))
21721 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21722 (setq hod (string-to-number (match-string 1 tp))
21723 mod (string-to-number (match-string 2 tp))))
21724 (or tp (setq hod (nth 2 (decode-time (current-time)))
21725 mod (nth 1 (decode-time (current-time))))))
21726 (cond
21727 ((eq major-mode 'calendar-mode)
21728 (setq date (calendar-cursor-to-date)
21729 defd (encode-time 0 (or mod 0) (or hod 0)
21730 (nth 1 date) (nth 0 date) (nth 2 date))))
21731 ((eq major-mode 'org-agenda-mode)
21732 (setq day (get-text-property (point) 'day))
21733 (if day
21734 (setq date (calendar-gregorian-from-absolute day)
21735 defd (encode-time 0 (or mod 0) (or hod 0)
21736 (nth 1 date) (nth 0 date) (nth 2 date))))))
21737 (or defd (current-time))))
21739 (defun org-mark-subtree (&optional up)
21740 "Mark the current subtree.
21741 This puts point at the start of the current subtree, and mark at
21742 the end. If a numeric prefix UP is given, move up into the
21743 hierarchy of headlines by UP levels before marking the subtree."
21744 (interactive "P")
21745 (org-with-limited-levels
21746 (cond ((org-at-heading-p) (beginning-of-line))
21747 ((org-before-first-heading-p) (error "Not in a subtree"))
21748 (t (outline-previous-visible-heading 1))))
21749 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21750 (if (org-called-interactively-p 'any)
21751 (call-interactively 'org-mark-element)
21752 (org-mark-element)))
21755 ;;; Indentation
21757 (defun org-indent-line ()
21758 "Indent line depending on context."
21759 (interactive)
21760 (let* ((pos (point))
21761 (itemp (org-at-item-p))
21762 (case-fold-search t)
21763 (org-drawer-regexp (or org-drawer-regexp "\000"))
21764 (inline-task-p (and (featurep 'org-inlinetask)
21765 (org-inlinetask-in-task-p)))
21766 (inline-re (and inline-task-p
21767 (org-inlinetask-outline-regexp)))
21768 column)
21769 (if (and orgstruct-is-++ (eq pos (point)))
21770 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21771 (indent-according-to-mode))
21772 (beginning-of-line 1)
21773 (cond
21774 ;; Headings
21775 ((looking-at org-outline-regexp) (setq column 0))
21776 ;; Footnote definition
21777 ((looking-at org-footnote-definition-re) (setq column 0))
21778 ;; Literal examples
21779 ((looking-at "[ \t]*:\\( \\|$\\)")
21780 (setq column (org-get-indentation))) ; do nothing
21781 ;; Lists
21782 ((ignore-errors (goto-char (org-in-item-p)))
21783 (setq column (if itemp
21784 (org-get-indentation)
21785 (org-list-item-body-column (point))))
21786 (goto-char pos))
21787 ;; Drawers
21788 ((and (looking-at "[ \t]*:END:")
21789 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21790 (save-excursion
21791 (goto-char (1- (match-beginning 1)))
21792 (setq column (current-column))))
21793 ;; Special blocks
21794 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21795 (save-excursion
21796 (re-search-backward
21797 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21798 (setq column (org-get-indentation (match-string 0))))
21799 ((and (not (looking-at "[ \t]*#\\+begin_"))
21800 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21801 (save-excursion
21802 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21803 (setq column
21804 (cond ((equal (downcase (match-string 1)) "src")
21805 ;; src blocks: let `org-edit-src-exit' handle them
21806 (org-get-indentation))
21807 ((equal (downcase (match-string 1)) "example")
21808 (max (org-get-indentation)
21809 (org-get-indentation (match-string 0))))
21811 (org-get-indentation (match-string 0))))))
21812 ;; This line has nothing special, look at the previous relevant
21813 ;; line to compute indentation
21815 (beginning-of-line 0)
21816 (while (and (not (bobp))
21817 (not (looking-at org-table-line-regexp))
21818 (not (looking-at org-drawer-regexp))
21819 ;; When point started in an inline task, do not move
21820 ;; above task starting line.
21821 (not (and inline-task-p (looking-at inline-re)))
21822 ;; Skip drawers, blocks, empty lines, verbatim,
21823 ;; comments, tables, footnotes definitions, lists,
21824 ;; inline tasks.
21825 (or (and (looking-at "[ \t]*:END:")
21826 (re-search-backward org-drawer-regexp nil t))
21827 (and (looking-at "[ \t]*#\\+end_")
21828 (re-search-backward "[ \t]*#\\+begin_"nil t))
21829 (looking-at "[ \t]*[\n:#|]")
21830 (looking-at org-footnote-definition-re)
21831 (and (ignore-errors (goto-char (org-in-item-p)))
21832 (goto-char
21833 (org-list-get-top-point (org-list-struct))))
21834 (and (not inline-task-p)
21835 (featurep 'org-inlinetask)
21836 (org-inlinetask-in-task-p)
21837 (or (org-inlinetask-goto-beginning) t))))
21838 (beginning-of-line 0))
21839 (cond
21840 ;; There was an heading above.
21841 ((looking-at "\\*+[ \t]+")
21842 (if (not org-adapt-indentation)
21843 (setq column 0)
21844 (goto-char (match-end 0))
21845 (setq column (current-column))))
21846 ;; A drawer had started and is unfinished
21847 ((looking-at org-drawer-regexp)
21848 (goto-char (1- (match-beginning 1)))
21849 (setq column (current-column)))
21850 ;; Else, nothing noticeable found: get indentation and go on.
21851 (t (setq column (org-get-indentation))))))
21852 ;; Now apply indentation and move cursor accordingly
21853 (goto-char pos)
21854 (if (<= (current-column) (current-indentation))
21855 (org-indent-line-to column)
21856 (save-excursion (org-indent-line-to column)))
21857 ;; Special polishing for properties, see `org-property-format'
21858 (setq column (current-column))
21859 (beginning-of-line 1)
21860 (if (looking-at
21861 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21862 (replace-match (concat (match-string 1)
21863 (format org-property-format
21864 (match-string 2) (match-string 3)))
21865 t t))
21866 (org-move-to-column column))))
21868 (defun org-indent-drawer ()
21869 "Indent the drawer at point."
21870 (interactive)
21871 (let ((p (point))
21872 (e (and (save-excursion (re-search-forward ":END:" nil t))
21873 (match-end 0)))
21874 (folded
21875 (save-excursion
21876 (end-of-line)
21877 (when (overlays-at (point))
21878 (member 'invisible (overlay-properties
21879 (car (overlays-at (point)))))))))
21880 (when folded (org-cycle))
21881 (indent-for-tab-command)
21882 (while (and (move-beginning-of-line 2) (< (point) e))
21883 (indent-for-tab-command))
21884 (goto-char p)
21885 (when folded (org-cycle)))
21886 (message "Drawer at point indented"))
21888 (defun org-indent-block ()
21889 "Indent the block at point."
21890 (interactive)
21891 (let ((p (point))
21892 (case-fold-search t)
21893 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21894 (match-end 0)))
21895 (folded
21896 (save-excursion
21897 (end-of-line)
21898 (when (overlays-at (point))
21899 (member 'invisible (overlay-properties
21900 (car (overlays-at (point)))))))))
21901 (when folded (org-cycle))
21902 (indent-for-tab-command)
21903 (while (and (move-beginning-of-line 2) (< (point) e))
21904 (indent-for-tab-command))
21905 (goto-char p)
21906 (when folded (org-cycle)))
21907 (message "Block at point indented"))
21909 (defun org-indent-region (start end)
21910 "Indent region."
21911 (interactive "r")
21912 (save-excursion
21913 (let ((line-end (org-current-line end)))
21914 (goto-char start)
21915 (while (< (org-current-line) line-end)
21916 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21917 (t (call-interactively 'org-indent-line)))
21918 (move-beginning-of-line 2)))))
21921 ;;; Filling
21923 ;; We use our own fill-paragraph and auto-fill functions.
21925 ;; `org-fill-paragraph' relies on adaptive filling and context
21926 ;; checking. Appropriate `fill-prefix' is computed with
21927 ;; `org-adaptive-fill-function'.
21929 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21930 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21931 ;; `org-adaptive-fill-function' value. Internally,
21932 ;; `org-comment-line-break-function' breaks the line.
21934 ;; `org-setup-filling' installs filling and auto-filling related
21935 ;; variables during `org-mode' initialization.
21937 (defun org-setup-filling ()
21938 (interactive)
21939 ;; Prevent auto-fill from inserting unwanted new items.
21940 (when (boundp 'fill-nobreak-predicate)
21941 (org-set-local
21942 'fill-nobreak-predicate
21943 (org-uniquify
21944 (append fill-nobreak-predicate
21945 '(org-fill-paragraph-separate-nobreak-p
21946 org-fill-line-break-nobreak-p
21947 org-fill-paragraph-with-timestamp-nobreak-p)))))
21948 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21949 (org-set-local 'auto-fill-inhibit-regexp nil)
21950 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21951 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21952 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21954 (defvar org-element-paragraph-separate) ; org-element.el
21955 (defun org-fill-paragraph-separate-nobreak-p ()
21956 "Non-nil when a line break at point would insert a new item."
21957 (looking-at (substring org-element-paragraph-separate 1)))
21959 (defun org-fill-line-break-nobreak-p ()
21960 "Non-nil when a line break at point would create an Org line break."
21961 (save-excursion
21962 (skip-chars-backward "[ \t]")
21963 (skip-chars-backward "\\\\")
21964 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21966 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21967 "Non-nil when a line break at point would insert a new item."
21968 (and (org-at-timestamp-p t)
21969 (not (looking-at org-ts-regexp-both))))
21971 (declare-function message-in-body-p "message" ())
21972 (defvar orgtbl-line-start-regexp) ; From org-table.el
21973 (defun org-adaptive-fill-function ()
21974 "Compute a fill prefix for the current line.
21975 Return fill prefix, as a string, or nil if current line isn't
21976 meant to be filled."
21977 (let (prefix)
21978 (catch 'exit
21979 (when (derived-mode-p 'message-mode)
21980 (save-excursion
21981 (beginning-of-line)
21982 (cond ((or (not (message-in-body-p))
21983 (looking-at orgtbl-line-start-regexp))
21984 (throw 'exit nil))
21985 ((looking-at message-cite-prefix-regexp)
21986 (throw 'exit (match-string-no-properties 0)))
21987 ((looking-at org-outline-regexp)
21988 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21989 (org-with-wide-buffer
21990 (let* ((p (line-beginning-position))
21991 (element (save-excursion (beginning-of-line)
21992 (org-element-at-point)))
21993 (type (org-element-type element))
21994 (post-affiliated (org-element-property :post-affiliated element)))
21995 (unless (and post-affiliated (< p post-affiliated))
21996 (case type
21997 (comment (looking-at "[ \t]*# ?") (match-string 0))
21998 (footnote-definition "")
21999 ((item plain-list)
22000 (make-string (org-list-item-body-column
22001 (or post-affiliated
22002 (org-element-property :begin element)))
22003 ? ))
22004 (paragraph
22005 ;; Fill prefix is usually the same as the current line,
22006 ;; except if the paragraph is at the beginning of an item.
22007 (let ((parent (org-element-property :parent element)))
22008 (cond ((eq (org-element-type parent) 'item)
22009 (make-string (org-list-item-body-column
22010 (org-element-property :begin parent))
22011 ? ))
22012 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22013 (match-string 0))
22014 (t ""))))
22015 (comment-block
22016 ;; Only fill contents if P is within block boundaries.
22017 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22018 (forward-line)
22019 (point)))
22020 (cend (save-excursion
22021 (goto-char (org-element-property :end element))
22022 (skip-chars-backward " \r\t\n")
22023 (line-beginning-position))))
22024 (when (and (>= p cbeg) (< p cend))
22025 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22026 (match-string 0)
22027 "")))))))))))
22029 (declare-function message-goto-body "message" ())
22030 (defvar message-cite-prefix-regexp) ; From message.el
22031 (defun org-fill-paragraph (&optional justify)
22032 "Fill element at point, when applicable.
22034 This function only applies to comment blocks, comments, example
22035 blocks and paragraphs. Also, as a special case, re-align table
22036 when point is at one.
22038 If JUSTIFY is non-nil (interactively, with prefix argument),
22039 justify as well. If `sentence-end-double-space' is non-nil, then
22040 period followed by one space does not end a sentence, so don't
22041 break a line there. The variable `fill-column' controls the
22042 width for filling.
22044 For convenience, when point is at a plain list, an item or
22045 a footnote definition, try to fill the first paragraph within."
22046 (interactive)
22047 (if (and (derived-mode-p 'message-mode)
22048 (or (not (message-in-body-p))
22049 (save-excursion (move-beginning-of-line 1)
22050 (looking-at message-cite-prefix-regexp))))
22051 ;; First ensure filling is correct in message-mode.
22052 (let ((fill-paragraph-function
22053 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22054 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22055 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22056 (paragraph-separate
22057 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22058 (fill-paragraph nil))
22059 (with-syntax-table org-mode-transpose-word-syntax-table
22060 ;; Move to end of line in order to get the first paragraph
22061 ;; within a plain list or a footnote definition.
22062 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22063 ;; First check if point is in a blank line at the beginning of
22064 ;; the buffer. In that case, ignore filling.
22065 (case (org-element-type element)
22066 ;; Use major mode filling function is src blocks.
22067 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22068 ;; Align Org tables, leave table.el tables as-is.
22069 (table-row (org-table-align) t)
22070 (table
22071 (when (eq (org-element-property :type element) 'org)
22072 (org-table-align))
22074 (paragraph
22075 ;; Paragraphs may contain `line-break' type objects.
22076 (let ((beg (max (point-min)
22077 (org-element-property :contents-begin element)))
22078 (end (min (point-max)
22079 (org-element-property :contents-end element))))
22080 ;; Do nothing if point is at an affiliated keyword.
22081 (if (< (line-end-position) beg) t
22082 (when (derived-mode-p 'message-mode)
22083 ;; In `message-mode', do not fill following citation
22084 ;; in current paragraph nor text before message body.
22085 (let ((body-start (save-excursion (message-goto-body))))
22086 (when body-start (setq beg (max body-start beg))))
22087 (when (save-excursion
22088 (re-search-forward
22089 (concat "^" message-cite-prefix-regexp) end t))
22090 (setq end (match-beginning 0))))
22091 ;; Fill paragraph, taking line breaks into account.
22092 ;; For that, slice the paragraph using line breaks as
22093 ;; separators, and fill the parts in reverse order to
22094 ;; avoid messing with markers.
22095 (save-excursion
22096 (goto-char end)
22097 (mapc
22098 (lambda (pos)
22099 (fill-region-as-paragraph pos (point) justify)
22100 (goto-char pos))
22101 ;; Find the list of ending positions for line breaks
22102 ;; in the current paragraph. Add paragraph
22103 ;; beginning to include first slice.
22104 (nreverse
22105 (cons beg
22106 (org-element-map
22107 (org-element--parse-objects
22108 beg end nil (org-element-restriction 'paragraph))
22109 'line-break
22110 (lambda (lb) (org-element-property :end lb)))))))
22111 t)))
22112 ;; Contents of `comment-block' type elements should be
22113 ;; filled as plain text, but only if point is within block
22114 ;; markers.
22115 (comment-block
22116 (let* ((case-fold-search t)
22117 (beg (save-excursion
22118 (goto-char (org-element-property :begin element))
22119 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22120 (forward-line)
22121 (point)))
22122 (end (save-excursion
22123 (goto-char (org-element-property :end element))
22124 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22125 (line-beginning-position))))
22126 (when (and (>= (point) beg) (< (point) end))
22127 (fill-region-as-paragraph
22128 (save-excursion
22129 (end-of-line)
22130 (re-search-backward "^[ \t]*$" beg 'move)
22131 (line-beginning-position))
22132 (save-excursion
22133 (beginning-of-line)
22134 (re-search-forward "^[ \t]*$" end 'move)
22135 (line-beginning-position))
22136 justify)))
22138 ;; Fill comments.
22139 (comment (fill-comment-paragraph justify))
22140 ;; Ignore every other element.
22141 (otherwise t))))))
22143 (defun org-auto-fill-function ()
22144 "Auto-fill function."
22145 ;; Check if auto-filling is meaningful.
22146 (let ((fc (current-fill-column)))
22147 (when (and fc (> (current-column) fc))
22148 (let* ((fill-prefix (org-adaptive-fill-function))
22149 ;; Enforce empty fill prefix, if required. Otherwise, it
22150 ;; will be computed again.
22151 (adaptive-fill-mode (not (equal fill-prefix ""))))
22152 (when fill-prefix (do-auto-fill))))))
22154 (defun org-comment-line-break-function (&optional soft)
22155 "Break line at point and indent, continuing comment if within one.
22156 The inserted newline is marked hard if variable
22157 `use-hard-newlines' is true, unless optional argument SOFT is
22158 non-nil."
22159 (if soft (insert-and-inherit ?\n) (newline 1))
22160 (save-excursion (forward-char -1) (delete-horizontal-space))
22161 (delete-horizontal-space)
22162 (indent-to-left-margin)
22163 (insert-before-markers-and-inherit fill-prefix))
22166 ;;; Comments
22168 ;; Org comments syntax is quite complex. It requires the entire line
22169 ;; to be just a comment. Also, even with the right syntax at the
22170 ;; beginning of line, some some elements (i.e. verse-block or
22171 ;; example-block) don't accept comments. Usual Emacs comment commands
22172 ;; cannot cope with those requirements. Therefore, Org replaces them.
22174 ;; Org still relies on `comment-dwim', but cannot trust
22175 ;; `comment-only-p'. So, `comment-region-function' and
22176 ;; `uncomment-region-function' both point
22177 ;; to`org-comment-or-uncomment-region'. Eventually,
22178 ;; `org-insert-comment' takes care of insertion of comments at the
22179 ;; beginning of line.
22181 ;; `org-setup-comments-handling' install comments related variables
22182 ;; during `org-mode' initialization.
22184 (defun org-setup-comments-handling ()
22185 (interactive)
22186 (org-set-local 'comment-use-syntax nil)
22187 (org-set-local 'comment-start "# ")
22188 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22189 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22190 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22191 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22193 (defun org-insert-comment ()
22194 "Insert an empty comment above current line.
22195 If the line is empty, insert comment at its beginning."
22196 (beginning-of-line)
22197 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22198 (org-indent-line)
22199 (insert "# "))
22201 (defvar comment-empty-lines) ; From newcomment.el.
22202 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22203 "Comment or uncomment each non-blank line in the region.
22204 Uncomment each non-blank line between BEG and END if it only
22205 contains commented lines. Otherwise, comment them."
22206 (save-restriction
22207 ;; Restrict region
22208 (narrow-to-region (save-excursion (goto-char beg)
22209 (skip-chars-forward " \r\t\n" end)
22210 (line-beginning-position))
22211 (save-excursion (goto-char end)
22212 (skip-chars-backward " \r\t\n" beg)
22213 (line-end-position)))
22214 (let ((uncommentp
22215 ;; UNCOMMENTP is non-nil when every non blank line between
22216 ;; BEG and END is a comment.
22217 (save-excursion
22218 (goto-char (point-min))
22219 (while (and (not (eobp))
22220 (let ((element (org-element-at-point)))
22221 (and (eq (org-element-type element) 'comment)
22222 (goto-char (min (point-max)
22223 (org-element-property
22224 :end element)))))))
22225 (eobp))))
22226 (if uncommentp
22227 ;; Only blank lines and comments in region: uncomment it.
22228 (save-excursion
22229 (goto-char (point-min))
22230 (while (not (eobp))
22231 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22232 (replace-match "" nil nil nil 1))
22233 (forward-line)))
22234 ;; Comment each line in region.
22235 (let ((min-indent (point-max)))
22236 ;; First find the minimum indentation across all lines.
22237 (save-excursion
22238 (goto-char (point-min))
22239 (while (and (not (eobp)) (not (zerop min-indent)))
22240 (unless (looking-at "[ \t]*$")
22241 (setq min-indent (min min-indent (current-indentation))))
22242 (forward-line)))
22243 ;; Then loop over all lines.
22244 (save-excursion
22245 (goto-char (point-min))
22246 (while (not (eobp))
22247 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22248 ;; Don't get fooled by invisible text (e.g. link path)
22249 ;; when moving to column MIN-INDENT.
22250 (let ((buffer-invisibility-spec nil))
22251 (org-move-to-column min-indent t))
22252 (insert comment-start))
22253 (forward-line))))))))
22256 ;;; Planning
22258 ;; This section contains tools to operate on timestamp objects, as
22259 ;; returned by, e.g. `org-element-context'.
22261 (defun org-timestamp-has-time-p (timestamp)
22262 "Non-nil when TIMESTAMP has a time specified."
22263 (org-element-property :hour-start timestamp))
22265 (defun org-timestamp-format (timestamp format &optional end utc)
22266 "Format a TIMESTAMP element into a string.
22268 FORMAT is a format specifier to be passed to
22269 `format-time-string'.
22271 When optional argument END is non-nil, use end of date-range or
22272 time-range, if possible.
22274 When optional argument UTC is non-nil, time will be expressed as
22275 Universal Time."
22276 (format-time-string
22277 format
22278 (apply 'encode-time
22279 (cons 0
22280 (mapcar
22281 (lambda (prop) (or (org-element-property prop timestamp) 0))
22282 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22283 '(:minute-start :hour-start :day-start :month-start
22284 :year-start)))))
22285 utc))
22287 (defun org-timestamp-split-range (timestamp &optional end)
22288 "Extract a timestamp object from a date or time range.
22290 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22291 the end of the range. Otherwise, extract its start.
22293 Return a new timestamp object sharing the same parent as
22294 TIMESTAMP."
22295 (let ((type (org-element-property :type timestamp)))
22296 (if (memq type '(active inactive diary)) timestamp
22297 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22298 ;; Set new type.
22299 (org-element-put-property
22300 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22301 ;; Copy start properties over end properties if END is
22302 ;; non-nil. Otherwise, copy end properties over `start' ones.
22303 (let ((p-alist '((:minute-start . :minute-end)
22304 (:hour-start . :hour-end)
22305 (:day-start . :day-end)
22306 (:month-start . :month-end)
22307 (:year-start . :year-end))))
22308 (dolist (p-cell p-alist)
22309 (org-element-put-property
22310 split-ts
22311 (funcall (if end 'car 'cdr) p-cell)
22312 (org-element-property
22313 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22314 ;; Eventually refresh `:raw-value'.
22315 (org-element-put-property split-ts :raw-value nil)
22316 (org-element-put-property
22317 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22319 (defun org-timestamp-translate (timestamp &optional boundary)
22320 "Apply `org-translate-time' on a TIMESTAMP object.
22321 When optional argument BOUNDARY is non-nil, it is either the
22322 symbol `start' or `end'. In this case, only translate the
22323 starting or ending part of TIMESTAMP if it is a date or time
22324 range. Otherwise, translate both parts."
22325 (if (and (not boundary)
22326 (memq (org-element-property :type timestamp)
22327 '(active-range inactive-range)))
22328 (concat
22329 (org-translate-time
22330 (org-element-property :raw-value
22331 (org-timestamp-split-range timestamp)))
22332 "--"
22333 (org-translate-time
22334 (org-element-property :raw-value
22335 (org-timestamp-split-range timestamp t))))
22336 (org-translate-time
22337 (org-element-property
22338 :raw-value
22339 (if (not boundary) timestamp
22340 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22344 ;;; Other stuff.
22346 (defun org-toggle-fixed-width-section (arg)
22347 "Toggle the fixed-width export.
22348 If there is no active region, the QUOTE keyword at the current headline is
22349 inserted or removed. When present, it causes the text between this headline
22350 and the next to be exported as fixed-width text, and unmodified.
22351 If there is an active region, this command adds or removes a colon as the
22352 first character of this line. If the first character of a line is a colon,
22353 this line is also exported in fixed-width font."
22354 (interactive "P")
22355 (let* ((cc 0)
22356 (regionp (org-region-active-p))
22357 (beg (if regionp (region-beginning) (point)))
22358 (end (if regionp (region-end)))
22359 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22360 (case-fold-search nil)
22361 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22362 off)
22363 (if regionp
22364 (save-excursion
22365 (goto-char beg)
22366 (setq cc (current-column))
22367 (beginning-of-line 1)
22368 (setq off (looking-at re))
22369 (while (> nlines 0)
22370 (setq nlines (1- nlines))
22371 (beginning-of-line 1)
22372 (cond
22373 (arg
22374 (org-move-to-column cc t)
22375 (insert ": \n")
22376 (forward-line -1))
22377 ((and off (looking-at re))
22378 (replace-match "" t t nil 1))
22379 ((not off) (org-move-to-column cc t) (insert ": ")))
22380 (forward-line 1)))
22381 (save-excursion
22382 (org-back-to-heading)
22383 (cond
22384 ((looking-at (format org-heading-keyword-regexp-format
22385 org-quote-string))
22386 (goto-char (match-end 1))
22387 (looking-at (concat " +" org-quote-string))
22388 (replace-match "" t t)
22389 (when (eolp) (insert " ")))
22390 ((looking-at org-outline-regexp)
22391 (goto-char (match-end 0))
22392 (insert org-quote-string " ")))))))
22394 (defun org-reftex-citation ()
22395 "Use reftex-citation to insert a citation into the buffer.
22396 This looks for a line like
22398 #+BIBLIOGRAPHY: foo plain option:-d
22400 and derives from it that foo.bib is the bibliography file relevant
22401 for this document. It then installs the necessary environment for RefTeX
22402 to work in this buffer and calls `reftex-citation' to insert a citation
22403 into the buffer.
22405 Export of such citations to both LaTeX and HTML is handled by the contributed
22406 package org-exp-bibtex by Taru Karttunen."
22407 (interactive)
22408 (let ((reftex-docstruct-symbol 'rds)
22409 (reftex-cite-format "\\cite{%l}")
22410 rds bib)
22411 (save-excursion
22412 (save-restriction
22413 (widen)
22414 (let ((case-fold-search t)
22415 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22416 (if (not (save-excursion
22417 (or (re-search-forward re nil t)
22418 (re-search-backward re nil t))))
22419 (error "No bibliography defined in file")
22420 (setq bib (concat (match-string 1) ".bib")
22421 rds (list (list 'bib bib)))))))
22422 (call-interactively 'reftex-citation)))
22424 ;;;; Functions extending outline functionality
22426 (defun org-beginning-of-line (&optional arg)
22427 "Go to the beginning of the current line. If that is invisible, continue
22428 to a visible line beginning. This makes the function of C-a more intuitive.
22429 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22430 first attempt, and only move to after the tags when the cursor is already
22431 beyond the end of the headline."
22432 (interactive "P")
22433 (let ((pos (point))
22434 (special (if (consp org-special-ctrl-a/e)
22435 (car org-special-ctrl-a/e)
22436 org-special-ctrl-a/e))
22437 refpos)
22438 (if (org-bound-and-true-p visual-line-mode)
22439 (beginning-of-visual-line 1)
22440 (beginning-of-line 1))
22441 (if (and arg (fboundp 'move-beginning-of-line))
22442 (call-interactively 'move-beginning-of-line)
22443 (if (bobp)
22445 (backward-char 1)
22446 (if (org-truely-invisible-p)
22447 (while (and (not (bobp)) (org-truely-invisible-p))
22448 (backward-char 1)
22449 (beginning-of-line 1))
22450 (forward-char 1))))
22451 (when special
22452 (cond
22453 ((and (looking-at org-complex-heading-regexp)
22454 (= (char-after (match-end 1)) ?\ ))
22455 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22456 (point-at-eol)))
22457 (goto-char
22458 (if (eq special t)
22459 (cond ((> pos refpos) refpos)
22460 ((= pos (point)) refpos)
22461 (t (point)))
22462 (cond ((> pos (point)) (point))
22463 ((not (eq last-command this-command)) (point))
22464 (t refpos)))))
22465 ((org-at-item-p)
22466 ;; Being at an item and not looking at an the item means point
22467 ;; was previously moved to beginning of a visual line, which
22468 ;; doesn't contain the item. Therefore, do nothing special,
22469 ;; just stay here.
22470 (when (looking-at org-list-full-item-re)
22471 ;; Set special position at first white space character after
22472 ;; bullet, and check-box, if any.
22473 (let ((after-bullet
22474 (let ((box (match-end 3)))
22475 (if (not box) (match-end 1)
22476 (let ((after (char-after box)))
22477 (if (and after (= after ? )) (1+ box) box))))))
22478 ;; Special case: Move point to special position when
22479 ;; currently after it or at beginning of line.
22480 (if (eq special t)
22481 (when (or (> pos after-bullet) (= (point) pos))
22482 (goto-char after-bullet))
22483 ;; Reversed case: Move point to special position when
22484 ;; point was already at beginning of line and command is
22485 ;; repeated.
22486 (when (and (= (point) pos) (eq last-command this-command))
22487 (goto-char after-bullet))))))))
22488 (org-no-warnings
22489 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22491 (defun org-end-of-line (&optional arg)
22492 "Go to the end of the line.
22493 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22494 tags on the first attempt, and only move to after the tags when
22495 the cursor is already beyond the end of the headline."
22496 (interactive "P")
22497 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22498 org-special-ctrl-a/e))
22499 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22500 'end-of-visual-line)
22501 ((fboundp 'move-end-of-line) 'move-end-of-line)
22502 (t 'end-of-line))))
22503 (if (or (not special) arg) (call-interactively move-fun)
22504 (let* ((element (save-excursion (beginning-of-line)
22505 (org-element-at-point)))
22506 (type (org-element-type element)))
22507 (cond
22508 ((memq type '(headline inlinetask))
22509 (let ((pos (point)))
22510 (beginning-of-line 1)
22511 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22512 (if (eq special t)
22513 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22514 (goto-char (match-beginning 1))
22515 (goto-char (match-end 0)))
22516 (if (or (< pos (match-end 0))
22517 (not (eq this-command last-command)))
22518 (goto-char (match-end 0))
22519 (goto-char (match-beginning 1))))
22520 (call-interactively move-fun))))
22521 ((org-element-property :hiddenp element)
22522 ;; If element is hidden, `move-end-of-line' would put point
22523 ;; after it. Use `end-of-line' to stay on current line.
22524 (call-interactively 'end-of-line))
22525 (t (call-interactively move-fun)))))
22526 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22528 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22529 (define-key org-mode-map "\C-e" 'org-end-of-line)
22531 (defun org-backward-sentence (&optional arg)
22532 "Go to beginning of sentence, or beginning of table field.
22533 This will call `backward-sentence' or `org-table-beginning-of-field',
22534 depending on context."
22535 (interactive "P")
22536 (cond
22537 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22538 (t (call-interactively 'backward-sentence))))
22540 (defun org-forward-sentence (&optional arg)
22541 "Go to end of sentence, or end of table field.
22542 This will call `forward-sentence' or `org-table-end-of-field',
22543 depending on context."
22544 (interactive "P")
22545 (cond
22546 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22547 (t (call-interactively 'forward-sentence))))
22549 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22550 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22552 (defun org-kill-line (&optional arg)
22553 "Kill line, to tags or end of line."
22554 (interactive "P")
22555 (cond
22556 ((or (not org-special-ctrl-k)
22557 (bolp)
22558 (not (org-at-heading-p)))
22559 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22560 org-ctrl-k-protect-subtree)
22561 (if (or (eq org-ctrl-k-protect-subtree 'error)
22562 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22563 (error "C-k aborted - would kill hidden subtree")))
22564 (call-interactively
22565 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22566 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22567 (kill-region (point) (match-beginning 1))
22568 (org-set-tags nil t))
22569 (t (kill-region (point) (point-at-eol)))))
22571 (define-key org-mode-map "\C-k" 'org-kill-line)
22573 (defun org-yank (&optional arg)
22574 "Yank. If the kill is a subtree, treat it specially.
22575 This command will look at the current kill and check if is a single
22576 subtree, or a series of subtrees[1]. If it passes the test, and if the
22577 cursor is at the beginning of a line or after the stars of a currently
22578 empty headline, then the yank is handled specially. How exactly depends
22579 on the value of the following variables, both set by default.
22581 org-yank-folded-subtrees
22582 When set, the subtree(s) will be folded after insertion, but only
22583 if doing so would now swallow text after the yanked text.
22585 org-yank-adjusted-subtrees
22586 When set, the subtree will be promoted or demoted in order to
22587 fit into the local outline tree structure, which means that the level
22588 will be adjusted so that it becomes the smaller one of the two
22589 *visible* surrounding headings.
22591 Any prefix to this command will cause `yank' to be called directly with
22592 no special treatment. In particular, a simple \\[universal-argument] prefix \
22593 will just
22594 plainly yank the text as it is.
22596 \[1] The test checks if the first non-white line is a heading
22597 and if there are no other headings with fewer stars."
22598 (interactive "P")
22599 (org-yank-generic 'yank arg))
22601 (defun org-yank-generic (command arg)
22602 "Perform some yank-like command.
22604 This function implements the behavior described in the `org-yank'
22605 documentation. However, it has been generalized to work for any
22606 interactive command with similar behavior."
22608 ;; pretend to be command COMMAND
22609 (setq this-command command)
22611 (if arg
22612 (call-interactively command)
22614 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22615 (and (org-kill-is-subtree-p)
22616 (or (bolp)
22617 (and (looking-at "[ \t]*$")
22618 (string-match
22619 "\\`\\*+\\'"
22620 (buffer-substring (point-at-bol) (point)))))))
22621 swallowp)
22622 (cond
22623 ((and subtreep org-yank-folded-subtrees)
22624 (let ((beg (point))
22625 end)
22626 (if (and subtreep org-yank-adjusted-subtrees)
22627 (org-paste-subtree nil nil 'for-yank)
22628 (call-interactively command))
22630 (setq end (point))
22631 (goto-char beg)
22632 (when (and (bolp) subtreep
22633 (not (setq swallowp
22634 (org-yank-folding-would-swallow-text beg end))))
22635 (org-with-limited-levels
22636 (or (looking-at org-outline-regexp)
22637 (re-search-forward org-outline-regexp-bol end t))
22638 (while (and (< (point) end) (looking-at org-outline-regexp))
22639 (hide-subtree)
22640 (org-cycle-show-empty-lines 'folded)
22641 (condition-case nil
22642 (outline-forward-same-level 1)
22643 (error (goto-char end))))))
22644 (when swallowp
22645 (message
22646 "Inserted text not folded because that would swallow text"))
22648 (goto-char end)
22649 (skip-chars-forward " \t\n\r")
22650 (beginning-of-line 1)
22651 (push-mark beg 'nomsg)))
22652 ((and subtreep org-yank-adjusted-subtrees)
22653 (let ((beg (point-at-bol)))
22654 (org-paste-subtree nil nil 'for-yank)
22655 (push-mark beg 'nomsg)))
22657 (call-interactively command))))))
22659 (defun org-yank-folding-would-swallow-text (beg end)
22660 "Would hide-subtree at BEG swallow any text after END?"
22661 (let (level)
22662 (org-with-limited-levels
22663 (save-excursion
22664 (goto-char beg)
22665 (when (or (looking-at org-outline-regexp)
22666 (re-search-forward org-outline-regexp-bol end t))
22667 (setq level (org-outline-level)))
22668 (goto-char end)
22669 (skip-chars-forward " \t\r\n\v\f")
22670 (if (or (eobp)
22671 (and (bolp) (looking-at org-outline-regexp)
22672 (<= (org-outline-level) level)))
22673 nil ; Nothing would be swallowed
22674 t))))) ; something would swallow
22676 (define-key org-mode-map "\C-y" 'org-yank)
22678 (defun org-truely-invisible-p ()
22679 "Check if point is at a character currently not visible.
22680 This version does not only check the character property, but also
22681 `visible-mode'."
22682 ;; Early versions of noutline don't have `outline-invisible-p'.
22683 (if (org-bound-and-true-p visible-mode)
22685 (outline-invisible-p)))
22687 (defun org-invisible-p2 ()
22688 "Check if point is at a character currently not visible."
22689 (save-excursion
22690 (if (and (eolp) (not (bobp))) (backward-char 1))
22691 ;; Early versions of noutline don't have `outline-invisible-p'.
22692 (outline-invisible-p)))
22694 (defun org-back-to-heading (&optional invisible-ok)
22695 "Call `outline-back-to-heading', but provide a better error message."
22696 (condition-case nil
22697 (outline-back-to-heading invisible-ok)
22698 (error (error "Before first headline at position %d in buffer %s"
22699 (point) (current-buffer)))))
22701 (defun org-before-first-heading-p ()
22702 "Before first heading?"
22703 (save-excursion
22704 (end-of-line)
22705 (null (re-search-backward org-outline-regexp-bol nil t))))
22707 (defun org-at-heading-p (&optional ignored)
22708 (outline-on-heading-p t))
22709 ;; Compatibility alias with Org versions < 7.8.03
22710 (defalias 'org-on-heading-p 'org-at-heading-p)
22712 (defun org-at-comment-p nil
22713 "Is cursor in a line starting with a # character?"
22714 (save-excursion
22715 (beginning-of-line)
22716 (looking-at "^#")))
22718 (defun org-at-drawer-p nil
22719 "Is cursor at a drawer keyword?"
22720 (save-excursion
22721 (move-beginning-of-line 1)
22722 (looking-at org-drawer-regexp)))
22724 (defun org-at-block-p nil
22725 "Is cursor at a block keyword?"
22726 (save-excursion
22727 (move-beginning-of-line 1)
22728 (looking-at org-block-regexp)))
22730 (defun org-point-at-end-of-empty-headline ()
22731 "If point is at the end of an empty headline, return t, else nil.
22732 If the heading only contains a TODO keyword, it is still still considered
22733 empty."
22734 (and (looking-at "[ \t]*$")
22735 (when org-todo-line-regexp
22736 (save-excursion
22737 (beginning-of-line 1)
22738 (let ((case-fold-search nil))
22739 (looking-at org-todo-line-regexp)
22740 (string= (match-string 3) ""))))))
22742 (defun org-at-heading-or-item-p ()
22743 (or (org-at-heading-p) (org-at-item-p)))
22745 (defun org-at-target-p ()
22746 (or (org-in-regexp org-radio-target-regexp)
22747 (org-in-regexp org-target-regexp)))
22748 ;; Compatibility alias with Org versions < 7.8.03
22749 (defalias 'org-on-target-p 'org-at-target-p)
22751 (defun org-up-heading-all (arg)
22752 "Move to the heading line of which the present line is a subheading.
22753 This function considers both visible and invisible heading lines.
22754 With argument, move up ARG levels."
22755 (if (fboundp 'outline-up-heading-all)
22756 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22757 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22759 (defun org-up-heading-safe ()
22760 "Move to the heading line of which the present line is a subheading.
22761 This version will not throw an error. It will return the level of the
22762 headline found, or nil if no higher level is found.
22764 Also, this function will be a lot faster than `outline-up-heading',
22765 because it relies on stars being the outline starters. This can really
22766 make a significant difference in outlines with very many siblings."
22767 (let (start-level re)
22768 (org-back-to-heading t)
22769 (setq start-level (funcall outline-level))
22770 (if (equal start-level 1)
22772 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22773 (if (re-search-backward re nil t)
22774 (funcall outline-level)))))
22776 (defun org-first-sibling-p ()
22777 "Is this heading the first child of its parents?"
22778 (interactive)
22779 (let ((re org-outline-regexp-bol)
22780 level l)
22781 (unless (org-at-heading-p t)
22782 (error "Not at a heading"))
22783 (setq level (funcall outline-level))
22784 (save-excursion
22785 (if (not (re-search-backward re nil t))
22787 (setq l (funcall outline-level))
22788 (< l level)))))
22790 (defun org-goto-sibling (&optional previous)
22791 "Goto the next sibling, even if it is invisible.
22792 When PREVIOUS is set, go to the previous sibling instead. Returns t
22793 when a sibling was found. When none is found, return nil and don't
22794 move point."
22795 (let ((fun (if previous 're-search-backward 're-search-forward))
22796 (pos (point))
22797 (re org-outline-regexp-bol)
22798 level l)
22799 (when (condition-case nil (org-back-to-heading t) (error nil))
22800 (setq level (funcall outline-level))
22801 (catch 'exit
22802 (or previous (forward-char 1))
22803 (while (funcall fun re nil t)
22804 (setq l (funcall outline-level))
22805 (when (< l level) (goto-char pos) (throw 'exit nil))
22806 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22807 (goto-char pos)
22808 nil))))
22810 (defun org-show-siblings ()
22811 "Show all siblings of the current headline."
22812 (save-excursion
22813 (while (org-goto-sibling) (org-flag-heading nil)))
22814 (save-excursion
22815 (while (org-goto-sibling 'previous)
22816 (org-flag-heading nil))))
22818 (defun org-goto-first-child ()
22819 "Goto the first child, even if it is invisible.
22820 Return t when a child was found. Otherwise don't move point and
22821 return nil."
22822 (let (level (pos (point)) (re org-outline-regexp-bol))
22823 (when (condition-case nil (org-back-to-heading t) (error nil))
22824 (setq level (outline-level))
22825 (forward-char 1)
22826 (if (and (re-search-forward re nil t) (> (outline-level) level))
22827 (progn (goto-char (match-beginning 0)) t)
22828 (goto-char pos) nil))))
22830 (defun org-show-hidden-entry ()
22831 "Show an entry where even the heading is hidden."
22832 (save-excursion
22833 (org-show-entry)))
22835 (defun org-flag-heading (flag &optional entry)
22836 "Flag the current heading. FLAG non-nil means make invisible.
22837 When ENTRY is non-nil, show the entire entry."
22838 (save-excursion
22839 (org-back-to-heading t)
22840 ;; Check if we should show the entire entry
22841 (if entry
22842 (progn
22843 (org-show-entry)
22844 (save-excursion
22845 (and (outline-next-heading)
22846 (org-flag-heading nil))))
22847 (outline-flag-region (max (point-min) (1- (point)))
22848 (save-excursion (outline-end-of-heading) (point))
22849 flag))))
22851 (defun org-get-next-sibling ()
22852 "Move to next heading of the same level, and return point.
22853 If there is no such heading, return nil.
22854 This is like outline-next-sibling, but invisible headings are ok."
22855 (let ((level (funcall outline-level)))
22856 (outline-next-heading)
22857 (while (and (not (eobp)) (> (funcall outline-level) level))
22858 (outline-next-heading))
22859 (if (or (eobp) (< (funcall outline-level) level))
22861 (point))))
22863 (defun org-get-last-sibling ()
22864 "Move to previous heading of the same level, and return point.
22865 If there is no such heading, return nil."
22866 (let ((opoint (point))
22867 (level (funcall outline-level)))
22868 (outline-previous-heading)
22869 (when (and (/= (point) opoint) (outline-on-heading-p t))
22870 (while (and (> (funcall outline-level) level)
22871 (not (bobp)))
22872 (outline-previous-heading))
22873 (if (< (funcall outline-level) level)
22875 (point)))))
22877 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22878 "Goto to the end of a subtree."
22879 ;; This contains an exact copy of the original function, but it uses
22880 ;; `org-back-to-heading', to make it work also in invisible
22881 ;; trees. And is uses an invisible-ok argument.
22882 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22883 ;; Furthermore, when used inside Org, finding the end of a large subtree
22884 ;; with many children and grandchildren etc, this can be much faster
22885 ;; than the outline version.
22886 (org-back-to-heading invisible-ok)
22887 (let ((first t)
22888 (level (funcall outline-level)))
22889 (if (and (derived-mode-p 'org-mode) (< level 1000))
22890 ;; A true heading (not a plain list item), in Org-mode
22891 ;; This means we can easily find the end by looking
22892 ;; only for the right number of stars. Using a regexp to do
22893 ;; this is so much faster than using a Lisp loop.
22894 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22895 (forward-char 1)
22896 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22897 ;; something else, do it the slow way
22898 (while (and (not (eobp))
22899 (or first (> (funcall outline-level) level)))
22900 (setq first nil)
22901 (outline-next-heading)))
22902 (unless to-heading
22903 (if (memq (preceding-char) '(?\n ?\^M))
22904 (progn
22905 ;; Go to end of line before heading
22906 (forward-char -1)
22907 (if (memq (preceding-char) '(?\n ?\^M))
22908 ;; leave blank line before heading
22909 (forward-char -1))))))
22910 (point))
22912 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22913 "Use Org version in org-mode, for dramatic speed-up."
22914 (if (derived-mode-p 'org-mode)
22915 (progn
22916 (org-end-of-subtree nil t)
22917 (unless (eobp) (backward-char 1)))
22918 ad-do-it))
22920 (defun org-end-of-meta-data-and-drawers ()
22921 "Jump to the first text after meta data and drawers in the current entry.
22922 This will move over empty lines, lines with planning time stamps,
22923 clocking lines, and drawers."
22924 (org-back-to-heading t)
22925 (let ((end (save-excursion (outline-next-heading) (point)))
22926 (re (concat "\\(" org-drawer-regexp "\\)"
22927 "\\|" "[ \t]*" org-keyword-time-regexp)))
22928 (forward-line 1)
22929 (while (re-search-forward re end t)
22930 (if (not (match-end 1))
22931 ;; empty or planning line
22932 (forward-line 1)
22933 ;; a drawer, find the end
22934 (re-search-forward "^[ \t]*:END:" end 'move)
22935 (forward-line 1)))
22936 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22937 (point)))
22939 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22940 "Move forward to the ARG'th subheading at same level as this one.
22941 Stop at the first and last subheadings of a superior heading.
22942 Normally this only looks at visible headings, but when INVISIBLE-OK is
22943 non-nil it will also look at invisible ones."
22944 (interactive "p")
22945 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22946 (if (and arg (< arg 0))
22947 (goto-char (point-min))
22948 (outline-next-heading))
22949 (org-at-heading-p)
22950 (let ((level (- (match-end 0) (match-beginning 0) 1))
22951 (f (if (and arg (< arg 0))
22952 're-search-backward
22953 're-search-forward))
22954 (count (if arg (abs arg) 1))
22955 (result (point)))
22956 (forward-char (if (and arg (< arg 0)) -1 1))
22957 (while (and (> count 0)
22958 (funcall f org-outline-regexp-bol nil 'move))
22959 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22960 (cond ((< l level) (setq count 0))
22961 ((and (= l level)
22962 (or invisible-ok
22963 (progn
22964 (goto-char (line-beginning-position))
22965 (not (outline-invisible-p)))))
22966 (setq count (1- count))
22967 (when (eq l level)
22968 (setq result (point)))))))
22969 (goto-char result))
22970 (beginning-of-line 1)))
22972 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22973 "Move backward to the ARG'th subheading at same level as this one.
22974 Stop at the first and last subheadings of a superior heading."
22975 (interactive "p")
22976 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22978 (defun org-next-block (arg &optional backward block-regexp)
22979 "Jump to the next block.
22980 With a prefix argument ARG, jump forward ARG many source blocks.
22981 When BACKWARD is non-nil, jump to the previous block.
22982 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22983 (interactive "p")
22984 (let ((re (or block-regexp org-block-regexp))
22985 (re-search-fn (or (and backward 're-search-backward)
22986 're-search-forward)))
22987 (if (looking-at re) (forward-char 1))
22988 (condition-case nil
22989 (funcall re-search-fn re nil nil arg)
22990 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22991 (goto-char (match-beginning 0)) (org-show-context)))
22993 (defun org-previous-block (arg &optional block-regexp)
22994 "Jump to the previous block.
22995 With a prefix argument ARG, jump backward ARG many source blocks.
22996 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22997 (interactive "p")
22998 (org-next-block arg t block-regexp))
23000 (defun org-forward-element ()
23001 "Move forward by one element.
23002 Move to the next element at the same level, when possible."
23003 (interactive)
23004 (cond ((eobp) (user-error "Cannot move further down"))
23005 ((org-with-limited-levels (org-at-heading-p))
23006 (let ((origin (point)))
23007 (goto-char (org-end-of-subtree nil t))
23008 (unless (org-with-limited-levels (org-at-heading-p))
23009 (goto-char origin)
23010 (user-error "Cannot move further down"))))
23012 (let* ((elem (org-element-at-point))
23013 (end (org-element-property :end elem))
23014 (parent (org-element-property :parent elem)))
23015 (if (and parent (= (org-element-property :contents-end parent) end))
23016 (goto-char (org-element-property :end parent))
23017 (goto-char end))))))
23019 (defun org-backward-element ()
23020 "Move backward by one element.
23021 Move to the previous element at the same level, when possible."
23022 (interactive)
23023 (cond ((bobp) (user-error "Cannot move further up"))
23024 ((org-with-limited-levels (org-at-heading-p))
23025 ;; At a headline, move to the previous one, if any, or stay
23026 ;; here.
23027 (let ((origin (point)))
23028 (org-with-limited-levels (org-backward-heading-same-level 1))
23029 ;; When current headline has no sibling above, move to its
23030 ;; parent.
23031 (when (= (point) origin)
23032 (or (org-with-limited-levels (org-up-heading-safe))
23033 (progn (goto-char origin)
23034 (user-error "Cannot move further up"))))))
23036 (let* ((trail (org-element-at-point 'keep-trail))
23037 (elem (car trail))
23038 (prev-elem (nth 1 trail))
23039 (beg (org-element-property :begin elem)))
23040 (cond
23041 ;; Move to beginning of current element if point isn't
23042 ;; there already.
23043 ((/= (point) beg) (goto-char beg))
23044 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23045 ((org-before-first-heading-p) (goto-char (point-min)))
23046 (t (org-back-to-heading)))))))
23048 (defun org-up-element ()
23049 "Move to upper element."
23050 (interactive)
23051 (if (org-with-limited-levels (org-at-heading-p))
23052 (unless (org-up-heading-safe) (error "No surrounding element"))
23053 (let* ((elem (org-element-at-point))
23054 (parent (org-element-property :parent elem)))
23055 (if parent (goto-char (org-element-property :begin parent))
23056 (if (org-with-limited-levels (org-before-first-heading-p))
23057 (error "No surrounding element")
23058 (org-with-limited-levels (org-back-to-heading)))))))
23060 (defvar org-element-greater-elements)
23061 (defun org-down-element ()
23062 "Move to inner element."
23063 (interactive)
23064 (let ((element (org-element-at-point)))
23065 (cond
23066 ((memq (org-element-type element) '(plain-list table))
23067 (goto-char (org-element-property :contents-begin element))
23068 (forward-char))
23069 ((memq (org-element-type element) org-element-greater-elements)
23070 ;; If contents are hidden, first disclose them.
23071 (when (org-element-property :hiddenp element) (org-cycle))
23072 (goto-char (or (org-element-property :contents-begin element)
23073 (error "No content for this element"))))
23074 (t (error "No inner element")))))
23076 (defun org-drag-element-backward ()
23077 "Move backward element at point."
23078 (interactive)
23079 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23080 (let* ((trail (org-element-at-point 'keep-trail))
23081 (elem (car trail))
23082 (prev-elem (nth 1 trail)))
23083 ;; Error out if no previous element or previous element is
23084 ;; a parent of the current one.
23085 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23086 (error "Cannot drag element backward")
23087 (let ((pos (point)))
23088 (org-element-swap-A-B prev-elem elem)
23089 (goto-char (+ (org-element-property :begin prev-elem)
23090 (- pos (org-element-property :begin elem)))))))))
23092 (defun org-drag-element-forward ()
23093 "Move forward element at point."
23094 (interactive)
23095 (let* ((pos (point))
23096 (elem (org-element-at-point)))
23097 (when (= (point-max) (org-element-property :end elem))
23098 (error "Cannot drag element forward"))
23099 (goto-char (org-element-property :end elem))
23100 (let ((next-elem (org-element-at-point)))
23101 (when (or (org-element-nested-p elem next-elem)
23102 (and (eq (org-element-type next-elem) 'headline)
23103 (not (eq (org-element-type elem) 'headline))))
23104 (goto-char pos)
23105 (error "Cannot drag element forward"))
23106 ;; Compute new position of point: it's shifted by NEXT-ELEM
23107 ;; body's length (without final blanks) and by the length of
23108 ;; blanks between ELEM and NEXT-ELEM.
23109 (let ((size-next (- (save-excursion
23110 (goto-char (org-element-property :end next-elem))
23111 (skip-chars-backward " \r\t\n")
23112 (forward-line)
23113 ;; Small correction if buffer doesn't end
23114 ;; with a newline character.
23115 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23116 (org-element-property :begin next-elem)))
23117 (size-blank (- (org-element-property :end elem)
23118 (save-excursion
23119 (goto-char (org-element-property :end elem))
23120 (skip-chars-backward " \r\t\n")
23121 (forward-line)
23122 (point)))))
23123 (org-element-swap-A-B elem next-elem)
23124 (goto-char (+ pos size-next size-blank))))))
23126 (defun org-drag-line-forward (arg)
23127 "Drag the line at point ARG lines forward."
23128 (interactive "p")
23129 (dotimes (n (abs arg))
23130 (let ((c (current-column)))
23131 (if (< 0 arg)
23132 (progn
23133 (beginning-of-line 2)
23134 (transpose-lines 1)
23135 (beginning-of-line 0))
23136 (transpose-lines 1)
23137 (beginning-of-line -1))
23138 (org-move-to-column c))))
23140 (defun org-drag-line-backward (arg)
23141 "Drag the line at point ARG lines backward."
23142 (interactive "p")
23143 (org-drag-line-forward (- arg)))
23145 (defun org-mark-element ()
23146 "Put point at beginning of this element, mark at end.
23148 Interactively, if this command is repeated or (in Transient Mark
23149 mode) if the mark is active, it marks the next element after the
23150 ones already marked."
23151 (interactive)
23152 (let (deactivate-mark)
23153 (if (and (org-called-interactively-p 'any)
23154 (or (and (eq last-command this-command) (mark t))
23155 (and transient-mark-mode mark-active)))
23156 (set-mark
23157 (save-excursion
23158 (goto-char (mark))
23159 (goto-char (org-element-property :end (org-element-at-point)))))
23160 (let ((element (org-element-at-point)))
23161 (end-of-line)
23162 (push-mark (org-element-property :end element) t t)
23163 (goto-char (org-element-property :begin element))))))
23165 (defun org-narrow-to-element ()
23166 "Narrow buffer to current element."
23167 (interactive)
23168 (let ((elem (org-element-at-point)))
23169 (cond
23170 ((eq (car elem) 'headline)
23171 (narrow-to-region
23172 (org-element-property :begin elem)
23173 (org-element-property :end elem)))
23174 ((memq (car elem) org-element-greater-elements)
23175 (narrow-to-region
23176 (org-element-property :contents-begin elem)
23177 (org-element-property :contents-end elem)))
23179 (narrow-to-region
23180 (org-element-property :begin elem)
23181 (org-element-property :end elem))))))
23183 (defun org-transpose-element ()
23184 "Transpose current and previous elements, keeping blank lines between.
23185 Point is moved after both elements."
23186 (interactive)
23187 (org-skip-whitespace)
23188 (let ((end (org-element-property :end (org-element-at-point))))
23189 (org-drag-element-backward)
23190 (goto-char end)))
23192 (defun org-unindent-buffer ()
23193 "Un-indent the visible part of the buffer.
23194 Relative indentation (between items, inside blocks, etc.) isn't
23195 modified."
23196 (interactive)
23197 (unless (eq major-mode 'org-mode)
23198 (error "Cannot un-indent a buffer not in Org mode"))
23199 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23200 unindent-tree ; For byte-compiler.
23201 (unindent-tree
23202 (function
23203 (lambda (contents)
23204 (mapc
23205 (lambda (element)
23206 (if (memq (org-element-type element) '(headline section))
23207 (funcall unindent-tree (org-element-contents element))
23208 (save-excursion
23209 (save-restriction
23210 (narrow-to-region
23211 (org-element-property :begin element)
23212 (org-element-property :end element))
23213 (org-do-remove-indentation)))))
23214 (reverse contents))))))
23215 (funcall unindent-tree (org-element-contents parse-tree))))
23217 (defun org-show-subtree ()
23218 "Show everything after this heading at deeper levels."
23219 (interactive)
23220 (outline-flag-region
23221 (point)
23222 (save-excursion
23223 (org-end-of-subtree t t))
23224 nil))
23226 (defun org-show-entry ()
23227 "Show the body directly following this heading.
23228 Show the heading too, if it is currently invisible."
23229 (interactive)
23230 (save-excursion
23231 (condition-case nil
23232 (progn
23233 (org-back-to-heading t)
23234 (outline-flag-region
23235 (max (point-min) (1- (point)))
23236 (save-excursion
23237 (if (re-search-forward
23238 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23239 (match-beginning 1)
23240 (point-max)))
23241 nil)
23242 (org-cycle-hide-drawers 'children))
23243 (error nil))))
23245 (defun org-make-options-regexp (kwds &optional extra)
23246 "Make a regular expression for keyword lines."
23247 (concat
23248 "^#\\+\\("
23249 (mapconcat 'regexp-quote kwds "\\|")
23250 (if extra (concat "\\|" extra))
23251 "\\):[ \t]*\\(.*\\)"))
23253 ;; Make isearch reveal the necessary context
23254 (defun org-isearch-end ()
23255 "Reveal context after isearch exits."
23256 (when isearch-success ; only if search was successful
23257 (if (featurep 'xemacs)
23258 ;; Under XEmacs, the hook is run in the correct place,
23259 ;; we directly show the context.
23260 (org-show-context 'isearch)
23261 ;; In Emacs the hook runs *before* restoring the overlays.
23262 ;; So we have to use a one-time post-command-hook to do this.
23263 ;; (Emacs 22 has a special variable, see function `org-mode')
23264 (unless (and (boundp 'isearch-mode-end-hook-quit)
23265 isearch-mode-end-hook-quit)
23266 ;; Only when the isearch was not quitted.
23267 (org-add-hook 'post-command-hook 'org-isearch-post-command
23268 'append 'local)))
23269 (org-fix-ellipsis-at-bol)))
23271 (defun org-isearch-post-command ()
23272 "Remove self from hook, and show context."
23273 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23274 (org-show-context 'isearch))
23277 ;;;; Integration with and fixes for other packages
23279 ;;; Imenu support
23281 (defvar org-imenu-markers nil
23282 "All markers currently used by Imenu.")
23283 (make-variable-buffer-local 'org-imenu-markers)
23285 (defun org-imenu-new-marker (&optional pos)
23286 "Return a new marker for use by Imenu, and remember the marker."
23287 (let ((m (make-marker)))
23288 (move-marker m (or pos (point)))
23289 (push m org-imenu-markers)
23292 (defun org-imenu-get-tree ()
23293 "Produce the index for Imenu."
23294 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23295 (setq org-imenu-markers nil)
23296 (let* ((n org-imenu-depth)
23297 (re (concat "^" (org-get-limited-outline-regexp)))
23298 (subs (make-vector (1+ n) nil))
23299 (last-level 0)
23300 m level head0 head)
23301 (save-excursion
23302 (save-restriction
23303 (widen)
23304 (goto-char (point-max))
23305 (while (re-search-backward re nil t)
23306 (setq level (org-reduced-level (funcall outline-level)))
23307 (when (and (<= level n)
23308 (looking-at org-complex-heading-regexp)
23309 (setq head0 (org-match-string-no-properties 4)))
23310 (setq head (org-link-display-format head0)
23311 m (org-imenu-new-marker))
23312 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23313 (if (>= level last-level)
23314 (push (cons head m) (aref subs level))
23315 (push (cons head (aref subs (1+ level))) (aref subs level))
23316 (loop for i from (1+ level) to n do (aset subs i nil)))
23317 (setq last-level level)))))
23318 (aref subs 1)))
23320 (eval-after-load "imenu"
23321 '(progn
23322 (add-hook 'imenu-after-jump-hook
23323 (lambda ()
23324 (if (derived-mode-p 'org-mode)
23325 (org-show-context 'org-goto))))))
23327 (defun org-link-display-format (link)
23328 "Replace a link with its the description.
23329 If there is no description, use the link target."
23330 (save-match-data
23331 (if (string-match org-bracket-link-analytic-regexp link)
23332 (replace-match (if (match-end 5)
23333 (match-string 5 link)
23334 (concat (match-string 1 link)
23335 (match-string 3 link)))
23336 nil t link)
23337 link)))
23339 (defun org-toggle-link-display ()
23340 "Toggle the literal or descriptive display of links."
23341 (interactive)
23342 (if org-descriptive-links
23343 (progn (org-remove-from-invisibility-spec '(org-link))
23344 (org-restart-font-lock)
23345 (setq org-descriptive-links nil))
23346 (progn (add-to-invisibility-spec '(org-link))
23347 (org-restart-font-lock)
23348 (setq org-descriptive-links t))))
23350 ;; Speedbar support
23352 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23353 "Overlay marking the agenda restriction line in speedbar.")
23354 (overlay-put org-speedbar-restriction-lock-overlay
23355 'face 'org-agenda-restriction-lock)
23356 (overlay-put org-speedbar-restriction-lock-overlay
23357 'help-echo "Agendas are currently limited to this item.")
23358 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23360 (defun org-speedbar-set-agenda-restriction ()
23361 "Restrict future agenda commands to the location at point in speedbar.
23362 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23363 (interactive)
23364 (require 'org-agenda)
23365 (let (p m tp np dir txt)
23366 (cond
23367 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23368 'org-imenu t))
23369 (setq m (get-text-property p 'org-imenu-marker))
23370 (with-current-buffer (marker-buffer m)
23371 (goto-char m)
23372 (org-agenda-set-restriction-lock 'subtree)))
23373 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23374 'speedbar-function 'speedbar-find-file))
23375 (setq tp (previous-single-property-change
23376 (1+ p) 'speedbar-function)
23377 np (next-single-property-change
23378 tp 'speedbar-function)
23379 dir (speedbar-line-directory)
23380 txt (buffer-substring-no-properties (or tp (point-min))
23381 (or np (point-max))))
23382 (with-current-buffer (find-file-noselect
23383 (let ((default-directory dir))
23384 (expand-file-name txt)))
23385 (unless (derived-mode-p 'org-mode)
23386 (error "Cannot restrict to non-Org-mode file"))
23387 (org-agenda-set-restriction-lock 'file)))
23388 (t (error "Don't know how to restrict Org-mode's agenda")))
23389 (move-overlay org-speedbar-restriction-lock-overlay
23390 (point-at-bol) (point-at-eol))
23391 (setq current-prefix-arg nil)
23392 (org-agenda-maybe-redo)))
23394 (eval-after-load "speedbar"
23395 '(progn
23396 (speedbar-add-supported-extension ".org")
23397 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23398 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23399 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23400 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23401 (add-hook 'speedbar-visiting-tag-hook
23402 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23404 ;;; Fixes and Hacks for problems with other packages
23406 ;; Make flyspell not check words in links, to not mess up our keymap
23407 (defvar org-element-affiliated-keywords) ; From org-element.el
23408 (defvar org-element-block-name-alist) ; From org-element.el
23409 (defun org-mode-flyspell-verify ()
23410 "Don't let flyspell put overlays at active buttons, or on
23411 {todo,all-time,additional-option-like}-keywords."
23412 (require 'org-element) ; For `org-element-affiliated-keywords'
23413 (let ((pos (max (1- (point)) (point-min)))
23414 (word (thing-at-point 'word)))
23415 (and (not (get-text-property pos 'keymap))
23416 (not (get-text-property pos 'org-no-flyspell))
23417 (not (member word org-todo-keywords-1))
23418 (not (member word org-all-time-keywords))
23419 (not (member word org-options-keywords))
23420 (not (member word (mapcar 'car org-startup-options)))
23421 (not (member-ignore-case word org-element-affiliated-keywords))
23422 (not (member-ignore-case word (org-get-export-keywords)))
23423 (not (member-ignore-case
23424 word (mapcar 'car org-element-block-name-alist)))
23425 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23427 (defun org-remove-flyspell-overlays-in (beg end)
23428 "Remove flyspell overlays in region."
23429 (and (org-bound-and-true-p flyspell-mode)
23430 (fboundp 'flyspell-delete-region-overlays)
23431 (flyspell-delete-region-overlays beg end))
23432 (add-text-properties beg end '(org-no-flyspell t)))
23434 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23435 (eval-after-load "bookmark"
23436 '(if (boundp 'bookmark-after-jump-hook)
23437 ;; We can use the hook
23438 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23439 ;; Hook not available, use advice
23440 (defadvice bookmark-jump (after org-make-visible activate)
23441 "Make the position visible."
23442 (org-bookmark-jump-unhide))))
23444 ;; Make sure saveplace shows the location if it was hidden
23445 (eval-after-load "saveplace"
23446 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23447 "Make the position visible."
23448 (org-bookmark-jump-unhide)))
23450 ;; Make sure ecb shows the location if it was hidden
23451 (eval-after-load "ecb"
23452 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23453 "Make hierarchy visible when jumping into location from ECB tree buffer."
23454 (if (derived-mode-p 'org-mode)
23455 (org-show-context))))
23457 (defun org-bookmark-jump-unhide ()
23458 "Unhide the current position, to show the bookmark location."
23459 (and (derived-mode-p 'org-mode)
23460 (or (outline-invisible-p)
23461 (save-excursion (goto-char (max (point-min) (1- (point))))
23462 (outline-invisible-p)))
23463 (org-show-context 'bookmark-jump)))
23465 ;; Make session.el ignore our circular variable
23466 (eval-after-load "session"
23467 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23469 ;;;; Experimental code
23471 (defun org-closed-in-range ()
23472 "Sparse tree of items closed in a certain time range.
23473 Still experimental, may disappear in the future."
23474 (interactive)
23475 ;; Get the time interval from the user.
23476 (let* ((time1 (org-float-time
23477 (org-read-date nil 'to-time nil "Starting date: ")))
23478 (time2 (org-float-time
23479 (org-read-date nil 'to-time nil "End date:")))
23480 ;; callback function
23481 (callback (lambda ()
23482 (let ((time
23483 (org-float-time
23484 (apply 'encode-time
23485 (org-parse-time-string
23486 (match-string 1))))))
23487 ;; check if time in interval
23488 (and (>= time time1) (<= time time2))))))
23489 ;; make tree, check each match with the callback
23490 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23492 ;;;; Finish up
23494 (provide 'org)
23496 (run-hooks 'org-load-hook)
23498 ;;; org.el ends here