Implement group tags
[org-mode.git] / lisp / org.el
blob27d8516317596f60230f81616374102bf6531163
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 (if (and (derived-mode-p 'org-agenda-mode)
4757 org-group-tags)
4758 (org-agenda-redo))
4759 (when (derived-mode-p 'org-mode)
4760 (org-set-regexps-and-options-for-tags)
4761 (org-set-regexps-and-options))
4762 (message "Groups tags support has been turned %s"
4763 (if org-group-tags "on" "off")))
4765 (defun org-set-regexps-and-options-for-tags ()
4766 "Precompute regular expressions used for tags in the current buffer."
4767 (when (derived-mode-p 'org-mode)
4768 (org-set-local 'org-file-tags nil)
4769 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4770 (splitre "[ \t]+")
4771 tags ftags key value
4772 (start 0))
4773 (save-excursion
4774 (save-restriction
4775 (widen)
4776 (goto-char (point-min))
4777 (while (re-search-forward re nil t)
4778 (setq key (upcase (org-match-string-no-properties 1))
4779 value (org-match-string-no-properties 2))
4780 (if (stringp value) (setq value (org-trim value)))
4781 (cond
4782 ((equal key "TAGS")
4783 (setq tags (append tags (if tags '("\\n") nil)
4784 (org-split-string value splitre))))
4785 ((equal key "FILETAGS")
4786 (when (string-match "\\S-" value)
4787 (setq ftags
4788 (append
4789 ftags
4790 (apply 'append
4791 (mapcar (lambda (x) (org-split-string x ":"))
4792 (org-split-string value)))))))))))
4793 ;; Process the file tags.
4794 (and ftags (org-set-local 'org-file-tags
4795 (mapcar 'org-add-prop-inherited ftags)))
4796 (org-set-local 'org-tag-groups-alist nil)
4797 ;; Process the tags.
4798 ;; FIXME
4799 (when tags
4800 (let (e tgs g)
4801 (while (setq e (pop tags))
4802 (cond
4803 ((equal e "{")
4804 (progn (push '(:startgroup) tgs)
4805 (when (equal (nth 1 tags) ":")
4806 (push (list (replace-regexp-in-string
4807 "(.+)$" "" (nth 0 tags)))
4808 org-tag-groups-alist)
4809 (setq g 0))))
4810 ((equal e ":") (push '(:grouptags) tgs))
4811 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4812 ((equal e "\\n") (push '(:newline) tgs))
4813 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4814 (push (cons (match-string 1 e)
4815 (string-to-char (match-string 2 e))) tgs)
4816 (if (and g (> g 0))
4817 (setcar org-tag-groups-alist
4818 (append (car org-tag-groups-alist)
4819 (list (match-string 1 e)))))
4820 (if g (setq g (1+ g))))
4821 (t (push (list e) tgs)
4822 (if (and g (> g 0))
4823 (setcar org-tag-groups-alist
4824 (append (car org-tag-groups-alist) (list e))))
4825 (if g (setq g (1+ g))))))
4826 (org-set-local 'org-tag-alist nil)
4827 (while (setq e (pop tgs))
4828 (or (and (stringp (car e))
4829 (assoc (car e) org-tag-alist))
4830 (push e org-tag-alist))))))))
4832 (defun org-set-regexps-and-options ()
4833 "Precompute regular expressions used in the current buffer."
4834 (when (derived-mode-p 'org-mode)
4835 (org-set-local 'org-todo-kwd-alist nil)
4836 (org-set-local 'org-todo-key-alist nil)
4837 (org-set-local 'org-todo-key-trigger nil)
4838 (org-set-local 'org-todo-keywords-1 nil)
4839 (org-set-local 'org-done-keywords nil)
4840 (org-set-local 'org-todo-heads nil)
4841 (org-set-local 'org-todo-sets nil)
4842 (org-set-local 'org-todo-log-states nil)
4843 (org-set-local 'org-file-properties nil)
4844 (let ((re (org-make-options-regexp
4845 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4846 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4847 "SETUPFILE" "OPTIONS")
4848 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4849 (splitre "[ \t]+")
4850 (scripts org-use-sub-superscripts)
4851 kwds kws0 kwsa key log value cat arch const links hw dws
4852 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4853 (start 0))
4854 (save-excursion
4855 (save-restriction
4856 (widen)
4857 (goto-char (point-min))
4858 (while (or (and ext-setup-or-nil
4859 (string-match re ext-setup-or-nil start)
4860 (setq start (match-end 0)))
4861 (and (setq ext-setup-or-nil nil start 0)
4862 (re-search-forward re nil t)))
4863 (setq key (upcase (match-string 1 ext-setup-or-nil))
4864 value (org-match-string-no-properties 2 ext-setup-or-nil))
4865 (if (stringp value) (setq value (org-trim value)))
4866 (cond
4867 ((equal key "CATEGORY")
4868 (setq cat value))
4869 ((member key '("SEQ_TODO" "TODO"))
4870 (push (cons 'sequence (org-split-string value splitre)) kwds))
4871 ((equal key "TYP_TODO")
4872 (push (cons 'type (org-split-string value splitre)) kwds))
4873 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4874 ;; general TODO-like setup
4875 (push (cons (intern (downcase (match-string 1 key)))
4876 (org-split-string value splitre)) kwds))
4877 ((equal key "COLUMNS")
4878 (org-set-local 'org-columns-default-format value))
4879 ((equal key "LINK")
4880 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4881 (push (cons (match-string 1 value)
4882 (org-trim (match-string 2 value)))
4883 links)))
4884 ((equal key "PRIORITIES")
4885 (setq prio (org-split-string value " +")))
4886 ((equal key "PROPERTY")
4887 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4888 (setq props (org-update-property-plist (match-string 1 value)
4889 (match-string 2 value)
4890 props))))
4891 ((equal key "DRAWERS")
4892 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4893 ((equal key "CONSTANTS")
4894 (org-table-set-constants))
4895 ((equal key "STARTUP")
4896 (let ((opts (org-split-string value splitre))
4897 l var val)
4898 (while (setq l (pop opts))
4899 (when (setq l (assoc l org-startup-options))
4900 (setq var (nth 1 l) val (nth 2 l))
4901 (if (not (nth 3 l))
4902 (set (make-local-variable var) val)
4903 (if (not (listp (symbol-value var)))
4904 (set (make-local-variable var) nil))
4905 (set (make-local-variable var) (symbol-value var))
4906 (add-to-list var val))))))
4907 ((equal key "ARCHIVE")
4908 (setq arch value)
4909 (remove-text-properties 0 (length arch)
4910 '(face t fontified t) arch))
4911 ((equal key "OPTIONS")
4912 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4913 (setq scripts (read (match-string 2 value)))))
4914 ((equal key "SETUPFILE")
4915 (setq setup-contents (org-file-contents
4916 (expand-file-name
4917 (org-remove-double-quotes value))
4918 'noerror))
4919 (if (not ext-setup-or-nil)
4920 (setq ext-setup-or-nil setup-contents start 0)
4921 (setq ext-setup-or-nil
4922 (concat (substring ext-setup-or-nil 0 start)
4923 "\n" setup-contents "\n"
4924 (substring ext-setup-or-nil start)))))))
4925 ;; search for property blocks
4926 (goto-char (point-min))
4927 (while (re-search-forward org-block-regexp nil t)
4928 (when (equal "PROPERTY" (upcase (match-string 1)))
4929 (setq value (replace-regexp-in-string
4930 "[\n\r]" " " (match-string 4)))
4931 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4932 (setq props (org-update-property-plist (match-string 1 value)
4933 (match-string 2 value)
4934 props)))))))
4935 (org-set-local 'org-use-sub-superscripts scripts)
4936 (when cat
4937 (org-set-local 'org-category (intern cat))
4938 (push (cons "CATEGORY" cat) props))
4939 (when prio
4940 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4941 (setq prio (mapcar 'string-to-char prio))
4942 (org-set-local 'org-highest-priority (nth 0 prio))
4943 (org-set-local 'org-lowest-priority (nth 1 prio))
4944 (org-set-local 'org-default-priority (nth 2 prio)))
4945 (and props (org-set-local 'org-file-properties (nreverse props)))
4946 (and drawers (org-set-local 'org-drawers drawers))
4947 (and arch (org-set-local 'org-archive-location arch))
4948 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4949 ;; Process the TODO keywords
4950 (unless kwds
4951 ;; Use the global values as if they had been given locally.
4952 (setq kwds (default-value 'org-todo-keywords))
4953 (if (stringp (car kwds))
4954 (setq kwds (list (cons org-todo-interpretation
4955 (default-value 'org-todo-keywords)))))
4956 (setq kwds (reverse kwds)))
4957 (setq kwds (nreverse kwds))
4958 (let (inter kws kw)
4959 (while (setq kws (pop kwds))
4960 (let ((kws (or
4961 (run-hook-with-args-until-success
4962 'org-todo-setup-filter-hook kws)
4963 kws)))
4964 (setq inter (pop kws) sep (member "|" kws)
4965 kws0 (delete "|" (copy-sequence kws))
4966 kwsa nil
4967 kws1 (mapcar
4968 (lambda (x)
4969 ;; 1 2
4970 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4971 (progn
4972 (setq kw (match-string 1 x)
4973 key (and (match-end 2) (match-string 2 x))
4974 log (org-extract-log-state-settings x))
4975 (push (cons kw (and key (string-to-char key))) kwsa)
4976 (and log (push log org-todo-log-states))
4978 (error "Invalid TODO keyword %s" x)))
4979 kws0)
4980 kwsa (if kwsa (append '((:startgroup))
4981 (nreverse kwsa)
4982 '((:endgroup))))
4983 hw (car kws1)
4984 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4985 tail (list inter hw (car dws) (org-last dws))))
4986 (add-to-list 'org-todo-heads hw 'append)
4987 (push kws1 org-todo-sets)
4988 (setq org-done-keywords (append org-done-keywords dws nil))
4989 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4990 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4991 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4992 (setq org-todo-sets (nreverse org-todo-sets)
4993 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4994 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4995 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4996 ;; Compute the regular expressions and other local variables.
4997 ;; Using `org-outline-regexp-bol' would complicate them much,
4998 ;; because of the fixed white space at the end of that string.
4999 (if (not org-done-keywords)
5000 (setq org-done-keywords (and org-todo-keywords-1
5001 (list (org-last org-todo-keywords-1)))))
5002 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5003 (length org-scheduled-string)
5004 (length org-clock-string)
5005 (length org-closed-string)))
5006 org-drawer-regexp
5007 (concat "^[ \t]*:\\("
5008 (mapconcat 'regexp-quote org-drawers "\\|")
5009 "\\):[ \t]*$")
5010 org-not-done-keywords
5011 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5012 org-todo-regexp
5013 (concat "\\("
5014 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5015 "\\)")
5016 org-not-done-regexp
5017 (concat "\\("
5018 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5019 "\\)")
5020 org-not-done-heading-regexp
5021 (format org-heading-keyword-regexp-format org-not-done-regexp)
5022 org-todo-line-regexp
5023 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5024 org-complex-heading-regexp
5025 (concat "^\\(\\*+\\)"
5026 "\\(?: +" org-todo-regexp "\\)?"
5027 "\\(?: +\\(\\[#.\\]\\)\\)?"
5028 "\\(?: +\\(.*?\\)\\)??"
5029 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5030 "[ \t]*$")
5031 org-complex-heading-regexp-format
5032 (concat "^\\(\\*+\\)"
5033 "\\(?: +" org-todo-regexp "\\)?"
5034 "\\(?: +\\(\\[#.\\]\\)\\)?"
5035 "\\(?: +"
5036 ;; Stats cookies can be stuck to body.
5037 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5038 "\\(%s\\)"
5039 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5040 "\\)"
5041 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5042 "[ \t]*$")
5043 org-todo-line-tags-regexp
5044 (concat "^\\(\\*+\\)"
5045 "\\(?: +" org-todo-regexp "\\)?"
5046 "\\(?: +\\(.*?\\)\\)??"
5047 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5048 "[ \t]*$")
5049 org-deadline-regexp (concat "\\<" org-deadline-string)
5050 org-deadline-time-regexp
5051 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5052 org-deadline-time-hour-regexp
5053 (concat "\\<" org-deadline-string
5054 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5055 org-deadline-line-regexp
5056 (concat "\\<\\(" org-deadline-string "\\).*")
5057 org-scheduled-regexp
5058 (concat "\\<" org-scheduled-string)
5059 org-scheduled-time-regexp
5060 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5061 org-scheduled-time-hour-regexp
5062 (concat "\\<" org-scheduled-string
5063 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5064 org-closed-time-regexp
5065 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5066 org-keyword-time-regexp
5067 (concat "\\<\\(" org-scheduled-string
5068 "\\|" org-deadline-string
5069 "\\|" org-closed-string
5070 "\\|" org-clock-string "\\)"
5071 " *[[<]\\([^]>]+\\)[]>]")
5072 org-keyword-time-not-clock-regexp
5073 (concat "\\<\\(" org-scheduled-string
5074 "\\|" org-deadline-string
5075 "\\|" org-closed-string
5076 "\\)"
5077 " *[[<]\\([^]>]+\\)[]>]")
5078 org-maybe-keyword-time-regexp
5079 (concat "\\(\\<\\(" org-scheduled-string
5080 "\\|" org-deadline-string
5081 "\\|" org-closed-string
5082 "\\|" org-clock-string "\\)\\)?"
5083 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5084 org-all-time-keywords
5085 (mapcar (lambda (w) (substring w 0 -1))
5086 (list org-scheduled-string org-deadline-string
5087 org-clock-string org-closed-string)))
5088 (org-compute-latex-and-related-regexp)
5089 (org-set-font-lock-defaults))))
5091 (defun org-file-contents (file &optional noerror)
5092 "Return the contents of FILE, as a string."
5093 (if (or (not file)
5094 (not (file-readable-p file)))
5095 (if noerror
5096 (progn
5097 (message "Cannot read file \"%s\"" file)
5098 (ding) (sit-for 2)
5100 (error "Cannot read file \"%s\"" file))
5101 (with-temp-buffer
5102 (insert-file-contents file)
5103 (buffer-string))))
5105 (defun org-extract-log-state-settings (x)
5106 "Extract the log state setting from a TODO keyword string.
5107 This will extract info from a string like \"WAIT(w@/!)\"."
5108 (let (kw key log1 log2)
5109 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5110 (setq kw (match-string 1 x)
5111 key (and (match-end 2) (match-string 2 x))
5112 log1 (and (match-end 3) (match-string 3 x))
5113 log2 (and (match-end 4) (match-string 4 x)))
5114 (and (or log1 log2)
5115 (list kw
5116 (and log1 (if (equal log1 "!") 'time 'note))
5117 (and log2 (if (equal log2 "!") 'time 'note)))))))
5119 (defun org-remove-keyword-keys (list)
5120 "Remove a pair of parenthesis at the end of each string in LIST."
5121 (mapcar (lambda (x)
5122 (if (string-match "(.*)$" x)
5123 (substring x 0 (match-beginning 0))
5125 list))
5127 (defun org-assign-fast-keys (alist)
5128 "Assign fast keys to a keyword-key alist.
5129 Respect keys that are already there."
5130 (let (new e (alt ?0))
5131 (while (setq e (pop alist))
5132 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5133 (cdr e)) ;; Key already assigned.
5134 (push e new)
5135 (let ((clist (string-to-list (downcase (car e))))
5136 (used (append new alist)))
5137 (when (= (car clist) ?@)
5138 (pop clist))
5139 (while (and clist (rassoc (car clist) used))
5140 (pop clist))
5141 (unless clist
5142 (while (rassoc alt used)
5143 (incf alt)))
5144 (push (cons (car e) (or (car clist) alt)) new))))
5145 (nreverse new)))
5147 ;;; Some variables used in various places
5149 (defvar org-window-configuration nil
5150 "Used in various places to store a window configuration.")
5151 (defvar org-selected-window nil
5152 "Used in various places to store a window configuration.")
5153 (defvar org-finish-function nil
5154 "Function to be called when `C-c C-c' is used.
5155 This is for getting out of special buffers like capture.")
5158 ;; FIXME: Occasionally check by commenting these, to make sure
5159 ;; no other functions uses these, forgetting to let-bind them.
5160 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5161 (defvar org-last-state)
5162 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5164 ;; Defined somewhere in this file, but used before definition.
5165 (defvar org-entities) ;; defined in org-entities.el
5166 (defvar org-struct-menu)
5167 (defvar org-org-menu)
5168 (defvar org-tbl-menu)
5170 ;;;; Define the Org-mode
5172 ;; We use a before-change function to check if a table might need
5173 ;; an update.
5174 (defvar org-table-may-need-update t
5175 "Indicates that a table might need an update.
5176 This variable is set by `org-before-change-function'.
5177 `org-table-align' sets it back to nil.")
5178 (defun org-before-change-function (beg end)
5179 "Every change indicates that a table might need an update."
5180 (setq org-table-may-need-update t))
5181 (defvar org-mode-map)
5182 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5183 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5184 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5185 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5186 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5187 (defvar org-table-buffer-is-an nil)
5189 (defvar bidi-paragraph-direction)
5190 (defvar buffer-face-mode-face)
5192 (require 'outline)
5193 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5194 (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"))
5195 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5197 ;; Other stuff we need.
5198 (require 'time-date)
5199 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5200 (require 'easymenu)
5201 (require 'overlay)
5203 ;; (require 'org-macs) moved higher up in the file before it is first used
5204 (require 'org-entities)
5205 ;; (require 'org-compat) moved higher up in the file before it is first used
5206 (require 'org-faces)
5207 (require 'org-list)
5208 (require 'org-pcomplete)
5209 (require 'org-src)
5210 (require 'org-footnote)
5211 (require 'org-macro)
5213 ;; babel
5214 (require 'ob)
5216 ;;;###autoload
5217 (define-derived-mode org-mode outline-mode "Org"
5218 "Outline-based notes management and organizer, alias
5219 \"Carsten's outline-mode for keeping track of everything.\"
5221 Org-mode develops organizational tasks around a NOTES file which
5222 contains information about projects as plain text. Org-mode is
5223 implemented on top of outline-mode, which is ideal to keep the content
5224 of large files well structured. It supports ToDo items, deadlines and
5225 time stamps, which magically appear in the diary listing of the Emacs
5226 calendar. Tables are easily created with a built-in table editor.
5227 Plain text URL-like links connect to websites, emails (VM), Usenet
5228 messages (Gnus), BBDB entries, and any files related to the project.
5229 For printing and sharing of notes, an Org-mode file (or a part of it)
5230 can be exported as a structured ASCII or HTML file.
5232 The following commands are available:
5234 \\{org-mode-map}"
5236 ;; Get rid of Outline menus, they are not needed
5237 ;; Need to do this here because define-derived-mode sets up
5238 ;; the keymap so late. Still, it is a waste to call this each time
5239 ;; we switch another buffer into org-mode.
5240 (if (featurep 'xemacs)
5241 (when (boundp 'outline-mode-menu-heading)
5242 ;; Assume this is Greg's port, it uses easymenu
5243 (easy-menu-remove outline-mode-menu-heading)
5244 (easy-menu-remove outline-mode-menu-show)
5245 (easy-menu-remove outline-mode-menu-hide))
5246 (define-key org-mode-map [menu-bar headings] 'undefined)
5247 (define-key org-mode-map [menu-bar hide] 'undefined)
5248 (define-key org-mode-map [menu-bar show] 'undefined))
5250 (org-load-modules-maybe)
5251 (easy-menu-add org-org-menu)
5252 (easy-menu-add org-tbl-menu)
5253 (org-install-agenda-files-menu)
5254 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5255 (add-to-invisibility-spec '(org-cwidth))
5256 (add-to-invisibility-spec '(org-hide-block . t))
5257 (when (featurep 'xemacs)
5258 (org-set-local 'line-move-ignore-invisible t))
5259 (org-set-local 'outline-regexp org-outline-regexp)
5260 (org-set-local 'outline-level 'org-outline-level)
5261 (setq bidi-paragraph-direction 'left-to-right)
5262 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5263 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5264 (when (and org-ellipsis
5265 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5266 (fboundp 'make-glyph-code))
5267 (unless org-display-table
5268 (setq org-display-table (make-display-table)))
5269 (set-display-table-slot
5270 org-display-table 4
5271 (vconcat (mapcar
5272 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5273 org-ellipsis)))
5274 (if (stringp org-ellipsis) org-ellipsis "..."))))
5275 (setq buffer-display-table org-display-table))
5276 (org-set-regexps-and-options-for-tags)
5277 (org-set-regexps-and-options)
5278 (when (and org-tag-faces (not org-tags-special-faces-re))
5279 ;; tag faces set outside customize.... force initialization.
5280 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5281 ;; Calc embedded
5282 (org-set-local 'calc-embedded-open-mode "# ")
5283 ;; Modify a few syntax entries
5284 (modify-syntax-entry ?@ "w")
5285 (modify-syntax-entry ?\" "\"")
5286 (if org-startup-truncated (setq truncate-lines t))
5287 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5288 (org-set-local 'font-lock-unfontify-region-function
5289 'org-unfontify-region)
5290 ;; Activate before-change-function
5291 (org-set-local 'org-table-may-need-update t)
5292 (org-add-hook 'before-change-functions 'org-before-change-function nil
5293 'local)
5294 ;; Check for running clock before killing a buffer
5295 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5296 ;; Initialize macros templates.
5297 (org-macro-initialize-templates)
5298 ;; Initialize radio targets.
5299 (org-update-radio-target-regexp)
5300 ;; Indentation.
5301 (org-set-local 'indent-line-function 'org-indent-line)
5302 (org-set-local 'indent-region-function 'org-indent-region)
5303 ;; Filling and auto-filling.
5304 (org-setup-filling)
5305 ;; Comments.
5306 (org-setup-comments-handling)
5307 ;; Beginning/end of defun
5308 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5309 (org-set-local 'end-of-defun-function 'org-forward-element)
5310 ;; Next error for sparse trees
5311 (org-set-local 'next-error-function 'org-occur-next-match)
5312 ;; Make sure dependence stuff works reliably, even for users who set it
5313 ;; too late :-(
5314 (if org-enforce-todo-dependencies
5315 (add-hook 'org-blocker-hook
5316 'org-block-todo-from-children-or-siblings-or-parent)
5317 (remove-hook 'org-blocker-hook
5318 'org-block-todo-from-children-or-siblings-or-parent))
5319 (if org-enforce-todo-checkbox-dependencies
5320 (add-hook 'org-blocker-hook
5321 'org-block-todo-from-checkboxes)
5322 (remove-hook 'org-blocker-hook
5323 'org-block-todo-from-checkboxes))
5325 ;; Align options lines
5326 (org-set-local
5327 'align-mode-rules-list
5328 '((org-in-buffer-settings
5329 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5330 (modes . '(org-mode)))))
5332 ;; Imenu
5333 (org-set-local 'imenu-create-index-function
5334 'org-imenu-get-tree)
5336 ;; Make isearch reveal context
5337 (if (or (featurep 'xemacs)
5338 (not (boundp 'outline-isearch-open-invisible-function)))
5339 ;; Emacs 21 and XEmacs make use of the hook
5340 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5341 ;; Emacs 22 deals with this through a special variable
5342 (org-set-local 'outline-isearch-open-invisible-function
5343 (lambda (&rest ignore) (org-show-context 'isearch)))
5344 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5346 ;; Setup the pcomplete hooks
5347 (set (make-local-variable 'pcomplete-command-completion-function)
5348 'org-pcomplete-initial)
5349 (set (make-local-variable 'pcomplete-command-name-function)
5350 'org-command-at-point)
5351 (set (make-local-variable 'pcomplete-default-completion-function)
5352 'ignore)
5353 (set (make-local-variable 'pcomplete-parse-arguments-function)
5354 'org-parse-arguments)
5355 (set (make-local-variable 'pcomplete-termination-string) "")
5356 (when (>= emacs-major-version 23)
5357 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5359 ;; If empty file that did not turn on org-mode automatically, make it to.
5360 (if (and org-insert-mode-line-in-empty-file
5361 (org-called-interactively-p 'any)
5362 (= (point-min) (point-max)))
5363 (insert "# -*- mode: org -*-\n\n"))
5364 (unless org-inhibit-startup
5365 (org-unmodified
5366 (and org-startup-with-beamer-mode (org-beamer-mode))
5367 (when org-startup-align-all-tables
5368 (org-table-map-tables 'org-table-align 'quietly))
5369 (when org-startup-with-inline-images
5370 (org-display-inline-images))
5371 (when org-startup-with-latex-preview
5372 (org-preview-latex-fragment))
5373 (unless org-inhibit-startup-visibility-stuff
5374 (org-set-startup-visibility))))
5375 ;; Try to set org-hide correctly
5376 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5378 ;; Update `customize-package-emacs-version-alist'
5379 (add-to-list 'customize-package-emacs-version-alist
5380 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5381 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5382 ("8.0" . "24.4")))
5384 (defvar org-mode-transpose-word-syntax-table
5385 (let ((st (make-syntax-table)))
5386 (mapc (lambda(c) (modify-syntax-entry
5387 (string-to-char (car c)) "w p" st))
5388 org-emphasis-alist)
5389 st))
5391 (when (fboundp 'abbrev-table-put)
5392 (abbrev-table-put org-mode-abbrev-table
5393 :parents (list text-mode-abbrev-table)))
5395 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5397 (defsubst org-fix-ellipsis-at-bol ()
5398 (save-excursion (goto-char (window-start)) (recenter 0)))
5400 (defun org-find-invisible-foreground ()
5401 (let ((candidates (remove
5402 "unspecified-bg"
5403 (nconc
5404 (list (face-background 'default)
5405 (face-background 'org-default))
5406 (mapcar
5407 (lambda (alist)
5408 (when (boundp alist)
5409 (cdr (assoc 'background-color (symbol-value alist)))))
5410 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5411 (list (face-foreground 'org-hide))))))
5412 (car (remove nil candidates))))
5414 (defun org-current-time (&optional rounding-minutes past)
5415 "Current time, possibly rounded to ROUNDING-MINUTES.
5416 When ROUNDING-MINUTES is not an integer, fall back on the car of
5417 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5418 the rounding returns a past time."
5419 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5420 (car org-time-stamp-rounding-minutes)))
5421 (time (decode-time)) res)
5422 (if (< r 1)
5423 (current-time)
5424 (setq res
5425 (apply 'encode-time
5426 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5427 (nthcdr 2 time))))
5428 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5429 (seconds-to-time (- (org-float-time res) (* r 60)))
5430 res))))
5432 (defun org-today ()
5433 "Return today date, considering `org-extend-today-until'."
5434 (time-to-days
5435 (time-subtract (current-time)
5436 (list 0 (* 3600 org-extend-today-until) 0))))
5438 ;;;; Font-Lock stuff, including the activators
5440 (defvar org-mouse-map (make-sparse-keymap))
5441 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5442 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5443 (when org-mouse-1-follows-link
5444 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5445 (when org-tab-follows-link
5446 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5447 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5449 (require 'font-lock)
5451 (defconst org-non-link-chars "]\t\n\r<>")
5452 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5453 "shell" "elisp" "doi" "message"))
5454 (defvar org-link-types-re nil
5455 "Matches a link that has a url-like prefix like \"http:\"")
5456 (defvar org-link-re-with-space nil
5457 "Matches a link with spaces, optional angular brackets around it.")
5458 (defvar org-link-re-with-space2 nil
5459 "Matches a link with spaces, optional angular brackets around it.")
5460 (defvar org-link-re-with-space3 nil
5461 "Matches a link with spaces, only for internal part in bracket links.")
5462 (defvar org-angle-link-re nil
5463 "Matches link with angular brackets, spaces are allowed.")
5464 (defvar org-plain-link-re nil
5465 "Matches plain link, without spaces.")
5466 (defvar org-bracket-link-regexp nil
5467 "Matches a link in double brackets.")
5468 (defvar org-bracket-link-analytic-regexp nil
5469 "Regular expression used to analyze links.
5470 Here is what the match groups contain after a match:
5471 1: http:
5472 2: http
5473 3: path
5474 4: [desc]
5475 5: desc")
5476 (defvar org-bracket-link-analytic-regexp++ nil
5477 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5478 (defvar org-any-link-re nil
5479 "Regular expression matching any link.")
5481 (defconst org-match-sexp-depth 3
5482 "Number of stacked braces for sub/superscript matching.")
5484 (defun org-create-multibrace-regexp (left right n)
5485 "Create a regular expression which will match a balanced sexp.
5486 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5487 as single character strings.
5488 The regexp returned will match the entire expression including the
5489 delimiters. It will also define a single group which contains the
5490 match except for the outermost delimiters. The maximum depth of
5491 stacked delimiters is N. Escaping delimiters is not possible."
5492 (let* ((nothing (concat "[^" left right "]*?"))
5493 (or "\\|")
5494 (re nothing)
5495 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5496 (while (> n 1)
5497 (setq n (1- n)
5498 re (concat re or next)
5499 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5500 (concat left "\\(" re "\\)" right)))
5502 (defvar org-match-substring-regexp
5503 (concat
5504 "\\(\\S-\\)\\([_^]\\)\\("
5505 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5506 "\\|"
5507 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5508 "\\|"
5509 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5510 "The regular expression matching a sub- or superscript.")
5512 (defvar org-match-substring-with-braces-regexp
5513 (concat
5514 "\\(\\S-\\)\\([_^]\\)\\("
5515 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5516 "\\)")
5517 "The regular expression matching a sub- or superscript, forcing braces.")
5519 (defun org-make-link-regexps ()
5520 "Update the link regular expressions.
5521 This should be called after the variable `org-link-types' has changed."
5522 (setq org-link-types-re
5523 (concat
5524 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5525 org-link-re-with-space
5526 (concat
5527 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5528 "\\([^" org-non-link-chars " ]"
5529 "[^" org-non-link-chars "]*"
5530 "[^" org-non-link-chars " ]\\)>?")
5531 org-link-re-with-space2
5532 (concat
5533 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5534 "\\([^" org-non-link-chars " ]"
5535 "[^\t\n\r]*"
5536 "[^" org-non-link-chars " ]\\)>?")
5537 org-link-re-with-space3
5538 (concat
5539 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5540 "\\([^" org-non-link-chars " ]"
5541 "[^\t\n\r]*\\)")
5542 org-angle-link-re
5543 (concat
5544 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5545 "\\([^" org-non-link-chars " ]"
5546 "[^" org-non-link-chars "]*"
5547 "\\)>")
5548 org-plain-link-re
5549 (concat
5550 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5551 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5552 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5553 org-bracket-link-regexp
5554 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5555 org-bracket-link-analytic-regexp
5556 (concat
5557 "\\[\\["
5558 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5559 "\\([^]]+\\)"
5560 "\\]"
5561 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5562 "\\]")
5563 org-bracket-link-analytic-regexp++
5564 (concat
5565 "\\[\\["
5566 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5567 "\\([^]]+\\)"
5568 "\\]"
5569 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5570 "\\]")
5571 org-any-link-re
5572 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5573 org-angle-link-re "\\)\\|\\("
5574 org-plain-link-re "\\)")))
5576 (org-make-link-regexps)
5578 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5579 "Regular expression for fast time stamp matching.")
5580 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5581 "Regular expression for fast time stamp matching.")
5582 (defconst org-ts-regexp0
5583 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5584 "Regular expression matching time strings for analysis.
5585 This one does not require the space after the date, so it can be used
5586 on a string that terminates immediately after the date.")
5587 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5588 "Regular expression matching time strings for analysis.")
5589 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5590 "Regular expression matching time stamps, with groups.")
5591 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5592 "Regular expression matching time stamps (also [..]), with groups.")
5593 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5594 "Regular expression matching a time stamp range.")
5595 (defconst org-tr-regexp-both
5596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5597 "Regular expression matching a time stamp range.")
5598 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5599 org-ts-regexp "\\)?")
5600 "Regular expression matching a time stamp or time stamp range.")
5601 (defconst org-tsr-regexp-both
5602 (concat org-ts-regexp-both "\\(--?-?"
5603 org-ts-regexp-both "\\)?")
5604 "Regular expression matching a time stamp or time stamp range.
5605 The time stamps may be either active or inactive.")
5607 (defvar org-emph-face nil)
5609 (defun org-do-emphasis-faces (limit)
5610 "Run through the buffer and add overlays to emphasized strings."
5611 (let (rtn a)
5612 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5613 (if (not (= (char-after (match-beginning 3))
5614 (char-after (match-beginning 4))))
5615 (progn
5616 (setq rtn t)
5617 (setq a (assoc (match-string 3) org-emphasis-alist))
5618 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5619 'face
5620 (nth 1 a))
5621 (and (nth 4 a)
5622 (org-remove-flyspell-overlays-in
5623 (match-beginning 0) (match-end 0)))
5624 (add-text-properties (match-beginning 2) (match-end 2)
5625 '(font-lock-multiline t org-emphasis t))
5626 (when org-hide-emphasis-markers
5627 (add-text-properties (match-end 4) (match-beginning 5)
5628 '(invisible org-link))
5629 (add-text-properties (match-beginning 3) (match-end 3)
5630 '(invisible org-link)))))
5631 (backward-char 1))
5632 rtn))
5634 (defun org-emphasize (&optional char)
5635 "Insert or change an emphasis, i.e. a font like bold or italic.
5636 If there is an active region, change that region to a new emphasis.
5637 If there is no region, just insert the marker characters and position
5638 the cursor between them.
5639 CHAR should be either the marker character, or the first character of the
5640 HTML tag associated with that emphasis. If CHAR is a space, the means
5641 to remove the emphasis of the selected region.
5642 If char is not given (for example in an interactive call) it
5643 will be prompted for."
5644 (interactive)
5645 (let ((eal org-emphasis-alist) e det
5646 (erc org-emphasis-regexp-components)
5647 (prompt "")
5648 (string "") beg end move tag c s)
5649 (if (org-region-active-p)
5650 (setq beg (region-beginning) end (region-end)
5651 string (buffer-substring beg end))
5652 (setq move t))
5654 (while (setq e (pop eal))
5655 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5656 c (aref tag 0))
5657 (push (cons c (string-to-char (car e))) det)
5658 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5659 (substring tag 1)))))
5660 (setq det (nreverse det))
5661 (unless char
5662 (message "%s" (concat "Emphasis marker or tag:" prompt))
5663 (setq char (read-char-exclusive)))
5664 (setq char (or (cdr (assoc char det)) char))
5665 (if (equal char ?\ )
5666 (setq s "" move nil)
5667 (unless (assoc (char-to-string char) org-emphasis-alist)
5668 (error "No such emphasis marker: \"%c\"" char))
5669 (setq s (char-to-string char)))
5670 (while (and (> (length string) 1)
5671 (equal (substring string 0 1) (substring string -1))
5672 (assoc (substring string 0 1) org-emphasis-alist))
5673 (setq string (substring string 1 -1)))
5674 (setq string (concat s string s))
5675 (if beg (delete-region beg end))
5676 (unless (or (bolp)
5677 (string-match (concat "[" (nth 0 erc) "\n]")
5678 (char-to-string (char-before (point)))))
5679 (insert " "))
5680 (unless (or (eobp)
5681 (string-match (concat "[" (nth 1 erc) "\n]")
5682 (char-to-string (char-after (point)))))
5683 (insert " ") (backward-char 1))
5684 (insert string)
5685 (and move (backward-char 1))))
5687 (defconst org-nonsticky-props
5688 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5690 (defsubst org-rear-nonsticky-at (pos)
5691 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5693 (defun org-activate-plain-links (limit)
5694 "Run through the buffer and add overlays to links."
5695 (let (f hl)
5696 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5697 (not (org-in-src-block-p)))
5698 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5699 (setq f (get-text-property (match-beginning 0) 'face))
5700 (setq hl (org-match-string-no-properties 0))
5701 (if (or (eq f 'org-tag)
5702 (and (listp f) (memq 'org-tag f)))
5704 (add-text-properties (match-beginning 0) (match-end 0)
5705 (list 'mouse-face 'highlight
5706 'face 'org-link
5707 'htmlize-link `(:uri ,hl)
5708 'keymap org-mouse-map))
5709 (org-rear-nonsticky-at (match-end 0)))
5710 t)))
5712 (defun org-activate-code (limit)
5713 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5714 (progn
5715 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5716 (remove-text-properties (match-beginning 0) (match-end 0)
5717 '(display t invisible t intangible t))
5718 t)))
5720 (defcustom org-src-fontify-natively nil
5721 "When non-nil, fontify code in code blocks."
5722 :type 'boolean
5723 :version "24.1"
5724 :group 'org-appearance
5725 :group 'org-babel)
5727 (defcustom org-allow-promoting-top-level-subtree nil
5728 "When non-nil, allow promoting a top level subtree.
5729 The leading star of the top level headline will be replaced
5730 by a #."
5731 :type 'boolean
5732 :version "24.1"
5733 :group 'org-appearance)
5735 (defun org-fontify-meta-lines-and-blocks (limit)
5736 (condition-case nil
5737 (org-fontify-meta-lines-and-blocks-1 limit)
5738 (error (message "org-mode fontification error"))))
5740 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5741 "Fontify #+ lines and blocks."
5742 (let ((case-fold-search t))
5743 (if (re-search-forward
5744 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5745 limit t)
5746 (let ((beg (match-beginning 0))
5747 (block-start (match-end 0))
5748 (block-end nil)
5749 (lang (match-string 7))
5750 (beg1 (line-beginning-position 2))
5751 (dc1 (downcase (match-string 2)))
5752 (dc3 (downcase (match-string 3)))
5753 end end1 quoting block-type ovl)
5754 (cond
5755 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5756 ;; a single line of backend-specific content
5757 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5758 (remove-text-properties (match-beginning 0) (match-end 0)
5759 '(display t invisible t intangible t))
5760 (add-text-properties (match-beginning 1) (match-end 3)
5761 '(font-lock-fontified t face org-meta-line))
5762 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5763 '(font-lock-fontified t face org-block))
5764 ; for backend-specific code
5766 ((and (match-end 4) (equal dc3 "+begin"))
5767 ;; Truly a block
5768 (setq block-type (downcase (match-string 5))
5769 quoting (member block-type org-protecting-blocks))
5770 (when (re-search-forward
5771 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5772 nil t) ;; on purpose, we look further than LIMIT
5773 (setq end (min (point-max) (match-end 0))
5774 end1 (min (point-max) (1- (match-beginning 0))))
5775 (setq block-end (match-beginning 0))
5776 (when quoting
5777 (remove-text-properties beg end
5778 '(display t invisible t intangible t)))
5779 (add-text-properties
5780 beg end
5781 '(font-lock-fontified t font-lock-multiline t))
5782 (add-text-properties beg beg1 '(face org-meta-line))
5783 (add-text-properties end1 (min (point-max) (1+ end))
5784 '(face org-meta-line)) ; for end_src
5785 (cond
5786 ((and lang (not (string= lang "")) org-src-fontify-natively)
5787 (org-src-font-lock-fontify-block lang block-start block-end)
5788 ;; remove old background overlays
5789 (mapc (lambda (ov)
5790 (if (eq (overlay-get ov 'face) 'org-block-background)
5791 (delete-overlay ov)))
5792 (overlays-at (/ (+ beg1 block-end) 2)))
5793 ;; add a background overlay
5794 (setq ovl (make-overlay beg1 block-end))
5795 (overlay-put ovl 'face 'org-block-background)
5796 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5797 (quoting
5798 (add-text-properties beg1 (min (point-max) (1+ end1))
5799 '(face org-block))) ; end of source block
5800 ((not org-fontify-quote-and-verse-blocks))
5801 ((string= block-type "quote")
5802 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5803 ((string= block-type "verse")
5804 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5805 (add-text-properties beg beg1 '(face org-block-begin-line))
5806 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5807 '(face org-block-end-line))
5809 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5810 (add-text-properties
5811 beg (match-end 3)
5812 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5813 '(font-lock-fontified t invisible t)
5814 '(font-lock-fontified t face org-document-info-keyword)))
5815 (add-text-properties
5816 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5817 (if (string-equal dc1 "+title:")
5818 '(font-lock-fontified t face org-document-title)
5819 '(font-lock-fontified t face org-document-info))))
5820 ((or (equal dc1 "+results")
5821 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5822 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5823 "+call:" "+header:" "+headers:" "+name:"))
5824 (and (match-end 4) (equal dc3 "+attr")))
5825 (add-text-properties
5826 beg (match-end 0)
5827 '(font-lock-fontified t face org-meta-line))
5829 ((member dc3 '(" " ""))
5830 (add-text-properties
5831 beg (match-end 0)
5832 '(font-lock-fontified t face font-lock-comment-face)))
5833 ((not (member (char-after beg) '(?\ ?\t)))
5834 ;; just any other in-buffer setting, but not indented
5835 (add-text-properties
5836 beg (match-end 0)
5837 '(font-lock-fontified t face org-meta-line))
5839 (t nil))))))
5841 (defun org-activate-angle-links (limit)
5842 "Run through the buffer and add overlays to links."
5843 (if (and (re-search-forward org-angle-link-re limit t)
5844 (not (org-in-src-block-p)))
5845 (progn
5846 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5847 (add-text-properties (match-beginning 0) (match-end 0)
5848 (list 'mouse-face 'highlight
5849 'keymap org-mouse-map))
5850 (org-rear-nonsticky-at (match-end 0))
5851 t)))
5853 (defun org-activate-footnote-links (limit)
5854 "Run through the buffer and add overlays to footnotes."
5855 (let ((fn (org-footnote-next-reference-or-definition limit)))
5856 (when fn
5857 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5858 (org-remove-flyspell-overlays-in beg end)
5859 (add-text-properties beg end
5860 (list 'mouse-face 'highlight
5861 'keymap org-mouse-map
5862 'help-echo
5863 (if (= (point-at-bol) beg)
5864 "Footnote definition"
5865 "Footnote reference")
5866 'font-lock-fontified t
5867 'font-lock-multiline t
5868 'face 'org-footnote))))))
5870 (defun org-activate-bracket-links (limit)
5871 "Run through the buffer and add overlays to bracketed links."
5872 (if (and (re-search-forward org-bracket-link-regexp limit t)
5873 (not (org-in-src-block-p)))
5874 (let* ((hl (org-match-string-no-properties 1))
5875 (help (concat "LINK: " hl))
5876 ;; FIXME: Above we should remove the escapes. But that
5877 ;; requires another match, protecting match data, a lot
5878 ;; of overhead for font-lock.
5879 (ip (org-maybe-intangible
5880 (list 'invisible 'org-link
5881 'keymap org-mouse-map 'mouse-face 'highlight
5882 'font-lock-multiline t 'help-echo help
5883 'htmlize-link `(:uri ,hl))))
5884 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5885 'font-lock-multiline t 'help-echo help
5886 'htmlize-link `(:uri ,hl))))
5887 ;; We need to remove the invisible property here. Table narrowing
5888 ;; may have made some of this invisible.
5889 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5890 (remove-text-properties (match-beginning 0) (match-end 0)
5891 '(invisible nil))
5892 (if (match-end 3)
5893 (progn
5894 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5895 (org-rear-nonsticky-at (match-beginning 3))
5896 (add-text-properties (match-beginning 3) (match-end 3) vp)
5897 (org-rear-nonsticky-at (match-end 3))
5898 (add-text-properties (match-end 3) (match-end 0) ip)
5899 (org-rear-nonsticky-at (match-end 0)))
5900 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5901 (org-rear-nonsticky-at (match-beginning 1))
5902 (add-text-properties (match-beginning 1) (match-end 1) vp)
5903 (org-rear-nonsticky-at (match-end 1))
5904 (add-text-properties (match-end 1) (match-end 0) ip)
5905 (org-rear-nonsticky-at (match-end 0)))
5906 t)))
5908 (defun org-activate-dates (limit)
5909 "Run through the buffer and add overlays to dates."
5910 (if (and (re-search-forward org-tsr-regexp-both limit t)
5911 (not (equal (char-before (match-beginning 0)) 91)))
5912 (progn
5913 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5914 (add-text-properties (match-beginning 0) (match-end 0)
5915 (list 'mouse-face 'highlight
5916 'keymap org-mouse-map))
5917 (org-rear-nonsticky-at (match-end 0))
5918 (when org-display-custom-times
5919 (if (match-end 3)
5920 (org-display-custom-time (match-beginning 3) (match-end 3)))
5921 (org-display-custom-time (match-beginning 1) (match-end 1)))
5922 t)))
5924 (defvar org-target-link-regexp nil
5925 "Regular expression matching radio targets in plain text.")
5926 (make-variable-buffer-local 'org-target-link-regexp)
5927 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5928 "Regular expression matching a link target.")
5929 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5930 "Regular expression matching a radio target.")
5931 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5932 "Regular expression matching any target.")
5934 (defun org-activate-target-links (limit)
5935 "Run through the buffer and add overlays to target matches."
5936 (when org-target-link-regexp
5937 (let ((case-fold-search t))
5938 (if (re-search-forward org-target-link-regexp limit t)
5939 (progn
5940 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5941 (add-text-properties (match-beginning 0) (match-end 0)
5942 (list 'mouse-face 'highlight
5943 'keymap org-mouse-map
5944 'help-echo "Radio target link"
5945 'org-linked-text t))
5946 (org-rear-nonsticky-at (match-end 0))
5947 t)))))
5949 (defun org-update-radio-target-regexp ()
5950 "Find all radio targets in this file and update the regular expression."
5951 (interactive)
5952 (when (memq 'radio org-activate-links)
5953 (setq org-target-link-regexp
5954 (org-make-target-link-regexp (org-all-targets 'radio)))
5955 (org-restart-font-lock)))
5957 (defun org-hide-wide-columns (limit)
5958 (let (s e)
5959 (setq s (text-property-any (point) (or limit (point-max))
5960 'org-cwidth t))
5961 (when s
5962 (setq e (next-single-property-change s 'org-cwidth))
5963 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5964 (goto-char e)
5965 t)))
5967 (defvar org-latex-and-related-regexp nil
5968 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5969 (defvar org-match-substring-regexp)
5970 (defvar org-match-substring-with-braces-regexp)
5972 (defun org-compute-latex-and-related-regexp ()
5973 "Compute regular expression for LaTeX, entities and sub/superscript.
5974 Result depends on variable `org-highlight-latex-and-related'."
5975 (org-set-local
5976 'org-latex-and-related-regexp
5977 (let* ((re-sub
5978 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5979 ((eq org-use-sub-superscripts '{})
5980 (list org-match-substring-with-braces-regexp))
5981 (org-use-sub-superscripts (list org-match-substring-regexp))))
5982 (re-latex
5983 (when (memq 'latex org-highlight-latex-and-related)
5984 (let ((matchers (plist-get org-format-latex-options :matchers)))
5985 (delq nil
5986 (mapcar (lambda (x)
5987 (and (member (car x) matchers) (nth 1 x)))
5988 org-latex-regexps)))))
5989 (re-entities
5990 (when (memq 'entities org-highlight-latex-and-related)
5991 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5992 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5994 (defun org-do-latex-and-related (limit)
5995 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5996 LIMIT bounds the search for syntax to highlight. Stop at first
5997 highlighted object, if any. Return t if some highlighting was
5998 done, nil otherwise."
5999 (when (org-string-nw-p org-latex-and-related-regexp)
6000 (catch 'found
6001 (while (re-search-forward org-latex-and-related-regexp limit t)
6002 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6003 'face))
6004 '(org-code org-verbatim underline))
6005 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6006 '(?_ ?^))
6008 0)))
6009 (font-lock-prepend-text-property
6010 (+ offset (match-beginning 0)) (match-end 0)
6011 'face 'org-latex-and-related)
6012 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6013 '(font-lock-multiline t)))
6014 (throw 'found t)))
6015 nil)))
6017 (defun org-restart-font-lock ()
6018 "Restart `font-lock-mode', to force refontification."
6019 (when (and (boundp 'font-lock-mode) font-lock-mode)
6020 (font-lock-mode -1)
6021 (font-lock-mode 1)))
6023 (defun org-all-targets (&optional radio)
6024 "Return a list of all targets in this file.
6025 When optional argument RADIO is non-nil, only find radio
6026 targets."
6027 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6028 (save-excursion
6029 (goto-char (point-min))
6030 (while (re-search-forward re nil t)
6031 ;; Make sure point is really within the object.
6032 (backward-char)
6033 (let ((obj (org-element-context)))
6034 (when (memq (org-element-type obj) '(radio-target target))
6035 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6036 rtn)))
6038 (defun org-make-target-link-regexp (targets)
6039 "Make regular expression matching all strings in TARGETS.
6040 The regular expression finds the targets also if there is a line break
6041 between words."
6042 (and targets
6043 (concat
6044 "\\<\\("
6045 (mapconcat
6046 (lambda (x)
6047 (setq x (regexp-quote x))
6048 (while (string-match " +" x)
6049 (setq x (replace-match "\\s-+" t t x)))
6051 targets
6052 "\\|")
6053 "\\)\\>")))
6055 (defun org-activate-tags (limit)
6056 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6057 (progn
6058 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6059 (add-text-properties (match-beginning 1) (match-end 1)
6060 (list 'mouse-face 'highlight
6061 'keymap org-mouse-map))
6062 (org-rear-nonsticky-at (match-end 1))
6063 t)))
6065 (defun org-outline-level ()
6066 "Compute the outline level of the heading at point.
6067 If this is called at a normal headline, the level is the number of stars.
6068 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6069 (save-excursion
6070 (if (not (condition-case nil
6071 (org-back-to-heading t)
6072 (error nil)))
6074 (looking-at org-outline-regexp)
6075 (1- (- (match-end 0) (match-beginning 0))))))
6077 (defvar org-font-lock-keywords nil)
6079 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6080 "Regular expression matching a property line.")
6082 (defvar org-font-lock-hook nil
6083 "Functions to be called for special font lock stuff.")
6085 (defvar org-font-lock-set-keywords-hook nil
6086 "Functions that can manipulate `org-font-lock-extra-keywords'.
6087 This is called after `org-font-lock-extra-keywords' is defined, but before
6088 it is installed to be used by font lock. This can be useful if something
6089 needs to be inserted at a specific position in the font-lock sequence.")
6091 (defun org-font-lock-hook (limit)
6092 "Run `org-font-lock-hook' within LIMIT."
6093 (run-hook-with-args 'org-font-lock-hook limit))
6095 (defun org-set-font-lock-defaults ()
6096 "Set font lock defaults for the current buffer."
6097 (let* ((em org-fontify-emphasized-text)
6098 (lk org-activate-links)
6099 (org-font-lock-extra-keywords
6100 (list
6101 ;; Call the hook
6102 '(org-font-lock-hook)
6103 ;; Headlines
6104 `(,(if org-fontify-whole-heading-line
6105 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6106 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6107 (1 (org-get-level-face 1))
6108 (2 (org-get-level-face 2))
6109 (3 (org-get-level-face 3)))
6110 ;; Table lines
6111 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6112 (1 'org-table t))
6113 ;; Table internals
6114 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6115 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6116 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6117 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6118 ;; Drawers
6119 (list org-drawer-regexp '(0 'org-special-keyword t))
6120 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6121 ;; Properties
6122 (list org-property-re
6123 '(1 'org-special-keyword t)
6124 '(3 'org-property-value t))
6125 ;; Links
6126 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6127 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6128 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6129 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6130 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6131 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6132 (if (memq 'footnote lk) '(org-activate-footnote-links))
6133 ;; Targets.
6134 (list org-any-target-regexp '(0 'org-target t))
6135 ;; Diary sexps.
6136 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6137 ;; Macro
6138 '("{{{.+}}}" (0 'org-macro t))
6139 '(org-hide-wide-columns (0 nil append))
6140 ;; TODO keyword
6141 (list (format org-heading-keyword-regexp-format
6142 org-todo-regexp)
6143 '(2 (org-get-todo-face 2) t))
6144 ;; DONE
6145 (if org-fontify-done-headline
6146 (list (format org-heading-keyword-regexp-format
6147 (concat
6148 "\\(?:"
6149 (mapconcat 'regexp-quote org-done-keywords "\\|")
6150 "\\)"))
6151 '(2 'org-headline-done t))
6152 nil)
6153 ;; Priorities
6154 '(org-font-lock-add-priority-faces)
6155 ;; Tags
6156 '(org-font-lock-add-tag-faces)
6157 ;; Tags groups
6158 (if (and org-group-tags org-tag-groups-alist)
6159 (list (concat org-outline-regexp-bol ".+\\(:"
6160 (regexp-opt (mapcar 'car org-tag-groups-alist))
6161 ":\\).*$")
6162 '(1 'org-tag-group prepend)))
6163 ;; Special keywords
6164 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6165 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6166 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6167 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6168 ;; Emphasis
6169 (if em
6170 (if (featurep 'xemacs)
6171 '(org-do-emphasis-faces (0 nil append))
6172 '(org-do-emphasis-faces)))
6173 ;; Checkboxes
6174 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6175 1 'org-checkbox prepend)
6176 (if (cdr (assq 'checkbox org-list-automatic-rules))
6177 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6178 (0 (org-get-checkbox-statistics-face) t)))
6179 ;; Description list items
6180 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6181 1 'org-list-dt prepend)
6182 ;; ARCHIVEd headings
6183 (list (concat
6184 org-outline-regexp-bol
6185 "\\(.*:" org-archive-tag ":.*\\)")
6186 '(1 'org-archived prepend))
6187 ;; Specials
6188 '(org-do-latex-and-related)
6189 '(org-fontify-entities)
6190 '(org-raise-scripts)
6191 ;; Code
6192 '(org-activate-code (1 'org-code t))
6193 ;; COMMENT
6194 (list (format org-heading-keyword-regexp-format
6195 (concat "\\("
6196 org-comment-string "\\|" org-quote-string
6197 "\\)"))
6198 '(2 'org-special-keyword t))
6199 ;; Blocks and meta lines
6200 '(org-fontify-meta-lines-and-blocks)
6202 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6203 (run-hooks 'org-font-lock-set-keywords-hook)
6204 ;; Now set the full font-lock-keywords
6205 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6206 (org-set-local 'font-lock-defaults
6207 '(org-font-lock-keywords t nil nil backward-paragraph))
6208 (kill-local-variable 'font-lock-keywords) nil))
6210 (defun org-toggle-pretty-entities ()
6211 "Toggle the composition display of entities as UTF8 characters."
6212 (interactive)
6213 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6214 (org-restart-font-lock)
6215 (if org-pretty-entities
6216 (message "Entities are displayed as UTF8 characters")
6217 (save-restriction
6218 (widen)
6219 (org-decompose-region (point-min) (point-max))
6220 (message "Entities are displayed plain"))))
6222 (defvar org-custom-properties-overlays nil
6223 "List of overlays used for custom properties.")
6224 (make-variable-buffer-local 'org-custom-properties-overlays)
6226 (defun org-toggle-custom-properties-visibility ()
6227 "Display or hide properties in `org-custom-properties'."
6228 (interactive)
6229 (if org-custom-properties-overlays
6230 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6231 (setq org-custom-properties-overlays nil))
6232 (unless (not org-custom-properties)
6233 (save-excursion
6234 (save-restriction
6235 (widen)
6236 (goto-char (point-min))
6237 (while (re-search-forward org-property-re nil t)
6238 (mapc (lambda(p)
6239 (when (equal p (substring (match-string 1) 1 -1))
6240 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6241 (overlay-put o 'invisible t)
6242 (overlay-put o 'org-custom-property t)
6243 (push o org-custom-properties-overlays))))
6244 org-custom-properties)))))))
6246 (defun org-fontify-entities (limit)
6247 "Find an entity to fontify."
6248 (let (ee)
6249 (when org-pretty-entities
6250 (catch 'match
6251 (while (re-search-forward
6252 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6253 limit t)
6254 (if (and (not (org-in-indented-comment-line))
6255 (setq ee (org-entity-get (match-string 1)))
6256 (= (length (nth 6 ee)) 1))
6257 (let*
6258 ((end (if (equal (match-string 2) "{}")
6259 (match-end 2)
6260 (match-end 1))))
6261 (add-text-properties
6262 (match-beginning 0) end
6263 (list 'font-lock-fontified t))
6264 (compose-region (match-beginning 0) end
6265 (nth 6 ee) nil)
6266 (backward-char 1)
6267 (throw 'match t))))
6268 nil))))
6270 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6271 "Fontify string S like in Org-mode."
6272 (with-temp-buffer
6273 (insert s)
6274 (let ((org-odd-levels-only odd-levels))
6275 (org-mode)
6276 (font-lock-fontify-buffer)
6277 (buffer-string))))
6279 (defvar org-m nil)
6280 (defvar org-l nil)
6281 (defvar org-f nil)
6282 (defun org-get-level-face (n)
6283 "Get the right face for match N in font-lock matching of headlines."
6284 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6285 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6286 (if org-cycle-level-faces
6287 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6288 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6289 (cond
6290 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6291 ((eq n 2) org-f)
6292 (t (if org-level-color-stars-only nil org-f))))
6295 (defun org-get-todo-face (kwd)
6296 "Get the right face for a TODO keyword KWD.
6297 If KWD is a number, get the corresponding match group."
6298 (if (numberp kwd) (setq kwd (match-string kwd)))
6299 (or (org-face-from-face-or-color
6300 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6301 (and (member kwd org-done-keywords) 'org-done)
6302 'org-todo))
6304 (defun org-face-from-face-or-color (context inherit face-or-color)
6305 "Create a face list that inherits INHERIT, but sets the foreground color.
6306 When FACE-OR-COLOR is not a string, just return it."
6307 (if (stringp face-or-color)
6308 (list :inherit inherit
6309 (cdr (assoc context org-faces-easy-properties))
6310 face-or-color)
6311 face-or-color))
6313 (defun org-font-lock-add-tag-faces (limit)
6314 "Add the special tag faces."
6315 (when (and org-tag-faces org-tags-special-faces-re)
6316 (while (re-search-forward org-tags-special-faces-re limit t)
6317 (add-text-properties (match-beginning 1) (match-end 1)
6318 (list 'face (org-get-tag-face 1)
6319 'font-lock-fontified t))
6320 (backward-char 1))))
6322 (defun org-font-lock-add-priority-faces (limit)
6323 "Add the special priority faces."
6324 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6325 (when (save-match-data (org-at-heading-p))
6326 (add-text-properties
6327 (match-beginning 0) (match-end 0)
6328 (list 'face (or (org-face-from-face-or-color
6329 'priority 'org-priority
6330 (cdr (assoc (char-after (match-beginning 1))
6331 org-priority-faces)))
6332 'org-priority)
6333 'font-lock-fontified t)))))
6335 (defun org-get-tag-face (kwd)
6336 "Get the right face for a TODO keyword KWD.
6337 If KWD is a number, get the corresponding match group."
6338 (if (numberp kwd) (setq kwd (match-string kwd)))
6339 (or (org-face-from-face-or-color
6340 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6341 'org-tag))
6343 (defun org-unfontify-region (beg end &optional maybe_loudly)
6344 "Remove fontification and activation overlays from links."
6345 (font-lock-default-unfontify-region beg end)
6346 (let* ((buffer-undo-list t)
6347 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6348 (inhibit-modification-hooks t)
6349 deactivate-mark buffer-file-name buffer-file-truename)
6350 (org-decompose-region beg end)
6351 (remove-text-properties beg end
6352 '(mouse-face t keymap t org-linked-text t
6353 invisible t intangible t
6354 org-no-flyspell t org-emphasis t))
6355 (org-remove-font-lock-display-properties beg end)))
6357 (defconst org-script-display '(((raise -0.3) (height 0.7))
6358 ((raise 0.3) (height 0.7))
6359 ((raise -0.5))
6360 ((raise 0.5)))
6361 "Display properties for showing superscripts and subscripts.")
6363 (defun org-remove-font-lock-display-properties (beg end)
6364 "Remove specific display properties that have been added by font lock.
6365 The will remove the raise properties that are used to show superscripts
6366 and subscripts."
6367 (let (next prop)
6368 (while (< beg end)
6369 (setq next (next-single-property-change beg 'display nil end)
6370 prop (get-text-property beg 'display))
6371 (if (member prop org-script-display)
6372 (put-text-property beg next 'display nil))
6373 (setq beg next))))
6375 (defun org-raise-scripts (limit)
6376 "Add raise properties to sub/superscripts."
6377 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6378 (if (re-search-forward
6379 (if (eq org-use-sub-superscripts t)
6380 org-match-substring-regexp
6381 org-match-substring-with-braces-regexp)
6382 limit t)
6383 (let* ((pos (point)) table-p comment-p
6384 (mpos (match-beginning 3))
6385 (emph-p (get-text-property mpos 'org-emphasis))
6386 (link-p (get-text-property mpos 'mouse-face))
6387 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6388 (goto-char (point-at-bol))
6389 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6390 comment-p (org-looking-at-p "[ \t]*#"))
6391 (goto-char pos)
6392 ;; FIXME: Should we go back one character here, for a_b^c
6393 ;; (goto-char (1- pos)) ;????????????????????
6394 (if (or comment-p emph-p link-p keyw-p)
6396 (put-text-property (match-beginning 3) (match-end 0)
6397 'display
6398 (if (equal (char-after (match-beginning 2)) ?^)
6399 (nth (if table-p 3 1) org-script-display)
6400 (nth (if table-p 2 0) org-script-display)))
6401 (add-text-properties (match-beginning 2) (match-end 2)
6402 (list 'invisible t
6403 'org-dwidth t 'org-dwidth-n 1))
6404 (if (and (eq (char-after (match-beginning 3)) ?{)
6405 (eq (char-before (match-end 3)) ?}))
6406 (progn
6407 (add-text-properties
6408 (match-beginning 3) (1+ (match-beginning 3))
6409 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6410 (add-text-properties
6411 (1- (match-end 3)) (match-end 3)
6412 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6413 t)))))
6415 ;;;; Visibility cycling, including org-goto and indirect buffer
6417 ;;; Cycling
6419 (defvar org-cycle-global-status nil)
6420 (make-variable-buffer-local 'org-cycle-global-status)
6421 (put 'org-cycle-global-status 'org-state t)
6422 (defvar org-cycle-subtree-status nil)
6423 (make-variable-buffer-local 'org-cycle-subtree-status)
6424 (put 'org-cycle-subtree-status 'org-state t)
6426 (defvar org-inlinetask-min-level)
6428 ;;;###autoload
6429 (defun org-cycle (&optional arg)
6430 "TAB-action and visibility cycling for Org-mode.
6432 This is the command invoked in Org-mode by the TAB key. Its main purpose
6433 is outline visibility cycling, but it also invokes other actions
6434 in special contexts.
6436 - When this function is called with a prefix argument, rotate the entire
6437 buffer through 3 states (global cycling)
6438 1. OVERVIEW: Show only top-level headlines.
6439 2. CONTENTS: Show all headlines of all levels, but no body text.
6440 3. SHOW ALL: Show everything.
6441 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6442 determined by the variable `org-startup-folded', and by any VISIBILITY
6443 properties in the buffer.
6444 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6445 including any drawers.
6447 - When inside a table, re-align the table and move to the next field.
6449 - When point is at the beginning of a headline, rotate the subtree started
6450 by this line through 3 different states (local cycling)
6451 1. FOLDED: Only the main headline is shown.
6452 2. CHILDREN: The main headline and the direct children are shown.
6453 From this state, you can move to one of the children
6454 and zoom in further.
6455 3. SUBTREE: Show the entire subtree, including body text.
6456 If there is no subtree, switch directly from CHILDREN to FOLDED.
6458 - When point is at the beginning of an empty headline and the variable
6459 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6460 of the headline by demoting and promoting it to likely levels. This
6461 speeds up creation document structure by pressing TAB once or several
6462 times right after creating a new headline.
6464 - When there is a numeric prefix, go up to a heading with level ARG, do
6465 a `show-subtree' and return to the previous cursor position. If ARG
6466 is negative, go up that many levels.
6468 - When point is not at the beginning of a headline, execute the global
6469 binding for TAB, which is re-indenting the line. See the option
6470 `org-cycle-emulate-tab' for details.
6472 - Special case: if point is at the beginning of the buffer and there is
6473 no headline in line 1, this function will act as if called with prefix arg
6474 (C-u TAB, same as S-TAB) also when called without prefix arg.
6475 But only if also the variable `org-cycle-global-at-bob' is t."
6476 (interactive "P")
6477 (org-load-modules-maybe)
6478 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6479 (and org-cycle-level-after-item/entry-creation
6480 (or (org-cycle-level)
6481 (org-cycle-item-indentation))))
6482 (let* (message-log-max ; Don't populate the *Messages* buffer
6483 (limit-level
6484 (or org-cycle-max-level
6485 (and (boundp 'org-inlinetask-min-level)
6486 org-inlinetask-min-level
6487 (1- org-inlinetask-min-level))))
6488 (nstars (and limit-level
6489 (if org-odd-levels-only
6490 (and limit-level (1- (* limit-level 2)))
6491 limit-level)))
6492 (org-outline-regexp
6493 (if (not (derived-mode-p 'org-mode))
6494 outline-regexp
6495 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6496 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6497 (not (looking-at org-outline-regexp))))
6498 (org-cycle-hook
6499 (if bob-special
6500 (delq 'org-optimize-window-after-visibility-change
6501 (copy-sequence org-cycle-hook))
6502 org-cycle-hook))
6503 (pos (point)))
6505 (if (or bob-special (equal arg '(4)))
6506 ;; special case: use global cycling
6507 (setq arg t))
6509 (cond
6511 ((equal arg '(16))
6512 (setq last-command 'dummy)
6513 (org-set-startup-visibility)
6514 (message "Startup visibility, plus VISIBILITY properties"))
6516 ((equal arg '(64))
6517 (show-all)
6518 (message "Entire buffer visible, including drawers"))
6520 ;; Table: enter it or move to the next field.
6521 ((org-at-table-p 'any)
6522 (if (org-at-table.el-p)
6523 (message "Use C-c ' to edit table.el tables")
6524 (if arg (org-table-edit-field t)
6525 (org-table-justify-field-maybe)
6526 (call-interactively 'org-table-next-field))))
6528 ((run-hook-with-args-until-success
6529 'org-tab-after-check-for-table-hook))
6531 ;; Global cycling: delegate to `org-cycle-internal-global'.
6532 ((eq arg t) (org-cycle-internal-global))
6534 ;; Drawers: delegate to `org-flag-drawer'.
6535 ((and org-drawers org-drawer-regexp
6536 (save-excursion
6537 (beginning-of-line 1)
6538 (looking-at org-drawer-regexp)))
6539 (org-flag-drawer ; toggle block visibility
6540 (not (get-char-property (match-end 0) 'invisible))))
6542 ;; Show-subtree, ARG levels up from here.
6543 ((integerp arg)
6544 (save-excursion
6545 (org-back-to-heading)
6546 (outline-up-heading (if (< arg 0) (- arg)
6547 (- (funcall outline-level) arg)))
6548 (org-show-subtree)))
6550 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6551 ((and (featurep 'org-inlinetask)
6552 (org-inlinetask-at-task-p)
6553 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6554 (org-inlinetask-toggle-visibility))
6556 ((org-try-cdlatex-tab))
6558 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6559 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6560 (save-excursion (beginning-of-line 1)
6561 (looking-at org-outline-regexp)))
6562 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6563 (org-cycle-internal-local))
6565 ;; From there: TAB emulation and template completion.
6566 (buffer-read-only (org-back-to-heading))
6568 ((run-hook-with-args-until-success
6569 'org-tab-after-check-for-cycling-hook))
6571 ((org-try-structure-completion))
6573 ((run-hook-with-args-until-success
6574 'org-tab-before-tab-emulation-hook))
6576 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6577 (or (not (bolp))
6578 (not (looking-at org-outline-regexp))))
6579 (call-interactively (global-key-binding "\t")))
6581 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6582 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6583 (or (and (eq org-cycle-emulate-tab 'white)
6584 (= (match-end 0) (point-at-eol)))
6585 (and (eq org-cycle-emulate-tab 'whitestart)
6586 (>= (match-end 0) pos))))
6588 (eq org-cycle-emulate-tab t))
6589 (call-interactively (global-key-binding "\t")))
6591 (t (save-excursion
6592 (org-back-to-heading)
6593 (org-cycle)))))))
6595 (defun org-cycle-internal-global ()
6596 "Do the global cycling action."
6597 ;; Hack to avoid display of messages for .org attachments in Gnus
6598 (let (message-log-max ; Don't populate the *Messages* buffer
6599 (ga (string-match "\\*fontification" (buffer-name))))
6600 (cond
6601 ((and (eq last-command this-command)
6602 (eq org-cycle-global-status 'overview))
6603 ;; We just created the overview - now do table of contents
6604 ;; This can be slow in very large buffers, so indicate action
6605 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6606 (unless ga (message "CONTENTS..."))
6607 (org-content)
6608 (unless ga (message "CONTENTS...done"))
6609 (setq org-cycle-global-status 'contents)
6610 (run-hook-with-args 'org-cycle-hook 'contents))
6612 ((and (eq last-command this-command)
6613 (eq org-cycle-global-status 'contents))
6614 ;; We just showed the table of contents - now show everything
6615 (run-hook-with-args 'org-pre-cycle-hook 'all)
6616 (show-all)
6617 (unless ga (message "SHOW ALL"))
6618 (setq org-cycle-global-status 'all)
6619 (run-hook-with-args 'org-cycle-hook 'all))
6622 ;; Default action: go to overview
6623 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6624 (org-overview)
6625 (unless ga (message "OVERVIEW"))
6626 (setq org-cycle-global-status 'overview)
6627 (run-hook-with-args 'org-cycle-hook 'overview)))))
6629 (defun org-cycle-internal-local ()
6630 "Do the local cycling action."
6631 (let (message-log-max ; Don't populate the *Messages* buffer
6632 (goal-column 0) eoh eol eos has-children children-skipped struct)
6633 ;; First, determine end of headline (EOH), end of subtree or item
6634 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6635 (save-excursion
6636 (if (org-at-item-p)
6637 (progn
6638 (beginning-of-line)
6639 (setq struct (org-list-struct))
6640 (setq eoh (point-at-eol))
6641 (setq eos (org-list-get-item-end-before-blank (point) struct))
6642 (setq has-children (org-list-has-child-p (point) struct)))
6643 (org-back-to-heading)
6644 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6645 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6646 (setq has-children
6647 (or (save-excursion
6648 (let ((level (funcall outline-level)))
6649 (outline-next-heading)
6650 (and (org-at-heading-p t)
6651 (> (funcall outline-level) level))))
6652 (save-excursion
6653 (org-list-search-forward (org-item-beginning-re) eos t)))))
6654 ;; Determine end invisible part of buffer (EOL)
6655 (beginning-of-line 2)
6656 ;; XEmacs doesn't have `next-single-char-property-change'
6657 (if (featurep 'xemacs)
6658 (while (and (not (eobp)) ;; this is like `next-line'
6659 (get-char-property (1- (point)) 'invisible))
6660 (beginning-of-line 2))
6661 (while (and (not (eobp)) ;; this is like `next-line'
6662 (get-char-property (1- (point)) 'invisible))
6663 (goto-char (next-single-char-property-change (point) 'invisible))
6664 (and (eolp) (beginning-of-line 2))))
6665 (setq eol (point)))
6666 ;; Find out what to do next and set `this-command'
6667 (cond
6668 ((= eos eoh)
6669 ;; Nothing is hidden behind this heading
6670 (unless (org-before-first-heading-p)
6671 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6672 (message "EMPTY ENTRY")
6673 (setq org-cycle-subtree-status nil)
6674 (save-excursion
6675 (goto-char eos)
6676 (outline-next-heading)
6677 (if (outline-invisible-p) (org-flag-heading nil))))
6678 ((and (or (>= eol eos)
6679 (not (string-match "\\S-" (buffer-substring eol eos))))
6680 (or has-children
6681 (not (setq children-skipped
6682 org-cycle-skip-children-state-if-no-children))))
6683 ;; Entire subtree is hidden in one line: children view
6684 (unless (org-before-first-heading-p)
6685 (run-hook-with-args 'org-pre-cycle-hook 'children))
6686 (if (org-at-item-p)
6687 (org-list-set-item-visibility (point-at-bol) struct 'children)
6688 (org-show-entry)
6689 (org-with-limited-levels (show-children))
6690 ;; FIXME: This slows down the func way too much.
6691 ;; How keep drawers hidden in subtree anyway?
6692 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6693 ;; (org-cycle-hide-drawers 'subtree))
6695 ;; Fold every list in subtree to top-level items.
6696 (when (eq org-cycle-include-plain-lists 'integrate)
6697 (save-excursion
6698 (org-back-to-heading)
6699 (while (org-list-search-forward (org-item-beginning-re) eos t)
6700 (beginning-of-line 1)
6701 (let* ((struct (org-list-struct))
6702 (prevs (org-list-prevs-alist struct))
6703 (end (org-list-get-bottom-point struct)))
6704 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6705 (org-list-get-all-items (point) struct prevs))
6706 (goto-char end))))))
6707 (message "CHILDREN")
6708 (save-excursion
6709 (goto-char eos)
6710 (outline-next-heading)
6711 (if (outline-invisible-p) (org-flag-heading nil)))
6712 (setq org-cycle-subtree-status 'children)
6713 (unless (org-before-first-heading-p)
6714 (run-hook-with-args 'org-cycle-hook 'children)))
6715 ((or children-skipped
6716 (and (eq last-command this-command)
6717 (eq org-cycle-subtree-status 'children)))
6718 ;; We just showed the children, or no children are there,
6719 ;; now show everything.
6720 (unless (org-before-first-heading-p)
6721 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6722 (outline-flag-region eoh eos nil)
6723 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6724 (setq org-cycle-subtree-status 'subtree)
6725 (unless (org-before-first-heading-p)
6726 (run-hook-with-args 'org-cycle-hook 'subtree)))
6728 ;; Default action: hide the subtree.
6729 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6730 (outline-flag-region eoh eos t)
6731 (message "FOLDED")
6732 (setq org-cycle-subtree-status 'folded)
6733 (unless (org-before-first-heading-p)
6734 (run-hook-with-args 'org-cycle-hook 'folded))))))
6736 ;;;###autoload
6737 (defun org-global-cycle (&optional arg)
6738 "Cycle the global visibility. For details see `org-cycle'.
6739 With \\[universal-argument] prefix arg, switch to startup visibility.
6740 With a numeric prefix, show all headlines up to that level."
6741 (interactive "P")
6742 (let ((org-cycle-include-plain-lists
6743 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6744 (cond
6745 ((integerp arg)
6746 (show-all)
6747 (hide-sublevels arg)
6748 (setq org-cycle-global-status 'contents))
6749 ((equal arg '(4))
6750 (org-set-startup-visibility)
6751 (message "Startup visibility, plus VISIBILITY properties."))
6753 (org-cycle '(4))))))
6755 (defun org-set-startup-visibility ()
6756 "Set the visibility required by startup options and properties."
6757 (cond
6758 ((eq org-startup-folded t)
6759 (org-cycle '(4)))
6760 ((eq org-startup-folded 'content)
6761 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6762 (org-cycle '(4)) (org-cycle '(4)))))
6763 (unless (eq org-startup-folded 'showeverything)
6764 (if org-hide-block-startup (org-hide-block-all))
6765 (org-set-visibility-according-to-property 'no-cleanup)
6766 (org-cycle-hide-archived-subtrees 'all)
6767 (org-cycle-hide-drawers 'all)
6768 (org-cycle-show-empty-lines t)))
6770 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6771 "Switch subtree visibilities according to :VISIBILITY: property."
6772 (interactive)
6773 (let (org-show-entry-below state)
6774 (save-excursion
6775 (goto-char (point-min))
6776 (while (re-search-forward
6777 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6778 nil t)
6779 (setq state (match-string 1))
6780 (save-excursion
6781 (org-back-to-heading t)
6782 (hide-subtree)
6783 (org-reveal)
6784 (cond
6785 ((equal state '("fold" "folded"))
6786 (hide-subtree))
6787 ((equal state "children")
6788 (org-show-hidden-entry)
6789 (show-children))
6790 ((equal state "content")
6791 (save-excursion
6792 (save-restriction
6793 (org-narrow-to-subtree)
6794 (org-content))))
6795 ((member state '("all" "showall"))
6796 (show-subtree)))))
6797 (unless no-cleanup
6798 (org-cycle-hide-archived-subtrees 'all)
6799 (org-cycle-hide-drawers 'all)
6800 (org-cycle-show-empty-lines 'all)))))
6802 ;; This function uses outline-regexp instead of the more fundamental
6803 ;; org-outline-regexp so that org-cycle-global works outside of Org
6804 ;; buffers, where outline-regexp is needed.
6805 (defun org-overview ()
6806 "Switch to overview mode, showing only top-level headlines.
6807 Really, this shows all headlines with level equal or greater than the level
6808 of the first headline in the buffer. This is important, because if the
6809 first headline is not level one, then (hide-sublevels 1) gives confusing
6810 results."
6811 (interactive)
6812 (let ((l (org-current-line))
6813 (level (save-excursion
6814 (goto-char (point-min))
6815 (if (re-search-forward (concat "^" outline-regexp) nil t)
6816 (progn
6817 (goto-char (match-beginning 0))
6818 (funcall outline-level))))))
6819 (and level (hide-sublevels level))
6820 (recenter '(4))
6821 (org-goto-line l)))
6823 (defun org-content (&optional arg)
6824 "Show all headlines in the buffer, like a table of contents.
6825 With numerical argument N, show content up to level N."
6826 (interactive "P")
6827 (save-excursion
6828 ;; Visit all headings and show their offspring
6829 (and (integerp arg) (org-overview))
6830 (goto-char (point-max))
6831 (catch 'exit
6832 (while (and (progn (condition-case nil
6833 (outline-previous-visible-heading 1)
6834 (error (goto-char (point-min))))
6836 (looking-at org-outline-regexp))
6837 (if (integerp arg)
6838 (show-children (1- arg))
6839 (show-branches))
6840 (if (bobp) (throw 'exit nil))))))
6843 (defun org-optimize-window-after-visibility-change (state)
6844 "Adjust the window after a change in outline visibility.
6845 This function is the default value of the hook `org-cycle-hook'."
6846 (when (get-buffer-window (current-buffer))
6847 (cond
6848 ((eq state 'content) nil)
6849 ((eq state 'all) nil)
6850 ((eq state 'folded) nil)
6851 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6852 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6854 (defun org-remove-empty-overlays-at (pos)
6855 "Remove outline overlays that do not contain non-white stuff."
6856 (mapc
6857 (lambda (o)
6858 (and (eq 'outline (overlay-get o 'invisible))
6859 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6860 (overlay-end o))))
6861 (delete-overlay o)))
6862 (overlays-at pos)))
6864 (defun org-clean-visibility-after-subtree-move ()
6865 "Fix visibility issues after moving a subtree."
6866 ;; First, find a reasonable region to look at:
6867 ;; Start two siblings above, end three below
6868 (let* ((beg (save-excursion
6869 (and (org-get-last-sibling)
6870 (org-get-last-sibling))
6871 (point)))
6872 (end (save-excursion
6873 (and (org-get-next-sibling)
6874 (org-get-next-sibling)
6875 (org-get-next-sibling))
6876 (if (org-at-heading-p)
6877 (point-at-eol)
6878 (point))))
6879 (level (looking-at "\\*+"))
6880 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6881 (save-excursion
6882 (save-restriction
6883 (narrow-to-region beg end)
6884 (when re
6885 ;; Properly fold already folded siblings
6886 (goto-char (point-min))
6887 (while (re-search-forward re nil t)
6888 (if (and (not (outline-invisible-p))
6889 (save-excursion
6890 (goto-char (point-at-eol)) (outline-invisible-p)))
6891 (hide-entry))))
6892 (org-cycle-show-empty-lines 'overview)
6893 (org-cycle-hide-drawers 'overview)))))
6895 (defun org-cycle-show-empty-lines (state)
6896 "Show empty lines above all visible headlines.
6897 The region to be covered depends on STATE when called through
6898 `org-cycle-hook'. Lisp program can use t for STATE to get the
6899 entire buffer covered. Note that an empty line is only shown if there
6900 are at least `org-cycle-separator-lines' empty lines before the headline."
6901 (when (not (= org-cycle-separator-lines 0))
6902 (save-excursion
6903 (let* ((n (abs org-cycle-separator-lines))
6904 (re (cond
6905 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6906 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6907 (t (let ((ns (number-to-string (- n 2))))
6908 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6909 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6910 beg end b e)
6911 (cond
6912 ((memq state '(overview contents t))
6913 (setq beg (point-min) end (point-max)))
6914 ((memq state '(children folded))
6915 (setq beg (point) end (progn (org-end-of-subtree t t)
6916 (beginning-of-line 2)
6917 (point)))))
6918 (when beg
6919 (goto-char beg)
6920 (while (re-search-forward re end t)
6921 (unless (get-char-property (match-end 1) 'invisible)
6922 (setq e (match-end 1))
6923 (if (< org-cycle-separator-lines 0)
6924 (setq b (save-excursion
6925 (goto-char (match-beginning 0))
6926 (org-back-over-empty-lines)
6927 (if (save-excursion
6928 (goto-char (max (point-min) (1- (point))))
6929 (org-at-heading-p))
6930 (1- (point))
6931 (point))))
6932 (setq b (match-beginning 1)))
6933 (outline-flag-region b e nil)))))))
6934 ;; Never hide empty lines at the end of the file.
6935 (save-excursion
6936 (goto-char (point-max))
6937 (outline-previous-heading)
6938 (outline-end-of-heading)
6939 (if (and (looking-at "[ \t\n]+")
6940 (= (match-end 0) (point-max)))
6941 (outline-flag-region (point) (match-end 0) nil))))
6943 (defun org-show-empty-lines-in-parent ()
6944 "Move to the parent and re-show empty lines before visible headlines."
6945 (save-excursion
6946 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6947 (org-cycle-show-empty-lines context))))
6949 (defun org-files-list ()
6950 "Return `org-agenda-files' list, plus all open org-mode files.
6951 This is useful for operations that need to scan all of a user's
6952 open and agenda-wise Org files."
6953 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6954 (dolist (buf (buffer-list))
6955 (with-current-buffer buf
6956 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6957 (let ((file (expand-file-name (buffer-file-name))))
6958 (unless (member file files)
6959 (push file files))))))
6960 files))
6962 (defsubst org-entry-beginning-position ()
6963 "Return the beginning position of the current entry."
6964 (save-excursion (outline-back-to-heading t) (point)))
6966 (defsubst org-entry-end-position ()
6967 "Return the end position of the current entry."
6968 (save-excursion (outline-next-heading) (point)))
6970 (defun org-cycle-hide-drawers (state)
6971 "Re-hide all drawers after a visibility state change."
6972 (when (and (derived-mode-p 'org-mode)
6973 (not (memq state '(overview folded contents))))
6974 (save-excursion
6975 (let* ((globalp (memq state '(contents all)))
6976 (beg (if globalp (point-min) (point)))
6977 (end (if globalp (point-max)
6978 (if (eq state 'children)
6979 (save-excursion (outline-next-heading) (point))
6980 (org-end-of-subtree t)))))
6981 (goto-char beg)
6982 (while (re-search-forward org-drawer-regexp end t)
6983 (org-flag-drawer t))))))
6985 (defun org-cycle-hide-inline-tasks (state)
6986 "Re-hide inline task when switching to 'contents visibility state."
6987 (when (and (eq state 'contents)
6988 (boundp 'org-inlinetask-min-level)
6989 org-inlinetask-min-level)
6990 (hide-sublevels (1- org-inlinetask-min-level))))
6992 (defun org-flag-drawer (flag)
6993 "When FLAG is non-nil, hide the drawer we are within.
6994 Otherwise make it visible."
6995 (save-excursion
6996 (beginning-of-line 1)
6997 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6998 (let ((b (match-end 0)))
6999 (if (re-search-forward
7000 "^[ \t]*:END:"
7001 (save-excursion (outline-next-heading) (point)) t)
7002 (outline-flag-region b (point-at-eol) flag)
7003 (error ":END: line missing at position %s" b))))))
7005 (defun org-subtree-end-visible-p ()
7006 "Is the end of the current subtree visible?"
7007 (pos-visible-in-window-p
7008 (save-excursion (org-end-of-subtree t) (point))))
7010 (defun org-first-headline-recenter (&optional N)
7011 "Move cursor to the first headline and recenter the headline.
7012 Optional argument N means put the headline into the Nth line of the window."
7013 (goto-char (point-min))
7014 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7015 (beginning-of-line)
7016 (recenter (prefix-numeric-value N))))
7018 ;;; Saving and restoring visibility
7020 (defun org-outline-overlay-data (&optional use-markers)
7021 "Return a list of the locations of all outline overlays.
7022 These are overlays with the `invisible' property value `outline'.
7023 The return value is a list of cons cells, with start and stop
7024 positions for each overlay.
7025 If USE-MARKERS is set, return the positions as markers."
7026 (let (beg end)
7027 (save-excursion
7028 (save-restriction
7029 (widen)
7030 (delq nil
7031 (mapcar (lambda (o)
7032 (when (eq (overlay-get o 'invisible) 'outline)
7033 (setq beg (overlay-start o)
7034 end (overlay-end o))
7035 (and beg end (> end beg)
7036 (if use-markers
7037 (cons (move-marker (make-marker) beg)
7038 (move-marker (make-marker) end))
7039 (cons beg end)))))
7040 (overlays-in (point-min) (point-max))))))))
7042 (defun org-set-outline-overlay-data (data)
7043 "Create visibility overlays for all positions in DATA.
7044 DATA should have been made by `org-outline-overlay-data'."
7045 (let (o)
7046 (save-excursion
7047 (save-restriction
7048 (widen)
7049 (show-all)
7050 (mapc (lambda (c)
7051 (outline-flag-region (car c) (cdr c) t))
7052 data)))))
7054 ;;; Folding of blocks
7056 (defvar org-hide-block-overlays nil
7057 "Overlays hiding blocks.")
7058 (make-variable-buffer-local 'org-hide-block-overlays)
7060 (defun org-block-map (function &optional start end)
7061 "Call FUNCTION at the head of all source blocks in the current buffer.
7062 Optional arguments START and END can be used to limit the range."
7063 (let ((start (or start (point-min)))
7064 (end (or end (point-max))))
7065 (save-excursion
7066 (goto-char start)
7067 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7068 (save-excursion
7069 (save-match-data
7070 (goto-char (match-beginning 0))
7071 (funcall function)))))))
7073 (defun org-hide-block-toggle-all ()
7074 "Toggle the visibility of all blocks in the current buffer."
7075 (org-block-map #'org-hide-block-toggle))
7077 (defun org-hide-block-all ()
7078 "Fold all blocks in the current buffer."
7079 (interactive)
7080 (org-show-block-all)
7081 (org-block-map #'org-hide-block-toggle-maybe))
7083 (defun org-show-block-all ()
7084 "Unfold all blocks in the current buffer."
7085 (interactive)
7086 (mapc 'delete-overlay org-hide-block-overlays)
7087 (setq org-hide-block-overlays nil))
7089 (defun org-hide-block-toggle-maybe ()
7090 "Toggle visibility of block at point."
7091 (interactive)
7092 (let ((case-fold-search t))
7093 (if (save-excursion
7094 (beginning-of-line 1)
7095 (looking-at org-block-regexp))
7096 (progn (org-hide-block-toggle)
7097 t) ;; to signal that we took action
7098 nil))) ;; to signal that we did not
7100 (defun org-hide-block-toggle (&optional force)
7101 "Toggle the visibility of the current block."
7102 (interactive)
7103 (save-excursion
7104 (beginning-of-line)
7105 (if (re-search-forward org-block-regexp nil t)
7106 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7107 (end (match-end 0)) ;; end of entire body
7109 (if (memq t (mapcar (lambda (overlay)
7110 (eq (overlay-get overlay 'invisible)
7111 'org-hide-block))
7112 (overlays-at start)))
7113 (if (or (not force) (eq force 'off))
7114 (mapc (lambda (ov)
7115 (when (member ov org-hide-block-overlays)
7116 (setq org-hide-block-overlays
7117 (delq ov org-hide-block-overlays)))
7118 (when (eq (overlay-get ov 'invisible)
7119 'org-hide-block)
7120 (delete-overlay ov)))
7121 (overlays-at start)))
7122 (setq ov (make-overlay start end))
7123 (overlay-put ov 'invisible 'org-hide-block)
7124 ;; make the block accessible to isearch
7125 (overlay-put
7126 ov 'isearch-open-invisible
7127 (lambda (ov)
7128 (when (member ov org-hide-block-overlays)
7129 (setq org-hide-block-overlays
7130 (delq ov org-hide-block-overlays)))
7131 (when (eq (overlay-get ov 'invisible)
7132 'org-hide-block)
7133 (delete-overlay ov))))
7134 (push ov org-hide-block-overlays)))
7135 (error "Not looking at a source block"))))
7137 ;; org-tab-after-check-for-cycling-hook
7138 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7139 ;; Remove overlays when changing major mode
7140 (add-hook 'org-mode-hook
7141 (lambda () (org-add-hook 'change-major-mode-hook
7142 'org-show-block-all 'append 'local)))
7144 ;;; Org-goto
7146 (defvar org-goto-window-configuration nil)
7147 (defvar org-goto-marker nil)
7148 (defvar org-goto-map)
7149 (defun org-goto-map ()
7150 "Set the keymap `org-goto'."
7151 (setq org-goto-map
7152 (let ((map (make-sparse-keymap)))
7153 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7154 mouse-drag-region universal-argument org-occur))
7155 cmd)
7156 (while (setq cmd (pop cmds))
7157 (substitute-key-definition cmd cmd map global-map)))
7158 (suppress-keymap map)
7159 (org-defkey map "\C-m" 'org-goto-ret)
7160 (org-defkey map [(return)] 'org-goto-ret)
7161 (org-defkey map [(left)] 'org-goto-left)
7162 (org-defkey map [(right)] 'org-goto-right)
7163 (org-defkey map [(control ?g)] 'org-goto-quit)
7164 (org-defkey map "\C-i" 'org-cycle)
7165 (org-defkey map [(tab)] 'org-cycle)
7166 (org-defkey map [(down)] 'outline-next-visible-heading)
7167 (org-defkey map [(up)] 'outline-previous-visible-heading)
7168 (if org-goto-auto-isearch
7169 (if (fboundp 'define-key-after)
7170 (define-key-after map [t] 'org-goto-local-auto-isearch)
7171 nil)
7172 (org-defkey map "q" 'org-goto-quit)
7173 (org-defkey map "n" 'outline-next-visible-heading)
7174 (org-defkey map "p" 'outline-previous-visible-heading)
7175 (org-defkey map "f" 'outline-forward-same-level)
7176 (org-defkey map "b" 'outline-backward-same-level)
7177 (org-defkey map "u" 'outline-up-heading))
7178 (org-defkey map "/" 'org-occur)
7179 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7180 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7181 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7182 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7183 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7184 map)))
7186 (defconst org-goto-help
7187 "Browse buffer copy, to find location or copy text.%s
7188 RET=jump to location C-g=quit and return to previous location
7189 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7191 (defvar org-goto-start-pos) ; dynamically scoped parameter
7193 (defun org-goto (&optional alternative-interface)
7194 "Look up a different location in the current file, keeping current visibility.
7196 When you want look-up or go to a different location in a
7197 document, the fastest way is often to fold the entire buffer and
7198 then dive into the tree. This method has the disadvantage, that
7199 the previous location will be folded, which may not be what you
7200 want.
7202 This command works around this by showing a copy of the current
7203 buffer in an indirect buffer, in overview mode. You can dive
7204 into the tree in that copy, use org-occur and incremental search
7205 to find a location. When pressing RET or `Q', the command
7206 returns to the original buffer in which the visibility is still
7207 unchanged. After RET it will also jump to the location selected
7208 in the indirect buffer and expose the headline hierarchy above.
7210 With a prefix argument, use the alternative interface: e.g. if
7211 `org-goto-interface' is 'outline use 'outline-path-completion."
7212 (interactive "P")
7213 (org-goto-map)
7214 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7215 (org-refile-use-outline-path t)
7216 (org-refile-target-verify-function nil)
7217 (interface
7218 (if (not alternative-interface)
7219 org-goto-interface
7220 (if (eq org-goto-interface 'outline)
7221 'outline-path-completion
7222 'outline)))
7223 (org-goto-start-pos (point))
7224 (selected-point
7225 (if (eq interface 'outline)
7226 (car (org-get-location (current-buffer) org-goto-help))
7227 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7228 (org-refile-check-position pa)
7229 (nth 3 pa)))))
7230 (if selected-point
7231 (progn
7232 (org-mark-ring-push org-goto-start-pos)
7233 (goto-char selected-point)
7234 (if (or (outline-invisible-p) (org-invisible-p2))
7235 (org-show-context 'org-goto)))
7236 (message "Quit"))))
7238 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7239 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7240 (defvar org-goto-local-auto-isearch-map) ; defined below
7242 (defun org-get-location (buf help)
7243 "Let the user select a location in the Org-mode buffer BUF.
7244 This function uses a recursive edit. It returns the selected position
7245 or nil."
7246 (org-no-popups
7247 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7248 (isearch-hide-immediately nil)
7249 (isearch-search-fun-function
7250 (lambda () 'org-goto-local-search-headings))
7251 (org-goto-selected-point org-goto-exit-command))
7252 (save-excursion
7253 (save-window-excursion
7254 (delete-other-windows)
7255 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7256 (org-pop-to-buffer-same-window
7257 (condition-case nil
7258 (make-indirect-buffer (current-buffer) "*org-goto*")
7259 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7260 (with-output-to-temp-buffer "*Org Help*"
7261 (princ (format help (if org-goto-auto-isearch
7262 " Just type for auto-isearch."
7263 " n/p/f/b/u to navigate, q to quit."))))
7264 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7265 (setq buffer-read-only nil)
7266 (let ((org-startup-truncated t)
7267 (org-startup-folded nil)
7268 (org-startup-align-all-tables nil))
7269 (org-mode)
7270 (org-overview))
7271 (setq buffer-read-only t)
7272 (if (and (boundp 'org-goto-start-pos)
7273 (integer-or-marker-p org-goto-start-pos))
7274 (let ((org-show-hierarchy-above t)
7275 (org-show-siblings t)
7276 (org-show-following-heading t))
7277 (goto-char org-goto-start-pos)
7278 (and (outline-invisible-p) (org-show-context)))
7279 (goto-char (point-min)))
7280 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7281 (message "Select location and press RET")
7282 (use-local-map org-goto-map)
7283 (recursive-edit)))
7284 (kill-buffer "*org-goto*")
7285 (cons org-goto-selected-point org-goto-exit-command))))
7287 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7288 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7289 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7290 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7292 (defun org-goto-local-search-headings (string bound noerror)
7293 "Search and make sure that any matches are in headlines."
7294 (catch 'return
7295 (while (if isearch-forward
7296 (search-forward string bound noerror)
7297 (search-backward string bound noerror))
7298 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7299 (and (member :headline context)
7300 (not (member :tags context))))
7301 (throw 'return (point))))))
7303 (defun org-goto-local-auto-isearch ()
7304 "Start isearch."
7305 (interactive)
7306 (goto-char (point-min))
7307 (let ((keys (this-command-keys)))
7308 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7309 (isearch-mode t)
7310 (isearch-process-search-char (string-to-char keys)))))
7312 (defun org-goto-ret (&optional arg)
7313 "Finish `org-goto' by going to the new location."
7314 (interactive "P")
7315 (setq org-goto-selected-point (point)
7316 org-goto-exit-command 'return)
7317 (throw 'exit nil))
7319 (defun org-goto-left ()
7320 "Finish `org-goto' by going to the new location."
7321 (interactive)
7322 (if (org-at-heading-p)
7323 (progn
7324 (beginning-of-line 1)
7325 (setq org-goto-selected-point (point)
7326 org-goto-exit-command 'left)
7327 (throw 'exit nil))
7328 (error "Not on a heading")))
7330 (defun org-goto-right ()
7331 "Finish `org-goto' by going to the new location."
7332 (interactive)
7333 (if (org-at-heading-p)
7334 (progn
7335 (setq org-goto-selected-point (point)
7336 org-goto-exit-command 'right)
7337 (throw 'exit nil))
7338 (error "Not on a heading")))
7340 (defun org-goto-quit ()
7341 "Finish `org-goto' without cursor motion."
7342 (interactive)
7343 (setq org-goto-selected-point nil)
7344 (setq org-goto-exit-command 'quit)
7345 (throw 'exit nil))
7347 ;;; Indirect buffer display of subtrees
7349 (defvar org-indirect-dedicated-frame nil
7350 "This is the frame being used for indirect tree display.")
7351 (defvar org-last-indirect-buffer nil)
7353 (defun org-tree-to-indirect-buffer (&optional arg)
7354 "Create indirect buffer and narrow it to current subtree.
7355 With a numerical prefix ARG, go up to this level and then take that tree.
7356 If ARG is negative, go up that many levels.
7358 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7359 indirect buffer previously made with this command, to avoid proliferation of
7360 indirect buffers. However, when you call the command with a \
7361 \\[universal-argument] prefix, or
7362 when `org-indirect-buffer-display' is `new-frame', the last buffer
7363 is kept so that you can work with several indirect buffers at the same time.
7364 If `org-indirect-buffer-display' is `dedicated-frame', the \
7365 \\[universal-argument] prefix also
7366 requests that a new frame be made for the new buffer, so that the dedicated
7367 frame is not changed."
7368 (interactive "P")
7369 (let ((cbuf (current-buffer))
7370 (cwin (selected-window))
7371 (pos (point))
7372 beg end level heading ibuf)
7373 (save-excursion
7374 (org-back-to-heading t)
7375 (when (numberp arg)
7376 (setq level (org-outline-level))
7377 (if (< arg 0) (setq arg (+ level arg)))
7378 (while (> (setq level (org-outline-level)) arg)
7379 (org-up-heading-safe)))
7380 (setq beg (point)
7381 heading (org-get-heading))
7382 (org-end-of-subtree t t)
7383 (if (org-at-heading-p) (backward-char 1))
7384 (setq end (point)))
7385 (if (and (buffer-live-p org-last-indirect-buffer)
7386 (not (eq org-indirect-buffer-display 'new-frame))
7387 (not arg))
7388 (kill-buffer org-last-indirect-buffer))
7389 (setq ibuf (org-get-indirect-buffer cbuf)
7390 org-last-indirect-buffer ibuf)
7391 (cond
7392 ((or (eq org-indirect-buffer-display 'new-frame)
7393 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7394 (select-frame (make-frame))
7395 (delete-other-windows)
7396 (org-pop-to-buffer-same-window ibuf)
7397 (org-set-frame-title heading))
7398 ((eq org-indirect-buffer-display 'dedicated-frame)
7399 (raise-frame
7400 (select-frame (or (and org-indirect-dedicated-frame
7401 (frame-live-p org-indirect-dedicated-frame)
7402 org-indirect-dedicated-frame)
7403 (setq org-indirect-dedicated-frame (make-frame)))))
7404 (delete-other-windows)
7405 (org-pop-to-buffer-same-window ibuf)
7406 (org-set-frame-title (concat "Indirect: " heading)))
7407 ((eq org-indirect-buffer-display 'current-window)
7408 (org-pop-to-buffer-same-window ibuf))
7409 ((eq org-indirect-buffer-display 'other-window)
7410 (pop-to-buffer ibuf))
7411 (t (error "Invalid value")))
7412 (if (featurep 'xemacs)
7413 (save-excursion (org-mode) (turn-on-font-lock)))
7414 (narrow-to-region beg end)
7415 (show-all)
7416 (goto-char pos)
7417 (run-hook-with-args 'org-cycle-hook 'all)
7418 (and (window-live-p cwin) (select-window cwin))))
7420 (defun org-get-indirect-buffer (&optional buffer)
7421 (setq buffer (or buffer (current-buffer)))
7422 (let ((n 1) (base (buffer-name buffer)) bname)
7423 (while (buffer-live-p
7424 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7425 (setq n (1+ n)))
7426 (condition-case nil
7427 (make-indirect-buffer buffer bname 'clone)
7428 (error (make-indirect-buffer buffer bname)))))
7430 (defun org-set-frame-title (title)
7431 "Set the title of the current frame to the string TITLE."
7432 ;; FIXME: how to name a single frame in XEmacs???
7433 (unless (featurep 'xemacs)
7434 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7436 ;;;; Structure editing
7438 ;;; Inserting headlines
7440 (defun org-previous-line-empty-p (&optional next)
7441 "Is the previous line a blank line?
7442 When NEXT is non-nil, check the next line instead."
7443 (save-excursion
7444 (and (not (bobp))
7445 (or (beginning-of-line (if next 2 0)) t)
7446 (save-match-data
7447 (looking-at "[ \t]*$")))))
7449 (defun org-insert-heading (&optional arg invisible-ok)
7450 "Insert a new heading or item with same depth at point.
7451 If point is in a plain list and ARG is nil, create a new list item.
7452 With one universal prefix argument, insert a heading even in lists.
7453 With two universal prefix arguments, insert the heading at the end
7454 of the parent subtree.
7456 If point is at the beginning of a headline, insert a sibling before
7457 the current headline. If point is not at the beginning, split the line
7458 and create a new headline with the text in the current line after point
7459 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7461 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7462 This is important for non-interactive uses of the command."
7463 (interactive "P")
7464 (cond
7465 ((or (= (buffer-size) 0)
7466 (and (not (save-excursion
7467 (and (ignore-errors (org-back-to-heading invisible-ok))
7468 (org-at-heading-p))))
7469 (or arg (not (org-in-item-p)))))
7470 (insert
7471 (if (org-previous-line-empty-p) "" "\n")
7472 (if (org-in-src-block-p) ",* " "* "))
7473 (run-hooks 'org-insert-heading-hook))
7474 ((or arg (not (org-insert-item
7475 (save-excursion
7476 (beginning-of-line)
7477 (looking-at org-list-full-item-re)
7478 (match-string 3)))))
7479 (let (begn endn)
7480 (when (org-buffer-narrowed-p)
7481 (setq begn (point-min) endn (point-max))
7482 (widen))
7483 (let* ((empty-line-p nil)
7484 (eops (equal arg '(16))) ; insert at end of parent subtree
7485 (org-insert-heading-respect-content
7486 (or (not (null arg)) org-insert-heading-respect-content))
7487 (level nil)
7488 (on-heading (org-at-heading-p))
7489 (head (save-excursion
7490 (condition-case nil
7491 (progn
7492 (org-back-to-heading invisible-ok)
7493 (when (and (not on-heading)
7494 (featurep 'org-inlinetask)
7495 (integerp org-inlinetask-min-level)
7496 (>= (length (match-string 0))
7497 org-inlinetask-min-level))
7498 ;; Find a heading level before the inline task
7499 (while (and (setq level (org-up-heading-safe))
7500 (>= level org-inlinetask-min-level)))
7501 (if (org-at-heading-p)
7502 (org-back-to-heading invisible-ok)
7503 (error "This should not happen")))
7504 (unless (and (save-excursion
7505 (save-match-data
7506 (org-backward-heading-same-level 1 invisible-ok))
7507 (= (point) (match-beginning 0)))
7508 (not (org-previous-line-empty-p t)))
7509 (setq empty-line-p (org-previous-line-empty-p)))
7510 (match-string 0))
7511 (error "* "))))
7512 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7513 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7514 pos hide-previous previous-pos)
7515 (if ;; At the beginning of a heading, open a new line for insertiong
7516 (and (bolp) (org-at-heading-p)
7517 (not eops)
7518 (or (bobp)
7519 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7520 (open-line (if blank 2 1))
7521 (save-excursion
7522 (setq previous-pos (point-at-bol))
7523 (end-of-line)
7524 (setq hide-previous (outline-invisible-p)))
7525 (and org-insert-heading-respect-content
7526 (save-excursion
7527 (while (outline-invisible-p)
7528 (org-show-subtree)
7529 (org-up-heading-safe))))
7530 (let ((split
7531 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7532 (save-excursion
7533 (let ((p (point)))
7534 (goto-char (point-at-bol))
7535 (and (looking-at org-complex-heading-regexp)
7536 (match-beginning 4)
7537 (> p (match-beginning 4)))))))
7538 tags pos)
7539 (cond
7540 ;; Insert a new line, possibly at end of parent subtree
7541 (org-insert-heading-respect-content
7542 (if (not eops)
7543 (progn
7544 (org-end-of-subtree nil t)
7545 (and (looking-at "^\\*") (backward-char 1))
7546 (while (and (not (bobp))
7547 ;; Don't delete spaces in empty headlines
7548 (not (looking-back org-outline-regexp))
7549 (member (char-before) '(?\ ?\t ?\n)))
7550 (backward-delete-char 1)))
7551 (let ((p (point)))
7552 (org-up-heading-safe)
7553 (if (= p (point))
7554 (goto-char (point-max))
7555 (org-end-of-subtree nil t))))
7556 (when (featurep 'org-inlinetask)
7557 (while (and (not (eobp))
7558 (looking-at "\\(\\*+\\)[ \t]+")
7559 (>= (length (match-string 1))
7560 org-inlinetask-min-level))
7561 (org-end-of-subtree nil t)))
7562 (or (bolp) (newline))
7563 (or (org-previous-line-empty-p)
7564 (and blank (newline)))
7565 (if (or empty-line-p eops) (open-line 1)))
7566 ;; Insert a headling containing text after point
7567 ((org-at-heading-p)
7568 (when hide-previous
7569 (show-children)
7570 (org-show-entry))
7571 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7572 (setq tags (and (match-end 2) (match-string 2)))
7573 (and (match-end 1)
7574 (delete-region (match-beginning 1) (match-end 1)))
7575 (setq pos (point-at-bol))
7576 (or split (end-of-line 1))
7577 (delete-horizontal-space)
7578 (if (string-match "\\`\\*+\\'"
7579 (buffer-substring (point-at-bol) (point)))
7580 (insert " "))
7581 (newline (if blank 2 1))
7582 (when tags
7583 (save-excursion
7584 (goto-char pos)
7585 (end-of-line 1)
7586 (insert " " tags)
7587 (org-set-tags nil 'align))))
7589 (or split (end-of-line 1))
7590 (newline (if blank 2 1))))))
7591 (insert head) (just-one-space)
7592 (setq pos (point))
7593 (end-of-line 1)
7594 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7595 (when (and org-insert-heading-respect-content hide-previous)
7596 (save-excursion
7597 (goto-char previous-pos)
7598 (hide-subtree)))
7599 (when (and begn endn)
7600 (narrow-to-region (min (point) begn) (max (point) endn)))
7601 (run-hooks 'org-insert-heading-hook))))))
7603 (defun org-get-heading (&optional no-tags no-todo)
7604 "Return the heading of the current entry, without the stars.
7605 When NO-TAGS is non-nil, don't include tags.
7606 When NO-TODO is non-nil, don't include TODO keywords."
7607 (save-excursion
7608 (org-back-to-heading t)
7609 (cond
7610 ((and no-tags no-todo)
7611 (looking-at org-complex-heading-regexp)
7612 (match-string 4))
7613 (no-tags
7614 (looking-at (concat org-outline-regexp
7615 "\\(.*?\\)"
7616 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7617 (match-string 1))
7618 (no-todo
7619 (looking-at org-todo-line-regexp)
7620 (match-string 3))
7621 (t (looking-at org-heading-regexp)
7622 (match-string 2)))))
7624 (defvar orgstruct-mode) ; defined below
7626 (defun org-heading-components ()
7627 "Return the components of the current heading.
7628 This is a list with the following elements:
7629 - the level as an integer
7630 - the reduced level, different if `org-odd-levels-only' is set.
7631 - the TODO keyword, or nil
7632 - the priority character, like ?A, or nil if no priority is given
7633 - the headline text itself, or the tags string if no headline text
7634 - the tags string, or nil."
7635 (save-excursion
7636 (org-back-to-heading t)
7637 (if (let (case-fold-search)
7638 (looking-at
7639 (if orgstruct-mode
7640 org-heading-regexp
7641 org-complex-heading-regexp)))
7642 (if orgstruct-mode
7643 (list (length (match-string 1))
7644 (org-reduced-level (length (match-string 1)))
7647 (match-string 2)
7648 nil)
7649 (list (length (match-string 1))
7650 (org-reduced-level (length (match-string 1)))
7651 (org-match-string-no-properties 2)
7652 (and (match-end 3) (aref (match-string 3) 2))
7653 (org-match-string-no-properties 4)
7654 (org-match-string-no-properties 5))))))
7656 (defun org-get-entry ()
7657 "Get the entry text, after heading, entire subtree."
7658 (save-excursion
7659 (org-back-to-heading t)
7660 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7662 (defun org-insert-heading-after-current ()
7663 "Insert a new heading with same level as current, after current subtree."
7664 (interactive)
7665 (org-back-to-heading)
7666 (org-insert-heading)
7667 (org-move-subtree-down)
7668 (end-of-line 1))
7670 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7671 "Insert heading with `org-insert-heading-respect-content' set to t."
7672 (interactive "P")
7673 (let ((org-insert-heading-respect-content t))
7674 (org-insert-heading arg invisible-ok)))
7676 (defun org-insert-todo-heading-respect-content (&optional force-state)
7677 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7678 (interactive "P")
7679 (let ((org-insert-heading-respect-content t))
7680 (org-insert-todo-heading force-state t)))
7682 (defun org-insert-todo-heading (arg &optional force-heading)
7683 "Insert a new heading with the same level and TODO state as current heading.
7684 If the heading has no TODO state, or if the state is DONE, use the first
7685 state (TODO by default). Also one prefix arg, force first state. With two
7686 prefix args, force inserting at the end of the parent subtree."
7687 (interactive "P")
7688 (when (or force-heading (not (org-insert-item 'checkbox)))
7689 (org-insert-heading (or (and (equal arg '(16)) '(16))
7690 force-heading))
7691 (save-excursion
7692 (org-back-to-heading)
7693 (outline-previous-heading)
7694 (looking-at org-todo-line-regexp))
7695 (let*
7696 ((new-mark-x
7697 (if (or arg
7698 (not (match-beginning 2))
7699 (member (match-string 2) org-done-keywords))
7700 (car org-todo-keywords-1)
7701 (match-string 2)))
7702 (new-mark
7704 (run-hook-with-args-until-success
7705 'org-todo-get-default-hook new-mark-x nil)
7706 new-mark-x)))
7707 (beginning-of-line 1)
7708 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7709 (if org-treat-insert-todo-heading-as-state-change
7710 (org-todo new-mark)
7711 (insert new-mark " "))))
7712 (when org-provide-todo-statistics
7713 (org-update-parent-todo-statistics))))
7715 (defun org-insert-subheading (arg)
7716 "Insert a new subheading and demote it.
7717 Works for outline headings and for plain lists alike."
7718 (interactive "P")
7719 (org-insert-heading arg)
7720 (cond
7721 ((org-at-heading-p) (org-do-demote))
7722 ((org-at-item-p) (org-indent-item))))
7724 (defun org-insert-todo-subheading (arg)
7725 "Insert a new subheading with TODO keyword or checkbox and demote it.
7726 Works for outline headings and for plain lists alike."
7727 (interactive "P")
7728 (org-insert-todo-heading arg)
7729 (cond
7730 ((org-at-heading-p) (org-do-demote))
7731 ((org-at-item-p) (org-indent-item))))
7733 ;;; Promotion and Demotion
7735 (defvar org-after-demote-entry-hook nil
7736 "Hook run after an entry has been demoted.
7737 The cursor will be at the beginning of the entry.
7738 When a subtree is being demoted, the hook will be called for each node.")
7740 (defvar org-after-promote-entry-hook nil
7741 "Hook run after an entry has been promoted.
7742 The cursor will be at the beginning of the entry.
7743 When a subtree is being promoted, the hook will be called for each node.")
7745 (defun org-promote-subtree ()
7746 "Promote the entire subtree.
7747 See also `org-promote'."
7748 (interactive)
7749 (save-excursion
7750 (org-with-limited-levels (org-map-tree 'org-promote)))
7751 (org-fix-position-after-promote))
7753 (defun org-demote-subtree ()
7754 "Demote the entire subtree. See `org-demote'.
7755 See also `org-promote'."
7756 (interactive)
7757 (save-excursion
7758 (org-with-limited-levels (org-map-tree 'org-demote)))
7759 (org-fix-position-after-promote))
7762 (defun org-do-promote ()
7763 "Promote the current heading higher up the tree.
7764 If the region is active in `transient-mark-mode', promote all headings
7765 in the region."
7766 (interactive)
7767 (save-excursion
7768 (if (org-region-active-p)
7769 (org-map-region 'org-promote (region-beginning) (region-end))
7770 (org-promote)))
7771 (org-fix-position-after-promote))
7773 (defun org-do-demote ()
7774 "Demote the current heading lower down the tree.
7775 If the region is active in `transient-mark-mode', demote all headings
7776 in the region."
7777 (interactive)
7778 (save-excursion
7779 (if (org-region-active-p)
7780 (org-map-region 'org-demote (region-beginning) (region-end))
7781 (org-demote)))
7782 (org-fix-position-after-promote))
7784 (defun org-fix-position-after-promote ()
7785 "Make sure that after pro/demotion cursor position is right."
7786 (let ((pos (point)))
7787 (when (save-excursion
7788 (beginning-of-line 1)
7789 (looking-at org-todo-line-regexp)
7790 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7791 (cond ((eobp) (insert " "))
7792 ((eolp) (insert " "))
7793 ((equal (char-after) ?\ ) (forward-char 1))))))
7795 (defun org-current-level ()
7796 "Return the level of the current entry, or nil if before the first headline.
7797 The level is the number of stars at the beginning of the headline."
7798 (save-excursion
7799 (org-with-limited-levels
7800 (if (ignore-errors (org-back-to-heading t))
7801 (funcall outline-level)))))
7803 (defun org-get-previous-line-level ()
7804 "Return the outline depth of the last headline before the current line.
7805 Returns 0 for the first headline in the buffer, and nil if before the
7806 first headline."
7807 (let ((current-level (org-current-level))
7808 (prev-level (when (> (line-number-at-pos) 1)
7809 (save-excursion
7810 (beginning-of-line 0)
7811 (org-current-level)))))
7812 (cond ((null current-level) nil) ; Before first headline
7813 ((null prev-level) 0) ; At first headline
7814 (prev-level))))
7816 (defun org-reduced-level (l)
7817 "Compute the effective level of a heading.
7818 This takes into account the setting of `org-odd-levels-only'."
7819 (cond
7820 ((zerop l) 0)
7821 (org-odd-levels-only (1+ (floor (/ l 2))))
7822 (t l)))
7824 (defun org-level-increment ()
7825 "Return the number of stars that will be added or removed at a
7826 time to headlines when structure editing, based on the value of
7827 `org-odd-levels-only'."
7828 (if org-odd-levels-only 2 1))
7830 (defun org-get-valid-level (level &optional change)
7831 "Rectify a level change under the influence of `org-odd-levels-only'
7832 LEVEL is a current level, CHANGE is by how much the level should be
7833 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7834 even level numbers will become the next higher odd number."
7835 (if org-odd-levels-only
7836 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7837 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7838 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7839 (max 1 (+ level (or change 0)))))
7841 (if (boundp 'define-obsolete-function-alias)
7842 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7843 (define-obsolete-function-alias 'org-get-legal-level
7844 'org-get-valid-level)
7845 (define-obsolete-function-alias 'org-get-legal-level
7846 'org-get-valid-level "23.1")))
7848 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7849 ;; ̀org-with-limited-levels'
7850 (defun org-promote ()
7851 "Promote the current heading higher up the tree.
7852 If the region is active in `transient-mark-mode', promote all headings
7853 in the region."
7854 (org-back-to-heading t)
7855 (let* ((level (save-match-data (funcall outline-level)))
7856 (after-change-functions (remove 'flyspell-after-change-function
7857 after-change-functions))
7858 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7859 (diff (abs (- level (length up-head) -1))))
7860 (cond ((and (= level 1) org-called-with-limited-levels
7861 org-allow-promoting-top-level-subtree)
7862 (replace-match "# " nil t))
7863 ((= level 1)
7864 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7865 (t (replace-match up-head nil t)))
7866 ;; Fixup tag positioning
7867 (unless (= level 1)
7868 (and org-auto-align-tags (org-set-tags nil t))
7869 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7870 (run-hooks 'org-after-promote-entry-hook)))
7872 (defun org-demote ()
7873 "Demote the current heading lower down the tree.
7874 If the region is active in `transient-mark-mode', demote all headings
7875 in the region."
7876 (org-back-to-heading t)
7877 (let* ((level (save-match-data (funcall outline-level)))
7878 (after-change-functions (remove 'flyspell-after-change-function
7879 after-change-functions))
7880 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7881 (diff (abs (- level (length down-head) -1))))
7882 (replace-match down-head nil t)
7883 ;; Fixup tag positioning
7884 (and org-auto-align-tags (org-set-tags nil t))
7885 (if org-adapt-indentation (org-fixup-indentation diff))
7886 (run-hooks 'org-after-demote-entry-hook)))
7888 (defun org-cycle-level ()
7889 "Cycle the level of an empty headline through possible states.
7890 This goes first to child, then to parent, level, then up the hierarchy.
7891 After top level, it switches back to sibling level."
7892 (interactive)
7893 (let ((org-adapt-indentation nil))
7894 (when (org-point-at-end-of-empty-headline)
7895 (setq this-command 'org-cycle-level) ; Only needed for caching
7896 (let ((cur-level (org-current-level))
7897 (prev-level (org-get-previous-line-level)))
7898 (cond
7899 ;; If first headline in file, promote to top-level.
7900 ((= prev-level 0)
7901 (loop repeat (/ (- cur-level 1) (org-level-increment))
7902 do (org-do-promote)))
7903 ;; If same level as prev, demote one.
7904 ((= prev-level cur-level)
7905 (org-do-demote))
7906 ;; If parent is top-level, promote to top level if not already.
7907 ((= prev-level 1)
7908 (loop repeat (/ (- cur-level 1) (org-level-increment))
7909 do (org-do-promote)))
7910 ;; If top-level, return to prev-level.
7911 ((= cur-level 1)
7912 (loop repeat (/ (- prev-level 1) (org-level-increment))
7913 do (org-do-demote)))
7914 ;; If less than prev-level, promote one.
7915 ((< cur-level prev-level)
7916 (org-do-promote))
7917 ;; If deeper than prev-level, promote until higher than
7918 ;; prev-level.
7919 ((> cur-level prev-level)
7920 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7921 do (org-do-promote))))
7922 t))))
7924 (defun org-map-tree (fun)
7925 "Call FUN for every heading underneath the current one."
7926 (org-back-to-heading)
7927 (let ((level (funcall outline-level)))
7928 (save-excursion
7929 (funcall fun)
7930 (while (and (progn
7931 (outline-next-heading)
7932 (> (funcall outline-level) level))
7933 (not (eobp)))
7934 (funcall fun)))))
7936 (defun org-map-region (fun beg end)
7937 "Call FUN for every heading between BEG and END."
7938 (let ((org-ignore-region t))
7939 (save-excursion
7940 (setq end (copy-marker end))
7941 (goto-char beg)
7942 (if (and (re-search-forward org-outline-regexp-bol nil t)
7943 (< (point) end))
7944 (funcall fun))
7945 (while (and (progn
7946 (outline-next-heading)
7947 (< (point) end))
7948 (not (eobp)))
7949 (funcall fun)))))
7951 (defvar org-property-end-re) ; silence byte-compiler
7952 (defun org-fixup-indentation (diff)
7953 "Change the indentation in the current entry by DIFF.
7954 However, if any line in the current entry has no indentation, or if it
7955 would end up with no indentation after the change, nothing at all is done."
7956 (save-excursion
7957 (let ((end (save-excursion (outline-next-heading)
7958 (point-marker)))
7959 (prohibit (if (> diff 0)
7960 "^\\S-"
7961 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7962 col)
7963 (unless (save-excursion (end-of-line 1)
7964 (re-search-forward prohibit end t))
7965 (while (and (< (point) end)
7966 (re-search-forward "^[ \t]+" end t))
7967 (goto-char (match-end 0))
7968 (setq col (current-column))
7969 (if (< diff 0) (replace-match ""))
7970 (org-indent-to-column (+ diff col))))
7971 (move-marker end nil))))
7973 (defun org-convert-to-odd-levels ()
7974 "Convert an org-mode file with all levels allowed to one with odd levels.
7975 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7976 level 5 etc."
7977 (interactive)
7978 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7979 (let ((outline-level 'org-outline-level)
7980 (org-odd-levels-only nil) n)
7981 (save-excursion
7982 (goto-char (point-min))
7983 (while (re-search-forward "^\\*\\*+ " nil t)
7984 (setq n (- (length (match-string 0)) 2))
7985 (while (>= (setq n (1- n)) 0)
7986 (org-demote))
7987 (end-of-line 1))))))
7989 (defun org-convert-to-oddeven-levels ()
7990 "Convert an org-mode file with only odd levels to one with odd/even levels.
7991 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7992 file contains a section with an even level, conversion would
7993 destroy the structure of the file. An error is signaled in this
7994 case."
7995 (interactive)
7996 (goto-char (point-min))
7997 ;; First check if there are no even levels
7998 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7999 (org-show-context t)
8000 (error "Not all levels are odd in this file. Conversion not possible"))
8001 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8002 (let ((outline-regexp org-outline-regexp)
8003 (outline-level 'org-outline-level)
8004 (org-odd-levels-only nil) n)
8005 (save-excursion
8006 (goto-char (point-min))
8007 (while (re-search-forward "^\\*\\*+ " nil t)
8008 (setq n (/ (1- (length (match-string 0))) 2))
8009 (while (>= (setq n (1- n)) 0)
8010 (org-promote))
8011 (end-of-line 1))))))
8013 (defun org-tr-level (n)
8014 "Make N odd if required."
8015 (if org-odd-levels-only (1+ (/ n 2)) n))
8017 ;;; Vertical tree motion, cutting and pasting of subtrees
8019 (defun org-move-subtree-up (&optional arg)
8020 "Move the current subtree up past ARG headlines of the same level."
8021 (interactive "p")
8022 (org-move-subtree-down (- (prefix-numeric-value arg))))
8024 (defun org-move-subtree-down (&optional arg)
8025 "Move the current subtree down past ARG headlines of the same level."
8026 (interactive "p")
8027 (setq arg (prefix-numeric-value arg))
8028 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8029 'org-get-last-sibling))
8030 (ins-point (make-marker))
8031 (cnt (abs arg))
8032 (col (current-column))
8033 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8034 ;; Select the tree
8035 (org-back-to-heading)
8036 (setq beg0 (point))
8037 (save-excursion
8038 (setq ne-beg (org-back-over-empty-lines))
8039 (setq beg (point)))
8040 (save-match-data
8041 (save-excursion (outline-end-of-heading)
8042 (setq folded (outline-invisible-p)))
8043 (outline-end-of-subtree))
8044 (outline-next-heading)
8045 (setq ne-end (org-back-over-empty-lines))
8046 (setq end (point))
8047 (goto-char beg0)
8048 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8049 ;; include less whitespace
8050 (save-excursion
8051 (goto-char beg)
8052 (forward-line (- ne-beg ne-end))
8053 (setq beg (point))))
8054 ;; Find insertion point, with error handling
8055 (while (> cnt 0)
8056 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8057 (progn (goto-char beg0)
8058 (user-error "Cannot move past superior level or buffer limit")))
8059 (setq cnt (1- cnt)))
8060 (if (> arg 0)
8061 ;; Moving forward - still need to move over subtree
8062 (progn (org-end-of-subtree t t)
8063 (save-excursion
8064 (org-back-over-empty-lines)
8065 (or (bolp) (newline)))))
8066 (setq ne-ins (org-back-over-empty-lines))
8067 (move-marker ins-point (point))
8068 (setq txt (buffer-substring beg end))
8069 (org-save-markers-in-region beg end)
8070 (delete-region beg end)
8071 (org-remove-empty-overlays-at beg)
8072 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8073 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8074 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8075 (let ((bbb (point)))
8076 (insert-before-markers txt)
8077 (org-reinstall-markers-in-region bbb)
8078 (move-marker ins-point bbb))
8079 (or (bolp) (insert "\n"))
8080 (setq ins-end (point))
8081 (goto-char ins-point)
8082 (org-skip-whitespace)
8083 (when (and (< arg 0)
8084 (org-first-sibling-p)
8085 (> ne-ins ne-beg))
8086 ;; Move whitespace back to beginning
8087 (save-excursion
8088 (goto-char ins-end)
8089 (let ((kill-whole-line t))
8090 (kill-line (- ne-ins ne-beg)) (point)))
8091 (insert (make-string (- ne-ins ne-beg) ?\n)))
8092 (move-marker ins-point nil)
8093 (if folded
8094 (hide-subtree)
8095 (org-show-entry)
8096 (show-children)
8097 (org-cycle-hide-drawers 'children))
8098 (org-clean-visibility-after-subtree-move)
8099 ;; move back to the initial column we were at
8100 (move-to-column col)))
8102 (defvar org-subtree-clip ""
8103 "Clipboard for cut and paste of subtrees.
8104 This is actually only a copy of the kill, because we use the normal kill
8105 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8107 (defvar org-subtree-clip-folded nil
8108 "Was the last copied subtree folded?
8109 This is used to fold the tree back after pasting.")
8111 (defun org-cut-subtree (&optional n)
8112 "Cut the current subtree into the clipboard.
8113 With prefix arg N, cut this many sequential subtrees.
8114 This is a short-hand for marking the subtree and then cutting it."
8115 (interactive "p")
8116 (org-copy-subtree n 'cut))
8118 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8119 "Cut the current subtree into the clipboard.
8120 With prefix arg N, cut this many sequential subtrees.
8121 This is a short-hand for marking the subtree and then copying it.
8122 If CUT is non-nil, actually cut the subtree.
8123 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8124 of some markers in the region, even if CUT is non-nil. This is
8125 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8126 (interactive "p")
8127 (let (beg end folded (beg0 (point)))
8128 (if (org-called-interactively-p 'any)
8129 (org-back-to-heading nil) ; take what looks like a subtree
8130 (org-back-to-heading t)) ; take what is really there
8131 (setq beg (point))
8132 (skip-chars-forward " \t\r\n")
8133 (save-match-data
8134 (if nosubtrees
8135 (outline-next-heading)
8136 (save-excursion (outline-end-of-heading)
8137 (setq folded (outline-invisible-p)))
8138 (condition-case nil
8139 (org-forward-heading-same-level (1- n) t)
8140 (error nil))
8141 (org-end-of-subtree t t)))
8142 (setq end (point))
8143 (goto-char beg0)
8144 (when (> end beg)
8145 (setq org-subtree-clip-folded folded)
8146 (when (or cut force-store-markers)
8147 (org-save-markers-in-region beg end))
8148 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8149 (setq org-subtree-clip (current-kill 0))
8150 (message "%s: Subtree(s) with %d characters"
8151 (if cut "Cut" "Copied")
8152 (length org-subtree-clip)))))
8154 (defun org-paste-subtree (&optional level tree for-yank)
8155 "Paste the clipboard as a subtree, with modification of headline level.
8156 The entire subtree is promoted or demoted in order to match a new headline
8157 level.
8159 If the cursor is at the beginning of a headline, the same level as
8160 that headline is used to paste the tree.
8162 If not, the new level is derived from the *visible* headings
8163 before and after the insertion point, and taken to be the inferior headline
8164 level of the two. So if the previous visible heading is level 3 and the
8165 next is level 4 (or vice versa), level 4 will be used for insertion.
8166 This makes sure that the subtree remains an independent subtree and does
8167 not swallow low level entries.
8169 You can also force a different level, either by using a numeric prefix
8170 argument, or by inserting the heading marker by hand. For example, if the
8171 cursor is after \"*****\", then the tree will be shifted to level 5.
8173 If optional TREE is given, use this text instead of the kill ring.
8175 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8176 move back over whitespace before inserting, and move point to the end of
8177 the inserted text when done."
8178 (interactive "P")
8179 (setq tree (or tree (and kill-ring (current-kill 0))))
8180 (unless (org-kill-is-subtree-p tree)
8181 (error "%s"
8182 (substitute-command-keys
8183 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8184 (org-with-limited-levels
8185 (let* ((visp (not (outline-invisible-p)))
8186 (txt tree)
8187 (^re_ "\\(\\*+\\)[ \t]*")
8188 (old-level (if (string-match org-outline-regexp-bol txt)
8189 (- (match-end 0) (match-beginning 0) 1)
8190 -1))
8191 (force-level (cond (level (prefix-numeric-value level))
8192 ((and (looking-at "[ \t]*$")
8193 (string-match
8194 "^\\*+$" (buffer-substring
8195 (point-at-bol) (point))))
8196 (- (match-end 1) (match-beginning 1)))
8197 ((and (bolp)
8198 (looking-at org-outline-regexp))
8199 (- (match-end 0) (point) 1))))
8200 (previous-level (save-excursion
8201 (condition-case nil
8202 (progn
8203 (outline-previous-visible-heading 1)
8204 (if (looking-at ^re_)
8205 (- (match-end 0) (match-beginning 0) 1)
8207 (error 1))))
8208 (next-level (save-excursion
8209 (condition-case nil
8210 (progn
8211 (or (looking-at org-outline-regexp)
8212 (outline-next-visible-heading 1))
8213 (if (looking-at ^re_)
8214 (- (match-end 0) (match-beginning 0) 1)
8216 (error 1))))
8217 (new-level (or force-level (max previous-level next-level)))
8218 (shift (if (or (= old-level -1)
8219 (= new-level -1)
8220 (= old-level new-level))
8222 (- new-level old-level)))
8223 (delta (if (> shift 0) -1 1))
8224 (func (if (> shift 0) 'org-demote 'org-promote))
8225 (org-odd-levels-only nil)
8226 beg end newend)
8227 ;; Remove the forced level indicator
8228 (if force-level
8229 (delete-region (point-at-bol) (point)))
8230 ;; Paste
8231 (beginning-of-line (if (bolp) 1 2))
8232 (setq beg (point))
8233 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8234 (insert-before-markers txt)
8235 (unless (string-match "\n\\'" txt) (insert "\n"))
8236 (setq newend (point))
8237 (org-reinstall-markers-in-region beg)
8238 (setq end (point))
8239 (goto-char beg)
8240 (skip-chars-forward " \t\n\r")
8241 (setq beg (point))
8242 (if (and (outline-invisible-p) visp)
8243 (save-excursion (outline-show-heading)))
8244 ;; Shift if necessary
8245 (unless (= shift 0)
8246 (save-restriction
8247 (narrow-to-region beg end)
8248 (while (not (= shift 0))
8249 (org-map-region func (point-min) (point-max))
8250 (setq shift (+ delta shift)))
8251 (goto-char (point-min))
8252 (setq newend (point-max))))
8253 (when (or (org-called-interactively-p 'interactive) for-yank)
8254 (message "Clipboard pasted as level %d subtree" new-level))
8255 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8256 kill-ring
8257 (eq org-subtree-clip (current-kill 0))
8258 org-subtree-clip-folded)
8259 ;; The tree was folded before it was killed/copied
8260 (hide-subtree))
8261 (and for-yank (goto-char newend)))))
8263 (defun org-kill-is-subtree-p (&optional txt)
8264 "Check if the current kill is an outline subtree, or a set of trees.
8265 Returns nil if kill does not start with a headline, or if the first
8266 headline level is not the largest headline level in the tree.
8267 So this will actually accept several entries of equal levels as well,
8268 which is OK for `org-paste-subtree'.
8269 If optional TXT is given, check this string instead of the current kill."
8270 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8271 (re (org-get-limited-outline-regexp))
8272 (^re (concat "^" re))
8273 (start-level (and kill
8274 (string-match
8275 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8276 kill)
8277 (- (match-end 2) (match-beginning 2) 1)))
8278 (start (1+ (or (match-beginning 2) -1))))
8279 (if (not start-level)
8280 (progn
8281 nil) ;; does not even start with a heading
8282 (catch 'exit
8283 (while (setq start (string-match ^re kill (1+ start)))
8284 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8285 (throw 'exit nil)))
8286 t))))
8288 (defvar org-markers-to-move nil
8289 "Markers that should be moved with a cut-and-paste operation.
8290 Those markers are stored together with their positions relative to
8291 the start of the region.")
8293 (defun org-save-markers-in-region (beg end)
8294 "Check markers in region.
8295 If these markers are between BEG and END, record their position relative
8296 to BEG, so that after moving the block of text, we can put the markers back
8297 into place.
8298 This function gets called just before an entry or tree gets cut from the
8299 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8300 called immediately, to move the markers with the entries."
8301 (setq org-markers-to-move nil)
8302 (when (featurep 'org-clock)
8303 (org-clock-save-markers-for-cut-and-paste beg end))
8304 (when (featurep 'org-agenda)
8305 (org-agenda-save-markers-for-cut-and-paste beg end)))
8307 (defun org-check-and-save-marker (marker beg end)
8308 "Check if MARKER is between BEG and END.
8309 If yes, remember the marker and the distance to BEG."
8310 (when (and (marker-buffer marker)
8311 (equal (marker-buffer marker) (current-buffer)))
8312 (if (and (>= marker beg) (< marker end))
8313 (push (cons marker (- marker beg)) org-markers-to-move))))
8315 (defun org-reinstall-markers-in-region (beg)
8316 "Move all remembered markers to their position relative to BEG."
8317 (mapc (lambda (x)
8318 (move-marker (car x) (+ beg (cdr x))))
8319 org-markers-to-move)
8320 (setq org-markers-to-move nil))
8322 (defun org-narrow-to-subtree ()
8323 "Narrow buffer to the current subtree."
8324 (interactive)
8325 (save-excursion
8326 (save-match-data
8327 (org-with-limited-levels
8328 (narrow-to-region
8329 (progn (org-back-to-heading t) (point))
8330 (progn (org-end-of-subtree t t)
8331 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8332 (point)))))))
8334 (defun org-narrow-to-block ()
8335 "Narrow buffer to the current block."
8336 (interactive)
8337 (let* ((case-fold-search t)
8338 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8339 "^[ \t]*#\\+end_.*")))
8340 (if blockp
8341 (narrow-to-region (car blockp) (cdr blockp))
8342 (error "Not in a block"))))
8344 (eval-when-compile
8345 (defvar org-property-drawer-re))
8347 (defvar org-property-start-re) ;; defined below
8348 (defun org-clone-subtree-with-time-shift (n &optional shift)
8349 "Clone the task (subtree) at point N times.
8350 The clones will be inserted as siblings.
8352 In interactive use, the user will be prompted for the number of
8353 clones to be produced. When called with a universal prefix argument
8354 and if the entry has a timestamp, the user will also be prompted for
8355 a time shift, which may be a repeater as used in time stamps, for
8356 example `+3d'.
8358 When a valid repeater is given and the entry contains any time
8359 stamps, the clones will become a sequence in time, with time
8360 stamps in the subtree shifted for each clone produced. If SHIFT
8361 is nil or the empty string, time stamps will be left alone. The
8362 ID property of the original subtree is removed.
8364 If the original subtree did contain time stamps with a repeater,
8365 the following will happen:
8366 - the repeater will be removed in each clone
8367 - an additional clone will be produced, with the current, unshifted
8368 date(s) in the entry.
8369 - the original entry will be placed *after* all the clones, with
8370 repeater intact.
8371 - the start days in the repeater in the original entry will be shifted
8372 to past the last clone.
8373 In this way you can spell out a number of instances of a repeating task,
8374 and still retain the repeater to cover future instances of the task."
8375 (interactive "nNumber of clones to produce: ")
8376 (let ((shift
8377 (or shift
8378 (if (and (equal current-prefix-arg '(4))
8379 (save-excursion
8380 (re-search-forward org-ts-regexp-both
8381 (save-excursion
8382 (org-end-of-subtree t)
8383 (point)) t)))
8384 (read-from-minibuffer
8385 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8386 ""))) ;; No time shift
8387 (n-no-remove -1)
8388 (drawer-re org-drawer-regexp)
8389 beg end template task idprop
8390 shift-n shift-what doshift nmin nmax)
8391 (if (not (and (integerp n) (> n 0)))
8392 (error "Invalid number of replications %s" n))
8393 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8394 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8395 shift)))
8396 (error "Invalid shift specification %s" shift))
8397 (when doshift
8398 (setq shift-n (string-to-number (match-string 1 shift))
8399 shift-what (cdr (assoc (match-string 2 shift)
8400 '(("d" . day) ("w" . week)
8401 ("m" . month) ("y" . year))))))
8402 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8403 (setq nmin 1 nmax n)
8404 (org-back-to-heading t)
8405 (setq beg (point))
8406 (setq idprop (org-entry-get nil "ID"))
8407 (org-end-of-subtree t t)
8408 (or (bolp) (insert "\n"))
8409 (setq end (point))
8410 (setq template (buffer-substring beg end))
8411 (when (and doshift
8412 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8413 (delete-region beg end)
8414 (setq end beg)
8415 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8416 (goto-char end)
8417 (loop for n from nmin to nmax do
8418 ;; prepare clone
8419 (with-temp-buffer
8420 (insert template)
8421 (org-mode)
8422 (goto-char (point-min))
8423 (org-show-subtree)
8424 (and idprop (if org-clone-delete-id
8425 (org-entry-delete nil "ID")
8426 (org-id-get-create t)))
8427 (unless (= n 0)
8428 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8429 (kill-whole-line))
8430 (goto-char (point-min))
8431 (while (re-search-forward drawer-re nil t)
8432 (mapc (lambda (d)
8433 (org-remove-empty-drawer-at d (point))) org-drawers)))
8434 (goto-char (point-min))
8435 (when doshift
8436 (while (re-search-forward org-ts-regexp-both nil t)
8437 (org-timestamp-change (* n shift-n) shift-what))
8438 (unless (= n n-no-remove)
8439 (goto-char (point-min))
8440 (while (re-search-forward org-ts-regexp nil t)
8441 (save-excursion
8442 (goto-char (match-beginning 0))
8443 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8444 (delete-region (match-beginning 1) (match-end 1)))))))
8445 (setq task (buffer-string)))
8446 (insert task))
8447 (goto-char beg)))
8449 ;;; Outline Sorting
8451 (defun org-sort (with-case)
8452 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8453 Optional argument WITH-CASE means sort case-sensitively."
8454 (interactive "P")
8455 (cond
8456 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8457 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8459 (org-call-with-arg 'org-sort-entries with-case))))
8461 (defun org-sort-remove-invisible (s)
8462 "Remove invisible links from string S."
8463 (remove-text-properties 0 (length s) org-rm-props s)
8464 (while (string-match org-bracket-link-regexp s)
8465 (setq s (replace-match (if (match-end 2)
8466 (match-string 3 s)
8467 (match-string 1 s)) t t s)))
8468 (let ((st (format " %s " s)))
8469 (while (string-match org-emph-re st)
8470 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8471 (setq s (substring st 1 -1)))
8474 (defvar org-priority-regexp) ; defined later in the file
8476 (defvar org-after-sorting-entries-or-items-hook nil
8477 "Hook that is run after a bunch of entries or items have been sorted.
8478 When children are sorted, the cursor is in the parent line when this
8479 hook gets called. When a region or a plain list is sorted, the cursor
8480 will be in the first entry of the sorted region/list.")
8482 (defun org-sort-entries
8483 (&optional with-case sorting-type getkey-func compare-func property)
8484 "Sort entries on a certain level of an outline tree.
8485 If there is an active region, the entries in the region are sorted.
8486 Else, if the cursor is before the first entry, sort the top-level items.
8487 Else, the children of the entry at point are sorted.
8489 Sorting can be alphabetically, numerically, by date/time as given by
8490 a time stamp, by a property, by priority order, or by a custom function.
8492 The command prompts for the sorting type unless it has been given to the
8493 function through the SORTING-TYPE argument, which needs to be a character,
8494 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8495 precise meaning of each character:
8497 n Numerically, by converting the beginning of the entry/item to a number.
8498 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8499 o By order of TODO keywords.
8500 t By date/time, either the first active time stamp in the entry, or, if
8501 none exist, by the first inactive one.
8502 s By the scheduled date/time.
8503 d By deadline date/time.
8504 c By creation time, which is assumed to be the first inactive time stamp
8505 at the beginning of a line.
8506 p By priority according to the cookie.
8507 r By the value of a property.
8509 Capital letters will reverse the sort order.
8511 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8512 called with point at the beginning of the record. It must return either
8513 a string or a number that should serve as the sorting key for that record.
8515 Comparing entries ignores case by default. However, with an optional argument
8516 WITH-CASE, the sorting considers case as well.
8518 Sorting is done against the visible part of the headlines, it ignores hidden
8519 links."
8520 (interactive "P")
8521 (let ((case-func (if with-case 'identity 'downcase))
8522 (cmstr
8523 ;; The clock marker is lost when using `sort-subr', let's
8524 ;; store the clocking string.
8525 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8526 (save-excursion
8527 (goto-char org-clock-marker)
8528 (looking-back "^.*") (match-string-no-properties 0))))
8529 start beg end stars re re2
8530 txt what tmp)
8531 ;; Find beginning and end of region to sort
8532 (cond
8533 ((org-region-active-p)
8534 ;; we will sort the region
8535 (setq end (region-end)
8536 what "region")
8537 (goto-char (region-beginning))
8538 (if (not (org-at-heading-p)) (outline-next-heading))
8539 (setq start (point)))
8540 ((or (org-at-heading-p)
8541 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8542 ;; we will sort the children of the current headline
8543 (org-back-to-heading)
8544 (setq start (point)
8545 end (progn (org-end-of-subtree t t)
8546 (or (bolp) (insert "\n"))
8547 (org-back-over-empty-lines)
8548 (point))
8549 what "children")
8550 (goto-char start)
8551 (show-subtree)
8552 (outline-next-heading))
8554 ;; we will sort the top-level entries in this file
8555 (goto-char (point-min))
8556 (or (org-at-heading-p) (outline-next-heading))
8557 (setq start (point))
8558 (goto-char (point-max))
8559 (beginning-of-line 1)
8560 (when (looking-at ".*?\\S-")
8561 ;; File ends in a non-white line
8562 (end-of-line 1)
8563 (insert "\n"))
8564 (setq end (point-max))
8565 (setq what "top-level")
8566 (goto-char start)
8567 (show-all)))
8569 (setq beg (point))
8570 (if (>= beg end) (error "Nothing to sort"))
8572 (looking-at "\\(\\*+\\)")
8573 (setq stars (match-string 1)
8574 re (concat "^" (regexp-quote stars) " +")
8575 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8576 txt (buffer-substring beg end))
8577 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8578 (if (and (not (equal stars "*")) (string-match re2 txt))
8579 (error "Region to sort contains a level above the first entry"))
8581 (unless sorting-type
8582 (message
8583 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8584 [t]ime [s]cheduled [d]eadline [c]reated
8585 A/N/P/R/O/F/T/S/D/C means reversed:"
8586 what)
8587 (setq sorting-type (read-char-exclusive))
8589 (unless getkey-func
8590 (and (= (downcase sorting-type) ?f)
8591 (setq getkey-func
8592 (org-icompleting-read "Sort using function: "
8593 obarray 'fboundp t nil nil))
8594 (setq getkey-func (intern getkey-func))))
8596 (and (= (downcase sorting-type) ?r)
8597 (not property)
8598 (setq property
8599 (org-icompleting-read "Property: "
8600 (mapcar 'list (org-buffer-property-keys t))
8601 nil t))))
8603 (message "Sorting entries...")
8605 (save-restriction
8606 (narrow-to-region start end)
8607 (let ((dcst (downcase sorting-type))
8608 (case-fold-search nil)
8609 (now (current-time)))
8610 (sort-subr
8611 (/= dcst sorting-type)
8612 ;; This function moves to the beginning character of the "record" to
8613 ;; be sorted.
8614 (lambda nil
8615 (if (re-search-forward re nil t)
8616 (goto-char (match-beginning 0))
8617 (goto-char (point-max))))
8618 ;; This function moves to the last character of the "record" being
8619 ;; sorted.
8620 (lambda nil
8621 (save-match-data
8622 (condition-case nil
8623 (outline-forward-same-level 1)
8624 (error
8625 (goto-char (point-max))))))
8626 ;; This function returns the value that gets sorted against.
8627 (lambda nil
8628 (cond
8629 ((= dcst ?n)
8630 (if (looking-at org-complex-heading-regexp)
8631 (string-to-number (org-sort-remove-invisible (match-string 4)))
8632 nil))
8633 ((= dcst ?a)
8634 (if (looking-at org-complex-heading-regexp)
8635 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8636 nil))
8637 ((= dcst ?t)
8638 (let ((end (save-excursion (outline-next-heading) (point))))
8639 (if (or (re-search-forward org-ts-regexp end t)
8640 (re-search-forward org-ts-regexp-both end t))
8641 (org-time-string-to-seconds (match-string 0))
8642 (org-float-time now))))
8643 ((= dcst ?c)
8644 (let ((end (save-excursion (outline-next-heading) (point))))
8645 (if (re-search-forward
8646 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8647 end t)
8648 (org-time-string-to-seconds (match-string 0))
8649 (org-float-time now))))
8650 ((= dcst ?s)
8651 (let ((end (save-excursion (outline-next-heading) (point))))
8652 (if (re-search-forward org-scheduled-time-regexp end t)
8653 (org-time-string-to-seconds (match-string 1))
8654 (org-float-time now))))
8655 ((= dcst ?d)
8656 (let ((end (save-excursion (outline-next-heading) (point))))
8657 (if (re-search-forward org-deadline-time-regexp end t)
8658 (org-time-string-to-seconds (match-string 1))
8659 (org-float-time now))))
8660 ((= dcst ?p)
8661 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8662 (string-to-char (match-string 2))
8663 org-default-priority))
8664 ((= dcst ?r)
8665 (or (org-entry-get nil property) ""))
8666 ((= dcst ?o)
8667 (if (looking-at org-complex-heading-regexp)
8668 (- 9999 (length (member (match-string 2)
8669 org-todo-keywords-1)))))
8670 ((= dcst ?f)
8671 (if getkey-func
8672 (progn
8673 (setq tmp (funcall getkey-func))
8674 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8675 tmp)
8676 (error "Invalid key function `%s'" getkey-func)))
8677 (t (error "Invalid sorting type `%c'" sorting-type))))
8679 (cond
8680 ((= dcst ?a) 'string<)
8681 ((= dcst ?f) compare-func)
8682 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8683 (run-hooks 'org-after-sorting-entries-or-items-hook)
8684 ;; Reset the clock marker if needed
8685 (when cmstr
8686 (save-excursion
8687 (goto-char start)
8688 (search-forward cmstr nil t)
8689 (move-marker org-clock-marker (point))))
8690 (message "Sorting entries...done")))
8692 (defun org-do-sort (table what &optional with-case sorting-type)
8693 "Sort TABLE of WHAT according to SORTING-TYPE.
8694 The user will be prompted for the SORTING-TYPE if the call to this
8695 function does not specify it. WHAT is only for the prompt, to indicate
8696 what is being sorted. The sorting key will be extracted from
8697 the car of the elements of the table.
8698 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8699 (unless sorting-type
8700 (message
8701 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8702 what)
8703 (setq sorting-type (read-char-exclusive)))
8704 (let ((dcst (downcase sorting-type))
8705 extractfun comparefun)
8706 ;; Define the appropriate functions
8707 (cond
8708 ((= dcst ?n)
8709 (setq extractfun 'string-to-number
8710 comparefun (if (= dcst sorting-type) '< '>)))
8711 ((= dcst ?a)
8712 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8713 (lambda(x) (downcase (org-sort-remove-invisible x))))
8714 comparefun (if (= dcst sorting-type)
8715 'string<
8716 (lambda (a b) (and (not (string< a b))
8717 (not (string= a b)))))))
8718 ((= dcst ?t)
8719 (setq extractfun
8720 (lambda (x)
8721 (if (or (string-match org-ts-regexp x)
8722 (string-match org-ts-regexp-both x))
8723 (org-float-time
8724 (org-time-string-to-time (match-string 0 x)))
8726 comparefun (if (= dcst sorting-type) '< '>)))
8727 (t (error "Invalid sorting type `%c'" sorting-type)))
8729 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8730 table)
8731 (lambda (a b) (funcall comparefun (car a) (car b))))))
8734 ;;; The orgstruct minor mode
8736 ;; Define a minor mode which can be used in other modes in order to
8737 ;; integrate the org-mode structure editing commands.
8739 ;; This is really a hack, because the org-mode structure commands use
8740 ;; keys which normally belong to the major mode. Here is how it
8741 ;; works: The minor mode defines all the keys necessary to operate the
8742 ;; structure commands, but wraps the commands into a function which
8743 ;; tests if the cursor is currently at a headline or a plain list
8744 ;; item. If that is the case, the structure command is used,
8745 ;; temporarily setting many Org-mode variables like regular
8746 ;; expressions for filling etc. However, when any of those keys is
8747 ;; used at a different location, function uses `key-binding' to look
8748 ;; up if the key has an associated command in another currently active
8749 ;; keymap (minor modes, major mode, global), and executes that
8750 ;; command. There might be problems if any of the keys is otherwise
8751 ;; used as a prefix key.
8753 (defcustom orgstruct-heading-prefix-regexp nil
8754 "Regexp that matches the custom prefix of Org headlines in
8755 orgstruct(++)-mode."
8756 :group 'org
8757 :version "24.4"
8758 :package-version '(Org . "8.0")
8759 :type 'string)
8760 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8762 (defcustom orgstruct-setup-hook nil
8763 "Hook run after orgstruct-mode-map is filled."
8764 :group 'org
8765 :version "24.4"
8766 :package-version '(Org . "8.0")
8767 :type 'hook)
8769 (defvar orgstruct-initialized nil)
8771 (defvar org-local-vars nil
8772 "List of local variables, for use by `orgstruct-mode'.")
8774 ;;;###autoload
8775 (define-minor-mode orgstruct-mode
8776 "Toggle the minor mode `orgstruct-mode'.
8777 This mode is for using Org-mode structure commands in other
8778 modes. The following keys behave as if Org-mode were active, if
8779 the cursor is on a headline, or on a plain list item (both as
8780 defined by Org-mode)."
8781 nil " OrgStruct" (make-sparse-keymap)
8782 (funcall (if orgstruct-mode
8783 'add-to-invisibility-spec
8784 'remove-from-invisibility-spec)
8785 '(outline . t))
8786 (when orgstruct-mode
8787 (org-load-modules-maybe)
8788 (unless orgstruct-initialized
8789 (orgstruct-setup)
8790 (setq orgstruct-initialized t))))
8792 ;;;###autoload
8793 (defun turn-on-orgstruct ()
8794 "Unconditionally turn on `orgstruct-mode'."
8795 (orgstruct-mode 1))
8797 (defvar org-fb-vars nil)
8798 (make-variable-buffer-local 'org-fb-vars)
8799 (defun orgstruct++-mode (&optional arg)
8800 "Toggle `orgstruct-mode', the enhanced version of it.
8801 In addition to setting orgstruct-mode, this also exports all
8802 indentation and autofilling variables from org-mode into the
8803 buffer. It will also recognize item context in multiline items."
8804 (interactive "P")
8805 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8806 (if (< arg 1)
8807 (progn (orgstruct-mode -1)
8808 (mapc (lambda(v)
8809 (org-set-local (car v)
8810 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8811 org-fb-vars))
8812 (orgstruct-mode 1)
8813 (setq org-fb-vars nil)
8814 (let (var val)
8815 (mapc
8816 (lambda (x)
8817 (when (string-match
8818 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8819 (symbol-name (car x)))
8820 (setq var (car x) val (nth 1 x))
8821 (push (list var `(quote ,(eval var))) org-fb-vars)
8822 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8823 org-local-vars)
8824 (org-set-local 'orgstruct-is-++ t))))
8826 (defvar orgstruct-is-++ nil
8827 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8828 (make-variable-buffer-local 'orgstruct-is-++)
8830 ;;;###autoload
8831 (defun turn-on-orgstruct++ ()
8832 "Unconditionally turn on `orgstruct++-mode'."
8833 (orgstruct++-mode 1))
8835 (defun orgstruct-error ()
8836 "Error when there is no default binding for a structure key."
8837 (interactive)
8838 (funcall (if (fboundp 'user-error)
8839 'user-error
8840 'error)
8841 "This key has no function outside structure elements"))
8843 (defun orgstruct-setup ()
8844 "Setup orgstruct keymap."
8845 (dolist (cell '((org-demote . t)
8846 (org-metaleft . t)
8847 (org-metaright . t)
8848 (org-promote . t)
8849 (org-shiftmetaleft . t)
8850 (org-shiftmetaright . t)
8851 org-backward-element
8852 org-backward-heading-same-level
8853 org-ctrl-c-ret
8854 org-ctrl-c-minus
8855 org-ctrl-c-star
8856 org-cycle
8857 org-forward-heading-same-level
8858 org-insert-heading
8859 org-insert-heading-respect-content
8860 org-kill-note-or-show-branches
8861 org-mark-subtree
8862 org-meta-return
8863 org-metadown
8864 org-metaup
8865 org-narrow-to-subtree
8866 org-promote-subtree
8867 org-reveal
8868 org-shiftdown
8869 org-shiftleft
8870 org-shiftmetadown
8871 org-shiftmetaup
8872 org-shiftright
8873 org-shifttab
8874 org-shifttab
8875 org-shiftup
8876 org-show-subtree
8877 org-sort
8878 org-up-element
8879 outline-demote
8880 outline-next-visible-heading
8881 outline-previous-visible-heading
8882 outline-promote
8883 outline-up-heading
8884 show-children))
8885 (let ((f (or (car-safe cell) cell))
8886 (disable-when-heading-prefix (cdr-safe cell)))
8887 (when (fboundp f)
8888 (dolist (binding (nconc (where-is-internal f org-mode-map)
8889 (where-is-internal f outline-mode-map)))
8890 ;; TODO use local-function-key-map
8891 (dolist (rep '(("<tab>" . "TAB")
8892 ("<return>" . "RET")
8893 ("<escape>" . "ESC")
8894 ("<delete>" . "DEL")))
8895 (setq binding (read-kbd-macro
8896 (let ((case-fold-search))
8897 (replace-regexp-in-string
8898 (regexp-quote (cdr rep))
8899 (car rep)
8900 (key-description binding))))))
8901 (let ((key (lookup-key orgstruct-mode-map binding)))
8902 (when (or (not key) (numberp key))
8903 (condition-case nil
8904 (org-defkey orgstruct-mode-map
8905 binding
8906 (orgstruct-make-binding f binding disable-when-heading-prefix))
8907 (error nil))))))))
8908 (run-hooks 'orgstruct-setup-hook))
8910 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8911 "Create a function for binding in the structure minor mode.
8912 FUN is the command to call inside a table. KEY is the key that
8913 should be checked in for a command to execute outside of tables.
8914 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8915 if `orgstruct-heading-prefix-regexp' is non-nil."
8916 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8917 (let ((nname name)
8918 (i 0))
8919 (while (fboundp (intern nname))
8920 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8921 (setq name (intern nname)))
8922 (eval
8923 (let ((bindings '((org-heading-regexp
8924 (concat "^"
8925 orgstruct-heading-prefix-regexp
8926 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8927 (org-outline-regexp
8928 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8929 (org-outline-regexp-bol
8930 (concat "^" org-outline-regexp))
8931 (outline-regexp org-outline-regexp)
8932 (outline-heading-end-regexp "\n")
8933 (outline-level 'org-outline-level)
8934 (outline-heading-alist))))
8935 `(defun ,name (arg)
8936 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8937 "Outside of structure, run the binding of `"
8938 (key-description key) "'."
8939 (when disable-when-heading-prefix
8940 (concat
8941 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8942 "back to the default binding due to limitations of Org's implementation of\n"
8943 "`" (symbol-name fun) "'.")))
8944 (interactive "p")
8945 (let* ((disable
8946 ,(when disable-when-heading-prefix
8947 '(and orgstruct-heading-prefix-regexp
8948 (not (string= orgstruct-heading-prefix-regexp "")))))
8949 (fallback
8950 (or disable
8951 (not
8952 (let* ,bindings
8953 (org-context-p 'headline 'item
8954 ,(when (memq fun '(org-insert-heading))
8955 '(when orgstruct-is-++
8956 'item-body))))))))
8957 (if fallback
8958 (let* ((orgstruct-mode)
8959 (binding
8960 (loop with key = ,key
8961 for rep in '(nil
8962 ("<tab>" . "TAB")
8963 ("<return>" . "RET")
8964 ("<escape>" . "ESC")
8965 ("<delete>" . "DEL"))
8967 (when rep
8968 (setq key (read-kbd-macro
8969 (let ((case-fold-search))
8970 (replace-regexp-in-string
8971 (regexp-quote (car rep))
8972 (cdr rep)
8973 (key-description key))))))
8974 thereis (key-binding key))))
8975 (if (keymapp binding)
8976 (set-temporary-overlay-map binding)
8977 (let ((func (or binding
8978 (unless disable
8979 'orgstruct-error))))
8980 (when func
8981 (call-interactively func)))))
8982 (org-run-like-in-org-mode
8983 (lambda ()
8984 (interactive)
8985 (let* ,bindings
8986 (call-interactively ',fun)))))))))
8987 name))
8989 (defun org-contextualize-keys (alist contexts)
8990 "Return valid elements in ALIST depending on CONTEXTS.
8992 `org-agenda-custom-commands' or `org-capture-templates' are the
8993 values used for ALIST, and `org-agenda-custom-commands-contexts'
8994 or `org-capture-templates-contexts' are the associated contexts
8995 definitions."
8996 (let ((contexts
8997 ;; normalize contexts
8998 (mapcar
8999 (lambda(c) (cond ((listp (cadr c))
9000 (list (car c) (car c) (cadr c)))
9001 ((string= "" (cadr c))
9002 (list (car c) (car c) (caddr c)))
9003 (t c))) contexts))
9004 (a alist) c r s)
9005 ;; loop over all commands or templates
9006 (while (setq c (pop a))
9007 (let (vrules repl)
9008 (cond
9009 ((not (assoc (car c) contexts))
9010 (push c r))
9011 ((and (assoc (car c) contexts)
9012 (setq vrules (org-contextualize-validate-key
9013 (car c) contexts)))
9014 (mapc (lambda (vr)
9015 (when (not (equal (car vr) (cadr vr)))
9016 (setq repl vr))) vrules)
9017 (if (not repl) (push c r)
9018 (push (cadr repl) s)
9019 (push
9020 (cons (car c)
9021 (cdr (or (assoc (cadr repl) alist)
9022 (error "Undefined key `%s' as contextual replacement for `%s'"
9023 (cadr repl) (car c)))))
9024 r))))))
9025 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9026 (delq
9028 (delete-dups
9029 (mapcar (lambda (x)
9030 (let ((tpl (car x)))
9031 (when (not (delq
9033 (mapcar (lambda(y)
9034 (equal y tpl)) s))) x)))
9035 (reverse r))))))
9037 (defun org-contextualize-validate-key (key contexts)
9038 "Check CONTEXTS for agenda or capture KEY."
9039 (let (r rr res)
9040 (while (setq r (pop contexts))
9041 (mapc
9042 (lambda (rr)
9043 (when
9044 (and (equal key (car r))
9045 (if (functionp rr) (funcall rr)
9046 (or (and (eq (car rr) 'in-file)
9047 (buffer-file-name)
9048 (string-match (cdr rr) (buffer-file-name)))
9049 (and (eq (car rr) 'in-mode)
9050 (string-match (cdr rr) (symbol-name major-mode)))
9051 (and (eq (car rr) 'in-buffer)
9052 (string-match (cdr rr) (buffer-name)))
9053 (when (and (eq (car rr) 'not-in-file)
9054 (buffer-file-name))
9055 (not (string-match (cdr rr) (buffer-file-name))))
9056 (when (eq (car rr) 'not-in-mode)
9057 (not (string-match (cdr rr) (symbol-name major-mode))))
9058 (when (eq (car rr) 'not-in-buffer)
9059 (not (string-match (cdr rr) (buffer-name)))))))
9060 (push r res)))
9061 (car (last r))))
9062 (delete-dups (delq nil res))))
9064 (defun org-context-p (&rest contexts)
9065 "Check if local context is any of CONTEXTS.
9066 Possible values in the list of contexts are `table', `headline', and `item'."
9067 (let ((pos (point)))
9068 (goto-char (point-at-bol))
9069 (prog1 (or (and (memq 'table contexts)
9070 (looking-at "[ \t]*|"))
9071 (and (memq 'headline contexts)
9072 (looking-at org-outline-regexp))
9073 (and (memq 'item contexts)
9074 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9075 (and (memq 'item-body contexts)
9076 (org-in-item-p)))
9077 (goto-char pos))))
9079 (defun org-get-local-variables ()
9080 "Return a list of all local variables in an Org mode buffer."
9081 (let (varlist)
9082 (with-current-buffer (get-buffer-create "*Org tmp*")
9083 (erase-buffer)
9084 (org-mode)
9085 (setq varlist (buffer-local-variables)))
9086 (kill-buffer "*Org tmp*")
9087 (delq nil
9088 (mapcar
9089 (lambda (x)
9090 (setq x
9091 (if (symbolp x)
9092 (list x)
9093 (list (car x) (cdr x))))
9094 (if (and (not (get (car x) 'org-state))
9095 (string-match
9096 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9097 (symbol-name (car x))))
9098 x nil))
9099 varlist))))
9101 (defun org-clone-local-variables (from-buffer &optional regexp)
9102 "Clone local variables from FROM-BUFFER.
9103 Optional argument REGEXP selects variables to clone."
9104 (mapc
9105 (lambda (pair)
9106 (and (symbolp (car pair))
9107 (or (null regexp)
9108 (string-match regexp (symbol-name (car pair))))
9109 (set (make-local-variable (car pair))
9110 (cdr pair))))
9111 (buffer-local-variables from-buffer)))
9113 ;;;###autoload
9114 (defun org-run-like-in-org-mode (cmd)
9115 "Run a command, pretending that the current buffer is in Org-mode.
9116 This will temporarily bind local variables that are typically bound in
9117 Org-mode to the values they have in Org-mode, and then interactively
9118 call CMD."
9119 (org-load-modules-maybe)
9120 (unless org-local-vars
9121 (setq org-local-vars (org-get-local-variables)))
9122 (let (binds)
9123 (dolist (var org-local-vars)
9124 (when (or (not (boundp (car var)))
9125 (eq (symbol-value (car var))
9126 (default-value (car var))))
9127 (push (list (car var) `(quote ,(cadr var))) binds)))
9128 (eval `(let ,binds
9129 (call-interactively (quote ,cmd))))))
9131 ;;;; Archiving
9133 (defun org-get-category (&optional pos force-refresh)
9134 "Get the category applying to position POS."
9135 (save-match-data
9136 (if force-refresh (org-refresh-category-properties))
9137 (let ((pos (or pos (point))))
9138 (or (get-text-property pos 'org-category)
9139 (progn (org-refresh-category-properties)
9140 (get-text-property pos 'org-category))))))
9142 (defun org-refresh-category-properties ()
9143 "Refresh category text properties in the buffer."
9144 (let ((case-fold-search t)
9145 (inhibit-read-only t)
9146 (def-cat (cond
9147 ((null org-category)
9148 (if buffer-file-name
9149 (file-name-sans-extension
9150 (file-name-nondirectory buffer-file-name))
9151 "???"))
9152 ((symbolp org-category) (symbol-name org-category))
9153 (t org-category)))
9154 beg end cat pos optionp)
9155 (org-with-silent-modifications
9156 (save-excursion
9157 (save-restriction
9158 (widen)
9159 (goto-char (point-min))
9160 (put-text-property (point) (point-max) 'org-category def-cat)
9161 (while (re-search-forward
9162 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9163 (setq pos (match-end 0)
9164 optionp (equal (char-after (match-beginning 0)) ?#)
9165 cat (org-trim (match-string 2)))
9166 (if optionp
9167 (setq beg (point-at-bol) end (point-max))
9168 (org-back-to-heading t)
9169 (setq beg (point) end (org-end-of-subtree t t)))
9170 (put-text-property beg end 'org-category cat)
9171 (put-text-property beg end 'org-category-position beg)
9172 (goto-char pos)))))))
9174 (defun org-refresh-properties (dprop tprop)
9175 "Refresh buffer text properties.
9176 DPROP is the drawer property and TPROP is the corresponding text
9177 property to set."
9178 (let ((case-fold-search t)
9179 (inhibit-read-only t) p)
9180 (org-with-silent-modifications
9181 (save-excursion
9182 (save-restriction
9183 (widen)
9184 (goto-char (point-min))
9185 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9186 (setq p (org-match-string-no-properties 1))
9187 (save-excursion
9188 (org-back-to-heading t)
9189 (put-text-property
9190 (point-at-bol) (point-at-eol) tprop p))))))))
9193 ;;;; Link Stuff
9195 ;;; Link abbreviations
9197 (defun org-link-expand-abbrev (link)
9198 "Apply replacements as defined in `org-link-abbrev-alist'."
9199 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9200 (let* ((key (match-string 1 link))
9201 (as (or (assoc key org-link-abbrev-alist-local)
9202 (assoc key org-link-abbrev-alist)))
9203 (tag (and (match-end 2) (match-string 3 link)))
9204 rpl)
9205 (if (not as)
9206 link
9207 (setq rpl (cdr as))
9208 (cond
9209 ((symbolp rpl) (funcall rpl tag))
9210 ((string-match "%(\\([^)]+\\))" rpl)
9211 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9212 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9213 ((string-match "%h" rpl)
9214 (replace-match (url-hexify-string (or tag "")) t t rpl))
9215 (t (concat rpl tag)))))
9216 link))
9218 ;;; Storing and inserting links
9220 (defvar org-insert-link-history nil
9221 "Minibuffer history for links inserted with `org-insert-link'.")
9223 (defvar org-stored-links nil
9224 "Contains the links stored with `org-store-link'.")
9226 (defvar org-store-link-plist nil
9227 "Plist with info about the most recently link created with `org-store-link'.")
9229 (defvar org-link-protocols nil
9230 "Link protocols added to Org-mode using `org-add-link-type'.")
9232 (defvar org-store-link-functions nil
9233 "List of functions that are called to create and store a link.
9234 Each function will be called in turn until one returns a non-nil
9235 value. Each function should check if it is responsible for creating
9236 this link (for example by looking at the major mode).
9237 If not, it must exit and return nil.
9238 If yes, it should return a non-nil value after a calling
9239 `org-store-link-props' with a list of properties and values.
9240 Special properties are:
9242 :type The link prefix, like \"http\". This must be given.
9243 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9244 This is obligatory as well.
9245 :description Optional default description for the second pair
9246 of brackets in an Org-mode link. The user can still change
9247 this when inserting this link into an Org-mode buffer.
9249 In addition to these, any additional properties can be specified
9250 and then used in capture templates.")
9252 (defun org-add-link-type (type &optional follow export)
9253 "Add TYPE to the list of `org-link-types'.
9254 Re-compute all regular expressions depending on `org-link-types'
9256 FOLLOW and EXPORT are two functions.
9258 FOLLOW should take the link path as the single argument and do whatever
9259 is necessary to follow the link, for example find a file or display
9260 a mail message.
9262 EXPORT should format the link path for export to one of the export formats.
9263 It should be a function accepting three arguments:
9265 path the path of the link, the text after the prefix (like \"http:\")
9266 desc the description of the link, if any, or a description added by
9267 org-export-normalize-links if there is none
9268 format the export format, a symbol like `html' or `latex' or `ascii'..
9270 The function may use the FORMAT information to return different values
9271 depending on the format. The return value will be put literally into
9272 the exported file. If the return value is nil, this means Org should
9273 do what it normally does with links which do not have EXPORT defined.
9275 Org-mode has a built-in default for exporting links. If you are happy with
9276 this default, there is no need to define an export function for the link
9277 type. For a simple example of an export function, see `org-bbdb.el'."
9278 (add-to-list 'org-link-types type t)
9279 (org-make-link-regexps)
9280 (if (assoc type org-link-protocols)
9281 (setcdr (assoc type org-link-protocols) (list follow export))
9282 (push (list type follow export) org-link-protocols)))
9284 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9285 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9287 ;;;###autoload
9288 (defun org-store-link (arg &optional ignore-region)
9289 "\\<org-mode-map>Store an org-link to the current location.
9290 This link is added to `org-stored-links' and can later be inserted
9291 into an org-buffer with \\[org-insert-link].
9293 For some link types, a prefix arg is interpreted.
9294 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9295 For file links, arg negates `org-context-in-file-links'.
9297 A double prefix arg force skipping storing functions that are not
9298 part of Org's core.
9300 When the region is active and IGNORE-REGION is nil, store each line
9301 in the region as a separate link."
9302 (interactive "P")
9303 (org-load-modules-maybe)
9304 (setq org-store-link-plist nil) ; reset
9305 (if (and (org-region-active-p) (not ignore-region))
9306 (save-excursion
9307 (let ((beg (region-beginning)) (end (region-end)))
9308 (goto-char beg)
9309 (while (< (point-at-eol) end)
9310 (funcall 'org-store-link arg t)
9311 (move-beginning-of-line 2))))
9312 (org-with-limited-levels
9313 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9314 (cond
9315 ((and (not (equal arg '(16)))
9316 (setq sfuns
9317 (delq
9318 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9319 org-store-link-functions))
9320 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9321 (or (and (cdr sfuns)
9322 (funcall (intern
9323 (completing-read "Which function for creating the link? "
9324 sfunsn t (car sfunsn)))))
9325 (funcall (caar sfuns)))
9326 (setq link (plist-get org-store-link-plist :link)
9327 desc (or (plist-get org-store-link-plist :description) link))))
9328 ((org-src-edit-buffer-p)
9329 (let (label gc)
9330 (while (or (not label)
9331 (save-excursion
9332 (save-restriction
9333 (widen)
9334 (goto-char (point-min))
9335 (re-search-forward
9336 (regexp-quote (format org-coderef-label-format label))
9337 nil t))))
9338 (when label (message "Label exists already") (sit-for 2))
9339 (setq label (read-string "Code line label: " label)))
9340 (end-of-line 1)
9341 (setq link (format org-coderef-label-format label))
9342 (setq gc (- 79 (length link)))
9343 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9344 (insert link)
9345 (setq link (concat "(" label ")") desc nil)))
9347 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9348 ;; We are in the agenda, link to referenced location
9349 (let ((m (or (get-text-property (point) 'org-hd-marker)
9350 (get-text-property (point) 'org-marker))))
9351 (when m
9352 (org-with-point-at m
9353 (setq agenda-link
9354 (if (org-called-interactively-p 'any)
9355 (call-interactively 'org-store-link)
9356 (org-store-link nil)))))))
9358 ((eq major-mode 'calendar-mode)
9359 (let ((cd (calendar-cursor-to-date)))
9360 (setq link
9361 (format-time-string
9362 (car org-time-stamp-formats)
9363 (apply 'encode-time
9364 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9365 nil nil nil))))
9366 (org-store-link-props :type "calendar" :date cd)))
9368 ((eq major-mode 'help-mode)
9369 (setq link (concat "help:" (save-excursion
9370 (goto-char (point-min))
9371 (looking-at "^[^ ]+")
9372 (match-string 0))))
9373 (org-store-link-props :type "help"))
9375 ((eq major-mode 'w3-mode)
9376 (setq cpltxt (if (and (buffer-name)
9377 (not (string-match "Untitled" (buffer-name))))
9378 (buffer-name)
9379 (url-view-url t))
9380 link (url-view-url t))
9381 (org-store-link-props :type "w3" :url (url-view-url t)))
9383 ((setq search (run-hook-with-args-until-success
9384 'org-create-file-search-functions))
9385 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9386 "::" search))
9387 (setq cpltxt (or description link)))
9389 ((eq major-mode 'image-mode)
9390 (setq cpltxt (concat "file:"
9391 (abbreviate-file-name buffer-file-name))
9392 link cpltxt)
9393 (org-store-link-props :type "image" :file buffer-file-name))
9395 ((eq major-mode 'dired-mode)
9396 ;; link to the file in the current line
9397 (let ((file (dired-get-filename nil t)))
9398 (setq file (if file
9399 (abbreviate-file-name
9400 (expand-file-name (dired-get-filename nil t)))
9401 ;; otherwise, no file so use current directory.
9402 default-directory))
9403 (setq cpltxt (concat "file:" file)
9404 link cpltxt)))
9406 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9407 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9408 (cond
9409 ((org-in-regexp "<<\\(.*?\\)>>")
9410 (setq cpltxt
9411 (concat "file:"
9412 (abbreviate-file-name
9413 (buffer-file-name (buffer-base-buffer)))
9414 "::" (match-string 1))
9415 link cpltxt))
9416 ((and (featurep 'org-id)
9417 (or (eq org-id-link-to-org-use-id t)
9418 (and (org-called-interactively-p 'any)
9419 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9420 (and (eq org-id-link-to-org-use-id
9421 'create-if-interactive-and-no-custom-id)
9422 (not custom-id))))
9423 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9424 ;; We can make a link using the ID.
9425 (setq link (condition-case nil
9426 (prog1 (org-id-store-link)
9427 (setq desc (plist-get org-store-link-plist :description)))
9428 (error
9429 ;; probably before first headline, link to file only
9430 (concat "file:"
9431 (abbreviate-file-name
9432 (buffer-file-name (buffer-base-buffer))))))))
9434 ;; Just link to current headline
9435 (setq cpltxt (concat "file:"
9436 (abbreviate-file-name
9437 (buffer-file-name (buffer-base-buffer)))))
9438 ;; Add a context search string
9439 (when (org-xor org-context-in-file-links arg)
9440 (let* ((ee (org-element-at-point))
9441 (et (org-element-type ee))
9442 (ev (plist-get (cadr ee) :value)))
9443 (setq txt (cond
9444 ((org-at-heading-p) nil)
9445 ((eq et 'keyword) ev)
9446 ((org-region-active-p)
9447 (buffer-substring (region-beginning) (region-end)))))
9448 (when (or (null txt) (string-match "\\S-" txt))
9449 (setq cpltxt
9450 (concat cpltxt "::"
9451 (condition-case nil
9452 (org-make-org-heading-search-string txt)
9453 (error "")))
9454 desc (or (and (eq et 'keyword) ev)
9455 (nth 4 (ignore-errors (org-heading-components)))
9456 "NONE")))))
9457 (if (string-match "::\\'" cpltxt)
9458 (setq cpltxt (substring cpltxt 0 -2)))
9459 (setq link cpltxt))))
9461 ((buffer-file-name (buffer-base-buffer))
9462 ;; Just link to this file here.
9463 (setq cpltxt (concat "file:"
9464 (abbreviate-file-name
9465 (buffer-file-name (buffer-base-buffer)))))
9466 ;; Add a context string
9467 (when (org-xor org-context-in-file-links arg)
9468 (setq txt (if (org-region-active-p)
9469 (buffer-substring (region-beginning) (region-end))
9470 (buffer-substring (point-at-bol) (point-at-eol))))
9471 ;; Only use search option if there is some text.
9472 (when (string-match "\\S-" txt)
9473 (setq cpltxt
9474 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9475 desc "NONE")))
9476 (setq link cpltxt))
9478 ((org-called-interactively-p 'interactive)
9479 (user-error "No method for storing a link from this buffer"))
9481 (t (setq link nil)))
9483 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9484 (setq link (or link cpltxt)
9485 desc (or desc cpltxt))
9486 (cond ((equal desc "NONE") (setq desc nil))
9487 ((string-match org-bracket-link-regexp desc)
9488 (setq desc (replace-regexp-in-string
9489 org-bracket-link-regexp
9490 (concat "\\3" (if (equal (length (match-string 0 desc))
9491 (length desc)) "*" "")) desc))))
9493 (if (and (or (org-called-interactively-p 'any)
9494 executing-kbd-macro ignore-region) link)
9495 (progn
9496 (setq org-stored-links
9497 (cons (list link desc) org-stored-links))
9498 (message "Stored: %s" (or desc link))
9499 (when custom-id
9500 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9501 "::#" custom-id))
9502 (setq org-stored-links
9503 (cons (list link desc) org-stored-links))))
9504 (or agenda-link (and link (org-make-link-string link desc))))))))
9506 (defun org-store-link-props (&rest plist)
9507 "Store link properties, extract names and addresses."
9508 (let (x adr)
9509 (when (setq x (plist-get plist :from))
9510 (setq adr (mail-extract-address-components x))
9511 (setq plist (plist-put plist :fromname (car adr)))
9512 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9513 (when (setq x (plist-get plist :to))
9514 (setq adr (mail-extract-address-components x))
9515 (setq plist (plist-put plist :toname (car adr)))
9516 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9517 (let ((from (plist-get plist :from))
9518 (to (plist-get plist :to)))
9519 (when (and from to org-from-is-user-regexp)
9520 (setq plist
9521 (plist-put plist :fromto
9522 (if (string-match org-from-is-user-regexp from)
9523 (concat "to %t")
9524 (concat "from %f"))))))
9525 (setq org-store-link-plist plist))
9527 (defun org-add-link-props (&rest plist)
9528 "Add these properties to the link property list."
9529 (let (key value)
9530 (while plist
9531 (setq key (pop plist) value (pop plist))
9532 (setq org-store-link-plist
9533 (plist-put org-store-link-plist key value)))))
9535 (defun org-email-link-description (&optional fmt)
9536 "Return the description part of an email link.
9537 This takes information from `org-store-link-plist' and formats it
9538 according to FMT (default from `org-email-link-description-format')."
9539 (setq fmt (or fmt org-email-link-description-format))
9540 (let* ((p org-store-link-plist)
9541 (to (plist-get p :toaddress))
9542 (from (plist-get p :fromaddress))
9543 (table
9544 (list
9545 (cons "%c" (plist-get p :fromto))
9546 (cons "%F" (plist-get p :from))
9547 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9548 (cons "%T" (plist-get p :to))
9549 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9550 (cons "%s" (plist-get p :subject))
9551 (cons "%d" (plist-get p :date))
9552 (cons "%m" (plist-get p :message-id)))))
9553 (when (string-match "%c" fmt)
9554 ;; Check if the user wrote this message
9555 (if (and org-from-is-user-regexp from to
9556 (save-match-data (string-match org-from-is-user-regexp from)))
9557 (setq fmt (replace-match "to %t" t t fmt))
9558 (setq fmt (replace-match "from %f" t t fmt))))
9559 (org-replace-escapes fmt table)))
9561 (defun org-make-org-heading-search-string (&optional string)
9562 "Make search string for the current headline or STRING."
9563 (let ((s (or string
9564 (and (derived-mode-p 'org-mode)
9565 (save-excursion
9566 (org-back-to-heading t)
9567 (org-element-property :raw-value (org-element-at-point))))))
9568 (lines org-context-in-file-links))
9569 (or string (setq s (concat "*" s))) ; Add * for headlines
9570 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9571 (when (and string (integerp lines) (> lines 0))
9572 (let ((slines (org-split-string s "\n")))
9573 (when (< lines (length slines))
9574 (setq s (mapconcat
9575 'identity
9576 (reverse (nthcdr (- (length slines) lines)
9577 (reverse slines))) "\n")))))
9578 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9580 (defun org-make-link-string (link &optional description)
9581 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9582 (unless (string-match "\\S-" link)
9583 (error "Empty link"))
9584 (when (and description
9585 (stringp description)
9586 (not (string-match "\\S-" description)))
9587 (setq description nil))
9588 (when (stringp description)
9589 ;; Remove brackets from the description, they are fatal.
9590 (while (string-match "\\[" description)
9591 (setq description (replace-match "{" t t description)))
9592 (while (string-match "\\]" description)
9593 (setq description (replace-match "}" t t description))))
9594 (when (equal link description)
9595 ;; No description needed, it is identical
9596 (setq description nil))
9597 (when (and (not description)
9598 (not (string-match (org-image-file-name-regexp) link))
9599 (not (equal link (org-link-escape link))))
9600 (setq description (org-extract-attributes link)))
9601 (setq link
9602 (cond ((string-match (org-image-file-name-regexp) link) link)
9603 ((string-match org-link-types-re link)
9604 (concat (match-string 1 link)
9605 (org-link-escape (substring link (match-end 1)))))
9606 (t (org-link-escape link))))
9607 (concat "[[" link "]"
9608 (if description (concat "[" description "]") "")
9609 "]"))
9611 (defconst org-link-escape-chars
9612 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9613 "List of characters that should be escaped in link.
9614 This is the list that is used for internal purposes.")
9616 (defconst org-link-escape-chars-browser
9617 '(?\ )
9618 "List of escapes for characters that are problematic in links.
9619 This is the list that is used before handing over to the browser.")
9621 (defun org-link-escape (text &optional table merge)
9622 "Return percent escaped representation of TEXT.
9623 TEXT is a string with the text to escape.
9624 Optional argument TABLE is a list with characters that should be
9625 escaped. When nil, `org-link-escape-chars' is used.
9626 If optional argument MERGE is set, merge TABLE into
9627 `org-link-escape-chars'."
9628 (cond
9629 ((and table merge)
9630 (mapc (lambda (defchr)
9631 (unless (member defchr table)
9632 (setq table (cons defchr table)))) org-link-escape-chars))
9633 ((null table)
9634 (setq table org-link-escape-chars)))
9635 (mapconcat
9636 (lambda (char)
9637 (if (or (member char table)
9638 (and (or (< char 32) (= char 37) (> char 126))
9639 org-url-hexify-p))
9640 (mapconcat (lambda (sequence-element)
9641 (format "%%%.2X" sequence-element))
9642 (or (encode-coding-char char 'utf-8)
9643 (error "Unable to percent escape character: %s"
9644 (char-to-string char))) "")
9645 (char-to-string char))) text ""))
9647 (defun org-link-unescape (str)
9648 "Unhex hexified Unicode strings as returned from the JavaScript function
9649 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9650 (unless (and (null str) (string= "" str))
9651 (let ((pos 0) (case-fold-search t) unhexed)
9652 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9653 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9654 (setq str (replace-match unhexed t t str))
9655 (setq pos (+ pos (length unhexed))))))
9656 str)
9658 (defun org-link-unescape-compound (hex)
9659 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9660 Note: this function also decodes single byte encodings like
9661 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9662 (save-match-data
9663 (let* ((bytes (cdr (split-string hex "%")))
9664 (ret "")
9665 (eat 0)
9666 (sum 0))
9667 (while bytes
9668 (let* ((val (string-to-number (pop bytes) 16))
9669 (shift-xor
9670 (if (= 0 eat)
9671 (cond
9672 ((>= val 252) (cons 6 252))
9673 ((>= val 248) (cons 5 248))
9674 ((>= val 240) (cons 4 240))
9675 ((>= val 224) (cons 3 224))
9676 ((>= val 192) (cons 2 192))
9677 (t (cons 0 0)))
9678 (cons 6 128))))
9679 (if (>= val 192) (setq eat (car shift-xor)))
9680 (setq val (logxor val (cdr shift-xor)))
9681 (setq sum (+ (lsh sum (car shift-xor)) val))
9682 (if (> eat 0) (setq eat (- eat 1)))
9683 (cond
9684 ((= 0 eat) ;multi byte
9685 (setq ret (concat ret (org-char-to-string sum)))
9686 (setq sum 0))
9687 ((not bytes) ; single byte(s)
9688 (setq ret (org-link-unescape-single-byte-sequence hex))))
9689 )) ;; end (while bytes
9690 ret )))
9692 (defun org-link-unescape-single-byte-sequence (hex)
9693 "Unhexify hex-encoded single byte character sequences."
9694 (mapconcat (lambda (byte)
9695 (char-to-string (string-to-number byte 16)))
9696 (cdr (split-string hex "%")) ""))
9698 (defun org-xor (a b)
9699 "Exclusive or."
9700 (if a (not b) b))
9702 (defun org-fixup-message-id-for-http (s)
9703 "Replace special characters in a message id, so it can be used in an http query."
9704 (when (string-match "%" s)
9705 (setq s (mapconcat (lambda (c)
9706 (if (eq c ?%)
9707 "%25"
9708 (char-to-string c)))
9709 s "")))
9710 (while (string-match "<" s)
9711 (setq s (replace-match "%3C" t t s)))
9712 (while (string-match ">" s)
9713 (setq s (replace-match "%3E" t t s)))
9714 (while (string-match "@" s)
9715 (setq s (replace-match "%40" t t s)))
9718 (defun org-link-prettify (link)
9719 "Return a human-readable representation of LINK.
9720 The car of LINK must be a raw link the cdr of LINK must be either
9721 a link description or nil."
9722 (let ((desc (or (cadr link) "<no description>")))
9723 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9724 "<" (car link) ">")))
9726 ;;;###autoload
9727 (defun org-insert-link-global ()
9728 "Insert a link like Org-mode does.
9729 This command can be called in any mode to insert a link in Org-mode syntax."
9730 (interactive)
9731 (org-load-modules-maybe)
9732 (org-run-like-in-org-mode 'org-insert-link))
9734 (defun org-insert-all-links (&optional keep)
9735 "Insert all links in `org-stored-links'."
9736 (interactive "P")
9737 (let ((links (copy-sequence org-stored-links)) l)
9738 (while (setq l (if keep (pop links) (pop org-stored-links)))
9739 (insert "- ")
9740 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9741 (insert "\n"))))
9743 (defun org-link-fontify-links-to-this-file ()
9744 "Fontify links to the current file in `org-stored-links'."
9745 (let ((f (buffer-file-name)) a b)
9746 (setq a (mapcar (lambda(l)
9747 (let ((ll (car l)))
9748 (when (and (string-match "^file:\\(.+\\)::" ll)
9749 (equal f (expand-file-name (match-string 1 ll))))
9750 ll)))
9751 org-stored-links))
9752 (when (featurep 'org-id)
9753 (setq b (mapcar (lambda(l)
9754 (let ((ll (car l)))
9755 (when (and (string-match "^id:\\(.+\\)$" ll)
9756 (equal f (expand-file-name
9757 (or (org-id-find-id-file
9758 (match-string 1 ll)) ""))))
9759 ll)))
9760 org-stored-links)))
9761 (mapcar (lambda(l)
9762 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9763 (delq nil (append a b)))))
9765 (defvar org-link-links-in-this-file nil)
9766 (defun org-insert-link (&optional complete-file link-location default-description)
9767 "Insert a link. At the prompt, enter the link.
9769 Completion can be used to insert any of the link protocol prefixes like
9770 http or ftp in use.
9772 The history can be used to select a link previously stored with
9773 `org-store-link'. When the empty string is entered (i.e. if you just
9774 press RET at the prompt), the link defaults to the most recently
9775 stored link. As SPC triggers completion in the minibuffer, you need to
9776 use M-SPC or C-q SPC to force the insertion of a space character.
9778 You will also be prompted for a description, and if one is given, it will
9779 be displayed in the buffer instead of the link.
9781 If there is already a link at point, this command will allow you to edit link
9782 and description parts.
9784 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9785 be selected using completion. The path to the file will be relative to the
9786 current directory if the file is in the current directory or a subdirectory.
9787 Otherwise, the link will be the absolute path as completed in the minibuffer
9788 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9789 option `org-link-file-path-type'.
9791 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9792 the current directory or below.
9794 With three \\[universal-argument] prefixes, negate the meaning of
9795 `org-keep-stored-link-after-insertion'.
9797 If `org-make-link-description-function' is non-nil, this function will be
9798 called with the link target, and the result will be the default
9799 link description.
9801 If the LINK-LOCATION parameter is non-nil, this value will be
9802 used as the link location instead of reading one interactively.
9804 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9805 be used as the default description."
9806 (interactive "P")
9807 (let* ((wcf (current-window-configuration))
9808 (origbuf (current-buffer))
9809 (region (if (org-region-active-p)
9810 (buffer-substring (region-beginning) (region-end))))
9811 (remove (and region (list (region-beginning) (region-end))))
9812 (desc region)
9813 tmphist ; byte-compile incorrectly complains about this
9814 (link link-location)
9815 (abbrevs org-link-abbrev-alist-local)
9816 entry file all-prefixes auto-desc)
9817 (cond
9818 (link-location) ; specified by arg, just use it.
9819 ((org-in-regexp org-bracket-link-regexp 1)
9820 ;; We do have a link at point, and we are going to edit it.
9821 (setq remove (list (match-beginning 0) (match-end 0)))
9822 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9823 (setq link (read-string "Link: "
9824 (org-link-unescape
9825 (org-match-string-no-properties 1)))))
9826 ((or (org-in-regexp org-angle-link-re)
9827 (org-in-regexp org-plain-link-re))
9828 ;; Convert to bracket link
9829 (setq remove (list (match-beginning 0) (match-end 0))
9830 link (read-string "Link: "
9831 (org-remove-angle-brackets (match-string 0)))))
9832 ((member complete-file '((4) (16)))
9833 ;; Completing read for file names.
9834 (setq link (org-file-complete-link complete-file)))
9836 ;; Read link, with completion for stored links.
9837 (org-link-fontify-links-to-this-file)
9838 (org-switch-to-buffer-other-window "*Org Links*")
9839 (with-current-buffer "*Org Links*"
9840 (erase-buffer)
9841 (insert "Insert a link.
9842 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9843 (when org-stored-links
9844 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9845 (insert (mapconcat 'org-link-prettify
9846 (reverse org-stored-links) "\n")))
9847 (goto-char (point-min)))
9848 (let ((cw (selected-window)))
9849 (select-window (get-buffer-window "*Org Links*" 'visible))
9850 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9851 (unless (pos-visible-in-window-p (point-max))
9852 (org-fit-window-to-buffer))
9853 (and (window-live-p cw) (select-window cw)))
9854 ;; Fake a link history, containing the stored links.
9855 (setq tmphist (append (mapcar 'car org-stored-links)
9856 org-insert-link-history))
9857 (setq all-prefixes (append (mapcar 'car abbrevs)
9858 (mapcar 'car org-link-abbrev-alist)
9859 org-link-types))
9860 (unwind-protect
9861 (progn
9862 (setq link
9863 (org-completing-read
9864 "Link: "
9865 (append
9866 (mapcar (lambda (x) (concat x ":"))
9867 all-prefixes)
9868 (mapcar 'car org-stored-links))
9869 nil nil nil
9870 'tmphist
9871 (caar org-stored-links)))
9872 (if (not (string-match "\\S-" link))
9873 (error "No link selected"))
9874 (mapc (lambda(l)
9875 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9876 org-stored-links)
9877 (if (or (member link all-prefixes)
9878 (and (equal ":" (substring link -1))
9879 (member (substring link 0 -1) all-prefixes)
9880 (setq link (substring link 0 -1))))
9881 (setq link (with-current-buffer origbuf
9882 (org-link-try-special-completion link)))))
9883 (set-window-configuration wcf)
9884 (kill-buffer "*Org Links*"))
9885 (setq entry (assoc link org-stored-links))
9886 (or entry (push link org-insert-link-history))
9887 (setq desc (or desc (nth 1 entry)))))
9889 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9890 (not org-keep-stored-link-after-insertion))
9891 (setq org-stored-links (delq (assoc link org-stored-links)
9892 org-stored-links)))
9894 (if (string-match org-plain-link-re link)
9895 ;; URL-like link, normalize the use of angular brackets.
9896 (setq link (org-remove-angle-brackets link)))
9898 ;; Check if we are linking to the current file with a search
9899 ;; option If yes, simplify the link by using only the search
9900 ;; option.
9901 (when (and buffer-file-name
9902 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9903 (let* ((path (match-string 1 link))
9904 (case-fold-search nil)
9905 (search (match-string 2 link)))
9906 (save-match-data
9907 (if (equal (file-truename buffer-file-name) (file-truename path))
9908 ;; We are linking to this same file, with a search option
9909 (setq link search)))))
9911 ;; Check if we can/should use a relative path. If yes, simplify the link
9912 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9913 (let* ((type (match-string 1 link))
9914 (path (match-string 2 link))
9915 (origpath path)
9916 (case-fold-search nil))
9917 (cond
9918 ((or (eq org-link-file-path-type 'absolute)
9919 (equal complete-file '(16)))
9920 (setq path (abbreviate-file-name (expand-file-name path))))
9921 ((eq org-link-file-path-type 'noabbrev)
9922 (setq path (expand-file-name path)))
9923 ((eq org-link-file-path-type 'relative)
9924 (setq path (file-relative-name path)))
9926 (save-match-data
9927 (if (string-match (concat "^" (regexp-quote
9928 (expand-file-name
9929 (file-name-as-directory
9930 default-directory))))
9931 (expand-file-name path))
9932 ;; We are linking a file with relative path name.
9933 (setq path (substring (expand-file-name path)
9934 (match-end 0)))
9935 (setq path (abbreviate-file-name (expand-file-name path)))))))
9936 (setq link (concat type path))
9937 (if (equal desc origpath)
9938 (setq desc path))))
9940 (if org-make-link-description-function
9941 (setq desc
9942 (or (condition-case nil
9943 (funcall org-make-link-description-function link desc)
9944 (error (progn (message "Can't get link description from `%s'"
9945 (symbol-name org-make-link-description-function))
9946 (sit-for 2) nil)))
9947 (read-string "Description: " default-description)))
9948 (if default-description (setq desc default-description)
9949 (setq desc (or (and auto-desc desc)
9950 (read-string "Description: " desc)))))
9952 (unless (string-match "\\S-" desc) (setq desc nil))
9953 (if remove (apply 'delete-region remove))
9954 (insert (org-make-link-string link desc))))
9956 (defun org-link-try-special-completion (type)
9957 "If there is completion support for link type TYPE, offer it."
9958 (let ((fun (intern (concat "org-" type "-complete-link"))))
9959 (if (functionp fun)
9960 (funcall fun)
9961 (read-string "Link (no completion support): " (concat type ":")))))
9963 (defun org-file-complete-link (&optional arg)
9964 "Create a file link using completion."
9965 (let (file link)
9966 (setq file (org-iread-file-name "File: "))
9967 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9968 (pwd1 (file-name-as-directory (abbreviate-file-name
9969 (expand-file-name ".")))))
9970 (cond
9971 ((equal arg '(16))
9972 (setq link (concat
9973 "file:"
9974 (abbreviate-file-name (expand-file-name file)))))
9975 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9976 (setq link (concat "file:" (match-string 1 file))))
9977 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9978 (expand-file-name file))
9979 (setq link (concat
9980 "file:" (match-string 1 (expand-file-name file)))))
9981 (t (setq link (concat "file:" file)))))
9982 link))
9984 (defun org-iread-file-name (&rest args)
9985 "Read-file-name using `ido-mode' speedup if available.
9986 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9987 See `read-file-name' for a description of parameters."
9988 (org-without-partial-completion
9989 (if (and org-completion-use-ido
9990 (fboundp 'ido-read-file-name)
9991 (boundp 'ido-mode) ido-mode
9992 (listp (second args)))
9993 (let ((ido-enter-matching-directory nil))
9994 (apply 'ido-read-file-name args))
9995 (apply 'read-file-name args))))
9997 (defun org-completing-read (&rest args)
9998 "Completing-read with SPACE being a normal character."
9999 (let ((enable-recursive-minibuffers t)
10000 (minibuffer-local-completion-map
10001 (copy-keymap minibuffer-local-completion-map)))
10002 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10003 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10004 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10005 (apply 'org-icompleting-read args)))
10007 (defun org-completing-read-no-i (&rest args)
10008 (let (org-completion-use-ido org-completion-use-iswitchb)
10009 (apply 'org-completing-read args)))
10011 (defun org-iswitchb-completing-read (prompt choices &rest args)
10012 "Use iswitch as a completing-read replacement to choose from choices.
10013 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10014 from."
10015 (let* ((iswitchb-use-virtual-buffers nil)
10016 (iswitchb-make-buflist-hook
10017 (lambda ()
10018 (setq iswitchb-temp-buflist choices))))
10019 (iswitchb-read-buffer prompt)))
10021 (defun org-icompleting-read (&rest args)
10022 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10023 (org-without-partial-completion
10024 (if (and org-completion-use-ido
10025 (fboundp 'ido-completing-read)
10026 (boundp 'ido-mode) ido-mode
10027 (listp (second args)))
10028 (let ((ido-enter-matching-directory nil))
10029 (apply 'ido-completing-read (concat (car args))
10030 (if (consp (car (nth 1 args)))
10031 (mapcar 'car (nth 1 args))
10032 (nth 1 args))
10033 (cddr args)))
10034 (if (and org-completion-use-iswitchb
10035 (boundp 'iswitchb-mode) iswitchb-mode
10036 (listp (second args)))
10037 (apply 'org-iswitchb-completing-read (concat (car args))
10038 (if (consp (car (nth 1 args)))
10039 (mapcar 'car (nth 1 args))
10040 (nth 1 args))
10041 (cddr args))
10042 (apply 'completing-read args)))))
10044 (defun org-extract-attributes (s)
10045 "Extract the attributes cookie from a string and set as text property."
10046 (let (a attr (start 0) key value)
10047 (save-match-data
10048 (when (string-match "{{\\([^}]+\\)}}$" s)
10049 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10050 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10051 (setq key (match-string 1 a) value (match-string 2 a)
10052 start (match-end 0)
10053 attr (plist-put attr (intern key) value))))
10054 (org-add-props s nil 'org-attr attr))
10057 (defun org-extract-attributes-from-string (tag)
10058 (let (key value attr)
10059 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10060 (setq key (match-string 1 tag) value (match-string 2 tag)
10061 tag (replace-match "" t t tag)
10062 attr (plist-put attr (intern key) value)))
10063 (cons tag attr)))
10065 (defun org-attributes-to-string (plist)
10066 "Format a property list into an HTML attribute list."
10067 (let ((s "") key value)
10068 (while plist
10069 (setq key (pop plist) value (pop plist))
10070 (and value
10071 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10074 ;;; Opening/following a link
10076 (defvar org-link-search-failed nil)
10078 (defvar org-open-link-functions nil
10079 "Hook for functions finding a plain text link.
10080 These functions must take a single argument, the link content.
10081 They will be called for links that look like [[link text][description]]
10082 when LINK TEXT does not have a protocol like \"http:\" and does not look
10083 like a filename (e.g. \"./blue.png\").
10085 These functions will be called *before* Org attempts to resolve the
10086 link by doing text searches in the current buffer - so if you want a
10087 link \"[[target]]\" to still find \"<<target>>\", your function should
10088 handle this as a special case.
10090 When the function does handle the link, it must return a non-nil value.
10091 If it decides that it is not responsible for this link, it must return
10092 nil to indicate that that Org-mode can continue with other options
10093 like exact and fuzzy text search.")
10095 (defun org-next-link (&optional search-backward)
10096 "Move forward to the next link.
10097 If the link is in hidden text, expose it."
10098 (interactive "P")
10099 (when (and org-link-search-failed (eq this-command last-command))
10100 (goto-char (point-min))
10101 (message "Link search wrapped back to beginning of buffer"))
10102 (setq org-link-search-failed nil)
10103 (let* ((pos (point))
10104 (ct (org-context))
10105 (a (assoc :link ct))
10106 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10107 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10108 ((looking-at org-any-link-re)
10109 ;; Don't stay stuck at link without an org-link face
10110 (forward-char (if search-backward -1 1))))
10111 (if (funcall srch-fun org-any-link-re nil t)
10112 (progn
10113 (goto-char (match-beginning 0))
10114 (if (outline-invisible-p) (org-show-context)))
10115 (goto-char pos)
10116 (setq org-link-search-failed t)
10117 (message "No further link found"))))
10119 (defun org-previous-link ()
10120 "Move backward to the previous link.
10121 If the link is in hidden text, expose it."
10122 (interactive)
10123 (funcall 'org-next-link t))
10125 (defun org-translate-link (s)
10126 "Translate a link string if a translation function has been defined."
10127 (if (and org-link-translation-function
10128 (fboundp org-link-translation-function)
10129 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10130 (progn
10131 (setq s (funcall org-link-translation-function
10132 (match-string 1 s) (match-string 2 s)))
10133 (concat (car s) ":" (cdr s)))
10136 (defun org-translate-link-from-planner (type path)
10137 "Translate a link from Emacs Planner syntax so that Org can follow it.
10138 This is still an experimental function, your mileage may vary."
10139 (cond
10140 ((member type '("http" "https" "news" "ftp"))
10141 ;; standard Internet links are the same.
10142 nil)
10143 ((and (equal type "irc") (string-match "^//" path))
10144 ;; Planner has two / at the beginning of an irc link, we have 1.
10145 ;; We should have zero, actually....
10146 (setq path (substring path 1)))
10147 ((and (equal type "lisp") (string-match "^/" path))
10148 ;; Planner has a slash, we do not.
10149 (setq type "elisp" path (substring path 1)))
10150 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10151 ;; A typical message link. Planner has the id after the final slash,
10152 ;; we separate it with a hash mark
10153 (setq path (concat (match-string 1 path) "#"
10154 (org-remove-angle-brackets (match-string 2 path)))))
10156 (cons type path))
10158 (defun org-find-file-at-mouse (ev)
10159 "Open file link or URL at mouse."
10160 (interactive "e")
10161 (mouse-set-point ev)
10162 (org-open-at-point 'in-emacs))
10164 (defun org-open-at-mouse (ev)
10165 "Open file link or URL at mouse.
10166 See the docstring of `org-open-file' for details."
10167 (interactive "e")
10168 (mouse-set-point ev)
10169 (if (eq major-mode 'org-agenda-mode)
10170 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10171 (org-open-at-point))
10173 (defvar org-window-config-before-follow-link nil
10174 "The window configuration before following a link.
10175 This is saved in case the need arises to restore it.")
10177 (defvar org-open-link-marker (make-marker)
10178 "Marker pointing to the location where `org-open-at-point; was called.")
10180 ;;;###autoload
10181 (defun org-open-at-point-global ()
10182 "Follow a link like Org-mode does.
10183 This command can be called in any mode to follow a link that has
10184 Org-mode syntax."
10185 (interactive)
10186 (org-run-like-in-org-mode 'org-open-at-point))
10188 ;;;###autoload
10189 (defun org-open-link-from-string (s &optional arg reference-buffer)
10190 "Open a link in the string S, as if it was in Org-mode."
10191 (interactive "sLink: \nP")
10192 (let ((reference-buffer (or reference-buffer (current-buffer))))
10193 (with-temp-buffer
10194 (let ((org-inhibit-startup (not reference-buffer)))
10195 (org-mode)
10196 (insert s)
10197 (goto-char (point-min))
10198 (when reference-buffer
10199 (setq org-link-abbrev-alist-local
10200 (with-current-buffer reference-buffer
10201 org-link-abbrev-alist-local)))
10202 (org-open-at-point arg reference-buffer)))))
10204 (defvar org-open-at-point-functions nil
10205 "Hook that is run when following a link at point.
10207 Functions in this hook must return t if they identify and follow
10208 a link at point. If they don't find anything interesting at point,
10209 they must return nil.")
10211 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10212 (defun org-open-at-point (&optional arg reference-buffer)
10213 "Open link at or after point.
10214 If there is no link at point, this function will search forward up to
10215 the end of the current line.
10216 Normally, files will be opened by an appropriate application. If the
10217 optional prefix argument ARG is non-nil, Emacs will visit the file.
10218 With a double prefix argument, try to open outside of Emacs, in the
10219 application the system uses for this file type."
10220 (interactive "P")
10221 ;; if in a code block, then open the block's results
10222 (unless (call-interactively #'org-babel-open-src-block-result)
10223 (org-load-modules-maybe)
10224 (move-marker org-open-link-marker (point))
10225 (setq org-window-config-before-follow-link (current-window-configuration))
10226 (org-remove-occur-highlights nil nil t)
10227 (cond
10228 ((and (org-at-heading-p)
10229 (not (org-at-timestamp-p t))
10230 (not (org-in-regexp
10231 (concat org-plain-link-re "\\|"
10232 org-bracket-link-regexp "\\|"
10233 org-angle-link-re "\\|"
10234 "[ \t]:[^ \t\n]+:[ \t]*$")))
10235 (not (get-text-property (point) 'org-linked-text)))
10236 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10237 (lk0 (car lkall))
10238 (lk (if (stringp lk0) (list lk0) lk0))
10239 (lkend (cdr lkall)))
10240 (mapcar (lambda(l)
10241 (search-forward l nil lkend)
10242 (goto-char (match-beginning 0))
10243 (org-open-at-point))
10244 lk))
10245 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10246 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10247 ((and (org-at-timestamp-p t)
10248 (not (org-in-regexp org-bracket-link-regexp)))
10249 (org-follow-timestamp-link))
10250 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10251 (not (org-in-regexp org-any-link-re)))
10252 (org-footnote-action))
10254 (let (type path link line search (pos (point)))
10255 (catch 'match
10256 (save-excursion
10257 (skip-chars-forward "^]\n\r")
10258 (when (org-in-regexp org-bracket-link-regexp 1)
10259 (setq link (org-extract-attributes
10260 (org-link-unescape (org-match-string-no-properties 1))))
10261 (while (string-match " *\n *" link)
10262 (setq link (replace-match " " t t link)))
10263 (setq link (org-link-expand-abbrev link))
10264 (cond
10265 ((or (file-name-absolute-p link)
10266 (string-match "^\\.\\.?/" link))
10267 (setq type "file" path link))
10268 ((string-match org-link-re-with-space3 link)
10269 (setq type (match-string 1 link) path (match-string 2 link)))
10270 ((string-match "^help:+\\(.+\\)" link)
10271 (setq type "help" path (match-string 1 link)))
10272 (t (setq type "thisfile" path link)))
10273 (throw 'match t)))
10275 (when (get-text-property (point) 'org-linked-text)
10276 (setq type "thisfile"
10277 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10278 (1+ (point)) (point))
10279 path (buffer-substring
10280 (or (previous-single-property-change pos 'org-linked-text)
10281 (point-min))
10282 (or (next-single-property-change pos 'org-linked-text)
10283 (point-max))))
10284 (throw 'match t))
10286 (save-excursion
10287 (when (or (org-in-regexp org-angle-link-re)
10288 (let ((match (org-in-regexp org-plain-link-re)))
10289 ;; Check a plain link is not within a bracket link
10290 (and match
10291 (save-excursion
10292 (progn
10293 (goto-char (car match))
10294 (not (org-in-regexp org-bracket-link-regexp))))))
10295 (let ((line_ending (save-excursion (end-of-line) (point))))
10296 ;; We are in a line before a plain or bracket link
10297 (or (re-search-forward org-plain-link-re line_ending t)
10298 (re-search-forward org-bracket-link-regexp line_ending t))))
10299 (setq type (match-string 1)
10300 path (org-link-unescape (match-string 2)))
10301 (throw 'match t)))
10302 (save-excursion
10303 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10304 (setq type "tags"
10305 path (match-string 1))
10306 (while (string-match ":" path)
10307 (setq path (replace-match "+" t t path)))
10308 (throw 'match t)))
10309 (when (org-in-regexp "<\\([^><\n]+\\)>")
10310 (setq type "tree-match"
10311 path (match-string 1))
10312 (throw 'match t)))
10313 (unless path
10314 (user-error "No link found"))
10316 ;; switch back to reference buffer
10317 ;; needed when if called in a temporary buffer through
10318 ;; org-open-link-from-string
10319 (with-current-buffer (or reference-buffer (current-buffer))
10321 ;; Remove any trailing spaces in path
10322 (if (string-match " +\\'" path)
10323 (setq path (replace-match "" t t path)))
10324 (if (and org-link-translation-function
10325 (fboundp org-link-translation-function))
10326 ;; Check if we need to translate the link
10327 (let ((tmp (funcall org-link-translation-function type path)))
10328 (setq type (car tmp) path (cdr tmp))))
10330 (cond
10332 ((assoc type org-link-protocols)
10333 (funcall (nth 1 (assoc type org-link-protocols)) path))
10335 ((equal type "help")
10336 (let ((f-or-v (intern path)))
10337 (cond ((fboundp f-or-v)
10338 (describe-function f-or-v))
10339 ((boundp f-or-v)
10340 (describe-variable f-or-v))
10341 (t (error "Not a known function or variable")))))
10343 ((equal type "mailto")
10344 (let ((cmd (car org-link-mailto-program))
10345 (args (cdr org-link-mailto-program)) args1
10346 (address path) (subject "") a)
10347 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10348 (setq address (match-string 1 path)
10349 subject (org-link-escape (match-string 2 path))))
10350 (while args
10351 (cond
10352 ((not (stringp (car args))) (push (pop args) args1))
10353 (t (setq a (pop args))
10354 (if (string-match "%a" a)
10355 (setq a (replace-match address t t a)))
10356 (if (string-match "%s" a)
10357 (setq a (replace-match subject t t a)))
10358 (push a args1))))
10359 (apply cmd (nreverse args1))))
10361 ((member type '("http" "https" "ftp" "news"))
10362 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10363 (org-link-escape
10364 path org-link-escape-chars-browser)
10365 path))))
10367 ((string= type "doi")
10368 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10369 (org-link-escape
10370 path org-link-escape-chars-browser)
10371 path))))
10373 ((member type '("message"))
10374 (browse-url (concat type ":" path)))
10376 ((string= type "tags")
10377 (org-tags-view arg path))
10379 ((string= type "tree-match")
10380 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10382 ((string= type "file")
10383 (if (string-match "::\\([0-9]+\\)\\'" path)
10384 (setq line (string-to-number (match-string 1 path))
10385 path (substring path 0 (match-beginning 0)))
10386 (if (string-match "::\\(.+\\)\\'" path)
10387 (setq search (match-string 1 path)
10388 path (substring path 0 (match-beginning 0)))))
10389 (if (string-match "[*?{]" (file-name-nondirectory path))
10390 (dired path)
10391 (org-open-file path arg line search)))
10393 ((string= type "shell")
10394 (let ((buf (generate-new-buffer "*Org Shell Output"))
10395 (cmd path))
10396 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10397 (string-match org-confirm-shell-link-not-regexp cmd))
10398 (not org-confirm-shell-link-function)
10399 (funcall org-confirm-shell-link-function
10400 (format "Execute \"%s\" in shell? "
10401 (org-add-props cmd nil
10402 'face 'org-warning))))
10403 (progn
10404 (message "Executing %s" cmd)
10405 (shell-command cmd buf)
10406 (if (featurep 'midnight)
10407 (setq clean-buffer-list-kill-buffer-names
10408 (cons buf clean-buffer-list-kill-buffer-names))))
10409 (error "Abort"))))
10411 ((string= type "elisp")
10412 (let ((cmd path))
10413 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10414 (string-match org-confirm-elisp-link-not-regexp cmd))
10415 (not org-confirm-elisp-link-function)
10416 (funcall org-confirm-elisp-link-function
10417 (format "Execute \"%s\" as elisp? "
10418 (org-add-props cmd nil
10419 'face 'org-warning))))
10420 (message "%s => %s" cmd
10421 (if (equal (string-to-char cmd) ?\()
10422 (eval (read cmd))
10423 (call-interactively (read cmd))))
10424 (error "Abort"))))
10426 ((and (string= type "thisfile")
10427 (run-hook-with-args-until-success
10428 'org-open-link-functions path)))
10430 ((string= type "thisfile")
10431 (if arg
10432 (switch-to-buffer-other-window
10433 (org-get-buffer-for-internal-link (current-buffer)))
10434 (org-mark-ring-push))
10435 (let ((cmd `(org-link-search
10436 ,path
10437 ,(cond ((equal arg '(4)) ''occur)
10438 ((equal arg '(16)) ''org-occur))
10439 ,pos)))
10440 (condition-case nil (let ((org-link-search-inhibit-query t))
10441 (eval cmd))
10442 (error (progn (widen) (eval cmd))))))
10444 (t (browse-url-at-point)))))))
10445 (move-marker org-open-link-marker nil)
10446 (run-hook-with-args 'org-follow-link-hook)))
10448 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10449 "Offer links in the current entry and return the selected link.
10450 If there is only one link, return it.
10451 If NTH is an integer, return the NTH link found.
10452 If ZERO is a string, check also this string for a link, and if
10453 there is one, return it."
10454 (with-current-buffer buffer
10455 (save-excursion
10456 (save-restriction
10457 (widen)
10458 (goto-char marker)
10459 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10460 "\\(" org-angle-link-re "\\)\\|"
10461 "\\(" org-plain-link-re "\\)"))
10462 (cnt ?0)
10463 (in-emacs (if (integerp nth) nil nth))
10464 have-zero end links link c)
10465 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10466 (push (match-string 0 zero) links)
10467 (setq cnt (1- cnt) have-zero t))
10468 (save-excursion
10469 (org-back-to-heading t)
10470 (setq end (save-excursion (outline-next-heading) (point)))
10471 (while (re-search-forward re end t)
10472 (push (match-string 0) links))
10473 (setq links (org-uniquify (reverse links))))
10474 (cond
10475 ((null links)
10476 (message "No links"))
10477 ((equal (length links) 1)
10478 (setq link (car links)))
10479 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10480 (setq link (nth (if have-zero nth (1- nth)) links)))
10481 (t ; we have to select a link
10482 (save-excursion
10483 (save-window-excursion
10484 (delete-other-windows)
10485 (with-output-to-temp-buffer "*Select Link*"
10486 (mapc (lambda (l)
10487 (if (not (string-match org-bracket-link-regexp l))
10488 (princ (format "[%c] %s\n" (incf cnt)
10489 (org-remove-angle-brackets l)))
10490 (if (match-end 3)
10491 (princ (format "[%c] %s (%s)\n" (incf cnt)
10492 (match-string 3 l) (match-string 1 l)))
10493 (princ (format "[%c] %s\n" (incf cnt)
10494 (match-string 1 l))))))
10495 links))
10496 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10497 (message "Select link to open, RET to open all:")
10498 (setq c (read-char-exclusive))
10499 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10500 (when (equal c ?q) (error "Abort"))
10501 (if (equal c ?\C-m)
10502 (setq link links)
10503 (setq nth (- c ?0))
10504 (if have-zero (setq nth (1+ nth)))
10505 (unless (and (integerp nth) (>= (length links) nth))
10506 (error "Invalid link selection"))
10507 (setq link (nth (1- nth) links)))))
10508 (cons link end))))))
10510 ;; Add special file links that specify the way of opening
10512 (org-add-link-type "file+sys" 'org-open-file-with-system)
10513 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10514 (defun org-open-file-with-system (path)
10515 "Open file at PATH using the system way of opening it."
10516 (org-open-file path 'system))
10517 (defun org-open-file-with-emacs (path)
10518 "Open file at PATH in Emacs."
10519 (org-open-file path 'emacs))
10522 ;;; File search
10524 (defvar org-create-file-search-functions nil
10525 "List of functions to construct the right search string for a file link.
10526 These functions are called in turn with point at the location to
10527 which the link should point.
10529 A function in the hook should first test if it would like to
10530 handle this file type, for example by checking the `major-mode'
10531 or the file extension. If it decides not to handle this file, it
10532 should just return nil to give other functions a chance. If it
10533 does handle the file, it must return the search string to be used
10534 when following the link. The search string will be part of the
10535 file link, given after a double colon, and `org-open-at-point'
10536 will automatically search for it. If special measures must be
10537 taken to make the search successful, another function should be
10538 added to the companion hook `org-execute-file-search-functions',
10539 which see.
10541 A function in this hook may also use `setq' to set the variable
10542 `description' to provide a suggestion for the descriptive text to
10543 be used for this link when it gets inserted into an Org-mode
10544 buffer with \\[org-insert-link].")
10546 (defvar org-execute-file-search-functions nil
10547 "List of functions to execute a file search triggered by a link.
10549 Functions added to this hook must accept a single argument, the
10550 search string that was part of the file link, the part after the
10551 double colon. The function must first check if it would like to
10552 handle this search, for example by checking the `major-mode' or
10553 the file extension. If it decides not to handle this search, it
10554 should just return nil to give other functions a chance. If it
10555 does handle the search, it must return a non-nil value to keep
10556 other functions from trying.
10558 Each function can access the current prefix argument through the
10559 variable `current-prefix-arg'. Note that a single prefix is used
10560 to force opening a link in Emacs, so it may be good to only use a
10561 numeric or double prefix to guide the search function.
10563 In case this is needed, a function in this hook can also restore
10564 the window configuration before `org-open-at-point' was called using:
10566 (set-window-configuration org-window-config-before-follow-link)")
10568 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10569 (defun org-link-search (s &optional type avoid-pos stealth)
10570 "Search for a link search option.
10571 If S is surrounded by forward slashes, it is interpreted as a
10572 regular expression. In org-mode files, this will create an `org-occur'
10573 sparse tree. In ordinary files, `occur' will be used to list matches.
10574 If the current buffer is in `dired-mode', grep will be used to search
10575 in all files. If AVOID-POS is given, ignore matches near that position.
10577 When optional argument STEALTH is non-nil, do not modify
10578 visibility around point, thus ignoring
10579 `org-show-hierarchy-above', `org-show-following-heading' and
10580 `org-show-siblings' variables."
10581 (let ((case-fold-search t)
10582 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10583 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10584 (append '(("") (" ") ("\t") ("\n"))
10585 org-emphasis-alist)
10586 "\\|") "\\)"))
10587 (pos (point))
10588 (pre nil) (post nil)
10589 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10590 (cond
10591 ;; First check if there are any special search functions
10592 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10593 ;; Now try the builtin stuff
10594 ((and (equal (string-to-char s0) ?#)
10595 (> (length s0) 1)
10596 (save-excursion
10597 (goto-char (point-min))
10598 (and
10599 (re-search-forward
10600 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10601 (setq type 'dedicated
10602 pos (match-beginning 0))))
10603 ;; There is an exact target for this
10604 (goto-char pos)
10605 (org-back-to-heading t)))
10606 ((save-excursion
10607 (goto-char (point-min))
10608 (and
10609 (re-search-forward
10610 (concat "<<" (regexp-quote s0) ">>") nil t)
10611 (setq type 'dedicated
10612 pos (match-beginning 0))))
10613 ;; There is an exact target for this
10614 (goto-char pos))
10615 ((save-excursion
10616 (goto-char (point-min))
10617 (and
10618 (re-search-forward
10619 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10620 (setq type 'dedicated pos (match-beginning 0))))
10621 ;; Found an invisible target.
10622 (goto-char pos))
10623 ((save-excursion
10624 (goto-char (point-min))
10625 (and
10626 (re-search-forward
10627 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10628 (setq type 'dedicated pos (match-beginning 0))))
10629 ;; Found an element with a matching #+name affiliated keyword.
10630 (goto-char pos))
10631 ((and (string-match "^(\\(.*\\))$" s0)
10632 (save-excursion
10633 (goto-char (point-min))
10634 (and
10635 (re-search-forward
10636 (concat "[^[]" (regexp-quote
10637 (format org-coderef-label-format
10638 (match-string 1 s0))))
10639 nil t)
10640 (setq type 'dedicated
10641 pos (1+ (match-beginning 0))))))
10642 ;; There is a coderef target for this
10643 (goto-char pos))
10644 ((string-match "^/\\(.*\\)/$" s)
10645 ;; A regular expression
10646 (cond
10647 ((derived-mode-p 'org-mode)
10648 (org-occur (match-string 1 s)))
10649 (t (org-do-occur (match-string 1 s)))))
10650 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10651 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10652 (goto-char (point-min))
10653 (cond
10654 ((let (case-fold-search)
10655 (re-search-forward (format org-complex-heading-regexp-format
10656 (regexp-quote s))
10657 nil t))
10658 ;; OK, found a match
10659 (setq type 'dedicated)
10660 (goto-char (match-beginning 0)))
10661 ((and (not org-link-search-inhibit-query)
10662 (eq org-link-search-must-match-exact-headline 'query-to-create)
10663 (y-or-n-p "No match - create this as a new heading? "))
10664 (goto-char (point-max))
10665 (or (bolp) (newline))
10666 (insert "* " s "\n")
10667 (beginning-of-line 0))
10669 (goto-char pos)
10670 (error "No match"))))
10672 ;; A normal search string
10673 (when (equal (string-to-char s) ?*)
10674 ;; Anchor on headlines, post may include tags.
10675 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10676 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10677 s (substring s 1)))
10678 (remove-text-properties
10679 0 (length s)
10680 '(face nil mouse-face nil keymap nil fontified nil) s)
10681 ;; Make a series of regular expressions to find a match
10682 (setq words (org-split-string s "[ \n\r\t]+")
10684 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10685 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10686 "\\)" markers)
10687 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10688 re2a (concat "[ \t\r\n]" re2a_)
10689 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10690 re4 (concat "[^a-zA-Z_]" re4_)
10692 re1 (concat pre re2 post)
10693 re3 (concat pre (if pre re4_ re4) post)
10694 re5 (concat pre ".*" re4)
10695 re2 (concat pre re2)
10696 re2a (concat pre (if pre re2a_ re2a))
10697 re4 (concat pre (if pre re4_ re4))
10698 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10699 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10700 re5 "\\)"
10702 (cond
10703 ((eq type 'org-occur) (org-occur reall))
10704 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10705 (t (goto-char (point-min))
10706 (setq type 'fuzzy)
10707 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10708 (org-search-not-self 1 re1 nil t)
10709 (org-search-not-self 1 re2 nil t)
10710 (org-search-not-self 1 re2a nil t)
10711 (org-search-not-self 1 re3 nil t)
10712 (org-search-not-self 1 re4 nil t)
10713 (org-search-not-self 1 re5 nil t)
10715 (goto-char (match-beginning 1))
10716 (goto-char pos)
10717 (error "No match"))))))
10718 (and (derived-mode-p 'org-mode)
10719 (not stealth)
10720 (org-show-context 'link-search))
10721 type))
10723 (defun org-search-not-self (group &rest args)
10724 "Execute `re-search-forward', but only accept matches that do not
10725 enclose the position of `org-open-link-marker'."
10726 (let ((m org-open-link-marker))
10727 (catch 'exit
10728 (while (apply 're-search-forward args)
10729 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10730 (goto-char (match-end group))
10731 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10732 (> (match-beginning 0) (marker-position m))
10733 (< (match-end 0) (marker-position m)))
10734 (save-match-data
10735 (or (not (org-in-regexp
10736 org-bracket-link-analytic-regexp 1))
10737 (not (match-end 4)) ; no description
10738 (and (<= (match-beginning 4) (point))
10739 (>= (match-end 4) (point))))))
10740 (throw 'exit (point))))))))
10742 (defun org-get-buffer-for-internal-link (buffer)
10743 "Return a buffer to be used for displaying the link target of internal links."
10744 (cond
10745 ((not org-display-internal-link-with-indirect-buffer)
10746 buffer)
10747 ((string-match "(Clone)$" (buffer-name buffer))
10748 (message "Buffer is already a clone, not making another one")
10749 ;; we also do not modify visibility in this case
10750 buffer)
10751 (t ; make a new indirect buffer for displaying the link
10752 (let* ((bn (buffer-name buffer))
10753 (ibn (concat bn "(Clone)"))
10754 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10755 (with-current-buffer ib (org-overview))
10756 ib))))
10758 (defun org-do-occur (regexp &optional cleanup)
10759 "Call the Emacs command `occur'.
10760 If CLEANUP is non-nil, remove the printout of the regular expression
10761 in the *Occur* buffer. This is useful if the regex is long and not useful
10762 to read."
10763 (occur regexp)
10764 (when cleanup
10765 (let ((cwin (selected-window)) win beg end)
10766 (when (setq win (get-buffer-window "*Occur*"))
10767 (select-window win))
10768 (goto-char (point-min))
10769 (when (re-search-forward "match[a-z]+" nil t)
10770 (setq beg (match-end 0))
10771 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10772 (setq end (1- (match-beginning 0)))))
10773 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10774 (goto-char (point-min))
10775 (select-window cwin))))
10777 ;;; The mark ring for links jumps
10779 (defvar org-mark-ring nil
10780 "Mark ring for positions before jumps in Org-mode.")
10781 (defvar org-mark-ring-last-goto nil
10782 "Last position in the mark ring used to go back.")
10783 ;; Fill and close the ring
10784 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10785 (loop for i from 1 to org-mark-ring-length do
10786 (push (make-marker) org-mark-ring))
10787 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10788 org-mark-ring)
10790 (defun org-mark-ring-push (&optional pos buffer)
10791 "Put the current position or POS into the mark ring and rotate it."
10792 (interactive)
10793 (setq pos (or pos (point)))
10794 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10795 (move-marker (car org-mark-ring)
10796 (or pos (point))
10797 (or buffer (current-buffer)))
10798 (message "%s"
10799 (substitute-command-keys
10800 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10802 (defun org-mark-ring-goto (&optional n)
10803 "Jump to the previous position in the mark ring.
10804 With prefix arg N, jump back that many stored positions. When
10805 called several times in succession, walk through the entire ring.
10806 Org-mode commands jumping to a different position in the current file,
10807 or to another Org-mode file, automatically push the old position
10808 onto the ring."
10809 (interactive "p")
10810 (let (p m)
10811 (if (eq last-command this-command)
10812 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10813 (setq p org-mark-ring))
10814 (setq org-mark-ring-last-goto p)
10815 (setq m (car p))
10816 (org-pop-to-buffer-same-window (marker-buffer m))
10817 (goto-char m)
10818 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10820 (defun org-remove-angle-brackets (s)
10821 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10822 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10824 (defun org-add-angle-brackets (s)
10825 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10826 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10828 (defun org-remove-double-quotes (s)
10829 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10830 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10833 ;;; Following specific links
10835 (defun org-follow-timestamp-link ()
10836 "Open an agenda view for the time-stamp date/range at point."
10837 (cond
10838 ((org-at-date-range-p t)
10839 (let ((org-agenda-start-on-weekday)
10840 (t1 (match-string 1))
10841 (t2 (match-string 2)) tt1 tt2)
10842 (setq tt1 (time-to-days (org-time-string-to-time t1))
10843 tt2 (time-to-days (org-time-string-to-time t2)))
10844 (let ((org-agenda-buffer-tmp-name
10845 (format "*Org Agenda(a:%s)"
10846 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10847 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10848 ((org-at-timestamp-p t)
10849 (let ((org-agenda-buffer-tmp-name
10850 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10851 (org-agenda-list nil (time-to-days (org-time-string-to-time
10852 (substring (match-string 1) 0 10)))
10853 1)))
10854 (t (error "This should not happen"))))
10857 ;;; Following file links
10858 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10859 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10860 (declare-function mailcap-mime-info
10861 "mailcap" (string &optional request no-decode))
10862 (defvar org-wait nil)
10863 (defun org-open-file (path &optional in-emacs line search)
10864 "Open the file at PATH.
10865 First, this expands any special file name abbreviations. Then the
10866 configuration variable `org-file-apps' is checked if it contains an
10867 entry for this file type, and if yes, the corresponding command is launched.
10869 If no application is found, Emacs simply visits the file.
10871 With optional prefix argument IN-EMACS, Emacs will visit the file.
10872 With a double \\[universal-argument] \\[universal-argument] \
10873 prefix arg, Org tries to avoid opening in Emacs
10874 and to use an external application to visit the file.
10876 Optional LINE specifies a line to go to, optional SEARCH a string
10877 to search for. If LINE or SEARCH is given, the file will be
10878 opened in Emacs, unless an entry from org-file-apps that makes
10879 use of groups in a regexp matches.
10881 If you want to change the way frames are used when following a
10882 link, please customize `org-link-frame-setup'.
10884 If the file does not exist, an error is thrown."
10885 (let* ((file (if (equal path "")
10886 buffer-file-name
10887 (substitute-in-file-name (expand-file-name path))))
10888 (file-apps (append org-file-apps (org-default-apps)))
10889 (apps (org-remove-if
10890 'org-file-apps-entry-match-against-dlink-p file-apps))
10891 (apps-dlink (org-remove-if-not
10892 'org-file-apps-entry-match-against-dlink-p file-apps))
10893 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10894 (dirp (if remp nil (file-directory-p file)))
10895 (file (if (and dirp org-open-directory-means-index-dot-org)
10896 (concat (file-name-as-directory file) "index.org")
10897 file))
10898 (a-m-a-p (assq 'auto-mode apps))
10899 (dfile (downcase file))
10900 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10901 (link (cond ((and (eq line nil)
10902 (eq search nil))
10903 file)
10904 (line
10905 (concat file "::" (number-to-string line)))
10906 (search
10907 (concat file "::" search))))
10908 (dlink (downcase link))
10909 (old-buffer (current-buffer))
10910 (old-pos (point))
10911 (old-mode major-mode)
10912 ext cmd link-match-data)
10913 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10914 (setq ext (match-string 1 dfile))
10915 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10916 (setq ext (match-string 1 dfile))))
10917 (cond
10918 ((member in-emacs '((16) system))
10919 (setq cmd (cdr (assoc 'system apps))))
10920 (in-emacs (setq cmd 'emacs))
10922 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10923 (and dirp (cdr (assoc 'directory apps)))
10924 ; first, try matching against apps-dlink
10925 ; if we get a match here, store the match data for later
10926 (let ((match (assoc-default dlink apps-dlink
10927 'string-match)))
10928 (if match
10929 (progn (setq link-match-data (match-data))
10930 match)
10931 (progn (setq in-emacs (or in-emacs line search))
10932 nil))) ; if we have no match in apps-dlink,
10933 ; always open the file in emacs if line or search
10934 ; is given (for backwards compatibility)
10935 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10936 'string-match)
10937 (cdr (assoc ext apps))
10938 (cdr (assoc t apps))))))
10939 (when (eq cmd 'system)
10940 (setq cmd (cdr (assoc 'system apps))))
10941 (when (eq cmd 'default)
10942 (setq cmd (cdr (assoc t apps))))
10943 (when (eq cmd 'mailcap)
10944 (require 'mailcap)
10945 (mailcap-parse-mailcaps)
10946 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10947 (command (mailcap-mime-info mime-type)))
10948 (if (stringp command)
10949 (setq cmd command)
10950 (setq cmd 'emacs))))
10951 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10952 (not (file-exists-p file))
10953 (not org-open-non-existing-files))
10954 (error "No such file: %s" file))
10955 (cond
10956 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10957 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10958 (while (string-match "['\"]%s['\"]" cmd)
10959 (setq cmd (replace-match "%s" t t cmd)))
10960 (while (string-match "%s" cmd)
10961 (setq cmd (replace-match
10962 (save-match-data
10963 (shell-quote-argument
10964 (convert-standard-filename file)))
10965 t t cmd)))
10967 ;; Replace "%1", "%2" etc. in command with group matches from regex
10968 (save-match-data
10969 (let ((match-index 1)
10970 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10971 (set-match-data link-match-data)
10972 (while (<= match-index number-of-groups)
10973 (let ((regex (concat "%" (number-to-string match-index)))
10974 (replace-with (match-string match-index dlink)))
10975 (while (string-match regex cmd)
10976 (setq cmd (replace-match replace-with t t cmd))))
10977 (setq match-index (+ match-index 1)))))
10979 (save-window-excursion
10980 (message "Running %s...done" cmd)
10981 (start-process-shell-command cmd nil cmd)
10982 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10983 ((or (stringp cmd)
10984 (eq cmd 'emacs))
10985 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10986 (widen)
10987 (if line (org-goto-line line)
10988 (if search (org-link-search search))))
10989 ((consp cmd)
10990 (let ((file (convert-standard-filename file)))
10991 (save-match-data
10992 (set-match-data link-match-data)
10993 (eval cmd))))
10994 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10995 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10996 (or (not (equal old-buffer (current-buffer)))
10997 (not (equal old-pos (point))))
10998 (org-mark-ring-push old-pos old-buffer))))
11000 (defun org-file-apps-entry-match-against-dlink-p (entry)
11001 "This function returns non-nil if `entry' uses a regular
11002 expression which should be matched against the whole link by
11003 org-open-file.
11005 It assumes that is the case when the entry uses a regular
11006 expression which has at least one grouping construct and the
11007 action is either a lisp form or a command string containing
11008 '%1', i.e. using at least one subexpression match as a
11009 parameter."
11010 (let ((selector (car entry))
11011 (action (cdr entry)))
11012 (if (stringp selector)
11013 (and (> (regexp-opt-depth selector) 0)
11014 (or (and (stringp action)
11015 (string-match "%[0-9]" action))
11016 (consp action)))
11017 nil)))
11019 (defun org-default-apps ()
11020 "Return the default applications for this operating system."
11021 (cond
11022 ((eq system-type 'darwin)
11023 org-file-apps-defaults-macosx)
11024 ((eq system-type 'windows-nt)
11025 org-file-apps-defaults-windowsnt)
11026 (t org-file-apps-defaults-gnu)))
11028 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11029 "Convert extensions to regular expressions in the cars of LIST.
11030 Also, weed out any non-string entries, because the return value is used
11031 only for regexp matching.
11032 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11033 point to the symbol `emacs', indicating that the file should
11034 be opened in Emacs."
11035 (append
11036 (delq nil
11037 (mapcar (lambda (x)
11038 (if (not (stringp (car x)))
11040 (if (string-match "\\W" (car x))
11042 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11043 list))
11044 (if add-auto-mode
11045 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11047 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11048 (defun org-file-remote-p (file)
11049 "Test whether FILE specifies a location on a remote system.
11050 Return non-nil if the location is indeed remote.
11052 For example, the filename \"/user@host:/foo\" specifies a location
11053 on the system \"/user@host:\"."
11054 (cond ((fboundp 'file-remote-p)
11055 (file-remote-p file))
11056 ((fboundp 'tramp-handle-file-remote-p)
11057 (tramp-handle-file-remote-p file))
11058 ((and (boundp 'ange-ftp-name-format)
11059 (string-match (car ange-ftp-name-format) file))
11060 t)))
11063 ;;;; Refiling
11065 (defun org-get-org-file ()
11066 "Read a filename, with default directory `org-directory'."
11067 (let ((default (or org-default-notes-file remember-data-file)))
11068 (read-file-name (format "File name [%s]: " default)
11069 (file-name-as-directory org-directory)
11070 default)))
11072 (defun org-notes-order-reversed-p ()
11073 "Check if the current file should receive notes in reversed order."
11074 (cond
11075 ((not org-reverse-note-order) nil)
11076 ((eq t org-reverse-note-order) t)
11077 ((not (listp org-reverse-note-order)) nil)
11078 (t (catch 'exit
11079 (let ((all org-reverse-note-order)
11080 entry)
11081 (while (setq entry (pop all))
11082 (if (string-match (car entry) buffer-file-name)
11083 (throw 'exit (cdr entry))))
11084 nil)))))
11086 (defvar org-refile-target-table nil
11087 "The list of refile targets, created by `org-refile'.")
11089 (defvar org-agenda-new-buffers nil
11090 "Buffers created to visit agenda files.")
11092 (defvar org-refile-cache nil
11093 "Cache for refile targets.")
11095 (defvar org-refile-markers nil
11096 "All the markers used for caching refile locations.")
11098 (defun org-refile-marker (pos)
11099 "Get a new refile marker, but only if caching is in use."
11100 (if (not org-refile-use-cache)
11102 (let ((m (make-marker)))
11103 (move-marker m pos)
11104 (push m org-refile-markers)
11105 m)))
11107 (defun org-refile-cache-clear ()
11108 "Clear the refile cache and disable all the markers."
11109 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11110 (setq org-refile-markers nil)
11111 (setq org-refile-cache nil)
11112 (message "Refile cache has been cleared"))
11114 (defun org-refile-cache-check-set (set)
11115 "Check if all the markers in the cache still have live buffers."
11116 (let (marker)
11117 (catch 'exit
11118 (while (and set (setq marker (nth 3 (pop set))))
11119 ;; if org-refile-use-outline-path is 'file, marker may be nil
11120 (when (and marker (null (marker-buffer marker)))
11121 (message "not found") (sit-for 3)
11122 (throw 'exit nil)))
11123 t)))
11125 (defun org-refile-cache-put (set &rest identifiers)
11126 "Push the refile targets SET into the cache, under IDENTIFIERS."
11127 (let* ((key (sha1 (prin1-to-string identifiers)))
11128 (entry (assoc key org-refile-cache)))
11129 (if entry
11130 (setcdr entry set)
11131 (push (cons key set) org-refile-cache))))
11133 (defun org-refile-cache-get (&rest identifiers)
11134 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11135 (cond
11136 ((not org-refile-cache) nil)
11137 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11139 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11140 org-refile-cache))))
11141 (and set (org-refile-cache-check-set set) set)))))
11143 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11144 "Produce a table with refile targets."
11145 (let ((case-fold-search nil)
11146 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11147 (entries (or org-refile-targets '((nil . (:level . 1)))))
11148 targets tgs txt re files f desc descre fast-path-p level pos0)
11149 (message "Getting targets...")
11150 (with-current-buffer (or default-buffer (current-buffer))
11151 (while (setq entry (pop entries))
11152 (setq files (car entry) desc (cdr entry))
11153 (setq fast-path-p nil)
11154 (cond
11155 ((null files) (setq files (list (current-buffer))))
11156 ((eq files 'org-agenda-files)
11157 (setq files (org-agenda-files 'unrestricted)))
11158 ((and (symbolp files) (fboundp files))
11159 (setq files (funcall files)))
11160 ((and (symbolp files) (boundp files))
11161 (setq files (symbol-value files))))
11162 (if (stringp files) (setq files (list files)))
11163 (cond
11164 ((eq (car desc) :tag)
11165 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11166 ((eq (car desc) :todo)
11167 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11168 ((eq (car desc) :regexp)
11169 (setq descre (cdr desc)))
11170 ((eq (car desc) :level)
11171 (setq descre (concat "^\\*\\{" (number-to-string
11172 (if org-odd-levels-only
11173 (1- (* 2 (cdr desc)))
11174 (cdr desc)))
11175 "\\}[ \t]")))
11176 ((eq (car desc) :maxlevel)
11177 (setq fast-path-p t)
11178 (setq descre (concat "^\\*\\{1," (number-to-string
11179 (if org-odd-levels-only
11180 (1- (* 2 (cdr desc)))
11181 (cdr desc)))
11182 "\\}[ \t]")))
11183 (t (error "Bad refiling target description %s" desc)))
11184 (while (setq f (pop files))
11185 (with-current-buffer
11186 (if (bufferp f) f (org-get-agenda-file-buffer f))
11188 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11189 (progn
11190 (if (bufferp f) (setq f (buffer-file-name
11191 (buffer-base-buffer f))))
11192 (setq f (and f (expand-file-name f)))
11193 (if (eq org-refile-use-outline-path 'file)
11194 (push (list (file-name-nondirectory f) f nil nil) tgs))
11195 (save-excursion
11196 (save-restriction
11197 (widen)
11198 (goto-char (point-min))
11199 (while (re-search-forward descre nil t)
11200 (goto-char (setq pos0 (point-at-bol)))
11201 (catch 'next
11202 (when org-refile-target-verify-function
11203 (save-match-data
11204 (or (funcall org-refile-target-verify-function)
11205 (throw 'next t))))
11206 (when (and (looking-at org-complex-heading-regexp)
11207 (not (member (match-string 4) excluded-entries))
11208 (match-string 4))
11209 (setq level (org-reduced-level
11210 (- (match-end 1) (match-beginning 1)))
11211 txt (org-link-display-format (match-string 4))
11212 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11213 re (format org-complex-heading-regexp-format
11214 (regexp-quote (match-string 4))))
11215 (when org-refile-use-outline-path
11216 (setq txt (mapconcat
11217 'org-protect-slash
11218 (append
11219 (if (eq org-refile-use-outline-path
11220 'file)
11221 (list (file-name-nondirectory
11222 (buffer-file-name
11223 (buffer-base-buffer))))
11224 (if (eq org-refile-use-outline-path
11225 'full-file-path)
11226 (list (buffer-file-name
11227 (buffer-base-buffer)))))
11228 (org-get-outline-path fast-path-p
11229 level txt)
11230 (list txt))
11231 "/")))
11232 (push (list txt f re (org-refile-marker (point)))
11233 tgs)))
11234 (when (= (point) pos0)
11235 ;; verification function has not moved point
11236 (goto-char (point-at-eol))))))))
11237 (when org-refile-use-cache
11238 (org-refile-cache-put tgs (buffer-file-name) descre))
11239 (setq targets (append tgs targets))
11240 ))))
11241 (message "Getting targets...done")
11242 (nreverse targets)))
11244 (defun org-protect-slash (s)
11245 (while (string-match "/" s)
11246 (setq s (replace-match "\\" t t s)))
11249 (defvar org-olpa (make-vector 20 nil))
11251 (defun org-get-outline-path (&optional fastp level heading)
11252 "Return the outline path to the current entry, as a list.
11254 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11255 routine which makes outline path derivations for an entire file,
11256 avoiding backtracing. Refile target collection makes use of that."
11257 (if fastp
11258 (progn
11259 (if (> level 19)
11260 (error "Outline path failure, more than 19 levels"))
11261 (loop for i from level upto 19 do
11262 (aset org-olpa i nil))
11263 (prog1
11264 (delq nil (append org-olpa nil))
11265 (aset org-olpa level heading)))
11266 (let (rtn case-fold-search)
11267 (save-excursion
11268 (save-restriction
11269 (widen)
11270 (while (org-up-heading-safe)
11271 (when (looking-at org-complex-heading-regexp)
11272 (push (org-match-string-no-properties 4) rtn)))
11273 rtn)))))
11275 (defun org-format-outline-path (path &optional width prefix separator)
11276 "Format the outline path PATH for display.
11277 WIDTH is the maximum number of characters that is available.
11278 PREFIX is a prefix to be included in the returned string,
11279 such as the file name.
11280 SEPARATOR is inserted between the different parts of the path,
11281 the default is \"/\"."
11282 (setq width (or width 79))
11283 (if prefix (setq width (- width (length prefix))))
11284 (if (not path)
11285 (or prefix "")
11286 (let* ((nsteps (length path))
11287 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11288 (maxwidth (if (<= total-width width)
11289 10000 ;; everything fits
11290 ;; we need to shorten the level headings
11291 (/ (- width nsteps) nsteps)))
11292 (org-odd-levels-only nil)
11293 (n 0)
11294 (total (1+ (length prefix))))
11295 (setq maxwidth (max maxwidth 10))
11296 (concat prefix
11297 (if prefix (or separator "/"))
11298 (mapconcat
11299 (lambda (h)
11300 (setq n (1+ n))
11301 (if (and (= n nsteps) (< maxwidth 10000))
11302 (setq maxwidth (- total-width total)))
11303 (if (< (length h) maxwidth)
11304 (progn (setq total (+ total (length h) 1)) h)
11305 (setq h (substring h 0 (- maxwidth 2))
11306 total (+ total maxwidth 1))
11307 (if (string-match "[ \t]+\\'" h)
11308 (setq h (substring h 0 (match-beginning 0))))
11309 (setq h (concat h "..")))
11310 (org-add-props h nil 'face
11311 (nth (% (1- n) org-n-level-faces)
11312 org-level-faces))
11314 path (or separator "/"))))))
11316 (defun org-display-outline-path (&optional file current separator just-return-string)
11317 "Display the current outline path in the echo area.
11319 If FILE is non-nil, prepend the output with the file name.
11320 If CURRENT is non-nil, append the current heading to the output.
11321 SEPARATOR is passed through to `org-format-outline-path'. It separates
11322 the different parts of the path and defaults to \"/\".
11323 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11324 (interactive "P")
11325 (let* (case-fold-search
11326 message-log-max ; Don't populate the *Messages* buffer
11327 (bfn (buffer-file-name (buffer-base-buffer)))
11328 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11329 res)
11330 (if current (setq path (append path
11331 (save-excursion
11332 (org-back-to-heading t)
11333 (if (looking-at org-complex-heading-regexp)
11334 (list (match-string 4)))))))
11335 (setq res
11336 (org-format-outline-path
11337 path
11338 (1- (frame-width))
11339 (and file bfn (concat (file-name-nondirectory bfn) separator))
11340 separator))
11341 (if just-return-string
11342 (org-no-properties res)
11343 (message "%s" res))))
11345 (defvar org-refile-history nil
11346 "History for refiling operations.")
11348 (defvar org-after-refile-insert-hook nil
11349 "Hook run after `org-refile' has inserted its stuff at the new location.
11350 Note that this is still *before* the stuff will be removed from
11351 the *old* location.")
11353 (defvar org-capture-last-stored-marker)
11354 (defvar org-refile-keep nil
11355 "Non-nil means `org-refile' will copy instead of refile.")
11357 (defun org-copy ()
11358 "Like `org-refile', but copy."
11359 (interactive)
11360 (let ((org-refile-keep t))
11361 (funcall 'org-refile nil nil nil "Copy")))
11363 (defun org-refile (&optional goto default-buffer rfloc msg)
11364 "Move the entry or entries at point to another heading.
11365 The list of target headings is compiled using the information in
11366 `org-refile-targets', which see.
11368 At the target location, the entry is filed as a subitem of the target
11369 heading. Depending on `org-reverse-note-order', the new subitem will
11370 either be the first or the last subitem.
11372 If there is an active region, all entries in that region will be moved.
11373 However, the region must fulfill the requirement that the first heading
11374 is the first one sets the top-level of the moved text - at most siblings
11375 below it are allowed.
11377 With prefix arg GOTO, the command will only visit the target location
11378 and not actually move anything.
11380 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11381 go to the location where the last refiling operation has put the subtree.
11382 With a prefix argument of `2', refile to the running clock.
11384 RFLOC can be a refile location obtained in a different way.
11386 MSG is a string to replace \"Refile\" in the default prompt with
11387 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11389 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11391 If you are using target caching (see `org-refile-use-cache'),
11392 you have to clear the target cache in order to find new targets.
11393 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11394 prefix argument (`C-u C-u C-u C-c C-w')."
11396 (interactive "P")
11397 (if (member goto '(0 (64)))
11398 (org-refile-cache-clear)
11399 (let* ((actionmsg (or msg "Refile"))
11400 (cbuf (current-buffer))
11401 (regionp (org-region-active-p))
11402 (region-start (and regionp (region-beginning)))
11403 (region-end (and regionp (region-end)))
11404 (region-length (and regionp (- region-end region-start)))
11405 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11406 pos it nbuf file re level reversed)
11407 (setq last-command nil)
11408 (when regionp
11409 (goto-char region-start)
11410 (or (bolp) (goto-char (point-at-bol)))
11411 (setq region-start (point))
11412 (unless (or (org-kill-is-subtree-p
11413 (buffer-substring region-start region-end))
11414 (prog1 org-refile-active-region-within-subtree
11415 (org-toggle-heading)))
11416 (error "The region is not a (sequence of) subtree(s)")))
11417 (if (equal goto '(16))
11418 (org-refile-goto-last-stored)
11419 (when (or
11420 (and (equal goto 2)
11421 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11422 (prog1
11423 (setq it (list (or org-clock-heading "running clock")
11424 (buffer-file-name
11425 (marker-buffer org-clock-hd-marker))
11427 (marker-position org-clock-hd-marker)))
11428 (setq goto nil)))
11429 (setq it (or rfloc
11430 (let (heading-text)
11431 (save-excursion
11432 (unless goto
11433 (org-back-to-heading t)
11434 (setq heading-text
11435 (nth 4 (org-heading-components))))
11437 (org-refile-get-location
11438 (cond (goto "Goto")
11439 (regionp (concat actionmsg " region to"))
11440 (t (concat actionmsg " subtree \""
11441 heading-text "\" to")))
11442 default-buffer
11443 (and (not (equal '(4) goto))
11444 org-refile-allow-creating-parent-nodes)
11445 goto))))))
11446 (setq file (nth 1 it)
11447 re (nth 2 it)
11448 pos (nth 3 it))
11449 (if (and (not goto)
11451 (equal (buffer-file-name) file)
11452 (if regionp
11453 (and (>= pos region-start)
11454 (<= pos region-end))
11455 (and (>= pos (point))
11456 (< pos (save-excursion
11457 (org-end-of-subtree t t))))))
11458 (error "Cannot refile to position inside the tree or region"))
11460 (setq nbuf (or (find-buffer-visiting file)
11461 (find-file-noselect file)))
11462 (if goto
11463 (progn
11464 (org-pop-to-buffer-same-window nbuf)
11465 (goto-char pos)
11466 (org-show-context 'org-goto))
11467 (if regionp
11468 (progn
11469 (org-kill-new (buffer-substring region-start region-end))
11470 (org-save-markers-in-region region-start region-end))
11471 (org-copy-subtree 1 nil t))
11472 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11473 (find-file-noselect file)))
11474 (setq reversed (org-notes-order-reversed-p))
11475 (save-excursion
11476 (save-restriction
11477 (widen)
11478 (if pos
11479 (progn
11480 (goto-char pos)
11481 (looking-at org-outline-regexp)
11482 (setq level (org-get-valid-level (funcall outline-level) 1))
11483 (goto-char
11484 (if reversed
11485 (or (outline-next-heading) (point-max))
11486 (or (save-excursion (org-get-next-sibling))
11487 (org-end-of-subtree t t)
11488 (point-max)))))
11489 (setq level 1)
11490 (if (not reversed)
11491 (goto-char (point-max))
11492 (goto-char (point-min))
11493 (or (outline-next-heading) (goto-char (point-max)))))
11494 (if (not (bolp)) (newline))
11495 (org-paste-subtree level)
11496 (when org-log-refile
11497 (org-add-log-setup 'refile nil nil 'findpos
11498 org-log-refile)
11499 (unless (eq org-log-refile 'note)
11500 (save-excursion (org-add-log-note))))
11501 (and org-auto-align-tags
11502 (let ((org-loop-over-headlines-in-active-region nil))
11503 (org-set-tags nil t)))
11504 (with-demoted-errors
11505 (bookmark-set "org-refile-last-stored"))
11506 ;; If we are refiling for capture, make sure that the
11507 ;; last-capture pointers point here
11508 (when (org-bound-and-true-p org-refile-for-capture)
11509 (with-demoted-errors
11510 (bookmark-set "org-capture-last-stored-marker"))
11511 (move-marker org-capture-last-stored-marker (point)))
11512 (if (fboundp 'deactivate-mark) (deactivate-mark))
11513 (run-hooks 'org-after-refile-insert-hook))))
11514 (unless org-refile-keep
11515 (if regionp
11516 (delete-region (point) (+ (point) region-length))
11517 (org-cut-subtree)))
11518 (when (featurep 'org-inlinetask)
11519 (org-inlinetask-remove-END-maybe))
11520 (setq org-markers-to-move nil)
11521 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11523 (defun org-refile-goto-last-stored ()
11524 "Go to the location where the last refile was stored."
11525 (interactive)
11526 (bookmark-jump "org-refile-last-stored")
11527 (message "This is the location of the last refile"))
11529 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11530 no-exclude)
11531 "Prompt the user for a refile location, using PROMPT.
11532 PROMPT should not be suffixed with a colon and a space, because
11533 this function appends the default value from
11534 `org-refile-history' automatically, if that is not empty.
11535 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11536 this is used for the GOTO interface."
11537 (let ((org-refile-targets org-refile-targets)
11538 (org-refile-use-outline-path org-refile-use-outline-path)
11539 excluded-entries)
11540 (when (and (derived-mode-p 'org-mode)
11541 (not org-refile-use-cache)
11542 (not no-exclude))
11543 (org-map-tree
11544 (lambda()
11545 (setq excluded-entries
11546 (append excluded-entries (list (org-get-heading t t)))))))
11547 (setq org-refile-target-table
11548 (org-refile-get-targets default-buffer excluded-entries)))
11549 (unless org-refile-target-table
11550 (error "No refile targets"))
11551 (let* ((cbuf (current-buffer))
11552 (partial-completion-mode nil)
11553 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11554 (cfunc (if (and org-refile-use-outline-path
11555 org-outline-path-complete-in-steps)
11556 'org-olpath-completing-read
11557 'org-icompleting-read))
11558 (extra (if org-refile-use-outline-path "/" ""))
11559 (cbnex (concat (buffer-name) extra))
11560 (filename (and cfn (expand-file-name cfn)))
11561 (tbl (mapcar
11562 (lambda (x)
11563 (if (and (not (member org-refile-use-outline-path
11564 '(file full-file-path)))
11565 (not (equal filename (nth 1 x))))
11566 (cons (concat (car x) extra " ("
11567 (file-name-nondirectory (nth 1 x)) ")")
11568 (cdr x))
11569 (cons (concat (car x) extra) (cdr x))))
11570 org-refile-target-table))
11571 (completion-ignore-case t)
11572 cdef
11573 (prompt (concat prompt
11574 (or (and (car org-refile-history)
11575 (concat " (default " (car org-refile-history) ")"))
11576 (and (assoc cbnex tbl) (setq cdef cbnex)
11577 (concat " (default " cbnex ")"))) ": "))
11578 pa answ parent-target child parent old-hist)
11579 (setq old-hist org-refile-history)
11580 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11581 nil 'org-refile-history (or cdef (car org-refile-history))))
11582 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11583 (org-refile-check-position pa)
11584 (if pa
11585 (progn
11586 (when (or (not org-refile-history)
11587 (not (eq old-hist org-refile-history))
11588 (not (equal (car pa) (car org-refile-history))))
11589 (setq org-refile-history
11590 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11591 org-refile-history
11592 (cdr org-refile-history))))
11593 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11594 (pop org-refile-history)))
11596 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11597 (progn
11598 (setq parent (match-string 1 answ)
11599 child (match-string 2 answ))
11600 (setq parent-target (or (assoc parent tbl)
11601 (assoc (concat parent "/") tbl)))
11602 (when (and parent-target
11603 (or (eq new-nodes t)
11604 (and (eq new-nodes 'confirm)
11605 (y-or-n-p (format "Create new node \"%s\"? "
11606 child)))))
11607 (org-refile-new-child parent-target child)))
11608 (error "Invalid target location")))))
11610 (declare-function org-string-nw-p "org-macs" (s))
11611 (defun org-refile-check-position (refile-pointer)
11612 "Check if the refile pointer matches the headline to which it points."
11613 (let* ((file (nth 1 refile-pointer))
11614 (re (nth 2 refile-pointer))
11615 (pos (nth 3 refile-pointer))
11616 buffer)
11617 (if (and (not (markerp pos)) (not file))
11618 (error "Please save the buffer to a file before refiling")
11619 (when (org-string-nw-p re)
11620 (setq buffer (if (markerp pos)
11621 (marker-buffer pos)
11622 (or (find-buffer-visiting file)
11623 (find-file-noselect file))))
11624 (with-current-buffer buffer
11625 (save-excursion
11626 (save-restriction
11627 (widen)
11628 (goto-char pos)
11629 (beginning-of-line 1)
11630 (unless (org-looking-at-p re)
11631 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11633 (defun org-refile-new-child (parent-target child)
11634 "Use refile target PARENT-TARGET to add new CHILD below it."
11635 (unless parent-target
11636 (error "Cannot find parent for new node"))
11637 (let ((file (nth 1 parent-target))
11638 (pos (nth 3 parent-target))
11639 level)
11640 (with-current-buffer (or (find-buffer-visiting file)
11641 (find-file-noselect file))
11642 (save-excursion
11643 (save-restriction
11644 (widen)
11645 (if pos
11646 (goto-char pos)
11647 (goto-char (point-max))
11648 (if (not (bolp)) (newline)))
11649 (when (looking-at org-outline-regexp)
11650 (setq level (funcall outline-level))
11651 (org-end-of-subtree t t))
11652 (org-back-over-empty-lines)
11653 (insert "\n" (make-string
11654 (if pos (org-get-valid-level level 1) 1) ?*)
11655 " " child "\n")
11656 (beginning-of-line 0)
11657 (list (concat (car parent-target) "/" child) file "" (point)))))))
11659 (defun org-olpath-completing-read (prompt collection &rest args)
11660 "Read an outline path like a file name."
11661 (let ((thetable collection)
11662 (org-completion-use-ido nil) ; does not work with ido.
11663 (org-completion-use-iswitchb nil)) ; or iswitchb
11664 (apply
11665 'org-icompleting-read prompt
11666 (lambda (string predicate &optional flag)
11667 (let (rtn r f (l (length string)))
11668 (cond
11669 ((eq flag nil)
11670 ;; try completion
11671 (try-completion string thetable))
11672 ((eq flag t)
11673 ;; all-completions
11674 (setq rtn (all-completions string thetable predicate))
11675 (mapcar
11676 (lambda (x)
11677 (setq r (substring x l))
11678 (if (string-match " ([^)]*)$" x)
11679 (setq f (match-string 0 x))
11680 (setq f ""))
11681 (if (string-match "/" r)
11682 (concat string (substring r 0 (match-end 0)) f)
11684 rtn))
11685 ((eq flag 'lambda)
11686 ;; exact match?
11687 (assoc string thetable)))))
11688 args)))
11690 ;;;; Dynamic blocks
11692 (defun org-find-dblock (name)
11693 "Find the first dynamic block with name NAME in the buffer.
11694 If not found, stay at current position and return nil."
11695 (let ((case-fold-search t) pos)
11696 (save-excursion
11697 (goto-char (point-min))
11698 (setq pos (and (re-search-forward
11699 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11700 (match-beginning 0))))
11701 (if pos (goto-char pos))
11702 pos))
11704 (defconst org-dblock-start-re
11705 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11706 "Matches the start line of a dynamic block, with parameters.")
11708 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11709 "Matches the end of a dynamic block.")
11711 (defun org-create-dblock (plist)
11712 "Create a dynamic block section, with parameters taken from PLIST.
11713 PLIST must contain a :name entry which is used as name of the block."
11714 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11715 (end-of-line 1)
11716 (newline))
11717 (let ((col (current-column))
11718 (name (plist-get plist :name)))
11719 (insert "#+BEGIN: " name)
11720 (while plist
11721 (if (eq (car plist) :name)
11722 (setq plist (cddr plist))
11723 (insert " " (prin1-to-string (pop plist)))))
11724 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11725 (beginning-of-line -2)))
11727 (defun org-prepare-dblock ()
11728 "Prepare dynamic block for refresh.
11729 This empties the block, puts the cursor at the insert position and returns
11730 the property list including an extra property :name with the block name."
11731 (unless (looking-at org-dblock-start-re)
11732 (error "Not at a dynamic block"))
11733 (let* ((begdel (1+ (match-end 0)))
11734 (name (org-no-properties (match-string 1)))
11735 (params (append (list :name name)
11736 (read (concat "(" (match-string 3) ")")))))
11737 (save-excursion
11738 (beginning-of-line 1)
11739 (skip-chars-forward " \t")
11740 (setq params (plist-put params :indentation-column (current-column))))
11741 (unless (re-search-forward org-dblock-end-re nil t)
11742 (error "Dynamic block not terminated"))
11743 (setq params
11744 (append params
11745 (list :content (buffer-substring
11746 begdel (match-beginning 0)))))
11747 (delete-region begdel (match-beginning 0))
11748 (goto-char begdel)
11749 (open-line 1)
11750 params))
11752 (defun org-map-dblocks (&optional command)
11753 "Apply COMMAND to all dynamic blocks in the current buffer.
11754 If COMMAND is not given, use `org-update-dblock'."
11755 (let ((cmd (or command 'org-update-dblock)))
11756 (save-excursion
11757 (goto-char (point-min))
11758 (while (re-search-forward org-dblock-start-re nil t)
11759 (goto-char (match-beginning 0))
11760 (save-excursion
11761 (condition-case nil
11762 (funcall cmd)
11763 (error (message "Error during update of dynamic block"))))
11764 (unless (re-search-forward org-dblock-end-re nil t)
11765 (error "Dynamic block not terminated"))))))
11767 (defun org-dblock-update (&optional arg)
11768 "User command for updating dynamic blocks.
11769 Update the dynamic block at point. With prefix ARG, update all dynamic
11770 blocks in the buffer."
11771 (interactive "P")
11772 (if arg
11773 (org-update-all-dblocks)
11774 (or (looking-at org-dblock-start-re)
11775 (org-beginning-of-dblock))
11776 (org-update-dblock)))
11778 (defun org-update-dblock ()
11779 "Update the dynamic block at point.
11780 This means to empty the block, parse for parameters and then call
11781 the correct writing function."
11782 (interactive)
11783 (save-window-excursion
11784 (let* ((pos (point))
11785 (line (org-current-line))
11786 (params (org-prepare-dblock))
11787 (name (plist-get params :name))
11788 (indent (plist-get params :indentation-column))
11789 (cmd (intern (concat "org-dblock-write:" name))))
11790 (message "Updating dynamic block `%s' at line %d..." name line)
11791 (funcall cmd params)
11792 (message "Updating dynamic block `%s' at line %d...done" name line)
11793 (goto-char pos)
11794 (when (and indent (> indent 0))
11795 (setq indent (make-string indent ?\ ))
11796 (save-excursion
11797 (org-beginning-of-dblock)
11798 (forward-line 1)
11799 (while (not (looking-at org-dblock-end-re))
11800 (insert indent)
11801 (beginning-of-line 2))
11802 (when (looking-at org-dblock-end-re)
11803 (and (looking-at "[ \t]+")
11804 (replace-match ""))
11805 (insert indent)))))))
11807 (defun org-beginning-of-dblock ()
11808 "Find the beginning of the dynamic block at point.
11809 Error if there is no such block at point."
11810 (let ((pos (point))
11811 beg)
11812 (end-of-line 1)
11813 (if (and (re-search-backward org-dblock-start-re nil t)
11814 (setq beg (match-beginning 0))
11815 (re-search-forward org-dblock-end-re nil t)
11816 (> (match-end 0) pos))
11817 (goto-char beg)
11818 (goto-char pos)
11819 (error "Not in a dynamic block"))))
11821 (defun org-update-all-dblocks ()
11822 "Update all dynamic blocks in the buffer.
11823 This function can be used in a hook."
11824 (interactive)
11825 (when (derived-mode-p 'org-mode)
11826 (org-map-dblocks 'org-update-dblock)))
11829 ;;;; Completion
11831 (defun org-get-export-keywords ()
11832 "Return a list of all currently understood export keywords.
11833 Export keywords include options, block names, attributes and
11834 keywords relative to each registered export back-end."
11835 (delq nil
11836 (let (keywords)
11837 (mapc
11838 (lambda (back-end)
11839 (let ((props (cdr back-end)))
11840 ;; Back-end name (for keywords, like #+LATEX:)
11841 (push (upcase (symbol-name (car back-end))) keywords)
11842 ;; Back-end options.
11843 (mapc (lambda (option) (push (cadr option) keywords))
11844 (plist-get (cdr back-end) :options-alist))))
11845 (org-bound-and-true-p org-export-registered-backends))
11846 keywords)))
11848 (defconst org-options-keywords
11849 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11850 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11851 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11852 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11853 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11855 (defcustom org-structure-template-alist
11856 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11857 "<src lang=\"?\">\n\n</src>")
11858 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11859 "<example>\n?\n</example>")
11860 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11861 "<quote>\n?\n</quote>")
11862 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11863 "<verse>\n?\n</verse>")
11864 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11865 "<verbatim>\n?\n</verbatim>")
11866 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11867 "<center>\n?\n</center>")
11868 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11869 "<literal style=\"latex\">\n?\n</literal>")
11870 ("L" "#+LaTeX: "
11871 "<literal style=\"latex\">?</literal>")
11872 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11873 "<literal style=\"html\">\n?\n</literal>")
11874 ("H" "#+HTML: "
11875 "<literal style=\"html\">?</literal>")
11876 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11877 ("A" "#+ASCII: ")
11878 ("i" "#+INDEX: ?"
11879 "#+INDEX: ?")
11880 ("I" "#+INCLUDE: %file ?"
11881 "<include file=%file markup=\"?\">"))
11882 "Structure completion elements.
11883 This is a list of abbreviation keys and values. The value gets inserted
11884 if you type `<' followed by the key and then press the completion key,
11885 usually `M-TAB'. %file will be replaced by a file name after prompting
11886 for the file using completion. The cursor will be placed at the position
11887 of the `?` in the template.
11888 There are two templates for each key, the first uses the original Org syntax,
11889 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11890 the default when the /org-mtags.el/ module has been loaded. See also the
11891 variable `org-mtags-prefer-muse-templates'."
11892 :group 'org-completion
11893 :type '(repeat
11894 (string :tag "Key")
11895 (string :tag "Template")
11896 (string :tag "Muse Template")))
11898 (defun org-try-structure-completion ()
11899 "Try to complete a structure template before point.
11900 This looks for strings like \"<e\" on an otherwise empty line and
11901 expands them."
11902 (let ((l (buffer-substring (point-at-bol) (point)))
11904 (when (and (looking-at "[ \t]*$")
11905 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11906 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11907 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11908 (match-beginning 1)) a)
11909 t)))
11911 (defun org-complete-expand-structure-template (start cell)
11912 "Expand a structure template."
11913 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11914 (rpl (nth (if musep 2 1) cell))
11915 (ind ""))
11916 (delete-region start (point))
11917 (when (string-match "\\`#\\+" rpl)
11918 (cond
11919 ((bolp))
11920 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11921 (setq ind (buffer-substring (point-at-bol) (point))))
11922 (t (newline))))
11923 (setq start (point))
11924 (if (string-match "%file" rpl)
11925 (setq rpl (replace-match
11926 (concat
11927 "\""
11928 (save-match-data
11929 (abbreviate-file-name (read-file-name "Include file: ")))
11930 "\"")
11931 t t rpl)))
11932 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11933 (concat "\n" ind)))
11934 (insert rpl)
11935 (if (re-search-backward "\\?" start t) (delete-char 1))))
11937 ;;;; TODO, DEADLINE, Comments
11939 (defun org-toggle-comment ()
11940 "Change the COMMENT state of an entry."
11941 (interactive)
11942 (save-excursion
11943 (org-back-to-heading)
11944 (let (case-fold-search)
11945 (cond
11946 ((looking-at (format org-heading-keyword-regexp-format
11947 org-comment-string))
11948 (goto-char (match-end 1))
11949 (looking-at (concat " +" org-comment-string))
11950 (replace-match "" t t)
11951 (when (eolp) (insert " ")))
11952 ((looking-at org-outline-regexp)
11953 (goto-char (match-end 0))
11954 (insert org-comment-string " "))))))
11956 (defvar org-last-todo-state-is-todo nil
11957 "This is non-nil when the last TODO state change led to a TODO state.
11958 If the last change removed the TODO tag or switched to DONE, then
11959 this is nil.")
11961 (defvar org-setting-tags nil) ; dynamically skipped
11963 (defvar org-todo-setup-filter-hook nil
11964 "Hook for functions that pre-filter todo specs.
11965 Each function takes a todo spec and returns either nil or the spec
11966 transformed into canonical form." )
11968 (defvar org-todo-get-default-hook nil
11969 "Hook for functions that get a default item for todo.
11970 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11971 nil or a string to be used for the todo mark." )
11973 (defvar org-agenda-headline-snapshot-before-repeat)
11975 (defun org-current-effective-time ()
11976 "Return current time adjusted for `org-extend-today-until' variable."
11977 (let* ((ct (org-current-time))
11978 (dct (decode-time ct))
11979 (ct1
11980 (cond
11981 (org-use-last-clock-out-time-as-effective-time
11982 (or (org-clock-get-last-clock-out-time) ct))
11983 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11984 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11985 (t ct))))
11986 ct1))
11988 (defun org-todo-yesterday (&optional arg)
11989 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11990 (interactive "P")
11991 (if (eq major-mode 'org-agenda-mode)
11992 (apply 'org-agenda-todo-yesterday arg)
11993 (let* ((hour (third (decode-time
11994 (org-current-time))))
11995 (org-extend-today-until (1+ hour)))
11996 (org-todo arg))))
11998 (defvar org-block-entry-blocking ""
11999 "First entry preventing the TODO state change.")
12001 (defun org-todo (&optional arg)
12002 "Change the TODO state of an item.
12003 The state of an item is given by a keyword at the start of the heading,
12004 like
12005 *** TODO Write paper
12006 *** DONE Call mom
12008 The different keywords are specified in the variable `org-todo-keywords'.
12009 By default the available states are \"TODO\" and \"DONE\".
12010 So for this example: when the item starts with TODO, it is changed to DONE.
12011 When it starts with DONE, the DONE is removed. And when neither TODO nor
12012 DONE are present, add TODO at the beginning of the heading.
12014 With \\[universal-argument] prefix arg, use completion to determine the new \
12015 state.
12016 With numeric prefix arg, switch to that state.
12017 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12018 keywords (nextset).
12019 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12020 With a numeric prefix arg of 0, inhibit note taking for the change.
12022 For calling through lisp, arg is also interpreted in the following way:
12023 'none -> empty state
12024 \"\"(empty string) -> switch to empty state
12025 'done -> switch to DONE
12026 'nextset -> switch to the next set of keywords
12027 'previousset -> switch to the previous set of keywords
12028 \"WAITING\" -> switch to the specified keyword, but only if it
12029 really is a member of `org-todo-keywords'."
12030 (interactive "P")
12031 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12032 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12033 'region-start-level 'region))
12034 org-loop-over-headlines-in-active-region)
12035 (org-map-entries
12036 `(org-todo ,arg)
12037 org-loop-over-headlines-in-active-region
12038 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12039 (if (equal arg '(16)) (setq arg 'nextset))
12040 (let ((org-blocker-hook org-blocker-hook)
12041 commentp
12042 case-fold-search)
12043 (when (equal arg '(64))
12044 (setq arg nil org-blocker-hook nil))
12045 (when (and org-blocker-hook
12046 (or org-inhibit-blocking
12047 (org-entry-get nil "NOBLOCKING")))
12048 (setq org-blocker-hook nil))
12049 (save-excursion
12050 (catch 'exit
12051 (org-back-to-heading t)
12052 (when (looking-at (concat "^\\*+ " org-comment-string))
12053 (org-toggle-comment)
12054 (setq commentp t))
12055 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12056 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12057 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12058 (let* ((match-data (match-data))
12059 (startpos (point-at-bol))
12060 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12061 (org-log-done org-log-done)
12062 (org-log-repeat org-log-repeat)
12063 (org-todo-log-states org-todo-log-states)
12064 (org-inhibit-logging
12065 (if (equal arg 0)
12066 (progn (setq arg nil) 'note) org-inhibit-logging))
12067 (this (match-string 1))
12068 (hl-pos (match-beginning 0))
12069 (head (org-get-todo-sequence-head this))
12070 (ass (assoc head org-todo-kwd-alist))
12071 (interpret (nth 1 ass))
12072 (done-word (nth 3 ass))
12073 (final-done-word (nth 4 ass))
12074 (org-last-state (or this ""))
12075 (completion-ignore-case t)
12076 (member (member this org-todo-keywords-1))
12077 (tail (cdr member))
12078 (org-state (cond
12079 ((and org-todo-key-trigger
12080 (or (and (equal arg '(4))
12081 (eq org-use-fast-todo-selection 'prefix))
12082 (and (not arg) org-use-fast-todo-selection
12083 (not (eq org-use-fast-todo-selection
12084 'prefix)))))
12085 ;; Use fast selection
12086 (org-fast-todo-selection))
12087 ((and (equal arg '(4))
12088 (or (not org-use-fast-todo-selection)
12089 (not org-todo-key-trigger)))
12090 ;; Read a state with completion
12091 (org-icompleting-read
12092 "State: " (mapcar 'list org-todo-keywords-1)
12093 nil t))
12094 ((eq arg 'right)
12095 (if this
12096 (if tail (car tail) nil)
12097 (car org-todo-keywords-1)))
12098 ((eq arg 'left)
12099 (if (equal member org-todo-keywords-1)
12101 (if this
12102 (nth (- (length org-todo-keywords-1)
12103 (length tail) 2)
12104 org-todo-keywords-1)
12105 (org-last org-todo-keywords-1))))
12106 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12107 (setq arg nil))) ; hack to fall back to cycling
12108 (arg
12109 ;; user or caller requests a specific state
12110 (cond
12111 ((equal arg "") nil)
12112 ((eq arg 'none) nil)
12113 ((eq arg 'done) (or done-word (car org-done-keywords)))
12114 ((eq arg 'nextset)
12115 (or (car (cdr (member head org-todo-heads)))
12116 (car org-todo-heads)))
12117 ((eq arg 'previousset)
12118 (let ((org-todo-heads (reverse org-todo-heads)))
12119 (or (car (cdr (member head org-todo-heads)))
12120 (car org-todo-heads))))
12121 ((car (member arg org-todo-keywords-1)))
12122 ((stringp arg)
12123 (error "State `%s' not valid in this file" arg))
12124 ((nth (1- (prefix-numeric-value arg))
12125 org-todo-keywords-1))))
12126 ((null member) (or head (car org-todo-keywords-1)))
12127 ((equal this final-done-word) nil) ;; -> make empty
12128 ((null tail) nil) ;; -> first entry
12129 ((memq interpret '(type priority))
12130 (if (eq this-command last-command)
12131 (car tail)
12132 (if (> (length tail) 0)
12133 (or done-word (car org-done-keywords))
12134 nil)))
12136 (car tail))))
12137 (org-state (or
12138 (run-hook-with-args-until-success
12139 'org-todo-get-default-hook org-state org-last-state)
12140 org-state))
12141 (next (if org-state (concat " " org-state " ") " "))
12142 (change-plist (list :type 'todo-state-change :from this :to org-state
12143 :position startpos))
12144 dolog now-done-p)
12145 (when org-blocker-hook
12146 (setq org-last-todo-state-is-todo
12147 (not (member this org-done-keywords)))
12148 (unless (save-excursion
12149 (save-match-data
12150 (org-with-wide-buffer
12151 (run-hook-with-args-until-failure
12152 'org-blocker-hook change-plist))))
12153 (if (org-called-interactively-p 'interactive)
12154 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12155 this org-state org-block-entry-blocking)
12156 ;; fail silently
12157 (message "TODO state change from %s to %s blocked (by \"%s\")"
12158 this org-state org-block-entry-blocking)
12159 (throw 'exit nil))))
12160 (store-match-data match-data)
12161 (replace-match next t t)
12162 (unless (pos-visible-in-window-p hl-pos)
12163 (message "TODO state changed to %s" (org-trim next)))
12164 (unless head
12165 (setq head (org-get-todo-sequence-head org-state)
12166 ass (assoc head org-todo-kwd-alist)
12167 interpret (nth 1 ass)
12168 done-word (nth 3 ass)
12169 final-done-word (nth 4 ass)))
12170 (when (memq arg '(nextset previousset))
12171 (message "Keyword-Set %d/%d: %s"
12172 (- (length org-todo-sets) -1
12173 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12174 (length org-todo-sets)
12175 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12176 (setq org-last-todo-state-is-todo
12177 (not (member org-state org-done-keywords)))
12178 (setq now-done-p (and (member org-state org-done-keywords)
12179 (not (member this org-done-keywords))))
12180 (and logging (org-local-logging logging))
12181 (when (and (or org-todo-log-states org-log-done)
12182 (not (eq org-inhibit-logging t))
12183 (not (memq arg '(nextset previousset))))
12184 ;; we need to look at recording a time and note
12185 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12186 (nth 2 (assoc this org-todo-log-states))))
12187 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12188 (setq dolog 'time))
12189 (when (and org-state
12190 (member org-state org-not-done-keywords)
12191 (not (member this org-not-done-keywords)))
12192 ;; This is now a todo state and was not one before
12193 ;; If there was a CLOSED time stamp, get rid of it.
12194 (org-add-planning-info nil nil 'closed))
12195 (when (and now-done-p org-log-done)
12196 ;; It is now done, and it was not done before
12197 (org-add-planning-info 'closed (org-current-effective-time))
12198 (if (and (not dolog) (eq 'note org-log-done))
12199 (org-add-log-setup 'done org-state this 'findpos 'note)))
12200 (when (and org-state dolog)
12201 ;; This is a non-nil state, and we need to log it
12202 (org-add-log-setup 'state org-state this 'findpos dolog)))
12203 ;; Fixup tag positioning
12204 (org-todo-trigger-tag-changes org-state)
12205 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12206 (when org-provide-todo-statistics
12207 (org-update-parent-todo-statistics))
12208 (run-hooks 'org-after-todo-state-change-hook)
12209 (if (and arg (not (member org-state org-done-keywords)))
12210 (setq head (org-get-todo-sequence-head org-state)))
12211 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12212 ;; Do we need to trigger a repeat?
12213 (when now-done-p
12214 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12215 ;; This is for the agenda, take a snapshot of the headline.
12216 (save-match-data
12217 (setq org-agenda-headline-snapshot-before-repeat
12218 (org-get-heading))))
12219 (org-auto-repeat-maybe org-state))
12220 ;; Fixup cursor location if close to the keyword
12221 (if (and (outline-on-heading-p)
12222 (not (bolp))
12223 (save-excursion (beginning-of-line 1)
12224 (looking-at org-todo-line-regexp))
12225 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12226 (progn
12227 (goto-char (or (match-end 2) (match-end 1)))
12228 (and (looking-at " ") (just-one-space))))
12229 (when org-trigger-hook
12230 (save-excursion
12231 (run-hook-with-args 'org-trigger-hook change-plist)))
12232 (when commentp (org-toggle-comment))))))))
12234 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12235 "Block turning an entry into a TODO, using the hierarchy.
12236 This checks whether the current task should be blocked from state
12237 changes. Such blocking occurs when:
12239 1. The task has children which are not all in a completed state.
12241 2. A task has a parent with the property :ORDERED:, and there
12242 are siblings prior to the current task with incomplete
12243 status.
12245 3. The parent of the task is blocked because it has siblings that should
12246 be done first, or is child of a block grandparent TODO entry."
12248 (if (not org-enforce-todo-dependencies)
12249 t ; if locally turned off don't block
12250 (catch 'dont-block
12251 ;; If this is not a todo state change, or if this entry is already DONE,
12252 ;; do not block
12253 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12254 (member (plist-get change-plist :from)
12255 (cons 'done org-done-keywords))
12256 (member (plist-get change-plist :to)
12257 (cons 'todo org-not-done-keywords))
12258 (not (plist-get change-plist :to)))
12259 (throw 'dont-block t))
12260 ;; If this task has children, and any are undone, it's blocked
12261 (save-excursion
12262 (org-back-to-heading t)
12263 (let ((this-level (funcall outline-level)))
12264 (outline-next-heading)
12265 (let ((child-level (funcall outline-level)))
12266 (while (and (not (eobp))
12267 (> child-level this-level))
12268 ;; this todo has children, check whether they are all
12269 ;; completed
12270 (if (and (not (org-entry-is-done-p))
12271 (org-entry-is-todo-p))
12272 (progn (setq org-block-entry-blocking (org-get-heading))
12273 (throw 'dont-block nil)))
12274 (outline-next-heading)
12275 (setq child-level (funcall outline-level))))))
12276 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12277 ;; any previous siblings are undone, it's blocked
12278 (save-excursion
12279 (org-back-to-heading t)
12280 (let* ((pos (point))
12281 (parent-pos (and (org-up-heading-safe) (point))))
12282 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12283 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12284 (forward-line 1)
12285 (re-search-forward org-not-done-heading-regexp pos t))
12286 (setq org-block-entry-blocking (match-string 0))
12287 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12288 ;; Search further up the hierarchy, to see if an ancestor is blocked
12289 (while t
12290 (goto-char parent-pos)
12291 (if (not (looking-at org-not-done-heading-regexp))
12292 (throw 'dont-block t)) ; do not block, parent is not a TODO
12293 (setq pos (point))
12294 (setq parent-pos (and (org-up-heading-safe) (point)))
12295 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12296 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12297 (forward-line 1)
12298 (re-search-forward org-not-done-heading-regexp pos t)
12299 (setq org-block-entry-blocking (org-get-heading)))
12300 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12302 (defcustom org-track-ordered-property-with-tag nil
12303 "Should the ORDERED property also be shown as a tag?
12304 The ORDERED property decides if an entry should require subtasks to be
12305 completed in sequence. Since a property is not very visible, setting
12306 this option means that toggling the ORDERED property with the command
12307 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12308 not relevant for the behavior, but it makes things more visible.
12310 Note that toggling the tag with tags commands will not change the property
12311 and therefore not influence behavior!
12313 This can be t, meaning the tag ORDERED should be used, It can also be a
12314 string to select a different tag for this task."
12315 :group 'org-todo
12316 :type '(choice
12317 (const :tag "No tracking" nil)
12318 (const :tag "Track with ORDERED tag" t)
12319 (string :tag "Use other tag")))
12321 (defun org-toggle-ordered-property ()
12322 "Toggle the ORDERED property of the current entry.
12323 For better visibility, you can track the value of this property with a tag.
12324 See variable `org-track-ordered-property-with-tag'."
12325 (interactive)
12326 (let* ((t1 org-track-ordered-property-with-tag)
12327 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12328 (save-excursion
12329 (org-back-to-heading)
12330 (if (org-entry-get nil "ORDERED")
12331 (progn
12332 (org-delete-property "ORDERED" "PROPERTIES")
12333 (and tag (org-toggle-tag tag 'off))
12334 (message "Subtasks can be completed in arbitrary order"))
12335 (org-entry-put nil "ORDERED" "t")
12336 (and tag (org-toggle-tag tag 'on))
12337 (message "Subtasks must be completed in sequence")))))
12339 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12340 (defun org-block-todo-from-checkboxes (change-plist)
12341 "Block turning an entry into a TODO, using checkboxes.
12342 This checks whether the current task should be blocked from state
12343 changes because there are unchecked boxes in this entry."
12344 (if (not org-enforce-todo-checkbox-dependencies)
12345 t ; if locally turned off don't block
12346 (catch 'dont-block
12347 ;; If this is not a todo state change, or if this entry is already DONE,
12348 ;; do not block
12349 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12350 (member (plist-get change-plist :from)
12351 (cons 'done org-done-keywords))
12352 (member (plist-get change-plist :to)
12353 (cons 'todo org-not-done-keywords))
12354 (not (plist-get change-plist :to)))
12355 (throw 'dont-block t))
12356 ;; If this task has checkboxes that are not checked, it's blocked
12357 (save-excursion
12358 (org-back-to-heading t)
12359 (let ((beg (point)) end)
12360 (outline-next-heading)
12361 (setq end (point))
12362 (goto-char beg)
12363 (if (org-list-search-forward
12364 (concat (org-item-beginning-re)
12365 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12366 "\\[[- ]\\]")
12367 end t)
12368 (progn
12369 (if (boundp 'org-blocked-by-checkboxes)
12370 (setq org-blocked-by-checkboxes t))
12371 (throw 'dont-block nil)))))
12372 t))) ; do not block
12374 (defun org-entry-blocked-p ()
12375 "Is the current entry blocked?"
12376 (org-with-silent-modifications
12377 (if (org-entry-get nil "NOBLOCKING")
12378 nil ;; Never block this entry
12379 (not (run-hook-with-args-until-failure
12380 'org-blocker-hook
12381 (list :type 'todo-state-change
12382 :position (point)
12383 :from 'todo
12384 :to 'done))))))
12386 (defun org-update-statistics-cookies (all)
12387 "Update the statistics cookie, either from TODO or from checkboxes.
12388 This should be called with the cursor in a line with a statistics cookie."
12389 (interactive "P")
12390 (if all
12391 (progn
12392 (org-update-checkbox-count 'all)
12393 (org-map-entries 'org-update-parent-todo-statistics))
12394 (if (not (org-at-heading-p))
12395 (org-update-checkbox-count)
12396 (let ((pos (point-marker))
12397 end l1 l2)
12398 (ignore-errors (org-back-to-heading t))
12399 (if (not (org-at-heading-p))
12400 (org-update-checkbox-count)
12401 (setq l1 (org-outline-level))
12402 (setq end (save-excursion
12403 (outline-next-heading)
12404 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12405 (point)))
12406 (if (and (save-excursion
12407 (re-search-forward
12408 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12409 (not (save-excursion (re-search-forward
12410 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12411 (org-update-checkbox-count)
12412 (if (and l2 (> l2 l1))
12413 (progn
12414 (goto-char end)
12415 (org-update-parent-todo-statistics))
12416 (goto-char pos)
12417 (beginning-of-line 1)
12418 (while (re-search-forward
12419 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12420 (point-at-eol) t)
12421 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12422 (goto-char pos)
12423 (move-marker pos nil)))))
12425 (defvar org-entry-property-inherited-from) ;; defined below
12426 (defun org-update-parent-todo-statistics ()
12427 "Update any statistics cookie in the parent of the current headline.
12428 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12429 the entire subtree and this will travel up the hierarchy and update
12430 statistics everywhere."
12431 (let* ((prop (save-excursion (org-up-heading-safe)
12432 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12433 (recursive (or (not org-hierarchical-todo-statistics)
12434 (and prop (string-match "\\<recursive\\>" prop))))
12435 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12437 (first t)
12438 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12439 level ltoggle l1 new ndel
12440 (cnt-all 0) (cnt-done 0) is-percent kwd
12441 checkbox-beg ov ovs ove cookie-present)
12442 (catch 'exit
12443 (save-excursion
12444 (beginning-of-line 1)
12445 (setq ltoggle (funcall outline-level))
12446 ;; Three situations are to consider:
12448 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12449 ;; to the top-level ancestor on the headline;
12451 ;; 2. If parent has "recursive" property, repeat up to the
12452 ;; headline setting that property, taking inheritance into
12453 ;; account;
12455 ;; 3. Else, move up to direct parent and proceed only once.
12456 (while (and (setq level (org-up-heading-safe))
12457 (or recursive first)
12458 (>= (point) lim))
12459 (setq first nil cookie-present nil)
12460 (unless (and level
12461 (not (string-match
12462 "\\<checkbox\\>"
12463 (downcase (or (org-entry-get nil "COOKIE_DATA")
12464 "")))))
12465 (throw 'exit nil))
12466 (while (re-search-forward box-re (point-at-eol) t)
12467 (setq cnt-all 0 cnt-done 0 cookie-present t)
12468 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12469 (save-match-data
12470 (unless (outline-next-heading) (throw 'exit nil))
12471 (while (and (looking-at org-complex-heading-regexp)
12472 (> (setq l1 (length (match-string 1))) level))
12473 (setq kwd (and (or recursive (= l1 ltoggle))
12474 (match-string 2)))
12475 (if (or (eq org-provide-todo-statistics 'all-headlines)
12476 (and (listp org-provide-todo-statistics)
12477 (or (member kwd org-provide-todo-statistics)
12478 (member kwd org-done-keywords))))
12479 (setq cnt-all (1+ cnt-all))
12480 (if (eq org-provide-todo-statistics t)
12481 (and kwd (setq cnt-all (1+ cnt-all)))))
12482 (and (member kwd org-done-keywords)
12483 (setq cnt-done (1+ cnt-done)))
12484 (outline-next-heading)))
12485 (setq new
12486 (if is-percent
12487 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12488 (format "[%d/%d]" cnt-done cnt-all))
12489 ndel (- (match-end 0) checkbox-beg))
12490 ;; handle overlays when updating cookie from column view
12491 (when (setq ov (car (overlays-at checkbox-beg)))
12492 (setq ovs (overlay-start ov) ove (overlay-end ov))
12493 (delete-overlay ov))
12494 (goto-char checkbox-beg)
12495 (insert new)
12496 (delete-region (point) (+ (point) ndel))
12497 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12498 (when ov (move-overlay ov ovs ove)))
12499 (when cookie-present
12500 (run-hook-with-args 'org-after-todo-statistics-hook
12501 cnt-done (- cnt-all cnt-done))))))
12502 (run-hooks 'org-todo-statistics-hook)))
12504 (defvar org-after-todo-statistics-hook nil
12505 "Hook that is called after a TODO statistics cookie has been updated.
12506 Each function is called with two arguments: the number of not-done entries
12507 and the number of done entries.
12509 For example, the following function, when added to this hook, will switch
12510 an entry to DONE when all children are done, and back to TODO when new
12511 entries are set to a TODO status. Note that this hook is only called
12512 when there is a statistics cookie in the headline!
12514 (defun org-summary-todo (n-done n-not-done)
12515 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12516 (let (org-log-done org-log-states) ; turn off logging
12517 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12520 (defvar org-todo-statistics-hook nil
12521 "Hook that is run whenever Org thinks TODO statistics should be updated.
12522 This hook runs even if there is no statistics cookie present, in which case
12523 `org-after-todo-statistics-hook' would not run.")
12525 (defun org-todo-trigger-tag-changes (state)
12526 "Apply the changes defined in `org-todo-state-tags-triggers'."
12527 (let ((l org-todo-state-tags-triggers)
12528 changes)
12529 (when (or (not state) (equal state ""))
12530 (setq changes (append changes (cdr (assoc "" l)))))
12531 (when (and (stringp state) (> (length state) 0))
12532 (setq changes (append changes (cdr (assoc state l)))))
12533 (when (member state org-not-done-keywords)
12534 (setq changes (append changes (cdr (assoc 'todo l)))))
12535 (when (member state org-done-keywords)
12536 (setq changes (append changes (cdr (assoc 'done l)))))
12537 (dolist (c changes)
12538 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12540 (defun org-local-logging (value)
12541 "Get logging settings from a property VALUE."
12542 (let* (words w a)
12543 ;; directly set the variables, they are already local.
12544 (setq org-log-done nil
12545 org-log-repeat nil
12546 org-todo-log-states nil)
12547 (setq words (org-split-string value))
12548 (while (setq w (pop words))
12549 (cond
12550 ((setq a (assoc w org-startup-options))
12551 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12552 (set (nth 1 a) (nth 2 a))))
12553 ((setq a (org-extract-log-state-settings w))
12554 (and (member (car a) org-todo-keywords-1)
12555 (push a org-todo-log-states)))))))
12557 (defun org-get-todo-sequence-head (kwd)
12558 "Return the head of the TODO sequence to which KWD belongs.
12559 If KWD is not set, check if there is a text property remembering the
12560 right sequence."
12561 (let (p)
12562 (cond
12563 ((not kwd)
12564 (or (get-text-property (point-at-bol) 'org-todo-head)
12565 (progn
12566 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12567 nil (point-at-eol)))
12568 (get-text-property p 'org-todo-head))))
12569 ((not (member kwd org-todo-keywords-1))
12570 (car org-todo-keywords-1))
12571 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12573 (defun org-fast-todo-selection ()
12574 "Fast TODO keyword selection with single keys.
12575 Returns the new TODO keyword, or nil if no state change should occur."
12576 (let* ((fulltable org-todo-key-alist)
12577 (done-keywords org-done-keywords) ;; needed for the faces.
12578 (maxlen (apply 'max (mapcar
12579 (lambda (x)
12580 (if (stringp (car x)) (string-width (car x)) 0))
12581 fulltable)))
12582 (expert nil)
12583 (fwidth (+ maxlen 3 1 3))
12584 (ncol (/ (- (window-width) 4) fwidth))
12585 tg cnt e c tbl
12586 groups ingroup)
12587 (save-excursion
12588 (save-window-excursion
12589 (if expert
12590 (set-buffer (get-buffer-create " *Org todo*"))
12591 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12592 (erase-buffer)
12593 (org-set-local 'org-done-keywords done-keywords)
12594 (setq tbl fulltable cnt 0)
12595 (while (setq e (pop tbl))
12596 (cond
12597 ((equal e '(:startgroup))
12598 (push '() groups) (setq ingroup t)
12599 (when (not (= cnt 0))
12600 (setq cnt 0)
12601 (insert "\n"))
12602 (insert "{ "))
12603 ((equal e '(:endgroup))
12604 (setq ingroup nil cnt 0)
12605 (insert "}\n"))
12606 ((equal e '(:newline))
12607 (when (not (= cnt 0))
12608 (setq cnt 0)
12609 (insert "\n")
12610 (setq e (car tbl))
12611 (while (equal (car tbl) '(:newline))
12612 (insert "\n")
12613 (setq tbl (cdr tbl)))))
12615 (setq tg (car e) c (cdr e))
12616 (if ingroup (push tg (car groups)))
12617 (setq tg (org-add-props tg nil 'face
12618 (org-get-todo-face tg)))
12619 (if (and (= cnt 0) (not ingroup)) (insert " "))
12620 (insert "[" c "] " tg (make-string
12621 (- fwidth 4 (length tg)) ?\ ))
12622 (when (= (setq cnt (1+ cnt)) ncol)
12623 (insert "\n")
12624 (if ingroup (insert " "))
12625 (setq cnt 0)))))
12626 (insert "\n")
12627 (goto-char (point-min))
12628 (if (not expert) (org-fit-window-to-buffer))
12629 (message "[a-z..]:Set [SPC]:clear")
12630 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12631 (cond
12632 ((or (= c ?\C-g)
12633 (and (= c ?q) (not (rassoc c fulltable))))
12634 (setq quit-flag t))
12635 ((= c ?\ ) nil)
12636 ((setq e (rassoc c fulltable) tg (car e))
12638 (t (setq quit-flag t)))))))
12640 (defun org-entry-is-todo-p ()
12641 (member (org-get-todo-state) org-not-done-keywords))
12643 (defun org-entry-is-done-p ()
12644 (member (org-get-todo-state) org-done-keywords))
12646 (defun org-get-todo-state ()
12647 (save-excursion
12648 (org-back-to-heading t)
12649 (and (looking-at org-todo-line-regexp)
12650 (match-end 2)
12651 (match-string 2))))
12653 (defun org-at-date-range-p (&optional inactive-ok)
12654 "Is the cursor inside a date range?"
12655 (interactive)
12656 (save-excursion
12657 (catch 'exit
12658 (let ((pos (point)))
12659 (skip-chars-backward "^[<\r\n")
12660 (skip-chars-backward "<[")
12661 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12662 (>= (match-end 0) pos)
12663 (throw 'exit t))
12664 (skip-chars-backward "^<[\r\n")
12665 (skip-chars-backward "<[")
12666 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12667 (>= (match-end 0) pos)
12668 (throw 'exit t)))
12669 nil)))
12671 (defun org-get-repeat (&optional tagline)
12672 "Check if there is a deadline/schedule with repeater in this entry."
12673 (save-match-data
12674 (save-excursion
12675 (org-back-to-heading t)
12676 (and (re-search-forward (if tagline
12677 (concat tagline "\\s-*" org-repeat-re)
12678 org-repeat-re)
12679 (org-entry-end-position) t)
12680 (match-string-no-properties 1)))))
12682 (defvar org-last-changed-timestamp)
12683 (defvar org-last-inserted-timestamp)
12684 (defvar org-log-post-message)
12685 (defvar org-log-note-purpose)
12686 (defvar org-log-note-how)
12687 (defvar org-log-note-extra)
12688 (defun org-auto-repeat-maybe (done-word)
12689 "Check if the current headline contains a repeated deadline/schedule.
12690 If yes, set TODO state back to what it was and change the base date
12691 of repeating deadline/scheduled time stamps to new date.
12692 This function is run automatically after each state change to a DONE state."
12693 ;; last-state is dynamically scoped into this function
12694 (let* ((repeat (org-get-repeat))
12695 (aa (assoc org-last-state org-todo-kwd-alist))
12696 (interpret (nth 1 aa))
12697 (head (nth 2 aa))
12698 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12699 (msg "Entry repeats: ")
12700 (org-log-done nil)
12701 (org-todo-log-states nil)
12702 re type n what ts time to-state)
12703 (when repeat
12704 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12705 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12706 org-todo-repeat-to-state))
12707 (unless (and to-state (member to-state org-todo-keywords-1))
12708 (setq to-state (if (eq interpret 'type) org-last-state head)))
12709 (org-todo to-state)
12710 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12711 (org-entry-put nil "LAST_REPEAT" (format-time-string
12712 (org-time-stamp-format t t))))
12713 (when org-log-repeat
12714 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12715 (memq 'org-add-log-note post-command-hook))
12716 ;; OK, we are already setup for some record
12717 (if (eq org-log-repeat 'note)
12718 ;; make sure we take a note, not only a time stamp
12719 (setq org-log-note-how 'note))
12720 ;; Set up for taking a record
12721 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12722 org-last-state
12723 'findpos org-log-repeat)))
12724 (org-back-to-heading t)
12725 (org-add-planning-info nil nil 'closed)
12726 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12727 org-deadline-time-regexp "\\)\\|\\("
12728 org-ts-regexp "\\)"))
12729 (while (re-search-forward
12730 re (save-excursion (outline-next-heading) (point)) t)
12731 (setq type (if (match-end 1) org-scheduled-string
12732 (if (match-end 3) org-deadline-string "Plain:"))
12733 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12734 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12735 (setq n (string-to-number (match-string 2 ts))
12736 what (match-string 3 ts))
12737 (if (equal what "w") (setq n (* n 7) what "d"))
12738 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12739 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12740 ;; Preparation, see if we need to modify the start date for the change
12741 (when (match-end 1)
12742 (setq time (save-match-data (org-time-string-to-time ts)))
12743 (cond
12744 ((equal (match-string 1 ts) ".")
12745 ;; Shift starting date to today
12746 (org-timestamp-change
12747 (- (org-today) (time-to-days time))
12748 'day))
12749 ((equal (match-string 1 ts) "+")
12750 (let ((nshiftmax 10) (nshift 0))
12751 (while (or (= nshift 0)
12752 (<= (time-to-days time)
12753 (time-to-days (current-time))))
12754 (when (= (incf nshift) nshiftmax)
12755 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12756 (error "Abort")))
12757 (org-timestamp-change n (cdr (assoc what whata)))
12758 (org-at-timestamp-p t)
12759 (setq ts (match-string 1))
12760 (setq time (save-match-data (org-time-string-to-time ts)))))
12761 (org-timestamp-change (- n) (cdr (assoc what whata)))
12762 ;; rematch, so that we have everything in place for the real shift
12763 (org-at-timestamp-p t)
12764 (setq ts (match-string 1))
12765 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12766 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12767 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12768 (setq org-log-post-message msg)
12769 (message "%s" msg))))
12771 (defun org-show-todo-tree (arg)
12772 "Make a compact tree which shows all headlines marked with TODO.
12773 The tree will show the lines where the regexp matches, and all higher
12774 headlines above the match.
12775 With a \\[universal-argument] prefix, prompt for a regexp to match.
12776 With a numeric prefix N, construct a sparse tree for the Nth element
12777 of `org-todo-keywords-1'."
12778 (interactive "P")
12779 (let ((case-fold-search nil)
12780 (kwd-re
12781 (cond ((null arg) org-not-done-regexp)
12782 ((equal arg '(4))
12783 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12784 (mapcar 'list org-todo-keywords-1))))
12785 (concat "\\("
12786 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12787 "\\)\\>")))
12788 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12789 (regexp-quote (nth (1- (prefix-numeric-value arg))
12790 org-todo-keywords-1)))
12791 (t (error "Invalid prefix argument: %s" arg)))))
12792 (message "%d TODO entries found"
12793 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12795 (defun org-deadline (arg &optional time)
12796 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12797 With one universal prefix argument, remove any deadline from the item.
12798 With two universal prefix arguments, prompt for a warning delay.
12799 With argument TIME, set the deadline at the corresponding date. TIME
12800 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12801 (interactive "P")
12802 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12803 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12804 'region-start-level 'region))
12805 org-loop-over-headlines-in-active-region)
12806 (org-map-entries
12807 `(org-deadline ',arg ,time)
12808 org-loop-over-headlines-in-active-region
12809 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12810 (let* ((old-date (org-entry-get nil "DEADLINE"))
12811 (old-date-time (if old-date (org-time-string-to-time old-date)))
12812 (repeater (and old-date
12813 (string-match
12814 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12815 old-date)
12816 (match-string 1 old-date))))
12817 (cond
12818 ((equal arg '(4))
12819 (when (and old-date org-log-redeadline)
12820 (org-add-log-setup 'deldeadline nil old-date 'findpos
12821 org-log-redeadline))
12822 (org-remove-timestamp-with-keyword org-deadline-string)
12823 (message "Item no longer has a deadline."))
12824 ((equal arg '(16))
12825 (save-excursion
12826 (if (re-search-forward
12827 org-deadline-time-regexp
12828 (save-excursion (outline-next-heading) (point)) t)
12829 (let* ((rpl0 (match-string 1))
12830 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12831 (replace-match
12832 (concat org-deadline-string
12833 " <" rpl
12834 (format " -%dd"
12835 (abs
12836 (- (time-to-days
12837 (save-match-data
12838 (org-read-date nil t nil "Warn starting from" old-date-time)))
12839 (time-to-days old-date-time))))
12840 ">") t t))
12841 (user-error "No deadline information to update"))))
12843 (org-add-planning-info 'deadline time 'closed)
12844 (when (and old-date org-log-redeadline
12845 (not (equal old-date
12846 (substring org-last-inserted-timestamp 1 -1))))
12847 (org-add-log-setup 'redeadline nil old-date 'findpos
12848 org-log-redeadline))
12849 (when repeater
12850 (save-excursion
12851 (org-back-to-heading t)
12852 (when (re-search-forward (concat org-deadline-string " "
12853 org-last-inserted-timestamp)
12854 (save-excursion
12855 (outline-next-heading) (point)) t)
12856 (goto-char (1- (match-end 0)))
12857 (insert " " repeater)
12858 (setq org-last-inserted-timestamp
12859 (concat (substring org-last-inserted-timestamp 0 -1)
12860 " " repeater
12861 (substring org-last-inserted-timestamp -1))))))
12862 (message "Deadline on %s" org-last-inserted-timestamp))))))
12864 (defun org-schedule (arg &optional time)
12865 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12866 With one universal prefix argument, remove any scheduling date from the item.
12867 With two universal prefix arguments, prompt for a delay cookie.
12868 With argument TIME, scheduled at the corresponding date. TIME can
12869 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12870 (interactive "P")
12871 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12872 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12873 'region-start-level 'region))
12874 org-loop-over-headlines-in-active-region)
12875 (org-map-entries
12876 `(org-schedule ',arg ,time)
12877 org-loop-over-headlines-in-active-region
12878 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12879 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12880 (old-date-time (if old-date (org-time-string-to-time old-date)))
12881 (repeater (and old-date
12882 (string-match
12883 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12884 old-date)
12885 (match-string 1 old-date))))
12886 (cond
12887 ((equal arg '(4))
12888 (progn
12889 (when (and old-date org-log-reschedule)
12890 (org-add-log-setup 'delschedule nil old-date 'findpos
12891 org-log-reschedule))
12892 (org-remove-timestamp-with-keyword org-scheduled-string)
12893 (message "Item is no longer scheduled.")))
12894 ((equal arg '(16))
12895 (save-excursion
12896 (if (re-search-forward
12897 org-scheduled-time-regexp
12898 (save-excursion (outline-next-heading) (point)) t)
12899 (let* ((rpl0 (match-string 1))
12900 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12901 (replace-match
12902 (concat org-scheduled-string
12903 " <" rpl
12904 (format " -%dd"
12905 (abs
12906 (- (time-to-days
12907 (save-match-data
12908 (org-read-date nil t nil "Delay until" old-date-time)))
12909 (time-to-days old-date-time))))
12910 ">") t t))
12911 (user-error "No scheduled information to update"))))
12913 (org-add-planning-info 'scheduled time 'closed)
12914 (when (and old-date org-log-reschedule
12915 (not (equal old-date
12916 (substring org-last-inserted-timestamp 1 -1))))
12917 (org-add-log-setup 'reschedule nil old-date 'findpos
12918 org-log-reschedule))
12919 (when repeater
12920 (save-excursion
12921 (org-back-to-heading t)
12922 (when (re-search-forward (concat org-scheduled-string " "
12923 org-last-inserted-timestamp)
12924 (save-excursion
12925 (outline-next-heading) (point)) t)
12926 (goto-char (1- (match-end 0)))
12927 (insert " " repeater)
12928 (setq org-last-inserted-timestamp
12929 (concat (substring org-last-inserted-timestamp 0 -1)
12930 " " repeater
12931 (substring org-last-inserted-timestamp -1))))))
12932 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12934 (defun org-get-scheduled-time (pom &optional inherit)
12935 "Get the scheduled time as a time tuple, of a format suitable
12936 for calling org-schedule with, or if there is no scheduling,
12937 returns nil."
12938 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12939 (when time
12940 (apply 'encode-time (org-parse-time-string time)))))
12942 (defun org-get-deadline-time (pom &optional inherit)
12943 "Get the deadline as a time tuple, of a format suitable for
12944 calling org-deadline with, or if there is no scheduling, returns
12945 nil."
12946 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12947 (when time
12948 (apply 'encode-time (org-parse-time-string time)))))
12950 (defun org-remove-timestamp-with-keyword (keyword)
12951 "Remove all time stamps with KEYWORD in the current entry."
12952 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12953 beg)
12954 (save-excursion
12955 (org-back-to-heading t)
12956 (setq beg (point))
12957 (outline-next-heading)
12958 (while (re-search-backward re beg t)
12959 (replace-match "")
12960 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12961 (equal (char-before) ?\ ))
12962 (backward-delete-char 1)
12963 (if (string-match "^[ \t]*$" (buffer-substring
12964 (point-at-bol) (point-at-eol)))
12965 (delete-region (point-at-bol)
12966 (min (point-max) (1+ (point-at-eol))))))))))
12968 (defun org-add-planning-info (what &optional time &rest remove)
12969 "Insert new timestamp with keyword in the line directly after the headline.
12970 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12971 If non is given, the user is prompted for a date.
12972 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12973 be removed."
12974 (interactive)
12975 (let (org-time-was-given org-end-time-was-given ts
12976 end default-time default-input)
12978 (catch 'exit
12979 (when (and (memq what '(scheduled deadline))
12980 (or (not time)
12981 (and (stringp time)
12982 (string-match "^[-+]+[0-9]" time))))
12983 ;; Try to get a default date/time from existing timestamp
12984 (save-excursion
12985 (org-back-to-heading t)
12986 (setq end (save-excursion (outline-next-heading) (point)))
12987 (when (re-search-forward (if (eq what 'scheduled)
12988 org-scheduled-time-regexp
12989 org-deadline-time-regexp)
12990 end t)
12991 (setq ts (match-string 1)
12992 default-time
12993 (apply 'encode-time (org-parse-time-string ts))
12994 default-input (and ts (org-get-compact-tod ts))))))
12995 (when what
12996 (setq time
12997 (if (stringp time)
12998 ;; This is a string (relative or absolute), set proper date
12999 (apply 'encode-time
13000 (org-read-date-analyze
13001 time default-time (decode-time default-time)))
13002 ;; If necessary, get the time from the user
13003 (or time (org-read-date nil 'to-time nil nil
13004 default-time default-input)))))
13006 (when (and org-insert-labeled-timestamps-at-point
13007 (member what '(scheduled deadline)))
13008 (insert
13009 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13010 (org-insert-time-stamp time org-time-was-given
13011 nil nil nil (list org-end-time-was-given))
13012 (setq what nil))
13013 (save-excursion
13014 (save-restriction
13015 (let (col list elt ts buffer-invisibility-spec)
13016 (org-back-to-heading t)
13017 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13018 (goto-char (match-end 1))
13019 (setq col (current-column))
13020 (goto-char (match-end 0))
13021 (if (eobp) (insert "\n") (forward-char 1))
13022 (when (and (not what)
13023 (not (looking-at
13024 (concat "[ \t]*"
13025 org-keyword-time-not-clock-regexp))))
13026 ;; Nothing to add, nothing to remove...... :-)
13027 (throw 'exit nil))
13028 (if (and (not (looking-at org-outline-regexp))
13029 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13030 "[^\r\n]*"))
13031 (not (equal (match-string 1) org-clock-string)))
13032 (narrow-to-region (match-beginning 0) (match-end 0))
13033 (insert-before-markers "\n")
13034 (backward-char 1)
13035 (narrow-to-region (point) (point))
13036 (and org-adapt-indentation (org-indent-to-column col)))
13037 ;; Check if we have to remove something.
13038 (setq list (cons what remove))
13039 (while list
13040 (setq elt (pop list))
13041 (when (or (and (eq elt 'scheduled)
13042 (re-search-forward org-scheduled-time-regexp nil t))
13043 (and (eq elt 'deadline)
13044 (re-search-forward org-deadline-time-regexp nil t))
13045 (and (eq elt 'closed)
13046 (re-search-forward org-closed-time-regexp nil t)))
13047 (replace-match "")
13048 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13049 (and (looking-at "[ \t]+") (replace-match ""))
13050 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13051 (when what
13052 (insert
13053 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13054 (cond ((eq what 'scheduled) org-scheduled-string)
13055 ((eq what 'deadline) org-deadline-string)
13056 ((eq what 'closed) org-closed-string))
13057 " ")
13058 (setq ts (org-insert-time-stamp
13059 time
13060 (or org-time-was-given
13061 (and (eq what 'closed) org-log-done-with-time))
13062 (eq what 'closed)
13063 nil nil (list org-end-time-was-given)))
13064 (insert
13065 (if (not (or (bolp) (eq (char-before) ?\ )
13066 (memq (char-after) '(32 10))
13067 (eobp))) " " ""))
13068 (end-of-line 1))
13069 (goto-char (point-min))
13070 (widen)
13071 (if (and (looking-at "[ \t]*\n")
13072 (equal (char-before) ?\n))
13073 (delete-region (1- (point)) (point-at-eol)))
13074 ts))))))
13076 (defvar org-log-note-marker (make-marker))
13077 (defvar org-log-note-purpose nil)
13078 (defvar org-log-note-state nil)
13079 (defvar org-log-note-previous-state nil)
13080 (defvar org-log-note-how nil)
13081 (defvar org-log-note-extra nil)
13082 (defvar org-log-note-window-configuration nil)
13083 (defvar org-log-note-return-to (make-marker))
13084 (defvar org-log-note-effective-time nil
13085 "Remembered current time so that dynamically scoped
13086 `org-extend-today-until' affects tha timestamps in state change
13087 log")
13089 (defvar org-log-post-message nil
13090 "Message to be displayed after a log note has been stored.
13091 The auto-repeater uses this.")
13093 (defun org-add-note ()
13094 "Add a note to the current entry.
13095 This is done in the same way as adding a state change note."
13096 (interactive)
13097 (org-add-log-setup 'note nil nil 'findpos nil))
13099 (defvar org-property-end-re)
13100 (defun org-add-log-setup (&optional purpose state prev-state
13101 findpos how extra)
13102 "Set up the post command hook to take a note.
13103 If this is about to TODO state change, the new state is expected in STATE.
13104 When FINDPOS is non-nil, find the correct position for the note in
13105 the current entry. If not, assume that it can be inserted at point.
13106 HOW is an indicator what kind of note should be created.
13107 EXTRA is additional text that will be inserted into the notes buffer."
13108 (let* ((org-log-into-drawer (org-log-into-drawer))
13109 (drawer (cond ((stringp org-log-into-drawer)
13110 org-log-into-drawer)
13111 (org-log-into-drawer "LOGBOOK"))))
13112 (save-restriction
13113 (save-excursion
13114 (when findpos
13115 (org-back-to-heading t)
13116 (narrow-to-region (point) (save-excursion
13117 (outline-next-heading) (point)))
13118 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13119 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13120 "[^\r\n]*\\)?"))
13121 (goto-char (match-end 0))
13122 (cond
13123 (drawer
13124 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13125 nil t)
13126 (progn
13127 (goto-char (match-end 0))
13128 (or org-log-states-order-reversed
13129 (and (re-search-forward org-property-end-re nil t)
13130 (goto-char (1- (match-beginning 0))))))
13131 (insert "\n:" drawer ":\n:END:")
13132 (beginning-of-line 0)
13133 (org-indent-line)
13134 (beginning-of-line 2)
13135 (org-indent-line)
13136 (end-of-line 0)))
13137 ((and org-log-state-notes-insert-after-drawers
13138 (save-excursion
13139 (forward-line) (looking-at org-drawer-regexp)))
13140 (forward-line)
13141 (while (looking-at org-drawer-regexp)
13142 (goto-char (match-end 0))
13143 (re-search-forward org-property-end-re (point-max) t)
13144 (forward-line))
13145 (forward-line -1)))
13146 (unless org-log-states-order-reversed
13147 (and (= (char-after) ?\n) (forward-char 1))
13148 (org-skip-over-state-notes)
13149 (skip-chars-backward " \t\n\r")))
13150 (move-marker org-log-note-marker (point))
13151 (setq org-log-note-purpose purpose
13152 org-log-note-state state
13153 org-log-note-previous-state prev-state
13154 org-log-note-how how
13155 org-log-note-extra extra
13156 org-log-note-effective-time (org-current-effective-time))
13157 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13159 (defun org-skip-over-state-notes ()
13160 "Skip past the list of State notes in an entry."
13161 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13162 (when (ignore-errors (goto-char (org-in-item-p)))
13163 (let* ((struct (org-list-struct))
13164 (prevs (org-list-prevs-alist struct)))
13165 (while (looking-at "[ \t]*- State")
13166 (goto-char (or (org-list-get-next-item (point) struct prevs)
13167 (org-list-get-item-end (point) struct)))))))
13169 (defun org-add-log-note (&optional purpose)
13170 "Pop up a window for taking a note, and add this note later at point."
13171 (remove-hook 'post-command-hook 'org-add-log-note)
13172 (setq org-log-note-window-configuration (current-window-configuration))
13173 (delete-other-windows)
13174 (move-marker org-log-note-return-to (point))
13175 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13176 (goto-char org-log-note-marker)
13177 (org-switch-to-buffer-other-window "*Org Note*")
13178 (erase-buffer)
13179 (if (memq org-log-note-how '(time state))
13180 (let (current-prefix-arg) (org-store-log-note))
13181 (let ((org-inhibit-startup t)) (org-mode))
13182 (insert (format "# Insert note for %s.
13183 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13184 (cond
13185 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13186 ((eq org-log-note-purpose 'done) "closed todo item")
13187 ((eq org-log-note-purpose 'state)
13188 (format "state change from \"%s\" to \"%s\""
13189 (or org-log-note-previous-state "")
13190 (or org-log-note-state "")))
13191 ((eq org-log-note-purpose 'reschedule)
13192 "rescheduling")
13193 ((eq org-log-note-purpose 'delschedule)
13194 "no longer scheduled")
13195 ((eq org-log-note-purpose 'redeadline)
13196 "changing deadline")
13197 ((eq org-log-note-purpose 'deldeadline)
13198 "removing deadline")
13199 ((eq org-log-note-purpose 'refile)
13200 "refiling")
13201 ((eq org-log-note-purpose 'note)
13202 "this entry")
13203 (t (error "This should not happen")))))
13204 (if org-log-note-extra (insert org-log-note-extra))
13205 (org-set-local 'org-finish-function 'org-store-log-note)
13206 (run-hooks 'org-log-buffer-setup-hook)))
13208 (defvar org-note-abort nil) ; dynamically scoped
13209 (defun org-store-log-note ()
13210 "Finish taking a log note, and insert it to where it belongs."
13211 (let ((txt (buffer-string)))
13212 (kill-buffer (current-buffer))
13213 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13214 lines ind bul)
13215 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13216 (setq txt (replace-match "" t t txt)))
13217 (if (string-match "\\s-+\\'" txt)
13218 (setq txt (replace-match "" t t txt)))
13219 (setq lines (org-split-string txt "\n"))
13220 (when (and note (string-match "\\S-" note))
13221 (setq note
13222 (org-replace-escapes
13223 note
13224 (list (cons "%u" (user-login-name))
13225 (cons "%U" user-full-name)
13226 (cons "%t" (format-time-string
13227 (org-time-stamp-format 'long 'inactive)
13228 org-log-note-effective-time))
13229 (cons "%T" (format-time-string
13230 (org-time-stamp-format 'long nil)
13231 org-log-note-effective-time))
13232 (cons "%d" (format-time-string
13233 (org-time-stamp-format nil 'inactive)
13234 org-log-note-effective-time))
13235 (cons "%D" (format-time-string
13236 (org-time-stamp-format nil nil)
13237 org-log-note-effective-time))
13238 (cons "%s" (if org-log-note-state
13239 (concat "\"" org-log-note-state "\"")
13240 ""))
13241 (cons "%S" (if org-log-note-previous-state
13242 (concat "\"" org-log-note-previous-state "\"")
13243 "\"\"")))))
13244 (if lines (setq note (concat note " \\\\")))
13245 (push note lines))
13246 (when (or current-prefix-arg org-note-abort)
13247 (when org-log-into-drawer
13248 (org-remove-empty-drawer-at
13249 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13250 org-log-note-marker))
13251 (setq lines nil))
13252 (when lines
13253 (with-current-buffer (marker-buffer org-log-note-marker)
13254 (save-excursion
13255 (goto-char org-log-note-marker)
13256 (move-marker org-log-note-marker nil)
13257 (end-of-line 1)
13258 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13259 (setq ind (save-excursion
13260 (if (ignore-errors (goto-char (org-in-item-p)))
13261 (let ((struct (org-list-struct)))
13262 (org-list-get-ind
13263 (org-list-get-top-point struct) struct))
13264 (skip-chars-backward " \r\t\n")
13265 (cond
13266 ((and (org-at-heading-p)
13267 org-adapt-indentation)
13268 (1+ (org-current-level)))
13269 ((org-at-heading-p) 0)
13270 (t (org-get-indentation))))))
13271 (setq bul (org-list-bullet-string "-"))
13272 (org-indent-line-to ind)
13273 (insert bul (pop lines))
13274 (let ((ind-body (+ (length bul) ind)))
13275 (while lines
13276 (insert "\n")
13277 (org-indent-line-to ind-body)
13278 (insert (pop lines))))
13279 (message "Note stored")
13280 (org-back-to-heading t)
13281 (org-cycle-hide-drawers 'children))))))
13282 (set-window-configuration org-log-note-window-configuration)
13283 (with-current-buffer (marker-buffer org-log-note-return-to)
13284 (goto-char org-log-note-return-to))
13285 (move-marker org-log-note-return-to nil)
13286 (and org-log-post-message (message "%s" org-log-post-message)))
13288 (defun org-remove-empty-drawer-at (drawer pos)
13289 "Remove an empty drawer DRAWER at position POS.
13290 POS may also be a marker."
13291 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13292 (save-excursion
13293 (save-restriction
13294 (widen)
13295 (goto-char pos)
13296 (if (org-in-regexp
13297 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13298 (replace-match ""))))))
13300 (defvar org-ts-type nil)
13301 (defun org-sparse-tree (&optional arg type)
13302 "Create a sparse tree, prompt for the details.
13303 This command can create sparse trees. You first need to select the type
13304 of match used to create the tree:
13306 t Show all TODO entries.
13307 T Show entries with a specific TODO keyword.
13308 m Show entries selected by a tags/property match.
13309 p Enter a property name and its value (both with completion on existing
13310 names/values) and show entries with that property.
13311 r Show entries matching a regular expression (`/' can be used as well).
13312 b Show deadlines and scheduled items before a date.
13313 a Show deadlines and scheduled items after a date.
13314 d Show deadlines due within `org-deadline-warning-days'.
13315 D Show deadlines and scheduled items between a date range."
13316 (interactive "P")
13317 (let (ans kwd value ts-type)
13318 (setq type (or type org-sparse-tree-default-date-type))
13319 (setq org-ts-type type)
13320 (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"
13321 (cond ((eq type 'all) "all timestamps")
13322 ((eq type 'scheduled) "only scheduled")
13323 ((eq type 'deadline) "only deadline")
13324 ((eq type 'active) "only active timestamps")
13325 ((eq type 'inactive) "only inactive timestamps")
13326 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13327 (t "scheduled/deadline")))
13328 (setq ans (read-char-exclusive))
13329 (cond
13330 ((equal ans ?c)
13331 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13332 ((equal ans ?d)
13333 (call-interactively 'org-check-deadlines))
13334 ((equal ans ?b)
13335 (call-interactively 'org-check-before-date))
13336 ((equal ans ?a)
13337 (call-interactively 'org-check-after-date))
13338 ((equal ans ?D)
13339 (call-interactively 'org-check-dates-range))
13340 ((equal ans ?t)
13341 (call-interactively 'org-show-todo-tree))
13342 ((equal ans ?T)
13343 (org-show-todo-tree '(4)))
13344 ((member ans '(?T ?m))
13345 (call-interactively 'org-match-sparse-tree))
13346 ((member ans '(?p ?P))
13347 (setq kwd (org-icompleting-read "Property: "
13348 (mapcar 'list (org-buffer-property-keys))))
13349 (setq value (org-icompleting-read "Value: "
13350 (mapcar 'list (org-property-values kwd))))
13351 (unless (string-match "\\`{.*}\\'" value)
13352 (setq value (concat "\"" value "\"")))
13353 (org-match-sparse-tree arg (concat kwd "=" value)))
13354 ((member ans '(?r ?R ?/))
13355 (call-interactively 'org-occur))
13356 (t (error "No such sparse tree command \"%c\"" ans)))))
13358 (defvar org-occur-highlights nil
13359 "List of overlays used for occur matches.")
13360 (make-variable-buffer-local 'org-occur-highlights)
13361 (defvar org-occur-parameters nil
13362 "Parameters of the active org-occur calls.
13363 This is a list, each call to org-occur pushes as cons cell,
13364 containing the regular expression and the callback, onto the list.
13365 The list can contain several entries if `org-occur' has been called
13366 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13367 will only contain one set of parameters. When the highlights are
13368 removed (for example with `C-c C-c', or with the next edit (depending
13369 on `org-remove-highlights-with-change'), this variable is emptied
13370 as well.")
13371 (make-variable-buffer-local 'org-occur-parameters)
13373 (defun org-occur (regexp &optional keep-previous callback)
13374 "Make a compact tree which shows all matches of REGEXP.
13375 The tree will show the lines where the regexp matches, and all higher
13376 headlines above the match. It will also show the heading after the match,
13377 to make sure editing the matching entry is easy.
13378 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13379 call to `org-occur' will be kept, to allow stacking of calls to this
13380 command.
13381 If CALLBACK is non-nil, it is a function which is called to confirm
13382 that the match should indeed be shown."
13383 (interactive "sRegexp: \nP")
13384 (when (equal regexp "")
13385 (error "Regexp cannot be empty"))
13386 (unless keep-previous
13387 (org-remove-occur-highlights nil nil t))
13388 (push (cons regexp callback) org-occur-parameters)
13389 (let ((cnt 0))
13390 (save-excursion
13391 (goto-char (point-min))
13392 (if (or (not keep-previous) ; do not want to keep
13393 (not org-occur-highlights)) ; no previous matches
13394 ;; hide everything
13395 (org-overview))
13396 (while (re-search-forward regexp nil t)
13397 (when (or (not callback)
13398 (save-match-data (funcall callback)))
13399 (setq cnt (1+ cnt))
13400 (when org-highlight-sparse-tree-matches
13401 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13402 (org-show-context 'occur-tree))))
13403 (when org-remove-highlights-with-change
13404 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13405 nil 'local))
13406 (unless org-sparse-tree-open-archived-trees
13407 (org-hide-archived-subtrees (point-min) (point-max)))
13408 (run-hooks 'org-occur-hook)
13409 (if (org-called-interactively-p 'interactive)
13410 (message "%d match(es) for regexp %s" cnt regexp))
13411 cnt))
13413 (defun org-occur-next-match (&optional n reset)
13414 "Function for `next-error-function' to find sparse tree matches.
13415 N is the number of matches to move, when negative move backwards.
13416 RESET is entirely ignored - this function always goes back to the
13417 starting point when no match is found."
13418 (let* ((limit (if (< n 0) (point-min) (point-max)))
13419 (search-func (if (< n 0)
13420 'previous-single-char-property-change
13421 'next-single-char-property-change))
13422 (n (abs n))
13423 (pos (point))
13425 (catch 'exit
13426 (while (setq p1 (funcall search-func (point) 'org-type))
13427 (when (equal p1 limit)
13428 (goto-char pos)
13429 (error "No more matches"))
13430 (when (equal (get-char-property p1 'org-type) 'org-occur)
13431 (setq n (1- n))
13432 (when (= n 0)
13433 (goto-char p1)
13434 (throw 'exit (point))))
13435 (goto-char p1))
13436 (goto-char p1)
13437 (error "No more matches"))))
13439 (defun org-show-context (&optional key)
13440 "Make sure point and context are visible.
13441 How much context is shown depends upon the variables
13442 `org-show-hierarchy-above', `org-show-following-heading',
13443 `org-show-entry-below' and `org-show-siblings'."
13444 (let ((heading-p (org-at-heading-p t))
13445 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13446 (following-p (org-get-alist-option org-show-following-heading key))
13447 (entry-p (org-get-alist-option org-show-entry-below key))
13448 (siblings-p (org-get-alist-option org-show-siblings key)))
13449 ;; Show heading or entry text
13450 (if (and heading-p (not entry-p))
13451 (org-flag-heading nil) ; only show the heading
13452 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13453 (org-show-hidden-entry))) ; show entire entry
13454 (when following-p
13455 ;; Show next sibling, or heading below text
13456 (save-excursion
13457 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13458 (org-flag-heading nil))))
13459 (when siblings-p (org-show-siblings))
13460 (when hierarchy-p
13461 ;; show all higher headings, possibly with siblings
13462 (save-excursion
13463 (while (and (condition-case nil
13464 (progn (org-up-heading-all 1) t)
13465 (error nil))
13466 (not (bobp)))
13467 (org-flag-heading nil)
13468 (when siblings-p (org-show-siblings)))))
13469 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13471 (defvar org-reveal-start-hook nil
13472 "Hook run before revealing a location.")
13474 (defun org-reveal (&optional siblings)
13475 "Show current entry, hierarchy above it, and the following headline.
13476 This can be used to show a consistent set of context around locations
13477 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13478 not t for the search context.
13480 With optional argument SIBLINGS, on each level of the hierarchy all
13481 siblings are shown. This repairs the tree structure to what it would
13482 look like when opened with hierarchical calls to `org-cycle'.
13483 With double optional argument \\[universal-argument] \\[universal-argument], \
13484 go to the parent and show the
13485 entire tree."
13486 (interactive "P")
13487 (run-hooks 'org-reveal-start-hook)
13488 (let ((org-show-hierarchy-above t)
13489 (org-show-following-heading t)
13490 (org-show-siblings (if siblings t org-show-siblings)))
13491 (org-show-context nil))
13492 (when (equal siblings '(16))
13493 (save-excursion
13494 (when (org-up-heading-safe)
13495 (org-show-subtree)
13496 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13498 (defun org-highlight-new-match (beg end)
13499 "Highlight from BEG to END and mark the highlight is an occur headline."
13500 (let ((ov (make-overlay beg end)))
13501 (overlay-put ov 'face 'secondary-selection)
13502 (overlay-put ov 'org-type 'org-occur)
13503 (push ov org-occur-highlights)))
13505 (defun org-remove-occur-highlights (&optional beg end noremove)
13506 "Remove the occur highlights from the buffer.
13507 BEG and END are ignored. If NOREMOVE is nil, remove this function
13508 from the `before-change-functions' in the current buffer."
13509 (interactive)
13510 (unless org-inhibit-highlight-removal
13511 (mapc 'delete-overlay org-occur-highlights)
13512 (setq org-occur-highlights nil)
13513 (setq org-occur-parameters nil)
13514 (unless noremove
13515 (remove-hook 'before-change-functions
13516 'org-remove-occur-highlights 'local))))
13518 ;;;; Priorities
13520 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13521 "Regular expression matching the priority indicator.")
13523 (defvar org-remove-priority-next-time nil)
13525 (defun org-priority-up ()
13526 "Increase the priority of the current item."
13527 (interactive)
13528 (org-priority 'up))
13530 (defun org-priority-down ()
13531 "Decrease the priority of the current item."
13532 (interactive)
13533 (org-priority 'down))
13535 (defun org-priority (&optional action show)
13536 "Change the priority of an item.
13537 ACTION can be `set', `up', `down', or a character."
13538 (interactive "P")
13539 (if (equal action '(4))
13540 (org-show-priority)
13541 (unless org-enable-priority-commands
13542 (error "Priority commands are disabled"))
13543 (setq action (or action 'set))
13544 (let (current new news have remove)
13545 (save-excursion
13546 (org-back-to-heading t)
13547 (if (looking-at org-priority-regexp)
13548 (setq current (string-to-char (match-string 2))
13549 have t))
13550 (cond
13551 ((eq action 'remove)
13552 (setq remove t new ?\ ))
13553 ((or (eq action 'set)
13554 (if (featurep 'xemacs) (characterp action) (integerp action)))
13555 (if (not (eq action 'set))
13556 (setq new action)
13557 (message "Priority %c-%c, SPC to remove: "
13558 org-highest-priority org-lowest-priority)
13559 (save-match-data
13560 (setq new (read-char-exclusive))))
13561 (if (and (= (upcase org-highest-priority) org-highest-priority)
13562 (= (upcase org-lowest-priority) org-lowest-priority))
13563 (setq new (upcase new)))
13564 (cond ((equal new ?\ ) (setq remove t))
13565 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13566 (error "Priority must be between `%c' and `%c'"
13567 org-highest-priority org-lowest-priority))))
13568 ((eq action 'up)
13569 (setq new (if have
13570 (1- current) ; normal cycling
13571 ;; last priority was empty
13572 (if (eq last-command this-command)
13573 org-lowest-priority ; wrap around empty to lowest
13574 ;; default
13575 (if org-priority-start-cycle-with-default
13576 org-default-priority
13577 (1- org-default-priority))))))
13578 ((eq action 'down)
13579 (setq new (if have
13580 (1+ current) ; normal cycling
13581 ;; last priority was empty
13582 (if (eq last-command this-command)
13583 org-highest-priority ; wrap around empty to highest
13584 ;; default
13585 (if org-priority-start-cycle-with-default
13586 org-default-priority
13587 (1+ org-default-priority))))))
13588 (t (error "Invalid action")))
13589 (if (or (< (upcase new) org-highest-priority)
13590 (> (upcase new) org-lowest-priority))
13591 (if (and (memq action '(up down))
13592 (not have) (not (eq last-command this-command)))
13593 ;; `new' is from default priority
13594 (error
13595 "The default can not be set, see `org-default-priority' why")
13596 ;; normal cycling: `new' is beyond highest/lowest priority
13597 ;; and is wrapped around to the empty priority
13598 (setq remove t)))
13599 (setq news (format "%c" new))
13600 (if have
13601 (if remove
13602 (replace-match "" t t nil 1)
13603 (replace-match news t t nil 2))
13604 (if remove
13605 (error "No priority cookie found in line")
13606 (let ((case-fold-search nil))
13607 (looking-at org-todo-line-regexp))
13608 (if (match-end 2)
13609 (progn
13610 (goto-char (match-end 2))
13611 (insert " [#" news "]"))
13612 (goto-char (match-beginning 3))
13613 (insert "[#" news "] "))))
13614 (org-preserve-lc (org-set-tags nil 'align)))
13615 (if remove
13616 (message "Priority removed")
13617 (message "Priority of current item set to %s" news)))))
13619 (defun org-show-priority ()
13620 "Show the priority of the current item.
13621 This priority is composed of the main priority given with the [#A] cookies,
13622 and by additional input from the age of a schedules or deadline entry."
13623 (interactive)
13624 (let ((pri (if (eq major-mode 'org-agenda-mode)
13625 (org-get-at-bol 'priority)
13626 (save-excursion
13627 (save-match-data
13628 (beginning-of-line)
13629 (and (looking-at org-heading-regexp)
13630 (org-get-priority (match-string 0))))))))
13631 (message "Priority is %d" (if pri pri -1000))))
13633 (defun org-get-priority (s)
13634 "Find priority cookie and return priority."
13635 (save-match-data
13636 (if (functionp org-get-priority-function)
13637 (funcall org-get-priority-function)
13638 (if (not (string-match org-priority-regexp s))
13639 (* 1000 (- org-lowest-priority org-default-priority))
13640 (* 1000 (- org-lowest-priority
13641 (string-to-char (match-string 2 s))))))))
13643 ;;;; Tags
13645 (defvar org-agenda-archives-mode)
13646 (defvar org-map-continue-from nil
13647 "Position from where mapping should continue.
13648 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13650 (defvar org-scanner-tags nil
13651 "The current tag list while the tags scanner is running.")
13652 (defvar org-trust-scanner-tags nil
13653 "Should `org-get-tags-at' use the tags for the scanner.
13654 This is for internal dynamical scoping only.
13655 When this is non-nil, the function `org-get-tags-at' will return the value
13656 of `org-scanner-tags' instead of building the list by itself. This
13657 can lead to large speed-ups when the tags scanner is used in a file with
13658 many entries, and when the list of tags is retrieved, for example to
13659 obtain a list of properties. Building the tags list for each entry in such
13660 a file becomes an N^2 operation - but with this variable set, it scales
13661 as N.")
13663 (defun org-scan-tags (action matcher todo-only &optional start-level)
13664 "Sca headline tags with inheritance and produce output ACTION.
13666 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13667 or `agenda' to produce an entry list for an agenda view. It can also be
13668 a Lisp form or a function that should be called at each matched headline, in
13669 this case the return value is a list of all return values from these calls.
13671 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13672 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13673 only lines with a not-done TODO keyword are included in the output.
13674 This should be the same variable that was scoped into
13675 and set by `org-make-tags-matcher' when it constructed MATCHER.
13677 START-LEVEL can be a string with asterisks, reducing the scope to
13678 headlines matching this string."
13679 (require 'org-agenda)
13680 (let* ((re (concat "^"
13681 (if start-level
13682 ;; Get the correct level to match
13683 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13684 org-outline-regexp)
13685 " *\\(\\<\\("
13686 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13687 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13688 (props (list 'face 'default
13689 'done-face 'org-agenda-done
13690 'undone-face 'default
13691 'mouse-face 'highlight
13692 'org-not-done-regexp org-not-done-regexp
13693 'org-todo-regexp org-todo-regexp
13694 'org-complex-heading-regexp org-complex-heading-regexp
13695 'help-echo
13696 (format "mouse-2 or RET jump to org file %s"
13697 (abbreviate-file-name
13698 (or (buffer-file-name (buffer-base-buffer))
13699 (buffer-name (buffer-base-buffer)))))))
13700 (case-fold-search nil)
13701 (org-map-continue-from nil)
13702 lspos tags tags-list
13703 (tags-alist (list (cons 0 org-file-tags)))
13704 (llast 0) rtn rtn1 level category i txt
13705 todo marker entry priority)
13706 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13707 (setq action (list 'lambda nil action)))
13708 (save-excursion
13709 (goto-char (point-min))
13710 (when (eq action 'sparse-tree)
13711 (org-overview)
13712 (org-remove-occur-highlights))
13713 (while (re-search-forward re nil t)
13714 (setq org-map-continue-from nil)
13715 (catch :skip
13716 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13717 tags (if (match-end 4) (org-match-string-no-properties 4)))
13718 (goto-char (setq lspos (match-beginning 0)))
13719 (setq level (org-reduced-level (org-outline-level))
13720 category (org-get-category))
13721 (setq i llast llast level)
13722 ;; remove tag lists from same and sublevels
13723 (while (>= i level)
13724 (when (setq entry (assoc i tags-alist))
13725 (setq tags-alist (delete entry tags-alist)))
13726 (setq i (1- i)))
13727 ;; add the next tags
13728 (when tags
13729 (setq tags (org-split-string tags ":")
13730 tags-alist
13731 (cons (cons level tags) tags-alist)))
13732 ;; compile tags for current headline
13733 (setq tags-list
13734 (if org-use-tag-inheritance
13735 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13736 tags)
13737 org-scanner-tags tags-list)
13738 (when org-use-tag-inheritance
13739 (setcdr (car tags-alist)
13740 (mapcar (lambda (x)
13741 (setq x (copy-sequence x))
13742 (org-add-prop-inherited x))
13743 (cdar tags-alist))))
13744 (when (and tags org-use-tag-inheritance
13745 (or (not (eq t org-use-tag-inheritance))
13746 org-tags-exclude-from-inheritance))
13747 ;; selective inheritance, remove uninherited ones
13748 (setcdr (car tags-alist)
13749 (org-remove-uninherited-tags (cdar tags-alist))))
13750 (when (and
13752 ;; eval matcher only when the todo condition is OK
13753 (and (or (not todo-only) (member todo org-not-done-keywords))
13754 (let ((case-fold-search t) (org-trust-scanner-tags t))
13755 (eval matcher)))
13757 ;; Call the skipper, but return t if it does not skip,
13758 ;; so that the `and' form continues evaluating
13759 (progn
13760 (unless (eq action 'sparse-tree) (org-agenda-skip))
13763 ;; Check if timestamps are deselecting this entry
13764 (or (not todo-only)
13765 (and (member todo org-not-done-keywords)
13766 (or (not org-agenda-tags-todo-honor-ignore-options)
13767 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13769 ;; select this headline
13770 (cond
13771 ((eq action 'sparse-tree)
13772 (and org-highlight-sparse-tree-matches
13773 (org-get-heading) (match-end 0)
13774 (org-highlight-new-match
13775 (match-beginning 1) (match-end 1)))
13776 (org-show-context 'tags-tree))
13777 ((eq action 'agenda)
13778 (setq txt (org-agenda-format-item
13780 (concat
13781 (if (eq org-tags-match-list-sublevels 'indented)
13782 (make-string (1- level) ?.) "")
13783 (org-get-heading))
13784 level category
13785 tags-list)
13786 priority (org-get-priority txt))
13787 (goto-char lspos)
13788 (setq marker (org-agenda-new-marker))
13789 (org-add-props txt props
13790 'org-marker marker 'org-hd-marker marker 'org-category category
13791 'todo-state todo
13792 'priority priority 'type "tagsmatch")
13793 (push txt rtn))
13794 ((functionp action)
13795 (setq org-map-continue-from nil)
13796 (save-excursion
13797 (setq rtn1 (funcall action))
13798 (push rtn1 rtn)))
13799 (t (error "Invalid action")))
13801 ;; if we are to skip sublevels, jump to end of subtree
13802 (unless org-tags-match-list-sublevels
13803 (org-end-of-subtree t)
13804 (backward-char 1))))
13805 ;; Get the correct position from where to continue
13806 (if org-map-continue-from
13807 (goto-char org-map-continue-from)
13808 (and (= (point) lspos) (end-of-line 1)))))
13809 (when (and (eq action 'sparse-tree)
13810 (not org-sparse-tree-open-archived-trees))
13811 (org-hide-archived-subtrees (point-min) (point-max)))
13812 (nreverse rtn)))
13814 (defun org-remove-uninherited-tags (tags)
13815 "Remove all tags that are not inherited from the list TAGS."
13816 (cond
13817 ((eq org-use-tag-inheritance t)
13818 (if org-tags-exclude-from-inheritance
13819 (org-delete-all org-tags-exclude-from-inheritance tags)
13820 tags))
13821 ((not org-use-tag-inheritance) nil)
13822 ((stringp org-use-tag-inheritance)
13823 (delq nil (mapcar
13824 (lambda (x)
13825 (if (and (string-match org-use-tag-inheritance x)
13826 (not (member x org-tags-exclude-from-inheritance)))
13827 x nil))
13828 tags)))
13829 ((listp org-use-tag-inheritance)
13830 (delq nil (mapcar
13831 (lambda (x)
13832 (if (member x org-use-tag-inheritance) x nil))
13833 tags)))))
13835 (defun org-match-sparse-tree (&optional todo-only match)
13836 "Create a sparse tree according to tags string MATCH.
13837 MATCH can contain positive and negative selection of tags, like
13838 \"+WORK+URGENT-WITHBOSS\".
13839 If optional argument TODO-ONLY is non-nil, only select lines that are
13840 also TODO lines."
13841 (interactive "P")
13842 (org-agenda-prepare-buffers (list (current-buffer)))
13843 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13845 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13847 (defvar org-cached-props nil)
13848 (defun org-cached-entry-get (pom property)
13849 (if (or (eq t org-use-property-inheritance)
13850 (and (stringp org-use-property-inheritance)
13851 (string-match org-use-property-inheritance property))
13852 (and (listp org-use-property-inheritance)
13853 (member property org-use-property-inheritance)))
13854 ;; Caching is not possible, check it directly
13855 (org-entry-get pom property 'inherit)
13856 ;; Get all properties, so that we can do complicated checks easily
13857 (cdr (assoc property (or org-cached-props
13858 (setq org-cached-props
13859 (org-entry-properties pom)))))))
13861 (defun org-global-tags-completion-table (&optional files)
13862 "Return the list of all tags in all agenda buffer/files.
13863 Optional FILES argument is a list of files which can be used
13864 instead of the agenda files."
13865 (save-excursion
13866 (org-uniquify
13867 (delq nil
13868 (apply 'append
13869 (mapcar
13870 (lambda (file)
13871 (set-buffer (find-file-noselect file))
13872 (append (org-get-buffer-tags)
13873 (mapcar (lambda (x) (if (stringp (car-safe x))
13874 (list (car-safe x)) nil))
13875 org-tag-alist)))
13876 (if (and files (car files))
13877 files
13878 (org-agenda-files))))))))
13880 (defun org-make-tags-matcher (match)
13881 "Create the TAGS/TODO matcher form for the selection string MATCH.
13883 The variable `todo-only' is scoped dynamically into this function.
13884 It will be set to t if the matcher restricts matching to TODO entries,
13885 otherwise will not be touched.
13887 Returns a cons of the selection string MATCH and the constructed
13888 lisp form implementing the matcher. The matcher is to be evaluated
13889 at an Org entry, with point on the headline, and returns t if the
13890 entry matches the selection string MATCH. The returned lisp form
13891 references two variables with information about the entry, which
13892 must be bound around the form's evaluation: todo, the TODO keyword
13893 at the entry (or nil of none); and tags-list, the list of all tags
13894 at the entry including inherited ones. Additionally, the category
13895 of the entry (if any) must be specified as the text property
13896 'org-category on the headline.
13898 See also `org-scan-tags'.
13900 (declare (special todo-only))
13901 (unless (boundp 'todo-only)
13902 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13903 (unless match
13904 ;; Get a new match request, with completion
13905 (let ((org-last-tags-completion-table
13906 (org-global-tags-completion-table)))
13907 (setq match (org-completing-read-no-i
13908 "Match: " 'org-tags-completion-function nil nil nil
13909 'org-tags-history))))
13911 ;; Parse the string and create a lisp form
13912 (let ((match0 match)
13913 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13914 minus tag mm
13915 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13916 orterms term orlist re-p str-p level-p level-op time-p
13917 prop-p pn pv po gv rest)
13918 ;; Expand group tags
13919 (setq match (org-tags-expand match))
13920 (if (string-match "/+" match)
13921 ;; match contains also a todo-matching request
13922 (progn
13923 (setq tagsmatch (substring match 0 (match-beginning 0))
13924 todomatch (substring match (match-end 0)))
13925 (if (string-match "^!" todomatch)
13926 (setq todo-only t todomatch (substring todomatch 1)))
13927 (if (string-match "^\\s-*$" todomatch)
13928 (setq todomatch nil)))
13929 ;; only matching tags
13930 (setq tagsmatch match todomatch nil))
13932 ;; Make the tags matcher
13933 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13934 (setq tagsmatcher t)
13935 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13936 (while (setq term (pop orterms))
13937 (while (and (equal (substring term -1) "\\") orterms)
13938 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13939 (while (string-match re term)
13940 (setq rest (substring term (match-end 0))
13941 minus (and (match-end 1)
13942 (equal (match-string 1 term) "-"))
13943 tag (save-match-data (replace-regexp-in-string
13944 "\\\\-" "-"
13945 (match-string 2 term)))
13946 re-p (equal (string-to-char tag) ?{)
13947 level-p (match-end 4)
13948 prop-p (match-end 5)
13949 mm (cond
13950 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13951 (level-p
13952 (setq level-op (org-op-to-function (match-string 3 term)))
13953 `(,level-op level ,(string-to-number
13954 (match-string 4 term))))
13955 (prop-p
13956 (setq pn (match-string 5 term)
13957 po (match-string 6 term)
13958 pv (match-string 7 term)
13959 re-p (equal (string-to-char pv) ?{)
13960 str-p (equal (string-to-char pv) ?\")
13961 time-p (save-match-data
13962 (string-match "^\"[[<].*[]>]\"$" pv))
13963 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13964 (if time-p (setq pv (org-matcher-time pv)))
13965 (setq po (org-op-to-function po (if time-p 'time str-p)))
13966 (cond
13967 ((equal pn "CATEGORY")
13968 (setq gv '(get-text-property (point) 'org-category)))
13969 ((equal pn "TODO")
13970 (setq gv 'todo))
13972 (setq gv `(org-cached-entry-get nil ,pn))))
13973 (if re-p
13974 (if (eq po 'org<>)
13975 `(not (string-match ,pv (or ,gv "")))
13976 `(string-match ,pv (or ,gv "")))
13977 (if str-p
13978 `(,po (or ,gv "") ,pv)
13979 `(,po (string-to-number (or ,gv ""))
13980 ,(string-to-number pv) ))))
13981 (t `(member ,tag tags-list)))
13982 mm (if minus (list 'not mm) mm)
13983 term rest)
13984 (push mm tagsmatcher))
13985 (push (if (> (length tagsmatcher) 1)
13986 (cons 'and tagsmatcher)
13987 (car tagsmatcher))
13988 orlist)
13989 (setq tagsmatcher nil))
13990 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13991 (setq tagsmatcher
13992 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13993 ;; Make the todo matcher
13994 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13995 (setq todomatcher t)
13996 (setq orterms (org-split-string todomatch "|") orlist nil)
13997 (while (setq term (pop orterms))
13998 (while (string-match re term)
13999 (setq minus (and (match-end 1)
14000 (equal (match-string 1 term) "-"))
14001 kwd (match-string 2 term)
14002 re-p (equal (string-to-char kwd) ?{)
14003 term (substring term (match-end 0))
14004 mm (if re-p
14005 `(string-match ,(substring kwd 1 -1) todo)
14006 (list 'equal 'todo kwd))
14007 mm (if minus (list 'not mm) mm))
14008 (push mm todomatcher))
14009 (push (if (> (length todomatcher) 1)
14010 (cons 'and todomatcher)
14011 (car todomatcher))
14012 orlist)
14013 (setq todomatcher nil))
14014 (setq todomatcher (if (> (length orlist) 1)
14015 (cons 'or orlist) (car orlist))))
14017 ;; Return the string and lisp forms of the matcher
14018 (setq matcher (if todomatcher
14019 (list 'and tagsmatcher todomatcher)
14020 tagsmatcher))
14021 (when todo-only
14022 (setq matcher (list 'and '(member todo org-not-done-keywords)
14023 matcher)))
14024 (cons match0 matcher)))
14026 (defun org-tags-expand (match &optional single-as-list downcased)
14027 "Expand group tags in MATCH.
14029 This replaces every group tag in MATCH with a regexp tag search.
14030 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14031 will be replaced like this:
14033 Work => {\(?:Work\|Lab\|Conf\}
14034 +Work => +{\(?:Work\|Lab\|Conf\}
14035 -Work => -{\(?:Work\|Lab\|Conf\}
14037 Replacing by a regexp preserves the structure of the match.
14038 E.g., this expansion
14040 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14042 will match anything tagged with \"Lab\" and \"Home\", or tagged
14043 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14045 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14046 assumed to be a single group tag, and the function will return
14047 the list of tags in this group.
14049 When DOWNCASE is non-nil, expand downcased TAGS."
14050 (if org-group-tags
14051 (let* ((case-fold-search t)
14052 (tal (or org-tag-groups-alist-for-agenda
14053 org-tag-groups-alist))
14054 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14055 (tml (mapcar 'car tal))
14056 (rtnmatch match) rpl)
14057 (while (and tml (string-match
14058 (concat "\\(?1:[+-]?\\)\\(?2:" (regexp-opt tml) "\\)")
14059 rtnmatch))
14060 (let* ((dir (match-string 1 rtnmatch))
14061 (tag (match-string 2 rtnmatch))
14062 (tag (if downcased (downcase tag) tag)))
14063 (setq tml (delete tag tml))
14064 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14065 (setq rtnmatch
14066 (replace-match
14067 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14068 (if single-as-list
14069 (or (reverse rpl) (list rtnmatch))
14070 rtnmatch))
14071 (if single-as-list (list (if downcased (downcase match) match))
14072 match)))
14074 (defun org-op-to-function (op &optional stringp)
14075 "Turn an operator into the appropriate function."
14076 (setq op
14077 (cond
14078 ((equal op "<" ) '(< string< org-time<))
14079 ((equal op ">" ) '(> org-string> org-time>))
14080 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14081 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14082 ((member op '("=" "==")) '(= string= org-time=))
14083 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14084 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14086 (defun org<> (a b) (not (= a b)))
14087 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14088 (defun org-string>= (a b) (not (string< a b)))
14089 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14090 (defun org-string<> (a b) (not (string= a b)))
14091 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14092 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14093 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14094 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14095 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14096 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14097 (defun org-2ft (s)
14098 "Convert S to a floating point time.
14099 If S is already a number, just return it. If it is a string, parse
14100 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14101 (cond
14102 ((numberp s) s)
14103 ((stringp s)
14104 (condition-case nil
14105 (float-time (apply 'encode-time (org-parse-time-string s)))
14106 (error 0.)))
14107 (t 0.)))
14109 (defun org-time-today ()
14110 "Time in seconds today at 0:00.
14111 Returns the float number of seconds since the beginning of the
14112 epoch to the beginning of today (00:00)."
14113 (float-time (apply 'encode-time
14114 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14116 (defun org-matcher-time (s)
14117 "Interpret a time comparison value."
14118 (save-match-data
14119 (cond
14120 ((string= s "<now>") (float-time))
14121 ((string= s "<today>") (org-time-today))
14122 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14123 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14124 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14125 (+ (org-time-today)
14126 (* (string-to-number (match-string 1 s))
14127 (cdr (assoc (match-string 2 s)
14128 '(("d" . 86400.0) ("w" . 604800.0)
14129 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14130 (t (org-2ft s)))))
14132 (defun org-match-any-p (re list)
14133 "Does re match any element of list?"
14134 (setq list (mapcar (lambda (x) (string-match re x)) list))
14135 (delq nil list))
14137 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14138 (defvar org-tags-overlay (make-overlay 1 1))
14139 (org-detach-overlay org-tags-overlay)
14141 (defun org-get-local-tags-at (&optional pos)
14142 "Get a list of tags defined in the current headline."
14143 (org-get-tags-at pos 'local))
14145 (defun org-get-local-tags ()
14146 "Get a list of tags defined in the current headline."
14147 (org-get-tags-at nil 'local))
14149 (defun org-get-tags-at (&optional pos local)
14150 "Get a list of all headline tags applicable at POS.
14151 POS defaults to point. If tags are inherited, the list contains
14152 the targets in the same sequence as the headlines appear, i.e.
14153 the tags of the current headline come last.
14154 When LOCAL is non-nil, only return tags from the current headline,
14155 ignore inherited ones."
14156 (interactive)
14157 (if (and org-trust-scanner-tags
14158 (or (not pos) (equal pos (point)))
14159 (not local))
14160 org-scanner-tags
14161 (let (tags ltags lastpos parent)
14162 (save-excursion
14163 (save-restriction
14164 (widen)
14165 (goto-char (or pos (point)))
14166 (save-match-data
14167 (catch 'done
14168 (condition-case nil
14169 (progn
14170 (org-back-to-heading t)
14171 (while (not (equal lastpos (point)))
14172 (setq lastpos (point))
14173 (when (looking-at
14174 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14175 (setq ltags (org-split-string
14176 (org-match-string-no-properties 1) ":"))
14177 (when parent
14178 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14179 (setq tags (append
14180 (if parent
14181 (org-remove-uninherited-tags ltags)
14182 ltags)
14183 tags)))
14184 (or org-use-tag-inheritance (throw 'done t))
14185 (if local (throw 'done t))
14186 (or (org-up-heading-safe) (error nil))
14187 (setq parent t)))
14188 (error nil)))))
14189 (if local
14190 tags
14191 (reverse (delete-dups
14192 (reverse (append
14193 (org-remove-uninherited-tags
14194 org-file-tags) tags)))))))))
14196 (defun org-add-prop-inherited (s)
14197 (add-text-properties 0 (length s) '(inherited t) s)
14200 (defun org-toggle-tag (tag &optional onoff)
14201 "Toggle the tag TAG for the current line.
14202 If ONOFF is `on' or `off', don't toggle but set to this state."
14203 (let (res current)
14204 (save-excursion
14205 (org-back-to-heading t)
14206 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14207 (point-at-eol) t)
14208 (progn
14209 (setq current (match-string 1))
14210 (replace-match ""))
14211 (setq current ""))
14212 (setq current (nreverse (org-split-string current ":")))
14213 (cond
14214 ((eq onoff 'on)
14215 (setq res t)
14216 (or (member tag current) (push tag current)))
14217 ((eq onoff 'off)
14218 (or (not (member tag current)) (setq current (delete tag current))))
14219 (t (if (member tag current)
14220 (setq current (delete tag current))
14221 (setq res t)
14222 (push tag current))))
14223 (end-of-line 1)
14224 (if current
14225 (progn
14226 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14227 (org-set-tags nil t))
14228 (delete-horizontal-space))
14229 (run-hooks 'org-after-tags-change-hook))
14230 res))
14232 (defun org-align-tags-here (to-col)
14233 ;; Assumes that this is a headline
14234 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14235 (beginning-of-line 1)
14236 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14237 (< pos (match-beginning 2)))
14238 (progn
14239 (setq tags-l (- (match-end 2) (match-beginning 2)))
14240 (goto-char (match-beginning 1))
14241 (insert " ")
14242 (delete-region (point) (1+ (match-beginning 2)))
14243 (setq ncol (max (current-column)
14244 (1+ col)
14245 (if (> to-col 0)
14246 to-col
14247 (- (abs to-col) tags-l))))
14248 (setq p (point))
14249 (insert (make-string (- ncol (current-column)) ?\ ))
14250 (setq ncol (current-column))
14251 (when indent-tabs-mode (tabify p (point-at-eol)))
14252 (org-move-to-column (min ncol col) t))
14253 (goto-char pos))))
14255 (defun org-set-tags-command (&optional arg just-align)
14256 "Call the set-tags command for the current entry."
14257 (interactive "P")
14258 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14259 (org-set-tags arg just-align)
14260 (save-excursion
14261 (unless (and (org-region-active-p)
14262 org-loop-over-headlines-in-active-region)
14263 (org-back-to-heading t))
14264 (org-set-tags arg just-align))))
14266 (defun org-set-tags-to (data)
14267 "Set the tags of the current entry to DATA, replacing the current tags.
14268 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14269 If DATA is nil or the empty string, any tags will be removed."
14270 (interactive "sTags: ")
14271 (setq data
14272 (cond
14273 ((eq data nil) "")
14274 ((equal data "") "")
14275 ((stringp data)
14276 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14277 ":"))
14278 ((listp data)
14279 (concat ":" (mapconcat 'identity data ":") ":"))))
14280 (when data
14281 (save-excursion
14282 (org-back-to-heading t)
14283 (when (looking-at org-complex-heading-regexp)
14284 (if (match-end 5)
14285 (progn
14286 (goto-char (match-beginning 5))
14287 (insert data)
14288 (delete-region (point) (point-at-eol))
14289 (org-set-tags nil 'align))
14290 (goto-char (point-at-eol))
14291 (insert " " data)
14292 (org-set-tags nil 'align)))
14293 (beginning-of-line 1)
14294 (if (looking-at ".*?\\([ \t]+\\)$")
14295 (delete-region (match-beginning 1) (match-end 1))))))
14297 (defun org-align-all-tags ()
14298 "Align the tags i all headings."
14299 (interactive)
14300 (save-excursion
14301 (or (ignore-errors (org-back-to-heading t))
14302 (outline-next-heading))
14303 (if (org-at-heading-p)
14304 (org-set-tags t)
14305 (message "No headings"))))
14307 (defvar org-indent-indentation-per-level)
14308 (defun org-set-tags (&optional arg just-align)
14309 "Set the tags for the current headline.
14310 With prefix ARG, realign all tags in headings in the current buffer."
14311 (interactive "P")
14312 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14313 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14314 'region-start-level 'region))
14315 org-loop-over-headlines-in-active-region)
14316 (org-map-entries
14317 ;; We don't use ARG and JUST-ALIGN here these args are not
14318 ;; useful when looping over headlines
14319 `(org-set-tags)
14320 org-loop-over-headlines-in-active-region
14321 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14322 (let* ((re org-outline-regexp-bol)
14323 (current (unless arg (org-get-tags-string)))
14324 (col (current-column))
14325 (org-setting-tags t)
14326 table current-tags inherited-tags ; computed below when needed
14327 tags p0 c0 c1 rpl di tc level)
14328 (if arg
14329 (save-excursion
14330 (goto-char (point-min))
14331 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14332 (while (re-search-forward re nil t)
14333 (org-set-tags nil t)
14334 (end-of-line 1)))
14335 (message "All tags realigned to column %d" org-tags-column))
14336 (if just-align
14337 (setq tags current)
14338 ;; Get a new set of tags from the user
14339 (save-excursion
14340 (setq table (append org-tag-persistent-alist
14341 (or org-tag-alist (org-get-buffer-tags))
14342 (and
14343 org-complete-tags-always-offer-all-agenda-tags
14344 (org-global-tags-completion-table
14345 (org-agenda-files))))
14346 org-last-tags-completion-table table
14347 current-tags (org-split-string current ":")
14348 inherited-tags (nreverse
14349 (nthcdr (length current-tags)
14350 (nreverse (org-get-tags-at))))
14351 tags
14352 (if (or (eq t org-use-fast-tag-selection)
14353 (and org-use-fast-tag-selection
14354 (delq nil (mapcar 'cdr table))))
14355 (org-fast-tag-selection
14356 current-tags inherited-tags table
14357 (if org-fast-tag-selection-include-todo
14358 org-todo-key-alist))
14359 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14360 (org-trim
14361 (org-icompleting-read "Tags: "
14362 'org-tags-completion-function
14363 nil nil current 'org-tags-history))))))
14364 (while (string-match "[-+&]+" tags)
14365 ;; No boolean logic, just a list
14366 (setq tags (replace-match ":" t t tags))))
14368 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14370 (if org-tags-sort-function
14371 (setq tags (mapconcat 'identity
14372 (sort (org-split-string
14373 tags (org-re "[^[:alnum:]_@#%]+"))
14374 org-tags-sort-function) ":")))
14376 (if (string-match "\\`[\t ]*\\'" tags)
14377 (setq tags "")
14378 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14379 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14381 ;; Insert new tags at the correct column
14382 (beginning-of-line 1)
14383 (setq level (or (and (looking-at org-outline-regexp)
14384 (- (match-end 0) (point) 1))
14386 (cond
14387 ((and (equal current "") (equal tags "")))
14388 ((re-search-forward
14389 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14390 (point-at-eol) t)
14391 (if (equal tags "")
14392 (setq rpl "")
14393 (goto-char (match-beginning 0))
14394 (setq c0 (current-column)
14395 ;; compute offset for the case of org-indent-mode active
14396 di (if org-indent-mode
14397 (* (1- org-indent-indentation-per-level) (1- level))
14399 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14400 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14401 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14402 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14403 (replace-match rpl t t)
14404 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14405 tags)
14406 (t (error "Tags alignment failed")))
14407 (org-move-to-column col)
14408 (unless just-align
14409 (run-hooks 'org-after-tags-change-hook))))))
14411 (defun org-change-tag-in-region (beg end tag off)
14412 "Add or remove TAG for each entry in the region.
14413 This works in the agenda, and also in an org-mode buffer."
14414 (interactive
14415 (list (region-beginning) (region-end)
14416 (let ((org-last-tags-completion-table
14417 (if (derived-mode-p 'org-mode)
14418 (org-get-buffer-tags)
14419 (org-global-tags-completion-table))))
14420 (org-icompleting-read
14421 "Tag: " 'org-tags-completion-function nil nil nil
14422 'org-tags-history))
14423 (progn
14424 (message "[s]et or [r]emove? ")
14425 (equal (read-char-exclusive) ?r))))
14426 (if (fboundp 'deactivate-mark) (deactivate-mark))
14427 (let ((agendap (equal major-mode 'org-agenda-mode))
14428 l1 l2 m buf pos newhead (cnt 0))
14429 (goto-char end)
14430 (setq l2 (1- (org-current-line)))
14431 (goto-char beg)
14432 (setq l1 (org-current-line))
14433 (loop for l from l1 to l2 do
14434 (org-goto-line l)
14435 (setq m (get-text-property (point) 'org-hd-marker))
14436 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14437 (and agendap m))
14438 (setq buf (if agendap (marker-buffer m) (current-buffer))
14439 pos (if agendap m (point)))
14440 (with-current-buffer buf
14441 (save-excursion
14442 (save-restriction
14443 (goto-char pos)
14444 (setq cnt (1+ cnt))
14445 (org-toggle-tag tag (if off 'off 'on))
14446 (setq newhead (org-get-heading)))))
14447 (and agendap (org-agenda-change-all-lines newhead m))))
14448 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14450 (defun org-tags-completion-function (string predicate &optional flag)
14451 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14452 (confirm (lambda (x) (stringp (car x)))))
14453 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14454 (setq s1 (match-string 1 string)
14455 s2 (match-string 2 string))
14456 (setq s1 "" s2 string))
14457 (cond
14458 ((eq flag nil)
14459 ;; try completion
14460 (setq rtn (try-completion s2 ctable confirm))
14461 (if (stringp rtn)
14462 (setq rtn
14463 (concat s1 s2 (substring rtn (length s2))
14464 (if (and org-add-colon-after-tag-completion
14465 (assoc rtn ctable))
14466 ":" ""))))
14467 rtn)
14468 ((eq flag t)
14469 ;; all-completions
14470 (all-completions s2 ctable confirm))
14471 ((eq flag 'lambda)
14472 ;; exact match?
14473 (assoc s2 ctable)))))
14475 (defun org-fast-tag-insert (kwd tags face &optional end)
14476 "Insert KDW, and the TAGS, the latter with face FACE.
14477 Also insert END."
14478 (insert (format "%-12s" (concat kwd ":"))
14479 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14480 (or end "")))
14482 (defun org-fast-tag-show-exit (flag)
14483 (save-excursion
14484 (org-goto-line 3)
14485 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14486 (replace-match ""))
14487 (when flag
14488 (end-of-line 1)
14489 (org-move-to-column (- (window-width) 19) t)
14490 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14492 (defun org-set-current-tags-overlay (current prefix)
14493 "Add an overlay to CURRENT tag with PREFIX."
14494 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14495 (if (featurep 'xemacs)
14496 (org-overlay-display org-tags-overlay (concat prefix s)
14497 'secondary-selection)
14498 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14499 (org-overlay-display org-tags-overlay (concat prefix s)))))
14501 (defvar org-last-tag-selection-key nil)
14502 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14503 "Fast tag selection with single keys.
14504 CURRENT is the current list of tags in the headline, INHERITED is the
14505 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14506 possibly with grouping information. TODO-TABLE is a similar table with
14507 TODO keywords, should these have keys assigned to them.
14508 If the keys are nil, a-z are automatically assigned.
14509 Returns the new tags string, or nil to not change the current settings."
14510 (let* ((fulltable (append table todo-table))
14511 (maxlen (apply 'max (mapcar
14512 (lambda (x)
14513 (if (stringp (car x)) (string-width (car x)) 0))
14514 fulltable)))
14515 (buf (current-buffer))
14516 (expert (eq org-fast-tag-selection-single-key 'expert))
14517 (buffer-tags nil)
14518 (fwidth (+ maxlen 3 1 3))
14519 (ncol (/ (- (window-width) 4) fwidth))
14520 (i-face 'org-done)
14521 (c-face 'org-todo)
14522 tg cnt e c char c1 c2 ntable tbl rtn
14523 ov-start ov-end ov-prefix
14524 (exit-after-next org-fast-tag-selection-single-key)
14525 (done-keywords org-done-keywords)
14526 groups ingroup)
14527 (save-excursion
14528 (beginning-of-line 1)
14529 (if (looking-at
14530 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14531 (setq ov-start (match-beginning 1)
14532 ov-end (match-end 1)
14533 ov-prefix "")
14534 (setq ov-start (1- (point-at-eol))
14535 ov-end (1+ ov-start))
14536 (skip-chars-forward "^\n\r")
14537 (setq ov-prefix
14538 (concat
14539 (buffer-substring (1- (point)) (point))
14540 (if (> (current-column) org-tags-column)
14542 (make-string (- org-tags-column (current-column)) ?\ ))))))
14543 (move-overlay org-tags-overlay ov-start ov-end)
14544 (save-window-excursion
14545 (if expert
14546 (set-buffer (get-buffer-create " *Org tags*"))
14547 (delete-other-windows)
14548 (split-window-vertically)
14549 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14550 (erase-buffer)
14551 (org-set-local 'org-done-keywords done-keywords)
14552 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14553 (org-fast-tag-insert "Current" current c-face "\n\n")
14554 (org-fast-tag-show-exit exit-after-next)
14555 (org-set-current-tags-overlay current ov-prefix)
14556 (setq tbl fulltable char ?a cnt 0)
14557 (while (setq e (pop tbl))
14558 (cond
14559 ((equal (car e) :startgroup)
14560 (push '() groups) (setq ingroup t)
14561 (when (not (= cnt 0))
14562 (setq cnt 0)
14563 (insert "\n"))
14564 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14565 ((equal (car e) :endgroup)
14566 (setq ingroup nil cnt 0)
14567 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14568 ((equal e '(:newline))
14569 (when (not (= cnt 0))
14570 (setq cnt 0)
14571 (insert "\n")
14572 (setq e (car tbl))
14573 (while (equal (car tbl) '(:newline))
14574 (insert "\n")
14575 (setq tbl (cdr tbl)))))
14576 ((equal e '(:grouptags)) nil)
14578 (setq tg (copy-sequence (car e)) c2 nil)
14579 (if (cdr e)
14580 (setq c (cdr e))
14581 ;; automatically assign a character.
14582 (setq c1 (string-to-char
14583 (downcase (substring
14584 tg (if (= (string-to-char tg) ?@) 1 0)))))
14585 (if (or (rassoc c1 ntable) (rassoc c1 table))
14586 (while (or (rassoc char ntable) (rassoc char table))
14587 (setq char (1+ char)))
14588 (setq c2 c1))
14589 (setq c (or c2 char)))
14590 (if ingroup (push tg (car groups)))
14591 (setq tg (org-add-props tg nil 'face
14592 (cond
14593 ((not (assoc tg table))
14594 (org-get-todo-face tg))
14595 ((member tg current) c-face)
14596 ((member tg inherited) i-face))))
14597 (if (equal (caar tbl) :grouptags)
14598 (org-add-props tg nil 'face 'org-tag-group))
14599 (if (and (= cnt 0) (not ingroup)) (insert " "))
14600 (insert "[" c "] " tg (make-string
14601 (- fwidth 4 (length tg)) ?\ ))
14602 (push (cons tg c) ntable)
14603 (when (= (setq cnt (1+ cnt)) ncol)
14604 (insert "\n")
14605 (if ingroup (insert " "))
14606 (setq cnt 0)))))
14607 (setq ntable (nreverse ntable))
14608 (insert "\n")
14609 (goto-char (point-min))
14610 (if (not expert) (org-fit-window-to-buffer))
14611 (setq rtn
14612 (catch 'exit
14613 (while t
14614 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14615 (if (not groups) "no " "")
14616 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14617 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14618 (setq org-last-tag-selection-key c)
14619 (cond
14620 ((= c ?\r) (throw 'exit t))
14621 ((= c ?!)
14622 (setq groups (not groups))
14623 (goto-char (point-min))
14624 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14625 ((= c ?\C-c)
14626 (if (not expert)
14627 (org-fast-tag-show-exit
14628 (setq exit-after-next (not exit-after-next)))
14629 (setq expert nil)
14630 (delete-other-windows)
14631 (set-window-buffer (split-window-vertically) " *Org tags*")
14632 (org-switch-to-buffer-other-window " *Org tags*")
14633 (org-fit-window-to-buffer)))
14634 ((or (= c ?\C-g)
14635 (and (= c ?q) (not (rassoc c ntable))))
14636 (org-detach-overlay org-tags-overlay)
14637 (setq quit-flag t))
14638 ((= c ?\ )
14639 (setq current nil)
14640 (if exit-after-next (setq exit-after-next 'now)))
14641 ((= c ?\t)
14642 (condition-case nil
14643 (setq tg (org-icompleting-read
14644 "Tag: "
14645 (or buffer-tags
14646 (with-current-buffer buf
14647 (org-get-buffer-tags)))))
14648 (quit (setq tg "")))
14649 (when (string-match "\\S-" tg)
14650 (add-to-list 'buffer-tags (list tg))
14651 (if (member tg current)
14652 (setq current (delete tg current))
14653 (push tg current)))
14654 (if exit-after-next (setq exit-after-next 'now)))
14655 ((setq e (rassoc c todo-table) tg (car e))
14656 (with-current-buffer buf
14657 (save-excursion (org-todo tg)))
14658 (if exit-after-next (setq exit-after-next 'now)))
14659 ((setq e (rassoc c ntable) tg (car e))
14660 (if (member tg current)
14661 (setq current (delete tg current))
14662 (loop for g in groups do
14663 (if (member tg g)
14664 (mapc (lambda (x)
14665 (setq current (delete x current)))
14666 g)))
14667 (push tg current))
14668 (if exit-after-next (setq exit-after-next 'now))))
14670 ;; Create a sorted list
14671 (setq current
14672 (sort current
14673 (lambda (a b)
14674 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14675 (if (eq exit-after-next 'now) (throw 'exit t))
14676 (goto-char (point-min))
14677 (beginning-of-line 2)
14678 (delete-region (point) (point-at-eol))
14679 (org-fast-tag-insert "Current" current c-face)
14680 (org-set-current-tags-overlay current ov-prefix)
14681 (while (re-search-forward
14682 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14683 (setq tg (match-string 1))
14684 (add-text-properties
14685 (match-beginning 1) (match-end 1)
14686 (list 'face
14687 (cond
14688 ((member tg current) c-face)
14689 ((member tg inherited) i-face)
14690 (t (get-text-property (match-beginning 1) 'face))))))
14691 (goto-char (point-min)))))
14692 (org-detach-overlay org-tags-overlay)
14693 (if rtn
14694 (mapconcat 'identity current ":")
14695 nil))))
14697 (defun org-get-tags-string ()
14698 "Get the TAGS string in the current headline."
14699 (unless (org-at-heading-p t)
14700 (error "Not on a heading"))
14701 (save-excursion
14702 (beginning-of-line 1)
14703 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14704 (org-match-string-no-properties 1)
14705 "")))
14707 (defun org-get-tags ()
14708 "Get the list of tags specified in the current headline."
14709 (org-split-string (org-get-tags-string) ":"))
14711 (defun org-get-buffer-tags ()
14712 "Get a table of all tags used in the buffer, for completion."
14713 (let (tags)
14714 (save-excursion
14715 (goto-char (point-min))
14716 (while (re-search-forward
14717 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14718 (when (equal (char-after (point-at-bol 0)) ?*)
14719 (mapc (lambda (x) (add-to-list 'tags x))
14720 (org-split-string (org-match-string-no-properties 1) ":")))))
14721 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14722 (mapcar 'list tags)))
14724 ;;;; The mapping API
14726 (defun org-map-entries (func &optional match scope &rest skip)
14727 "Call FUNC at each headline selected by MATCH in SCOPE.
14729 FUNC is a function or a lisp form. The function will be called without
14730 arguments, with the cursor positioned at the beginning of the headline.
14731 The return values of all calls to the function will be collected and
14732 returned as a list.
14734 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14735 does not need to preserve point. After evaluation, the cursor will be
14736 moved to the end of the line (presumably of the headline of the
14737 processed entry) and search continues from there. Under some
14738 circumstances, this may not produce the wanted results. For example,
14739 if you have removed (e.g. archived) the current (sub)tree it could
14740 mean that the next entry will be skipped entirely. In such cases, you
14741 can specify the position from where search should continue by making
14742 FUNC set the variable `org-map-continue-from' to the desired buffer
14743 position.
14745 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14746 Only headlines that are matched by this query will be considered during
14747 the iteration. When MATCH is nil or t, all headlines will be
14748 visited by the iteration.
14750 SCOPE determines the scope of this command. It can be any of:
14752 nil The current buffer, respecting the restriction if any
14753 tree The subtree started with the entry at point
14754 region The entries within the active region, if any
14755 region-start-level
14756 The entries within the active region, but only those at
14757 the same level than the first one.
14758 file The current buffer, without restriction
14759 file-with-archives
14760 The current buffer, and any archives associated with it
14761 agenda All agenda files
14762 agenda-with-archives
14763 All agenda files with any archive files associated with them
14764 \(file1 file2 ...)
14765 If this is a list, all files in the list will be scanned
14767 The remaining args are treated as settings for the skipping facilities of
14768 the scanner. The following items can be given here:
14770 archive skip trees with the archive tag
14771 comment skip trees with the COMMENT keyword
14772 function or Emacs Lisp form:
14773 will be used as value for `org-agenda-skip-function', so
14774 whenever the function returns a position, FUNC will not be
14775 called for that entry and search will continue from the
14776 position returned
14778 If your function needs to retrieve the tags including inherited tags
14779 at the *current* entry, you can use the value of the variable
14780 `org-scanner-tags' which will be much faster than getting the value
14781 with `org-get-tags-at'. If your function gets properties with
14782 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14783 to t around the call to `org-entry-properties' to get the same speedup.
14784 Note that if your function moves around to retrieve tags and properties at
14785 a *different* entry, you cannot use these techniques."
14786 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14787 (not (org-region-active-p)))
14788 (let* ((org-agenda-archives-mode nil) ; just to make sure
14789 (org-agenda-skip-archived-trees (memq 'archive skip))
14790 (org-agenda-skip-comment-trees (memq 'comment skip))
14791 (org-agenda-skip-function
14792 (car (org-delete-all '(comment archive) skip)))
14793 (org-tags-match-list-sublevels t)
14794 (start-level (eq scope 'region-start-level))
14795 matcher file res
14796 org-todo-keywords-for-agenda
14797 org-done-keywords-for-agenda
14798 org-todo-keyword-alist-for-agenda
14799 org-drawers-for-agenda
14800 org-tag-alist-for-agenda
14801 todo-only)
14803 (cond
14804 ((eq match t) (setq matcher t))
14805 ((eq match nil) (setq matcher t))
14806 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14808 (save-window-excursion
14809 (save-restriction
14810 (cond ((eq scope 'tree)
14811 (org-back-to-heading t)
14812 (org-narrow-to-subtree)
14813 (setq scope nil))
14814 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14815 (org-region-active-p))
14816 ;; If needed, set start-level to a string like "2"
14817 (when start-level
14818 (save-excursion
14819 (goto-char (region-beginning))
14820 (unless (org-at-heading-p) (outline-next-heading))
14821 (setq start-level (org-current-level))))
14822 (narrow-to-region (region-beginning)
14823 (save-excursion
14824 (goto-char (region-end))
14825 (unless (and (bolp) (org-at-heading-p))
14826 (outline-next-heading))
14827 (point)))
14828 (setq scope nil)))
14830 (if (not scope)
14831 (progn
14832 (org-agenda-prepare-buffers
14833 (list (buffer-file-name (current-buffer))))
14834 (setq res (org-scan-tags func matcher todo-only start-level)))
14835 ;; Get the right scope
14836 (cond
14837 ((and scope (listp scope) (symbolp (car scope)))
14838 (setq scope (eval scope)))
14839 ((eq scope 'agenda)
14840 (setq scope (org-agenda-files t)))
14841 ((eq scope 'agenda-with-archives)
14842 (setq scope (org-agenda-files t))
14843 (setq scope (org-add-archive-files scope)))
14844 ((eq scope 'file)
14845 (setq scope (list (buffer-file-name))))
14846 ((eq scope 'file-with-archives)
14847 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14848 (org-agenda-prepare-buffers scope)
14849 (while (setq file (pop scope))
14850 (with-current-buffer (org-find-base-buffer-visiting file)
14851 (save-excursion
14852 (save-restriction
14853 (widen)
14854 (goto-char (point-min))
14855 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14856 res)))
14858 ;;;; Properties
14860 ;;; Setting and retrieving properties
14862 (defconst org-special-properties
14863 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14864 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14865 "The special properties valid in Org-mode.
14867 These are properties that are not defined in the property drawer,
14868 but in some other way.")
14870 (defconst org-default-properties
14871 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14872 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14873 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14874 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14875 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14876 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14877 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14878 "Some properties that are used by Org-mode for various purposes.
14879 Being in this list makes sure that they are offered for completion.")
14881 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14882 "Regular expression matching the first line of a property drawer.")
14884 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14885 "Regular expression matching the last line of a property drawer.")
14887 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14888 "Regular expression matching the first line of a property drawer.")
14890 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14891 "Regular expression matching the first line of a property drawer.")
14893 (defconst org-property-drawer-re
14894 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14895 org-property-end-re "\\)\n?")
14896 "Matches an entire property drawer.")
14898 (defconst org-clock-drawer-re
14899 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14900 org-property-end-re "\\)\n?")
14901 "Matches an entire clock drawer.")
14903 (defsubst org-re-property (property)
14904 "Return a regexp matching a PROPERTY line.
14905 Match group 1 will be set to the value."
14906 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14908 (defsubst org-re-property-keyword (property)
14909 "Return a regexp matching a PROPERTY line, possibly with no
14910 value for the property."
14911 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14913 (defun org-property-action ()
14914 "Do an action on properties."
14915 (interactive)
14916 (let (c)
14917 (org-at-property-p)
14918 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14919 (setq c (read-char-exclusive))
14920 (cond
14921 ((equal c ?s)
14922 (call-interactively 'org-set-property))
14923 ((equal c ?d)
14924 (call-interactively 'org-delete-property))
14925 ((equal c ?D)
14926 (call-interactively 'org-delete-property-globally))
14927 ((equal c ?c)
14928 (call-interactively 'org-compute-property-at-point))
14929 (t (error "No such property action %c" c)))))
14931 (defun org-inc-effort ()
14932 "Increment the value of the effort property in the current entry."
14933 (interactive)
14934 (org-set-effort nil t))
14936 (defvar org-clock-effort) ;; Defined in org-clock.el
14937 (defvar org-clock-current-task) ;; Defined in org-clock.el
14938 (defun org-set-effort (&optional value increment)
14939 "Set the effort property of the current entry.
14940 With numerical prefix arg, use the nth allowed value, 0 stands for the
14941 10th allowed value.
14943 When INCREMENT is non-nil, set the property to the next allowed value."
14944 (interactive "P")
14945 (if (equal value 0) (setq value 10))
14946 (let* ((completion-ignore-case t)
14947 (prop org-effort-property)
14948 (cur (org-entry-get nil prop))
14949 (allowed (org-property-get-allowed-values nil prop 'table))
14950 (existing (mapcar 'list (org-property-values prop)))
14951 (heading (nth 4 (org-heading-components)))
14953 (val (cond
14954 ((stringp value) value)
14955 ((and allowed (integerp value))
14956 (or (car (nth (1- value) allowed))
14957 (car (org-last allowed))))
14958 ((and allowed increment)
14959 (or (caadr (member (list cur) allowed))
14960 (error "Allowed effort values are not set")))
14961 (allowed
14962 (message "Select 1-9,0, [RET%s]: %s"
14963 (if cur (concat "=" cur) "")
14964 (mapconcat 'car allowed " "))
14965 (setq rpl (read-char-exclusive))
14966 (if (equal rpl ?\r)
14968 (setq rpl (- rpl ?0))
14969 (if (equal rpl 0) (setq rpl 10))
14970 (if (and (> rpl 0) (<= rpl (length allowed)))
14971 (car (nth (1- rpl) allowed))
14972 (org-completing-read "Effort: " allowed nil))))
14974 (let (org-completion-use-ido org-completion-use-iswitchb)
14975 (org-completing-read
14976 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14977 (concat "[" cur "]") "")
14978 ": ")
14979 existing nil nil "" nil cur))))))
14980 (unless (equal (org-entry-get nil prop) val)
14981 (org-entry-put nil prop val))
14982 (save-excursion
14983 (org-back-to-heading t)
14984 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14985 (when (string= heading org-clock-current-task)
14986 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14987 (org-clock-update-mode-line))
14988 (message "%s is now %s" prop val)))
14990 (defun org-at-property-p ()
14991 "Is cursor inside a property drawer?"
14992 (save-excursion
14993 (beginning-of-line 1)
14994 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14995 (save-match-data ;; Used by calling procedures
14996 (let ((p (point))
14997 (range (unless (org-before-first-heading-p)
14998 (org-get-property-block))))
14999 (and range (<= (car range) p) (< p (cdr range))))))))
15001 (defun org-get-property-block (&optional beg end force)
15002 "Return the (beg . end) range of the body of the property drawer.
15003 BEG and END are the beginning and end of the current subtree, or of
15004 the part before the first headline. If they are not given, they will
15005 be found. If the drawer does not exist and FORCE is non-nil, create
15006 the drawer."
15007 (catch 'exit
15008 (save-excursion
15009 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15010 (progn (org-back-to-heading t) (point))))
15011 (end (or end (and (not (outline-next-heading)) (point-max))
15012 (point))))
15013 (goto-char beg)
15014 (if (re-search-forward org-property-start-re end t)
15015 (setq beg (1+ (match-end 0)))
15016 (if force
15017 (save-excursion
15018 (org-insert-property-drawer)
15019 (setq end (progn (outline-next-heading) (point))))
15020 (throw 'exit nil))
15021 (goto-char beg)
15022 (if (re-search-forward org-property-start-re end t)
15023 (setq beg (1+ (match-end 0)))))
15024 (if (re-search-forward org-property-end-re end t)
15025 (setq end (match-beginning 0))
15026 (or force (throw 'exit nil))
15027 (goto-char beg)
15028 (setq end beg)
15029 (org-indent-line)
15030 (insert ":END:\n"))
15031 (cons beg end)))))
15033 (defun org-entry-properties (&optional pom which specific)
15034 "Get all properties of the entry at point-or-marker POM.
15035 This includes the TODO keyword, the tags, time strings for deadline,
15036 scheduled, and clocking, and any additional properties defined in the
15037 entry. The return value is an alist, keys may occur multiple times
15038 if the property key was used several times.
15039 POM may also be nil, in which case the current entry is used.
15040 If WHICH is nil or `all', get all properties. If WHICH is
15041 `special' or `standard', only get that subclass. If WHICH
15042 is a string only get exactly this property. SPECIFIC can be a string, the
15043 specific property we are interested in. Specifying it can speed
15044 things up because then unnecessary parsing is avoided."
15045 (setq which (or which 'all))
15046 (org-with-point-at pom
15047 (let ((clockstr (substring org-clock-string 0 -1))
15048 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15049 (case-fold-search nil)
15050 beg end range props sum-props key key1 value string clocksum clocksumt)
15051 (save-excursion
15052 (when (condition-case nil
15053 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15054 (error nil))
15055 (setq beg (point))
15056 (setq sum-props (get-text-property (point) 'org-summaries))
15057 (setq clocksum (get-text-property (point) :org-clock-minutes)
15058 clocksumt (get-text-property (point) :org-clock-minutes-today))
15059 (outline-next-heading)
15060 (setq end (point))
15061 (when (memq which '(all special))
15062 ;; Get the special properties, like TODO and tags
15063 (goto-char beg)
15064 (when (and (or (not specific) (string= specific "TODO"))
15065 (looking-at org-todo-line-regexp) (match-end 2))
15066 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15067 (when (and (or (not specific) (string= specific "PRIORITY"))
15068 (looking-at org-priority-regexp))
15069 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15070 (when (or (not specific) (string= specific "FILE"))
15071 (push (cons "FILE" buffer-file-name) props))
15072 (when (and (or (not specific) (string= specific "TAGS"))
15073 (setq value (org-get-tags-string))
15074 (string-match "\\S-" value))
15075 (push (cons "TAGS" value) props))
15076 (when (and (or (not specific) (string= specific "ALLTAGS"))
15077 (setq value (org-get-tags-at)))
15078 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15079 ":"))
15080 props))
15081 (when (or (not specific) (string= specific "BLOCKED"))
15082 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15083 (when (or (not specific)
15084 (member specific
15085 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15086 "TIMESTAMP" "TIMESTAMP_IA")))
15087 (catch 'match
15088 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15089 (setq key (if (match-end 1)
15090 (substring (org-match-string-no-properties 1)
15091 0 -1))
15092 string (if (equal key clockstr)
15093 (org-trim
15094 (buffer-substring-no-properties
15095 (match-beginning 3) (goto-char
15096 (point-at-eol))))
15097 (substring (org-match-string-no-properties 3)
15098 1 -1)))
15099 ;; Get the correct property name from the key. This is
15100 ;; necessary if the user has configured time keywords.
15101 (setq key1 (concat key ":"))
15102 (cond
15103 ((not key)
15104 (setq key
15105 (if (= (char-after (match-beginning 3)) ?\[)
15106 "TIMESTAMP_IA" "TIMESTAMP")))
15107 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15108 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15109 ((equal key1 org-closed-string) (setq key "CLOSED"))
15110 ((equal key1 org-clock-string) (setq key "CLOCK")))
15111 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15112 (progn
15113 (push (cons key string) props)
15114 ;; no need to search further if match is found
15115 (throw 'match t))
15116 (when (or (equal key "CLOCK") (not (assoc key props)))
15117 (push (cons key string) props)))))))
15119 (when (memq which '(all standard))
15120 ;; Get the standard properties, like :PROP: ...
15121 (setq range (org-get-property-block beg end))
15122 (when range
15123 (goto-char (car range))
15124 (while (re-search-forward
15125 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15126 (cdr range) t)
15127 (setq key (org-match-string-no-properties 1)
15128 value (org-trim (or (org-match-string-no-properties 2) "")))
15129 (unless (member key excluded)
15130 (push (cons key (or value "")) props)))))
15131 (if clocksum
15132 (push (cons "CLOCKSUM"
15133 (org-columns-number-to-string (/ (float clocksum) 60.)
15134 'add_times))
15135 props))
15136 (if clocksumt
15137 (push (cons "CLOCKSUM_T"
15138 (org-columns-number-to-string (/ (float clocksumt) 60.)
15139 'add_times))
15140 props))
15141 (unless (assoc "CATEGORY" props)
15142 (push (cons "CATEGORY" (org-get-category)) props))
15143 (append sum-props (nreverse props)))))))
15145 (defun org-entry-get (pom property &optional inherit literal-nil)
15146 "Get value of PROPERTY for entry or content at point-or-marker POM.
15147 If INHERIT is non-nil and the entry does not have the property,
15148 then also check higher levels of the hierarchy.
15149 If INHERIT is the symbol `selective', use inheritance only if the setting
15150 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15151 If the property is present but empty, the return value is the empty string.
15152 If the property is not present at all, nil is returned.
15154 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15155 do not interpret it as the list atom nil. This is used for inheritance
15156 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15157 (org-with-point-at pom
15158 (if (and inherit (if (eq inherit 'selective)
15159 (org-property-inherit-p property)
15161 (org-entry-get-with-inheritance property literal-nil)
15162 (if (member property org-special-properties)
15163 ;; We need a special property. Use `org-entry-properties' to
15164 ;; retrieve it, but specify the wanted property
15165 (cdr (assoc property (org-entry-properties nil 'special property)))
15166 (let ((range (org-get-property-block)))
15167 (when (and range (not (eq (car range) (cdr range))))
15168 (let* ((props (list (or (assoc property org-file-properties)
15169 (assoc property org-global-properties)
15170 (assoc property org-global-properties-fixed))))
15171 (ap (lambda (key)
15172 (when (re-search-forward
15173 (org-re-property key) (cdr range) t)
15174 (setq props
15175 (org-update-property-plist
15177 (if (match-end 1)
15178 (org-match-string-no-properties 1) "")
15179 props)))))
15180 val)
15181 (goto-char (car range))
15182 (funcall ap property)
15183 (goto-char (car range))
15184 (while (funcall ap (concat property "+")))
15185 (setq val (cdr (assoc property props)))
15186 (when val (if literal-nil val (org-not-nil val))))))))))
15188 (defun org-property-or-variable-value (var &optional inherit)
15189 "Check if there is a property fixing the value of VAR.
15190 If yes, return this value. If not, return the current value of the variable."
15191 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15192 (if (and prop (stringp prop) (string-match "\\S-" prop))
15193 (read prop)
15194 (symbol-value var))))
15196 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15197 "Delete the property PROPERTY from entry at point-or-marker POM.
15198 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15199 an empty drawer to delete."
15200 (org-with-point-at pom
15201 (if (member property org-special-properties)
15202 nil ; cannot delete these properties.
15203 (let ((range (org-get-property-block)))
15204 (if (and range
15205 (goto-char (car range))
15206 (re-search-forward
15207 (org-re-property property)
15208 (cdr range) t))
15209 (progn
15210 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15211 (and delete-empty-drawer
15212 (org-remove-empty-drawer-at
15213 delete-empty-drawer (car range)))
15215 nil)))))
15217 ;; Multi-values properties are properties that contain multiple values
15218 ;; These values are assumed to be single words, separated by whitespace.
15219 (defun org-entry-add-to-multivalued-property (pom property value)
15220 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15221 (let* ((old (org-entry-get pom property))
15222 (values (and old (org-split-string old "[ \t]"))))
15223 (setq value (org-entry-protect-space value))
15224 (unless (member value values)
15225 (setq values (append values (list value)))
15226 (org-entry-put pom property
15227 (mapconcat 'identity values " ")))))
15229 (defun org-entry-remove-from-multivalued-property (pom property value)
15230 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15231 (let* ((old (org-entry-get pom property))
15232 (values (and old (org-split-string old "[ \t]"))))
15233 (setq value (org-entry-protect-space value))
15234 (when (member value values)
15235 (setq values (delete value values))
15236 (org-entry-put pom property
15237 (mapconcat 'identity values " ")))))
15239 (defun org-entry-member-in-multivalued-property (pom property value)
15240 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15241 (let* ((old (org-entry-get pom property))
15242 (values (and old (org-split-string old "[ \t]"))))
15243 (setq value (org-entry-protect-space value))
15244 (member value values)))
15246 (defun org-entry-get-multivalued-property (pom property)
15247 "Return a list of values in a multivalued property."
15248 (let* ((value (org-entry-get pom property))
15249 (values (and value (org-split-string value "[ \t]"))))
15250 (mapcar 'org-entry-restore-space values)))
15252 (defun org-entry-put-multivalued-property (pom property &rest values)
15253 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15254 VALUES should be a list of strings. Spaces will be protected."
15255 (org-entry-put pom property
15256 (mapconcat 'org-entry-protect-space values " "))
15257 (let* ((value (org-entry-get pom property))
15258 (values (and value (org-split-string value "[ \t]"))))
15259 (mapcar 'org-entry-restore-space values)))
15261 (defun org-entry-protect-space (s)
15262 "Protect spaces and newline in string S."
15263 (while (string-match " " s)
15264 (setq s (replace-match "%20" t t s)))
15265 (while (string-match "\n" s)
15266 (setq s (replace-match "%0A" t t s)))
15269 (defun org-entry-restore-space (s)
15270 "Restore spaces and newline in string S."
15271 (while (string-match "%20" s)
15272 (setq s (replace-match " " t t s)))
15273 (while (string-match "%0A" s)
15274 (setq s (replace-match "\n" t t s)))
15277 (defvar org-entry-property-inherited-from (make-marker)
15278 "Marker pointing to the entry from where a property was inherited.
15279 Each call to `org-entry-get-with-inheritance' will set this marker to the
15280 location of the entry where the inheritance search matched. If there was
15281 no match, the marker will point nowhere.
15282 Note that also `org-entry-get' calls this function, if the INHERIT flag
15283 is set.")
15285 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15286 "Get PROPERTY of entry or content at point, search higher levels if needed.
15287 The search will stop at the first ancestor which has the property defined.
15288 If the value found is \"nil\", return nil to show that the property
15289 should be considered as undefined (this is the meaning of nil here).
15290 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15291 (move-marker org-entry-property-inherited-from nil)
15292 (let (tmp)
15293 (save-excursion
15294 (save-restriction
15295 (widen)
15296 (catch 'ex
15297 (while t
15298 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15299 (or (ignore-errors (org-back-to-heading t))
15300 (goto-char (point-min)))
15301 (move-marker org-entry-property-inherited-from (point))
15302 (throw 'ex tmp))
15303 (or (ignore-errors (org-up-heading-safe))
15304 (throw 'ex nil))))))
15305 (setq tmp (or tmp
15306 (cdr (assoc property org-file-properties))
15307 (cdr (assoc property org-global-properties))
15308 (cdr (assoc property org-global-properties-fixed))))
15309 (if literal-nil tmp (org-not-nil tmp))))
15311 (defvar org-property-changed-functions nil
15312 "Hook called when the value of a property has changed.
15313 Each hook function should accept two arguments, the name of the property
15314 and the new value.")
15316 (defun org-entry-put (pom property value)
15317 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15318 (org-with-point-at pom
15319 (org-back-to-heading t)
15320 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15321 range)
15322 (cond
15323 ((equal property "TODO")
15324 (when (and (stringp value) (string-match "\\S-" value)
15325 (not (member value org-todo-keywords-1)))
15326 (error "\"%s\" is not a valid TODO state" value))
15327 (if (or (not value)
15328 (not (string-match "\\S-" value)))
15329 (setq value 'none))
15330 (org-todo value)
15331 (org-set-tags nil 'align))
15332 ((equal property "PRIORITY")
15333 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15334 (string-to-char value) ?\ ))
15335 (org-set-tags nil 'align))
15336 ((equal property "CLOCKSUM")
15337 (if (not (re-search-forward
15338 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15339 (error "Cannot find a clock log")
15340 (goto-char (- (match-end 1) 2))
15341 (cond
15342 ((eq value 'earlier) (org-timestamp-down))
15343 ((eq value 'later) (org-timestamp-up)))
15344 (org-clock-sum-current-item)))
15345 ((equal property "SCHEDULED")
15346 (if (re-search-forward org-scheduled-time-regexp end t)
15347 (cond
15348 ((eq value 'earlier) (org-timestamp-change -1 'day))
15349 ((eq value 'later) (org-timestamp-change 1 'day))
15350 (t (call-interactively 'org-schedule)))
15351 (call-interactively 'org-schedule)))
15352 ((equal property "DEADLINE")
15353 (if (re-search-forward org-deadline-time-regexp end t)
15354 (cond
15355 ((eq value 'earlier) (org-timestamp-change -1 'day))
15356 ((eq value 'later) (org-timestamp-change 1 'day))
15357 (t (call-interactively 'org-deadline)))
15358 (call-interactively 'org-deadline)))
15359 ((member property org-special-properties)
15360 (error "The %s property can not yet be set with `org-entry-put'"
15361 property))
15362 (t ; a non-special property
15363 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15364 (setq range (org-get-property-block beg end 'force))
15365 (goto-char (car range))
15366 (if (re-search-forward
15367 (org-re-property-keyword property) (cdr range) t)
15368 (progn
15369 (delete-region (match-beginning 0) (match-end 0))
15370 (goto-char (match-beginning 0)))
15371 (goto-char (cdr range))
15372 (insert "\n")
15373 (backward-char 1)
15374 (org-indent-line))
15375 (insert ":" property ":")
15376 (and value (insert " " value))
15377 (org-indent-line)))))
15378 (run-hook-with-args 'org-property-changed-functions property value)))
15380 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15381 "Get all property keys in the current buffer.
15382 With INCLUDE-SPECIALS, also list the special properties that reflect things
15383 like tags and TODO state.
15384 With INCLUDE-DEFAULTS, also include properties that has special meaning
15385 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15386 and others.
15387 With INCLUDE-COLUMNS, also include property names given in COLUMN
15388 formats in the current buffer."
15389 (let (rtn range cfmt s p)
15390 (save-excursion
15391 (save-restriction
15392 (widen)
15393 (goto-char (point-min))
15394 (while (re-search-forward org-property-start-re nil t)
15395 (setq range (org-get-property-block))
15396 (goto-char (car range))
15397 (while (re-search-forward
15398 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15399 (cdr range) t)
15400 (add-to-list 'rtn (org-match-string-no-properties 1)))
15401 (outline-next-heading))))
15403 (when include-specials
15404 (setq rtn (append org-special-properties rtn)))
15406 (when include-defaults
15407 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15408 (add-to-list 'rtn org-effort-property))
15410 (when include-columns
15411 (save-excursion
15412 (save-restriction
15413 (widen)
15414 (goto-char (point-min))
15415 (while (re-search-forward
15416 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15417 nil t)
15418 (setq cfmt (match-string 2) s 0)
15419 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15420 cfmt s)
15421 (setq s (match-end 0)
15422 p (match-string 1 cfmt))
15423 (unless (or (equal p "ITEM")
15424 (member p org-special-properties))
15425 (add-to-list 'rtn (match-string 1 cfmt))))))))
15427 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15429 (defun org-property-values (key)
15430 "Return a list of all values of property KEY in the current buffer."
15431 (save-excursion
15432 (save-restriction
15433 (widen)
15434 (goto-char (point-min))
15435 (let ((re (org-re-property key))
15436 values)
15437 (while (re-search-forward re nil t)
15438 (add-to-list 'values (org-trim (match-string 1))))
15439 (delete "" values)))))
15441 (defun org-insert-property-drawer ()
15442 "Insert a property drawer into the current entry."
15443 (org-back-to-heading t)
15444 (looking-at org-outline-regexp)
15445 (let ((indent (if org-adapt-indentation
15446 (- (match-end 0) (match-beginning 0))
15448 (beg (point))
15449 (re (concat "^[ \t]*" org-keyword-time-regexp))
15450 end hiddenp)
15451 (outline-next-heading)
15452 (setq end (point))
15453 (goto-char beg)
15454 (while (re-search-forward re end t))
15455 (setq hiddenp (outline-invisible-p))
15456 (end-of-line 1)
15457 (and (equal (char-after) ?\n) (forward-char 1))
15458 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15459 (if (member (match-string 1) '("CLOCK:" ":END:"))
15460 ;; just skip this line
15461 (beginning-of-line 2)
15462 ;; Drawer start, find the end
15463 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15464 (beginning-of-line 1)))
15465 (org-skip-over-state-notes)
15466 (skip-chars-backward " \t\n\r")
15467 (if (eq (char-before) ?*) (forward-char 1))
15468 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15469 (beginning-of-line 0)
15470 (org-indent-to-column indent)
15471 (beginning-of-line 2)
15472 (org-indent-to-column indent)
15473 (beginning-of-line 0)
15474 (if hiddenp
15475 (save-excursion
15476 (org-back-to-heading t)
15477 (hide-entry))
15478 (org-flag-drawer t))))
15480 (defun org-insert-drawer (&optional arg drawer)
15481 "Insert a drawer at point.
15483 Optional argument DRAWER, when non-nil, is a string representing
15484 drawer's name. Otherwise, the user is prompted for a name.
15486 If a region is active, insert the drawer around that region
15487 instead.
15489 Point is left between drawer's boundaries."
15490 (interactive "P")
15491 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15492 "LOGBOOK"))
15493 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15494 ;; internally by Org. They are meant to be inserted
15495 ;; automatically.
15496 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15497 ;; Remove system drawers from list. Note: For some reason,
15498 ;; `org-completing-read' ignores the predicate while
15499 ;; `completing-read' handles it fine.
15500 (drawer (if arg "PROPERTIES"
15501 (or drawer
15502 (completing-read
15503 "Drawer: " org-drawers
15504 (lambda (d) (not (member d system-drawers))))))))
15505 (cond
15506 ;; With C-u, fall back on `org-insert-property-drawer'
15507 (arg (org-insert-property-drawer))
15508 ;; With an active region, insert a drawer at point.
15509 ((not (org-region-active-p))
15510 (progn
15511 (unless (bolp) (insert "\n"))
15512 (insert (format ":%s:\n\n:END:\n" drawer))
15513 (forward-line -2)))
15514 ;; Otherwise, insert the drawer at point
15516 (let ((rbeg (region-beginning))
15517 (rend (copy-marker (region-end))))
15518 (unwind-protect
15519 (progn
15520 (goto-char rbeg)
15521 (beginning-of-line)
15522 (when (save-excursion
15523 (re-search-forward org-outline-regexp-bol rend t))
15524 (error "Drawers cannot contain headlines"))
15525 ;; Position point at the beginning of the first
15526 ;; non-blank line in region. Insert drawer's opening
15527 ;; there, then indent it.
15528 (org-skip-whitespace)
15529 (beginning-of-line)
15530 (insert ":" drawer ":\n")
15531 (forward-line -1)
15532 (indent-for-tab-command)
15533 ;; Move point to the beginning of the first blank line
15534 ;; after the last non-blank line in region. Insert
15535 ;; drawer's closing, then indent it.
15536 (goto-char rend)
15537 (skip-chars-backward " \r\t\n")
15538 (insert "\n:END:")
15539 (deactivate-mark t)
15540 (indent-for-tab-command)
15541 (unless (eolp) (insert "\n")))
15542 ;; Clear marker, whatever the outcome of insertion is.
15543 (set-marker rend nil)))))))
15545 (defvar org-property-set-functions-alist nil
15546 "Property set function alist.
15547 Each entry should have the following format:
15549 (PROPERTY . READ-FUNCTION)
15551 The read function will be called with the same argument as
15552 `org-completing-read'.")
15554 (defun org-set-property-function (property)
15555 "Get the function that should be used to set PROPERTY.
15556 This is computed according to `org-property-set-functions-alist'."
15557 (or (cdr (assoc property org-property-set-functions-alist))
15558 'org-completing-read))
15560 (defun org-read-property-value (property)
15561 "Read PROPERTY value from user."
15562 (let* ((completion-ignore-case t)
15563 (allowed (org-property-get-allowed-values nil property 'table))
15564 (cur (org-entry-get nil property))
15565 (prompt (concat property " value"
15566 (if (and cur (string-match "\\S-" cur))
15567 (concat " [" cur "]") "") ": "))
15568 (set-function (org-set-property-function property))
15569 (val (if allowed
15570 (funcall set-function prompt allowed nil
15571 (not (get-text-property 0 'org-unrestricted
15572 (caar allowed))))
15573 (let (org-completion-use-ido org-completion-use-iswitchb)
15574 (funcall set-function prompt
15575 (mapcar 'list (org-property-values property))
15576 nil nil "" nil cur)))))
15577 (if (equal val "")
15579 val)))
15581 (defvar org-last-set-property nil)
15582 (defvar org-last-set-property-value nil)
15583 (defun org-read-property-name ()
15584 "Read a property name."
15585 (let* ((completion-ignore-case t)
15586 (keys (org-buffer-property-keys nil t t))
15587 (default-prop (or (save-excursion
15588 (save-match-data
15589 (beginning-of-line)
15590 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15591 (null (string= (match-string 1) "END"))
15592 (match-string 1))))
15593 org-last-set-property))
15594 (property (org-icompleting-read
15595 (concat "Property"
15596 (if default-prop (concat " [" default-prop "]") "")
15597 ": ")
15598 (mapcar 'list keys)
15599 nil nil nil nil
15600 default-prop)))
15601 (if (member property keys)
15602 property
15603 (or (cdr (assoc (downcase property)
15604 (mapcar (lambda (x) (cons (downcase x) x))
15605 keys)))
15606 property))))
15608 (defun org-set-property-and-value (use-last)
15609 "Allow to set [PROPERTY]: [value] direction from prompt.
15610 When use-default, don't even ask, just use the last
15611 \"[PROPERTY]: [value]\" string from the history."
15612 (interactive "P")
15613 (let* ((completion-ignore-case t)
15614 (pv (or (and use-last org-last-set-property-value)
15615 (org-completing-read
15616 "Enter a \"[Property]: [value]\" pair: "
15617 nil nil nil nil nil
15618 org-last-set-property-value)))
15619 prop val)
15620 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15621 (setq prop (match-string 1 pv)
15622 val (match-string 2 pv))
15623 (org-set-property prop val))))
15625 (defun org-set-property (property value)
15626 "In the current entry, set PROPERTY to VALUE.
15627 When called interactively, this will prompt for a property name, offering
15628 completion on existing and default properties. And then it will prompt
15629 for a value, offering completion either on allowed values (via an inherited
15630 xxx_ALL property) or on existing values in other instances of this property
15631 in the current file."
15632 (interactive (list nil nil))
15633 (let* ((property (or property (org-read-property-name)))
15634 (value (or value (org-read-property-value property)))
15635 (fn (cdr (assoc property org-properties-postprocess-alist))))
15636 (setq org-last-set-property property)
15637 (setq org-last-set-property-value (concat property ": " value))
15638 ;; Possibly postprocess the inserted value:
15639 (when fn (setq value (funcall fn value)))
15640 (unless (equal (org-entry-get nil property) value)
15641 (org-entry-put nil property value))))
15643 (defun org-delete-property (property &optional delete-empty-drawer)
15644 "In the current entry, delete PROPERTY.
15645 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15646 an empty drawer to delete."
15647 (interactive
15648 (let* ((completion-ignore-case t)
15649 (prop (org-icompleting-read "Property: "
15650 (org-entry-properties nil 'standard))))
15651 (list prop)))
15652 (message "Property %s %s" property
15653 (if (org-entry-delete nil property delete-empty-drawer)
15654 "deleted"
15655 "was not present in the entry")))
15657 (defun org-delete-property-globally (property)
15658 "Remove PROPERTY globally, from all entries."
15659 (interactive
15660 (let* ((completion-ignore-case t)
15661 (prop (org-icompleting-read
15662 "Globally remove property: "
15663 (mapcar 'list (org-buffer-property-keys)))))
15664 (list prop)))
15665 (save-excursion
15666 (save-restriction
15667 (widen)
15668 (goto-char (point-min))
15669 (let ((cnt 0))
15670 (while (re-search-forward
15671 (org-re-property property)
15672 nil t)
15673 (setq cnt (1+ cnt))
15674 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15675 (message "Property \"%s\" removed from %d entries" property cnt)))))
15677 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15679 (defun org-compute-property-at-point ()
15680 "Compute the property at point.
15681 This looks for an enclosing column format, extracts the operator and
15682 then applies it to the property in the column format's scope."
15683 (interactive)
15684 (unless (org-at-property-p)
15685 (error "Not at a property"))
15686 (let ((prop (org-match-string-no-properties 2)))
15687 (org-columns-get-format-and-top-level)
15688 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15689 (error "No operator defined for property %s" prop))
15690 (org-columns-compute prop)))
15692 (defvar org-property-allowed-value-functions nil
15693 "Hook for functions supplying allowed values for a specific property.
15694 The functions must take a single argument, the name of the property, and
15695 return a flat list of allowed values. If \":ETC\" is one of
15696 the values, this means that these values are intended as defaults for
15697 completion, but that other values should be allowed too.
15698 The functions must return nil if they are not responsible for this
15699 property.")
15701 (defun org-property-get-allowed-values (pom property &optional table)
15702 "Get allowed values for the property PROPERTY.
15703 When TABLE is non-nil, return an alist that can directly be used for
15704 completion."
15705 (let (vals)
15706 (cond
15707 ((equal property "TODO")
15708 (setq vals (org-with-point-at pom
15709 (append org-todo-keywords-1 '("")))))
15710 ((equal property "PRIORITY")
15711 (let ((n org-lowest-priority))
15712 (while (>= n org-highest-priority)
15713 (push (char-to-string n) vals)
15714 (setq n (1- n)))))
15715 ((member property org-special-properties))
15716 ((setq vals (run-hook-with-args-until-success
15717 'org-property-allowed-value-functions property)))
15719 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15720 (when (and vals (string-match "\\S-" vals))
15721 (setq vals (car (read-from-string (concat "(" vals ")"))))
15722 (setq vals (mapcar (lambda (x)
15723 (cond ((stringp x) x)
15724 ((numberp x) (number-to-string x))
15725 ((symbolp x) (symbol-name x))
15726 (t "???")))
15727 vals)))))
15728 (when (member ":ETC" vals)
15729 (setq vals (remove ":ETC" vals))
15730 (org-add-props (car vals) '(org-unrestricted t)))
15731 (if table (mapcar 'list vals) vals)))
15733 (defun org-property-previous-allowed-value (&optional previous)
15734 "Switch to the next allowed value for this property."
15735 (interactive)
15736 (org-property-next-allowed-value t))
15738 (defun org-property-next-allowed-value (&optional previous)
15739 "Switch to the next allowed value for this property."
15740 (interactive)
15741 (unless (org-at-property-p)
15742 (error "Not at a property"))
15743 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15744 (key (match-string 2))
15745 (value (match-string 3))
15746 (allowed (or (org-property-get-allowed-values (point) key)
15747 (and (member value '("[ ]" "[-]" "[X]"))
15748 '("[ ]" "[X]"))))
15749 (heading (save-match-data (nth 4 (org-heading-components))))
15750 nval)
15751 (unless allowed
15752 (error "Allowed values for this property have not been defined"))
15753 (if previous (setq allowed (reverse allowed)))
15754 (if (member value allowed)
15755 (setq nval (car (cdr (member value allowed)))))
15756 (setq nval (or nval (car allowed)))
15757 (if (equal nval value)
15758 (error "Only one allowed value for this property"))
15759 (org-at-property-p)
15760 (replace-match (concat " :" key ": " nval) t t)
15761 (org-indent-line)
15762 (beginning-of-line 1)
15763 (skip-chars-forward " \t")
15764 (when (equal prop org-effort-property)
15765 (save-excursion
15766 (org-back-to-heading t)
15767 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15768 (when (string= org-clock-current-task heading)
15769 (setq org-clock-effort nval)
15770 (org-clock-update-mode-line)))
15771 (run-hook-with-args 'org-property-changed-functions key nval)))
15773 (defun org-find-olp (path &optional this-buffer)
15774 "Return a marker pointing to the entry at outline path OLP.
15775 If anything goes wrong, throw an error.
15776 You can wrap this call to catch the error like this:
15778 (condition-case msg
15779 (org-mobile-locate-entry (match-string 4))
15780 (error (nth 1 msg)))
15782 The return value will then be either a string with the error message,
15783 or a marker if everything is OK.
15785 If THIS-BUFFER is set, the outline path does not contain a file,
15786 only headings."
15787 (let* ((file (if this-buffer buffer-file-name (pop path)))
15788 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15789 (level 1)
15790 (lmin 1)
15791 (lmax 1)
15792 limit re end found pos heading cnt flevel)
15793 (unless buffer (error "File not found :%s" file))
15794 (with-current-buffer buffer
15795 (save-excursion
15796 (save-restriction
15797 (widen)
15798 (setq limit (point-max))
15799 (goto-char (point-min))
15800 (while (setq heading (pop path))
15801 (setq re (format org-complex-heading-regexp-format
15802 (regexp-quote heading)))
15803 (setq cnt 0 pos (point))
15804 (while (re-search-forward re end t)
15805 (setq level (- (match-end 1) (match-beginning 1)))
15806 (if (and (>= level lmin) (<= level lmax))
15807 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15808 (when (= cnt 0) (error "Heading not found on level %d: %s"
15809 lmax heading))
15810 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15811 lmax heading))
15812 (goto-char found)
15813 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15814 (setq end (save-excursion (org-end-of-subtree t t))))
15815 (when (org-at-heading-p)
15816 (point-marker)))))))
15818 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15819 "Find node HEADING in BUFFER.
15820 Return a marker to the heading if it was found, or nil if not.
15821 If POS-ONLY is set, return just the position instead of a marker.
15823 The heading text must match exact, but it may have a TODO keyword,
15824 a priority cookie and tags in the standard locations."
15825 (with-current-buffer (or buffer (current-buffer))
15826 (save-excursion
15827 (save-restriction
15828 (widen)
15829 (goto-char (point-min))
15830 (let (case-fold-search)
15831 (if (re-search-forward
15832 (format org-complex-heading-regexp-format
15833 (regexp-quote heading)) nil t)
15834 (if pos-only
15835 (match-beginning 0)
15836 (move-marker (make-marker) (match-beginning 0)))))))))
15838 (defun org-find-exact-heading-in-directory (heading &optional dir)
15839 "Find Org node headline HEADING in all .org files in directory DIR.
15840 When the target headline is found, return a marker to this location."
15841 (let ((files (directory-files (or dir default-directory)
15842 nil "\\`[^.#].*\\.org\\'"))
15843 file visiting m buffer)
15844 (catch 'found
15845 (while (setq file (pop files))
15846 (message "trying %s" file)
15847 (setq visiting (org-find-base-buffer-visiting file))
15848 (setq buffer (or visiting (find-file-noselect file)))
15849 (setq m (org-find-exact-headline-in-buffer
15850 heading buffer))
15851 (when (and (not m) (not visiting)) (kill-buffer buffer))
15852 (and m (throw 'found m))))))
15854 (defun org-find-entry-with-id (ident)
15855 "Locate the entry that contains the ID property with exact value IDENT.
15856 IDENT can be a string, a symbol or a number, this function will search for
15857 the string representation of it.
15858 Return the position where this entry starts, or nil if there is no such entry."
15859 (interactive "sID: ")
15860 (let ((id (cond
15861 ((stringp ident) ident)
15862 ((symbol-name ident) (symbol-name ident))
15863 ((numberp ident) (number-to-string ident))
15864 (t (error "IDENT %s must be a string, symbol or number" ident))))
15865 (case-fold-search nil))
15866 (save-excursion
15867 (save-restriction
15868 (widen)
15869 (goto-char (point-min))
15870 (when (re-search-forward
15871 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15872 nil t)
15873 (org-back-to-heading t)
15874 (point))))))
15876 ;;;; Timestamps
15878 (defvar org-last-changed-timestamp nil)
15879 (defvar org-last-inserted-timestamp nil
15880 "The last time stamp inserted with `org-insert-time-stamp'.")
15881 (defvar org-time-was-given) ; dynamically scoped parameter
15882 (defvar org-end-time-was-given) ; dynamically scoped parameter
15883 (defvar org-ts-what) ; dynamically scoped parameter
15885 (defun org-time-stamp (arg &optional inactive)
15886 "Prompt for a date/time and insert a time stamp.
15887 If the user specifies a time like HH:MM or if this command is
15888 called with at least one prefix argument, the time stamp contains
15889 the date and the time. Otherwise, only the date is be included.
15891 All parts of a date not specified by the user is filled in from
15892 the current date/time. So if you just press return without
15893 typing anything, the time stamp will represent the current
15894 date/time.
15896 If there is already a timestamp at the cursor, it will be
15897 modified.
15899 With two universal prefix arguments, insert an active timestamp
15900 with the current time without prompting the user."
15901 (interactive "P")
15902 (let* ((ts nil)
15903 (default-time
15904 ;; Default time is either today, or, when entering a range,
15905 ;; the range start.
15906 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15907 (save-excursion
15908 (re-search-backward
15909 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15910 (- (point) 20) t)))
15911 (apply 'encode-time (org-parse-time-string (match-string 1)))
15912 (current-time)))
15913 (default-input (and ts (org-get-compact-tod ts)))
15914 (repeater (save-excursion
15915 (save-match-data
15916 (beginning-of-line)
15917 (when (re-search-forward
15918 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15919 (save-excursion (progn (end-of-line) (point))) t)
15920 (match-string 0)))))
15921 org-time-was-given org-end-time-was-given time)
15922 (cond
15923 ((and (org-at-timestamp-p t)
15924 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15925 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15926 (insert "--")
15927 (setq time (let ((this-command this-command))
15928 (org-read-date arg 'totime nil nil
15929 default-time default-input inactive)))
15930 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15931 ((org-at-timestamp-p t)
15932 (setq time (let ((this-command this-command))
15933 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15934 (when (org-at-timestamp-p t) ; just to get the match data
15935 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15936 (replace-match "")
15937 (setq org-last-changed-timestamp
15938 (org-insert-time-stamp
15939 time (or org-time-was-given arg)
15940 inactive nil nil (list org-end-time-was-given)))
15941 (when repeater (goto-char (1- (point))) (insert " " repeater)
15942 (setq org-last-changed-timestamp
15943 (concat (substring org-last-inserted-timestamp 0 -1)
15944 " " repeater ">"))))
15945 (message "Timestamp updated"))
15946 ((equal arg '(16))
15947 (org-insert-time-stamp (current-time) t))
15949 (setq time (let ((this-command this-command))
15950 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15951 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15952 nil nil (list org-end-time-was-given))))))
15954 ;; FIXME: can we use this for something else, like computing time differences?
15955 (defun org-get-compact-tod (s)
15956 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15957 (let* ((t1 (match-string 1 s))
15958 (h1 (string-to-number (match-string 2 s)))
15959 (m1 (string-to-number (match-string 3 s)))
15960 (t2 (and (match-end 4) (match-string 5 s)))
15961 (h2 (and t2 (string-to-number (match-string 6 s))))
15962 (m2 (and t2 (string-to-number (match-string 7 s))))
15963 dh dm)
15964 (if (not t2)
15966 (setq dh (- h2 h1) dm (- m2 m1))
15967 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15968 (concat t1 "+" (number-to-string dh)
15969 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15971 (defun org-time-stamp-inactive (&optional arg)
15972 "Insert an inactive time stamp.
15973 An inactive time stamp is enclosed in square brackets instead of angle
15974 brackets. It is inactive in the sense that it does not trigger agenda entries,
15975 does not link to the calendar and cannot be changed with the S-cursor keys.
15976 So these are more for recording a certain time/date."
15977 (interactive "P")
15978 (org-time-stamp arg 'inactive))
15980 (defvar org-date-ovl (make-overlay 1 1))
15981 (overlay-put org-date-ovl 'face 'org-date-selected)
15982 (org-detach-overlay org-date-ovl)
15984 (defvar org-ans1) ; dynamically scoped parameter
15985 (defvar org-ans2) ; dynamically scoped parameter
15987 (defvar org-plain-time-of-day-regexp) ; defined below
15989 (defvar org-overriding-default-time nil) ; dynamically scoped
15990 (defvar org-read-date-overlay nil)
15991 (defvar org-dcst nil) ; dynamically scoped
15992 (defvar org-read-date-history nil)
15993 (defvar org-read-date-final-answer nil)
15994 (defvar org-read-date-analyze-futurep nil)
15995 (defvar org-read-date-analyze-forced-year nil)
15996 (defvar org-read-date-inactive)
15998 (defvar org-read-date-minibuffer-local-map
15999 (let ((map (make-sparse-keymap)))
16000 (set-keymap-parent map minibuffer-local-map)
16001 (org-defkey map (kbd ".")
16002 (lambda () (interactive)
16003 (org-eval-in-calendar '(calendar-goto-today))))
16004 (org-defkey map [(meta shift left)]
16005 (lambda () (interactive)
16006 (org-eval-in-calendar '(calendar-backward-month 1))))
16007 (org-defkey map [(meta shift right)]
16008 (lambda () (interactive)
16009 (org-eval-in-calendar '(calendar-forward-month 1))))
16010 (org-defkey map [(meta shift up)]
16011 (lambda () (interactive)
16012 (org-eval-in-calendar '(calendar-backward-year 1))))
16013 (org-defkey map [(meta shift down)]
16014 (lambda () (interactive)
16015 (org-eval-in-calendar '(calendar-forward-year 1))))
16016 (org-defkey map [?\e (shift left)]
16017 (lambda () (interactive)
16018 (org-eval-in-calendar '(calendar-backward-month 1))))
16019 (org-defkey map [?\e (shift right)]
16020 (lambda () (interactive)
16021 (org-eval-in-calendar '(calendar-forward-month 1))))
16022 (org-defkey map [?\e (shift up)]
16023 (lambda () (interactive)
16024 (org-eval-in-calendar '(calendar-backward-year 1))))
16025 (org-defkey map [?\e (shift down)]
16026 (lambda () (interactive)
16027 (org-eval-in-calendar '(calendar-forward-year 1))))
16028 (org-defkey map [(shift up)]
16029 (lambda () (interactive)
16030 (org-eval-in-calendar '(calendar-backward-week 1))))
16031 (org-defkey map [(shift down)]
16032 (lambda () (interactive)
16033 (org-eval-in-calendar '(calendar-forward-week 1))))
16034 (org-defkey map [(shift left)]
16035 (lambda () (interactive)
16036 (org-eval-in-calendar '(calendar-backward-day 1))))
16037 (org-defkey map [(shift right)]
16038 (lambda () (interactive)
16039 (org-eval-in-calendar '(calendar-forward-day 1))))
16040 (org-defkey map "!"
16041 (lambda () (interactive)
16042 (org-eval-in-calendar '(diary-view-entries))
16043 (message "")))
16044 (org-defkey map ">"
16045 (lambda () (interactive)
16046 (org-eval-in-calendar '(scroll-calendar-left 1))))
16047 (org-defkey map "<"
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(scroll-calendar-right 1))))
16050 (org-defkey map "\C-v"
16051 (lambda () (interactive)
16052 (org-eval-in-calendar
16053 '(calendar-scroll-left-three-months 1))))
16054 (org-defkey map "\M-v"
16055 (lambda () (interactive)
16056 (org-eval-in-calendar
16057 '(calendar-scroll-right-three-months 1))))
16058 map)
16059 "Keymap for minibuffer commands when using `org-read-date'.")
16061 (defun org-read-date (&optional org-with-time to-time from-string prompt
16062 default-time default-input inactive)
16063 "Read a date, possibly a time, and make things smooth for the user.
16064 The prompt will suggest to enter an ISO date, but you can also enter anything
16065 which will at least partially be understood by `parse-time-string'.
16066 Unrecognized parts of the date will default to the current day, month, year,
16067 hour and minute. If this command is called to replace a timestamp at point,
16068 or to enter the second timestamp of a range, the default time is taken
16069 from the existing stamp. Furthermore, the command prefers the future,
16070 so if you are giving a date where the year is not given, and the day-month
16071 combination is already past in the current year, it will assume you
16072 mean next year. For details, see the manual. A few examples:
16074 3-2-5 --> 2003-02-05
16075 feb 15 --> currentyear-02-15
16076 2/15 --> currentyear-02-15
16077 sep 12 9 --> 2009-09-12
16078 12:45 --> today 12:45
16079 22 sept 0:34 --> currentyear-09-22 0:34
16080 12 --> currentyear-currentmonth-12
16081 Fri --> nearest Friday (today or later)
16082 etc.
16084 Furthermore you can specify a relative date by giving, as the *first* thing
16085 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16086 change in days weeks, months, years.
16087 With a single plus or minus, the date is relative to today. With a double
16088 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16089 +4d --> four days from today
16090 +4 --> same as above
16091 +2w --> two weeks from today
16092 ++5 --> five days from default date
16094 The function understands only English month and weekday abbreviations.
16096 While prompting, a calendar is popped up - you can also select the
16097 date with the mouse (button 1). The calendar shows a period of three
16098 months. To scroll it to other months, use the keys `>' and `<'.
16099 If you don't like the calendar, turn it off with
16100 \(setq org-read-date-popup-calendar nil)
16102 With optional argument TO-TIME, the date will immediately be converted
16103 to an internal time.
16104 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16105 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16106 still enter a time, and this function will inform the calling routine
16107 about this change. The calling routine may then choose to change the
16108 format used to insert the time stamp into the buffer to include the time.
16109 With optional argument FROM-STRING, read from this string instead from
16110 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16111 the time/date that is used for everything that is not specified by the
16112 user."
16113 (require 'parse-time)
16114 (let* ((org-time-stamp-rounding-minutes
16115 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16116 (org-dcst org-display-custom-times)
16117 (ct (org-current-time))
16118 (org-def (or org-overriding-default-time default-time ct))
16119 (org-defdecode (decode-time org-def))
16120 (dummy (progn
16121 (when (< (nth 2 org-defdecode) org-extend-today-until)
16122 (setcar (nthcdr 2 org-defdecode) -1)
16123 (setcar (nthcdr 1 org-defdecode) 59)
16124 (setq org-def (apply 'encode-time org-defdecode)
16125 org-defdecode (decode-time org-def)))))
16126 (mouse-autoselect-window nil) ; Don't let the mouse jump
16127 (calendar-frame-setup nil)
16128 (calendar-setup nil)
16129 (calendar-move-hook nil)
16130 (calendar-view-diary-initially-flag nil)
16131 (calendar-view-holidays-initially-flag nil)
16132 (timestr (format-time-string
16133 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16134 (prompt (concat (if prompt (concat prompt " ") "")
16135 (format "Date+time [%s]: " timestr)))
16136 ans (org-ans0 "") org-ans1 org-ans2 final)
16138 (cond
16139 (from-string (setq ans from-string))
16140 (org-read-date-popup-calendar
16141 (save-excursion
16142 (save-window-excursion
16143 (calendar)
16144 (org-eval-in-calendar '(setq cursor-type nil) t)
16145 (unwind-protect
16146 (progn
16147 (calendar-forward-day (- (time-to-days org-def)
16148 (calendar-absolute-from-gregorian
16149 (calendar-current-date))))
16150 (org-eval-in-calendar nil t)
16151 (let* ((old-map (current-local-map))
16152 (map (copy-keymap calendar-mode-map))
16153 (minibuffer-local-map
16154 (copy-keymap org-read-date-minibuffer-local-map)))
16155 (org-defkey map (kbd "RET") 'org-calendar-select)
16156 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16157 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16158 (unwind-protect
16159 (progn
16160 (use-local-map map)
16161 (setq org-read-date-inactive inactive)
16162 (add-hook 'post-command-hook 'org-read-date-display)
16163 (setq org-ans0 (read-string prompt default-input
16164 'org-read-date-history nil))
16165 ;; org-ans0: from prompt
16166 ;; org-ans1: from mouse click
16167 ;; org-ans2: from calendar motion
16168 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16169 (remove-hook 'post-command-hook 'org-read-date-display)
16170 (use-local-map old-map)
16171 (when org-read-date-overlay
16172 (delete-overlay org-read-date-overlay)
16173 (setq org-read-date-overlay nil)))))
16174 (bury-buffer "*Calendar*")))))
16176 (t ; Naked prompt only
16177 (unwind-protect
16178 (setq ans (read-string prompt default-input
16179 'org-read-date-history timestr))
16180 (when org-read-date-overlay
16181 (delete-overlay org-read-date-overlay)
16182 (setq org-read-date-overlay nil)))))
16184 (setq final (org-read-date-analyze ans org-def org-defdecode))
16186 (when org-read-date-analyze-forced-year
16187 (message "Year was forced into %s"
16188 (if org-read-date-force-compatible-dates
16189 "compatible range (1970-2037)"
16190 "range representable on this machine"))
16191 (ding))
16193 ;; One round trip to get rid of 34th of August and stuff like that....
16194 (setq final (decode-time (apply 'encode-time final)))
16196 (setq org-read-date-final-answer ans)
16198 (if to-time
16199 (apply 'encode-time final)
16200 (if (and (boundp 'org-time-was-given) org-time-was-given)
16201 (format "%04d-%02d-%02d %02d:%02d"
16202 (nth 5 final) (nth 4 final) (nth 3 final)
16203 (nth 2 final) (nth 1 final))
16204 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16206 (defvar org-def)
16207 (defvar org-defdecode)
16208 (defvar org-with-time)
16209 (defun org-read-date-display ()
16210 "Display the current date prompt interpretation in the minibuffer."
16211 (when org-read-date-display-live
16212 (when org-read-date-overlay
16213 (delete-overlay org-read-date-overlay))
16214 (when (minibufferp (current-buffer))
16215 (save-excursion
16216 (end-of-line 1)
16217 (while (not (equal (buffer-substring
16218 (max (point-min) (- (point) 4)) (point))
16219 " "))
16220 (insert " ")))
16221 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16222 " " (or org-ans1 org-ans2)))
16223 (org-end-time-was-given nil)
16224 (f (org-read-date-analyze ans org-def org-defdecode))
16225 (fmts (if org-dcst
16226 org-time-stamp-custom-formats
16227 org-time-stamp-formats))
16228 (fmt (if (or org-with-time
16229 (and (boundp 'org-time-was-given) org-time-was-given))
16230 (cdr fmts)
16231 (car fmts)))
16232 (txt (format-time-string fmt (apply 'encode-time f)))
16233 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16234 (txt (concat "=> " txt)))
16235 (when (and org-end-time-was-given
16236 (string-match org-plain-time-of-day-regexp txt))
16237 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16238 org-end-time-was-given
16239 (substring txt (match-end 0)))))
16240 (when org-read-date-analyze-futurep
16241 (setq txt (concat txt " (=>F)")))
16242 (setq org-read-date-overlay
16243 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16244 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16246 (defun org-read-date-analyze (ans org-def org-defdecode)
16247 "Analyze the combined answer of the date prompt."
16248 ;; FIXME: cleanup and comment
16249 (let ((nowdecode (decode-time (current-time)))
16250 delta deltan deltaw deltadef year month day
16251 hour minute second wday pm h2 m2 tl wday1
16252 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16253 (setq org-read-date-analyze-futurep nil
16254 org-read-date-analyze-forced-year nil)
16255 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16256 (setq ans "+0"))
16258 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16259 (setq ans (replace-match "" t t ans)
16260 deltan (car delta)
16261 deltaw (nth 1 delta)
16262 deltadef (nth 2 delta)))
16264 ;; Check if there is an iso week date in there. If yes, store the
16265 ;; info and postpone interpreting it until the rest of the parsing
16266 ;; is done.
16267 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16268 (setq iso-year (if (match-end 1)
16269 (org-small-year-to-year
16270 (string-to-number (match-string 1 ans))))
16271 iso-weekday (if (match-end 3)
16272 (string-to-number (match-string 3 ans)))
16273 iso-week (string-to-number (match-string 2 ans)))
16274 (setq ans (replace-match "" t t ans)))
16276 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16277 (when (string-match
16278 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16279 (setq year (if (match-end 2)
16280 (string-to-number (match-string 2 ans))
16281 (progn (setq kill-year t)
16282 (string-to-number (format-time-string "%Y"))))
16283 month (string-to-number (match-string 3 ans))
16284 day (string-to-number (match-string 4 ans)))
16285 (if (< year 100) (setq year (+ 2000 year)))
16286 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16287 t nil ans)))
16289 ;; Help matching dotted european dates
16290 (when (string-match
16291 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16292 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16293 (setq kill-year t)
16294 (string-to-number (format-time-string "%Y")))
16295 day (string-to-number (match-string 1 ans))
16296 month (string-to-number (match-string 2 ans))
16297 ans (replace-match (format "%04d-%02d-%02d" year month day)
16298 t nil ans)))
16300 ;; Help matching american dates, like 5/30 or 5/30/7
16301 (when (string-match
16302 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16303 (setq year (if (match-end 4)
16304 (string-to-number (match-string 4 ans))
16305 (progn (setq kill-year t)
16306 (string-to-number (format-time-string "%Y"))))
16307 month (string-to-number (match-string 1 ans))
16308 day (string-to-number (match-string 2 ans)))
16309 (if (< year 100) (setq year (+ 2000 year)))
16310 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16311 t nil ans)))
16312 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16313 ;; If there is a time with am/pm, and *no* time without it, we convert
16314 ;; so that matching will be successful.
16315 (loop for i from 1 to 2 do ; twice, for end time as well
16316 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16317 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16318 (setq hour (string-to-number (match-string 1 ans))
16319 minute (if (match-end 3)
16320 (string-to-number (match-string 3 ans))
16322 pm (equal ?p
16323 (string-to-char (downcase (match-string 4 ans)))))
16324 (if (and (= hour 12) (not pm))
16325 (setq hour 0)
16326 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16327 (setq ans (replace-match (format "%02d:%02d" hour minute)
16328 t t ans))))
16330 ;; Check if a time range is given as a duration
16331 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16332 (setq hour (string-to-number (match-string 1 ans))
16333 h2 (+ hour (string-to-number (match-string 3 ans)))
16334 minute (string-to-number (match-string 2 ans))
16335 m2 (+ minute (if (match-end 5) (string-to-number
16336 (match-string 5 ans))0)))
16337 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16338 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16339 t t ans)))
16341 ;; Check if there is a time range
16342 (when (boundp 'org-end-time-was-given)
16343 (setq org-time-was-given nil)
16344 (when (and (string-match org-plain-time-of-day-regexp ans)
16345 (match-end 8))
16346 (setq org-end-time-was-given (match-string 8 ans))
16347 (setq ans (concat (substring ans 0 (match-beginning 7))
16348 (substring ans (match-end 7))))))
16350 (setq tl (parse-time-string ans)
16351 day (or (nth 3 tl) (nth 3 org-defdecode))
16352 month (or (nth 4 tl)
16353 (if (and org-read-date-prefer-future
16354 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16355 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16356 (nth 4 org-defdecode)))
16357 year (or (and (not kill-year) (nth 5 tl))
16358 (if (and org-read-date-prefer-future
16359 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16360 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16361 (nth 5 org-defdecode)))
16362 hour (or (nth 2 tl) (nth 2 org-defdecode))
16363 minute (or (nth 1 tl) (nth 1 org-defdecode))
16364 second (or (nth 0 tl) 0)
16365 wday (nth 6 tl))
16367 (when (and (eq org-read-date-prefer-future 'time)
16368 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16369 (equal day (nth 3 nowdecode))
16370 (equal month (nth 4 nowdecode))
16371 (equal year (nth 5 nowdecode))
16372 (nth 2 tl)
16373 (or (< (nth 2 tl) (nth 2 nowdecode))
16374 (and (= (nth 2 tl) (nth 2 nowdecode))
16375 (nth 1 tl)
16376 (< (nth 1 tl) (nth 1 nowdecode)))))
16377 (setq day (1+ day)
16378 futurep t))
16380 ;; Special date definitions below
16381 (cond
16382 (iso-week
16383 ;; There was an iso week
16384 (require 'cal-iso)
16385 (setq futurep nil)
16386 (setq year (or iso-year year)
16387 day (or iso-weekday wday 1)
16388 wday nil ; to make sure that the trigger below does not match
16389 iso-date (calendar-gregorian-from-absolute
16390 (calendar-absolute-from-iso
16391 (list iso-week day year))))
16392 ; FIXME: Should we also push ISO weeks into the future?
16393 ; (when (and org-read-date-prefer-future
16394 ; (not iso-year)
16395 ; (< (calendar-absolute-from-gregorian iso-date)
16396 ; (time-to-days (current-time))))
16397 ; (setq year (1+ year)
16398 ; iso-date (calendar-gregorian-from-absolute
16399 ; (calendar-absolute-from-iso
16400 ; (list iso-week day year)))))
16401 (setq month (car iso-date)
16402 year (nth 2 iso-date)
16403 day (nth 1 iso-date)))
16404 (deltan
16405 (setq futurep nil)
16406 (unless deltadef
16407 (let ((now (decode-time (current-time))))
16408 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16409 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16410 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16411 ((equal deltaw "m") (setq month (+ month deltan)))
16412 ((equal deltaw "y") (setq year (+ year deltan)))))
16413 ((and wday (not (nth 3 tl)))
16414 ;; Weekday was given, but no day, so pick that day in the week
16415 ;; on or after the derived date.
16416 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16417 (unless (equal wday wday1)
16418 (setq day (+ day (% (- wday wday1 -7) 7))))))
16419 (if (and (boundp 'org-time-was-given)
16420 (nth 2 tl))
16421 (setq org-time-was-given t))
16422 (if (< year 100) (setq year (+ 2000 year)))
16423 ;; Check of the date is representable
16424 (if org-read-date-force-compatible-dates
16425 (progn
16426 (if (< year 1970)
16427 (setq year 1970 org-read-date-analyze-forced-year t))
16428 (if (> year 2037)
16429 (setq year 2037 org-read-date-analyze-forced-year t)))
16430 (condition-case nil
16431 (ignore (encode-time second minute hour day month year))
16432 (error
16433 (setq year (nth 5 org-defdecode))
16434 (setq org-read-date-analyze-forced-year t))))
16435 (setq org-read-date-analyze-futurep futurep)
16436 (list second minute hour day month year)))
16438 (defvar parse-time-weekdays)
16439 (defun org-read-date-get-relative (s today default)
16440 "Check string S for special relative date string.
16441 TODAY and DEFAULT are internal times, for today and for a default.
16442 Return shift list (N what def-flag)
16443 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16444 N is the number of WHATs to shift.
16445 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16446 the DEFAULT date rather than TODAY."
16447 (require 'parse-time)
16448 (when (and
16449 (string-match
16450 (concat
16451 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16452 "\\([0-9]+\\)?"
16453 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16454 "\\([ \t]\\|$\\)") s)
16455 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16456 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16457 (string-to-char (substring (match-string 1 s) -1))
16458 ?+))
16459 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16460 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16461 (what (if (match-end 3) (match-string 3 s) "d"))
16462 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16463 (date (if rel default today))
16464 (wday (nth 6 (decode-time date)))
16465 delta)
16466 (if wday1
16467 (progn
16468 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16469 (if (= dir ?-) (setq delta (- delta 7)))
16470 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16471 (list delta "d" rel))
16472 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16474 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16475 "Turn a user-specified date into the internal representation.
16476 The internal representation needed by the calendar is (month day year).
16477 This is a wrapper to handle the brain-dead convention in calendar that
16478 user function argument order change dependent on argument order."
16479 (if (boundp 'calendar-date-style)
16480 (cond
16481 ((eq calendar-date-style 'american)
16482 (list arg1 arg2 arg3))
16483 ((eq calendar-date-style 'european)
16484 (list arg2 arg1 arg3))
16485 ((eq calendar-date-style 'iso)
16486 (list arg2 arg3 arg1)))
16487 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16488 (if (org-bound-and-true-p european-calendar-style)
16489 (list arg2 arg1 arg3)
16490 (list arg1 arg2 arg3)))))
16492 (defun org-eval-in-calendar (form &optional keepdate)
16493 "Eval FORM in the calendar window and return to current window.
16494 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16495 otherwise stick to the current value of `org-ans2'."
16496 (let ((sf (selected-frame))
16497 (sw (selected-window)))
16498 (select-window (get-buffer-window "*Calendar*" t))
16499 (eval form)
16500 (when (and (not keepdate) (calendar-cursor-to-date))
16501 (let* ((date (calendar-cursor-to-date))
16502 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16503 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16504 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16505 (select-window sw)
16506 (org-select-frame-set-input-focus sf)))
16508 (defun org-calendar-select ()
16509 "Return to `org-read-date' with the date currently selected.
16510 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16511 (interactive)
16512 (when (calendar-cursor-to-date)
16513 (let* ((date (calendar-cursor-to-date))
16514 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16515 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16516 (if (active-minibuffer-window) (exit-minibuffer))))
16518 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16519 "Insert a date stamp for the date given by the internal TIME.
16520 WITH-HM means use the stamp format that includes the time of the day.
16521 INACTIVE means use square brackets instead of angular ones, so that the
16522 stamp will not contribute to the agenda.
16523 PRE and POST are optional strings to be inserted before and after the
16524 stamp.
16525 The command returns the inserted time stamp."
16526 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16527 stamp)
16528 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16529 (insert-before-markers (or pre ""))
16530 (when (listp extra)
16531 (setq extra (car extra))
16532 (if (and (stringp extra)
16533 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16534 (setq extra (format "-%02d:%02d"
16535 (string-to-number (match-string 1 extra))
16536 (string-to-number (match-string 2 extra))))
16537 (setq extra nil)))
16538 (when extra
16539 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16540 (insert-before-markers (setq stamp (format-time-string fmt time)))
16541 (insert-before-markers (or post ""))
16542 (setq org-last-inserted-timestamp stamp)))
16544 (defun org-toggle-time-stamp-overlays ()
16545 "Toggle the use of custom time stamp formats."
16546 (interactive)
16547 (setq org-display-custom-times (not org-display-custom-times))
16548 (unless org-display-custom-times
16549 (let ((p (point-min)) (bmp (buffer-modified-p)))
16550 (while (setq p (next-single-property-change p 'display))
16551 (if (and (get-text-property p 'display)
16552 (eq (get-text-property p 'face) 'org-date))
16553 (remove-text-properties
16554 p (setq p (next-single-property-change p 'display))
16555 '(display t))))
16556 (set-buffer-modified-p bmp)))
16557 (if (featurep 'xemacs)
16558 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16559 (org-restart-font-lock)
16560 (setq org-table-may-need-update t)
16561 (if org-display-custom-times
16562 (message "Time stamps are overlaid with custom format")
16563 (message "Time stamp overlays removed")))
16565 (defun org-display-custom-time (beg end)
16566 "Overlay modified time stamp format over timestamp between BEG and END."
16567 (let* ((ts (buffer-substring beg end))
16568 t1 w1 with-hm tf time str w2 (off 0))
16569 (save-match-data
16570 (setq t1 (org-parse-time-string ts t))
16571 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16572 (setq off (- (match-end 0) (match-beginning 0)))))
16573 (setq end (- end off))
16574 (setq w1 (- end beg)
16575 with-hm (and (nth 1 t1) (nth 2 t1))
16576 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16577 time (org-fix-decoded-time t1)
16578 str (org-add-props
16579 (format-time-string
16580 (substring tf 1 -1) (apply 'encode-time time))
16581 nil 'mouse-face 'highlight)
16582 w2 (length str))
16583 (if (not (= w2 w1))
16584 (add-text-properties (1+ beg) (+ 2 beg)
16585 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16586 (if (featurep 'xemacs)
16587 (progn
16588 (put-text-property beg end 'invisible t)
16589 (put-text-property beg end 'end-glyph (make-glyph str)))
16590 (put-text-property beg end 'display str))))
16592 (defun org-translate-time (string)
16593 "Translate all timestamps in STRING to custom format.
16594 But do this only if the variable `org-display-custom-times' is set."
16595 (when org-display-custom-times
16596 (save-match-data
16597 (let* ((start 0)
16598 (re org-ts-regexp-both)
16599 t1 with-hm inactive tf time str beg end)
16600 (while (setq start (string-match re string start))
16601 (setq beg (match-beginning 0)
16602 end (match-end 0)
16603 t1 (save-match-data
16604 (org-parse-time-string (substring string beg end) t))
16605 with-hm (and (nth 1 t1) (nth 2 t1))
16606 inactive (equal (substring string beg (1+ beg)) "[")
16607 tf (funcall (if with-hm 'cdr 'car)
16608 org-time-stamp-custom-formats)
16609 time (org-fix-decoded-time t1)
16610 str (format-time-string
16611 (concat
16612 (if inactive "[" "<") (substring tf 1 -1)
16613 (if inactive "]" ">"))
16614 (apply 'encode-time time))
16615 string (replace-match str t t string)
16616 start (+ start (length str)))))))
16617 string)
16619 (defun org-fix-decoded-time (time)
16620 "Set 0 instead of nil for the first 6 elements of time.
16621 Don't touch the rest."
16622 (let ((n 0))
16623 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16625 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16627 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16628 "Difference between TIMESTAMP-STRING and now in days.
16629 If SECONDS is non-nil, return the difference in seconds."
16630 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16631 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16632 (funcall fdiff (current-time)))))
16634 (defun org-deadline-close (timestamp-string &optional ndays)
16635 "Is the time in TIMESTAMP-STRING close to the current date?"
16636 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16637 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16638 (not (org-entry-is-done-p))))
16640 (defun org-get-wdays (ts &optional delay zero-delay)
16641 "Get the deadline lead time appropriate for timestring TS.
16642 When DELAY is non-nil, get the delay time for scheduled items
16643 instead of the deadline lead time. When ZERO-DELAY is non-nil
16644 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16645 don't try to find the delay cookie in the scheduled timestamp."
16646 (let ((tv (if delay org-scheduled-delay-days
16647 org-deadline-warning-days)))
16648 (cond
16649 ((or (and delay (< tv 0))
16650 (and delay zero-delay (<= tv 0))
16651 (and (not delay) (<= tv 0)))
16652 ;; Enforce this value no matter what
16653 (- tv))
16654 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16655 ;; lead time is specified.
16656 (floor (* (string-to-number (match-string 1 ts))
16657 (cdr (assoc (match-string 2 ts)
16658 '(("d" . 1) ("w" . 7)
16659 ("m" . 30.4) ("y" . 365.25)
16660 ("h" . 0.041667)))))))
16661 ;; go for the default.
16662 (t tv))))
16664 (defun org-calendar-select-mouse (ev)
16665 "Return to `org-read-date' with the date currently selected.
16666 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16667 (interactive "e")
16668 (mouse-set-point ev)
16669 (when (calendar-cursor-to-date)
16670 (let* ((date (calendar-cursor-to-date))
16671 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16672 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16673 (if (active-minibuffer-window) (exit-minibuffer))))
16675 (defun org-check-deadlines (ndays)
16676 "Check if there are any deadlines due or past due.
16677 A deadline is considered due if it happens within `org-deadline-warning-days'
16678 days from today's date. If the deadline appears in an entry marked DONE,
16679 it is not shown. The prefix arg NDAYS can be used to test that many
16680 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16681 (interactive "P")
16682 (let* ((org-warn-days
16683 (cond
16684 ((equal ndays '(4)) 100000)
16685 (ndays (prefix-numeric-value ndays))
16686 (t (abs org-deadline-warning-days))))
16687 (case-fold-search nil)
16688 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16689 (callback
16690 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16692 (message "%d deadlines past-due or due within %d days"
16693 (org-occur regexp nil callback)
16694 org-warn-days)))
16696 (defsubst org-re-timestamp (type)
16697 "Return a regexp for timestamp TYPE.
16698 Allowed values for TYPE are:
16700 all: all timestamps
16701 active: only active timestamps (<...>)
16702 inactive: only inactive timestamps ([...])
16703 scheduled: only scheduled timestamps
16704 deadline: only deadline timestamps
16706 When TYPE is nil, fall back on returning a regexp that matches
16707 both scheduled and deadline timestamps."
16708 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16709 ((eq type 'active) org-ts-regexp)
16710 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16711 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16712 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16713 ((eq type 'scheduled-or-deadline)
16714 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16716 (defun org-check-before-date (date)
16717 "Check if there are deadlines or scheduled entries before DATE."
16718 (interactive (list (org-read-date)))
16719 (let ((case-fold-search nil)
16720 (regexp (org-re-timestamp org-ts-type))
16721 (callback
16722 (lambda () (time-less-p
16723 (org-time-string-to-time (match-string 1))
16724 (org-time-string-to-time date)))))
16725 (message "%d entries before %s"
16726 (org-occur regexp nil callback) date)))
16728 (defun org-check-after-date (date)
16729 "Check if there are deadlines or scheduled entries after DATE."
16730 (interactive (list (org-read-date)))
16731 (let ((case-fold-search nil)
16732 (regexp (org-re-timestamp org-ts-type))
16733 (callback
16734 (lambda () (not
16735 (time-less-p
16736 (org-time-string-to-time (match-string 1))
16737 (org-time-string-to-time date))))))
16738 (message "%d entries after %s"
16739 (org-occur regexp nil callback) date)))
16741 (defun org-check-dates-range (start-date end-date)
16742 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16743 (interactive (list (org-read-date nil nil nil "Range starts")
16744 (org-read-date nil nil nil "Range end")))
16745 (let ((case-fold-search nil)
16746 (regexp (org-re-timestamp org-ts-type))
16747 (callback
16748 (lambda ()
16749 (let ((match (match-string 1)))
16750 (and
16751 (not (time-less-p
16752 (org-time-string-to-time match)
16753 (org-time-string-to-time start-date)))
16754 (time-less-p
16755 (org-time-string-to-time match)
16756 (org-time-string-to-time end-date)))))))
16757 (message "%d entries between %s and %s"
16758 (org-occur regexp nil callback) start-date end-date)))
16760 (defun org-evaluate-time-range (&optional to-buffer)
16761 "Evaluate a time range by computing the difference between start and end.
16762 Normally the result is just printed in the echo area, but with prefix arg
16763 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16764 If the time range is actually in a table, the result is inserted into the
16765 next column.
16766 For time difference computation, a year is assumed to be exactly 365
16767 days in order to avoid rounding problems."
16768 (interactive "P")
16770 (org-clock-update-time-maybe)
16771 (save-excursion
16772 (unless (org-at-date-range-p t)
16773 (goto-char (point-at-bol))
16774 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16775 (if (not (org-at-date-range-p t))
16776 (error "Not at a time-stamp range, and none found in current line")))
16777 (let* ((ts1 (match-string 1))
16778 (ts2 (match-string 2))
16779 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16780 (match-end (match-end 0))
16781 (time1 (org-time-string-to-time ts1))
16782 (time2 (org-time-string-to-time ts2))
16783 (t1 (org-float-time time1))
16784 (t2 (org-float-time time2))
16785 (diff (abs (- t2 t1)))
16786 (negative (< (- t2 t1) 0))
16787 ;; (ys (floor (* 365 24 60 60)))
16788 (ds (* 24 60 60))
16789 (hs (* 60 60))
16790 (fy "%dy %dd %02d:%02d")
16791 (fy1 "%dy %dd")
16792 (fd "%dd %02d:%02d")
16793 (fd1 "%dd")
16794 (fh "%02d:%02d")
16795 y d h m align)
16796 (if havetime
16797 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16799 d (floor (/ diff ds)) diff (mod diff ds)
16800 h (floor (/ diff hs)) diff (mod diff hs)
16801 m (floor (/ diff 60)))
16802 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16804 d (floor (+ (/ diff ds) 0.5))
16805 h 0 m 0))
16806 (if (not to-buffer)
16807 (message "%s" (org-make-tdiff-string y d h m))
16808 (if (org-at-table-p)
16809 (progn
16810 (goto-char match-end)
16811 (setq align t)
16812 (and (looking-at " *|") (goto-char (match-end 0))))
16813 (goto-char match-end))
16814 (if (looking-at
16815 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16816 (replace-match ""))
16817 (if negative (insert " -"))
16818 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16819 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16820 (insert " " (format fh h m))))
16821 (if align (org-table-align))
16822 (message "Time difference inserted")))))
16824 (defun org-make-tdiff-string (y d h m)
16825 (let ((fmt "")
16826 (l nil))
16827 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16828 l (push y l)))
16829 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16830 l (push d l)))
16831 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16832 l (push h l)))
16833 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16834 l (push m l)))
16835 (apply 'format fmt (nreverse l))))
16837 (defun org-time-string-to-time (s &optional buffer pos)
16838 "Convert a timestamp string into internal time."
16839 (condition-case errdata
16840 (apply 'encode-time (org-parse-time-string s))
16841 (error (error "Bad timestamp `%s'%s\nError was: %s"
16842 s (if (not (and buffer pos))
16844 (format " at %d in buffer `%s'" pos buffer))
16845 (cdr errdata)))))
16847 (defun org-time-string-to-seconds (s)
16848 "Convert a timestamp string to a number of seconds."
16849 (org-float-time (org-time-string-to-time s)))
16851 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16852 "Convert a time stamp to an absolute day number.
16853 If there is a specifier for a cyclic time stamp, get the closest
16854 date to DAYNR.
16855 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16856 The variable `date' is bound by the calendar when this is called."
16857 (cond
16858 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16859 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16860 daynr
16861 (+ daynr 1000)))
16862 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16863 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16864 (time-to-days (current-time))) (match-string 0 s)
16865 prefer show-all))
16866 (t (time-to-days
16867 (condition-case errdata
16868 (apply 'encode-time (org-parse-time-string s))
16869 (error (error "Bad timestamp `%s'%s\nError was: %s"
16870 s (if (not (and buffer pos))
16872 (format " at %d in buffer `%s'" pos buffer))
16873 (cdr errdata))))))))
16875 (defun org-days-to-iso-week (days)
16876 "Return the iso week number."
16877 (require 'cal-iso)
16878 (car (calendar-iso-from-absolute days)))
16880 (defun org-small-year-to-year (year)
16881 "Convert 2-digit years into 4-digit years.
16882 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16883 The year 2000 cannot be abbreviated. Any year larger than 99
16884 is returned unchanged."
16885 (if (< year 38)
16886 (setq year (+ 2000 year))
16887 (if (< year 100)
16888 (setq year (+ 1900 year))))
16889 year)
16891 (defun org-time-from-absolute (d)
16892 "Return the time corresponding to date D.
16893 D may be an absolute day number, or a calendar-type list (month day year)."
16894 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16895 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16897 (defun org-calendar-holiday ()
16898 "List of holidays, for Diary display in Org-mode."
16899 (require 'holidays)
16900 (let ((hl (funcall
16901 (if (fboundp 'calendar-check-holidays)
16902 'calendar-check-holidays 'check-calendar-holidays) date)))
16903 (if hl (mapconcat 'identity hl "; "))))
16905 (defun org-diary-sexp-entry (sexp entry date)
16906 "Process a SEXP diary ENTRY for DATE."
16907 (require 'diary-lib)
16908 (let ((result (if calendar-debug-sexp
16909 (let ((stack-trace-on-error t))
16910 (eval (car (read-from-string sexp))))
16911 (condition-case nil
16912 (eval (car (read-from-string sexp)))
16913 (error
16914 (beep)
16915 (message "Bad sexp at line %d in %s: %s"
16916 (org-current-line)
16917 (buffer-file-name) sexp)
16918 (sleep-for 2))))))
16919 (cond ((stringp result) (split-string result "; "))
16920 ((and (consp result)
16921 (not (consp (cdr result)))
16922 (stringp (cdr result))) (cdr result))
16923 ((and (consp result)
16924 (stringp (car result))) result)
16925 (result entry))))
16927 (defun org-diary-to-ical-string (frombuf)
16928 "Get iCalendar entries from diary entries in buffer FROMBUF.
16929 This uses the icalendar.el library."
16930 (let* ((tmpdir (if (featurep 'xemacs)
16931 (temp-directory)
16932 temporary-file-directory))
16933 (tmpfile (make-temp-name
16934 (expand-file-name "orgics" tmpdir)))
16935 buf rtn b e)
16936 (with-current-buffer frombuf
16937 (icalendar-export-region (point-min) (point-max) tmpfile)
16938 (setq buf (find-buffer-visiting tmpfile))
16939 (set-buffer buf)
16940 (goto-char (point-min))
16941 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16942 (setq b (match-beginning 0)))
16943 (goto-char (point-max))
16944 (if (re-search-backward "^END:VEVENT" nil t)
16945 (setq e (match-end 0)))
16946 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16947 (kill-buffer buf)
16948 (delete-file tmpfile)
16949 rtn))
16951 (defun org-closest-date (start current change prefer show-all)
16952 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16953 When PREFER is `past', return a date that is either CURRENT or past.
16954 When PREFER is `future', return a date that is either CURRENT or future.
16955 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16956 ;; Make the proper lists from the dates
16957 (catch 'exit
16958 (let ((a1 '(("h" . hour)
16959 ("d" . day)
16960 ("w" . week)
16961 ("m" . month)
16962 ("y" . year)))
16963 (shour (nth 2 (org-parse-time-string start)))
16964 dn dw sday cday n1 n2 n0
16965 d m y y1 y2 date1 date2 nmonths nm ny m2)
16967 (setq start (org-date-to-gregorian start)
16968 current (org-date-to-gregorian
16969 (if show-all
16970 current
16971 (time-to-days (current-time))))
16972 sday (calendar-absolute-from-gregorian start)
16973 cday (calendar-absolute-from-gregorian current))
16975 (if (<= cday sday) (throw 'exit sday))
16977 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16978 (setq dn (string-to-number (match-string 1 change))
16979 dw (cdr (assoc (match-string 2 change) a1)))
16980 (error "Invalid change specifier: %s" change))
16981 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16982 (cond
16983 ((eq dw 'hour)
16984 (let ((missing-hours
16985 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16986 dn)))
16987 (setq n1 (if (zerop missing-hours) cday
16988 (- cday (1+ (floor (/ missing-hours 24)))))
16989 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16990 ((eq dw 'day)
16991 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16992 n2 (+ n1 dn)))
16993 ((eq dw 'year)
16994 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16995 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16996 (setq date1 (list m d y1)
16997 n1 (calendar-absolute-from-gregorian date1)
16998 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16999 n2 (calendar-absolute-from-gregorian date2)))
17000 ((eq dw 'month)
17001 ;; approx number of month between the two dates
17002 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17003 ;; How often does dn fit in there?
17004 (setq d (nth 1 start) m (car start) y (nth 2 start)
17005 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17006 m (+ m nm)
17007 ny (floor (/ m 12))
17008 y (+ y ny)
17009 m (- m (* ny 12)))
17010 (while (> m 12) (setq m (- m 12) y (1+ y)))
17011 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17012 (setq m2 (+ m dn) y2 y)
17013 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17014 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17015 (while (<= n2 cday)
17016 (setq n1 n2 m m2 y y2)
17017 (setq m2 (+ m dn) y2 y)
17018 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17019 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17020 ;; Make sure n1 is the earlier date
17021 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17022 (if show-all
17023 (cond
17024 ((eq prefer 'past) (if (= cday n2) n2 n1))
17025 ((eq prefer 'future) (if (= cday n1) n1 n2))
17026 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17027 (cond
17028 ((eq prefer 'past) (if (= cday n2) n2 n1))
17029 ((eq prefer 'future) (if (= cday n1) n1 n2))
17030 (t (if (= cday n1) n1 n2)))))))
17032 (defun org-date-to-gregorian (date)
17033 "Turn any specification of DATE into a Gregorian date for the calendar."
17034 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17035 ((and (listp date) (= (length date) 3)) date)
17036 ((stringp date)
17037 (setq date (org-parse-time-string date))
17038 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17039 ((listp date)
17040 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17042 (defun org-parse-time-string (s &optional nodefault)
17043 "Parse the standard Org-mode time string.
17044 This should be a lot faster than the normal `parse-time-string'.
17045 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17046 hour and minute fields will be nil if not given."
17047 (cond ((string-match org-ts-regexp0 s)
17048 (list 0
17049 (if (or (match-beginning 8) (not nodefault))
17050 (string-to-number (or (match-string 8 s) "0")))
17051 (if (or (match-beginning 7) (not nodefault))
17052 (string-to-number (or (match-string 7 s) "0")))
17053 (string-to-number (match-string 4 s))
17054 (string-to-number (match-string 3 s))
17055 (string-to-number (match-string 2 s))
17056 nil nil nil))
17057 ((string-match "^<[^>]+>$" s)
17058 (decode-time (seconds-to-time (org-matcher-time s))))
17059 (t (error "Not a standard Org-mode time string: %s" s))))
17061 (defun org-timestamp-up (&optional arg)
17062 "Increase the date item at the cursor by one.
17063 If the cursor is on the year, change the year. If it is on the month,
17064 the day or the time, change that.
17065 With prefix ARG, change by that many units."
17066 (interactive "p")
17067 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17069 (defun org-timestamp-down (&optional arg)
17070 "Decrease the date item at the cursor by one.
17071 If the cursor is on the year, change the year. If it is on the month,
17072 the day or the time, change that.
17073 With prefix ARG, change by that many units."
17074 (interactive "p")
17075 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17077 (defun org-timestamp-up-day (&optional arg)
17078 "Increase the date in the time stamp by one day.
17079 With prefix ARG, change that many days."
17080 (interactive "p")
17081 (if (and (not (org-at-timestamp-p t))
17082 (org-at-heading-p))
17083 (org-todo 'up)
17084 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17086 (defun org-timestamp-down-day (&optional arg)
17087 "Decrease the date in the time stamp by one day.
17088 With prefix ARG, change that many days."
17089 (interactive "p")
17090 (if (and (not (org-at-timestamp-p t))
17091 (org-at-heading-p))
17092 (org-todo 'down)
17093 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17095 (defun org-at-timestamp-p (&optional inactive-ok)
17096 "Determine if the cursor is in or at a timestamp."
17097 (interactive)
17098 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17099 (pos (point))
17100 (ans (or (looking-at tsr)
17101 (save-excursion
17102 (skip-chars-backward "^[<\n\r\t")
17103 (if (> (point) (point-min)) (backward-char 1))
17104 (and (looking-at tsr)
17105 (> (- (match-end 0) pos) -1))))))
17106 (and ans
17107 (boundp 'org-ts-what)
17108 (setq org-ts-what
17109 (cond
17110 ((= pos (match-beginning 0)) 'bracket)
17111 ;; Point is considered to be "on the bracket" whether
17112 ;; it's really on it or right after it.
17113 ((= pos (1- (match-end 0))) 'bracket)
17114 ((= pos (match-end 0)) 'after)
17115 ((org-pos-in-match-range pos 2) 'year)
17116 ((org-pos-in-match-range pos 3) 'month)
17117 ((org-pos-in-match-range pos 7) 'hour)
17118 ((org-pos-in-match-range pos 8) 'minute)
17119 ((or (org-pos-in-match-range pos 4)
17120 (org-pos-in-match-range pos 5)) 'day)
17121 ((and (> pos (or (match-end 8) (match-end 5)))
17122 (< pos (match-end 0)))
17123 (- pos (or (match-end 8) (match-end 5))))
17124 (t 'day))))
17125 ans))
17127 (defun org-toggle-timestamp-type ()
17128 "Toggle the type (<active> or [inactive]) of a time stamp."
17129 (interactive)
17130 (when (org-at-timestamp-p t)
17131 (let ((beg (match-beginning 0)) (end (match-end 0))
17132 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17133 (save-excursion
17134 (goto-char beg)
17135 (while (re-search-forward "[][<>]" end t)
17136 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17137 t t)))
17138 (message "Timestamp is now %sactive"
17139 (if (equal (char-after beg) ?<) "" "in")))))
17141 (defun org-at-clock-log-p nil
17142 "Is the cursor on the clock log line?"
17143 (save-excursion
17144 (move-beginning-of-line 1)
17145 (looking-at "^[ \t]*CLOCK:")))
17147 (defvar org-clock-history) ; defined in org-clock.el
17148 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17149 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17150 "Change the date in the time stamp at point.
17151 The date will be changed by N times WHAT. WHAT can be `day', `month',
17152 `year', `minute', `second'. If WHAT is not given, the cursor position
17153 in the timestamp determines what will be changed.
17154 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17155 (let ((origin (point)) origin-cat
17156 with-hm inactive
17157 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17158 org-ts-what
17159 extra rem
17160 ts time time0 fixnext clrgx)
17161 (if (not (org-at-timestamp-p t))
17162 (error "Not at a timestamp"))
17163 (if (and (not what) (eq org-ts-what 'bracket))
17164 (org-toggle-timestamp-type)
17165 ;; Point isn't on brackets. Remember the part of the time-stamp
17166 ;; the point was in. Indeed, size of time-stamps may change,
17167 ;; but point must be kept in the same category nonetheless.
17168 (setq origin-cat org-ts-what)
17169 (if (and (not what) (not (eq org-ts-what 'day))
17170 org-display-custom-times
17171 (get-text-property (point) 'display)
17172 (not (get-text-property (1- (point)) 'display)))
17173 (setq org-ts-what 'day))
17174 (setq org-ts-what (or what org-ts-what)
17175 inactive (= (char-after (match-beginning 0)) ?\[)
17176 ts (match-string 0))
17177 (replace-match "")
17178 (when (string-match
17179 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17181 (setq extra (match-string 1 ts))
17182 (if suppress-tmp-delay
17183 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17184 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17185 (setq with-hm t))
17186 (setq time0 (org-parse-time-string ts))
17187 (when (and updown
17188 (eq org-ts-what 'minute)
17189 (not current-prefix-arg))
17190 ;; This looks like s-up and s-down. Change by one rounding step.
17191 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17192 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17193 (setcar (cdr time0) (+ (nth 1 time0)
17194 (if (> n 0) (- rem) (- dm rem))))))
17195 (setq time
17196 (encode-time (or (car time0) 0)
17197 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17198 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17199 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17200 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17201 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17202 (nthcdr 6 time0)))
17203 (when (and (member org-ts-what '(hour minute))
17204 extra
17205 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17206 (setq extra (org-modify-ts-extra
17207 extra
17208 (if (eq org-ts-what 'hour) 2 5)
17209 n dm)))
17210 (when (integerp org-ts-what)
17211 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17212 (if (eq what 'calendar)
17213 (let ((cal-date (org-get-date-from-calendar)))
17214 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17215 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17216 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17217 (setcar time0 (or (car time0) 0))
17218 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17219 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17220 (setq time (apply 'encode-time time0))))
17221 ;; Insert the new time-stamp, and ensure point stays in the same
17222 ;; category as before (i.e. not after the last position in that
17223 ;; category).
17224 (let ((pos (point)))
17225 ;; Stay before inserted string. `save-excursion' is of no use.
17226 (setq org-last-changed-timestamp
17227 (org-insert-time-stamp time with-hm inactive nil nil extra))
17228 (goto-char pos))
17229 (save-match-data
17230 (looking-at org-ts-regexp3)
17231 (goto-char (cond
17232 ;; `day' category ends before `hour' if any, or at
17233 ;; the end of the day name.
17234 ((eq origin-cat 'day)
17235 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17236 ((eq origin-cat 'hour) (min (match-end 7) origin))
17237 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17238 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17239 ;; `year' and `month' have both fixed size: point
17240 ;; couldn't have moved into another part.
17241 (t origin))))
17242 ;; Update clock if on a CLOCK line.
17243 (org-clock-update-time-maybe)
17244 ;; Maybe adjust the closest clock in `org-clock-history'
17245 (when org-clock-adjust-closest
17246 (if (not (and (org-at-clock-log-p)
17247 (< 1 (length (delq nil (mapcar 'marker-position
17248 org-clock-history))))))
17249 (message "No clock to adjust")
17250 (cond ((save-excursion ; fix previous clock?
17251 (re-search-backward org-ts-regexp0 nil t)
17252 (org-looking-back (concat org-clock-string " \\[")))
17253 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17254 ((save-excursion ; fix next clock?
17255 (re-search-backward org-ts-regexp0 nil t)
17256 (looking-at (concat org-ts-regexp0 "\\] =>")))
17257 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17258 (save-window-excursion
17259 ;; Find closest clock to point, adjust the previous/next one in history
17260 (let* ((p (save-excursion (org-back-to-heading t)))
17261 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17262 (clfixnth
17263 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17264 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17265 (if (not clfixpos)
17266 (message "No clock to adjust")
17267 (save-excursion
17268 (org-goto-marker-or-bmk clfixpos)
17269 (org-show-subtree)
17270 (when (re-search-forward clrgx nil t)
17271 (goto-char (match-beginning 1))
17272 (let (org-clock-adjust-closest)
17273 (org-timestamp-change n org-ts-what updown))
17274 (message "Clock adjusted in %s for heading: %s"
17275 (file-name-nondirectory (buffer-file-name))
17276 (org-get-heading t t)))))))))
17277 ;; Try to recenter the calendar window, if any.
17278 (if (and org-calendar-follow-timestamp-change
17279 (get-buffer-window "*Calendar*" t)
17280 (memq org-ts-what '(day month year)))
17281 (org-recenter-calendar (time-to-days time))))))
17283 (defun org-modify-ts-extra (s pos n dm)
17284 "Change the different parts of the lead-time and repeat fields in timestamp."
17285 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17286 ng h m new rem)
17287 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17288 (cond
17289 ((or (org-pos-in-match-range pos 2)
17290 (org-pos-in-match-range pos 3))
17291 (setq m (string-to-number (match-string 3 s))
17292 h (string-to-number (match-string 2 s)))
17293 (if (org-pos-in-match-range pos 2)
17294 (setq h (+ h n))
17295 (setq n (* dm (org-no-warnings (signum n))))
17296 (when (not (= 0 (setq rem (% m dm))))
17297 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17298 (setq m (+ m n)))
17299 (if (< m 0) (setq m (+ m 60) h (1- h)))
17300 (if (> m 59) (setq m (- m 60) h (1+ h)))
17301 (setq h (min 24 (max 0 h)))
17302 (setq ng 1 new (format "-%02d:%02d" h m)))
17303 ((org-pos-in-match-range pos 6)
17304 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17305 ((org-pos-in-match-range pos 5)
17306 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17308 ((org-pos-in-match-range pos 9)
17309 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17310 ((org-pos-in-match-range pos 8)
17311 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17313 (when ng
17314 (setq s (concat
17315 (substring s 0 (match-beginning ng))
17317 (substring s (match-end ng))))))
17320 (defun org-recenter-calendar (date)
17321 "If the calendar is visible, recenter it to DATE."
17322 (let ((cwin (get-buffer-window "*Calendar*" t)))
17323 (when cwin
17324 (let ((calendar-move-hook nil))
17325 (with-selected-window cwin
17326 (calendar-goto-date (if (listp date) date
17327 (calendar-gregorian-from-absolute date))))))))
17329 (defun org-goto-calendar (&optional arg)
17330 "Go to the Emacs calendar at the current date.
17331 If there is a time stamp in the current line, go to that date.
17332 A prefix ARG can be used to force the current date."
17333 (interactive "P")
17334 (let ((tsr org-ts-regexp) diff
17335 (calendar-move-hook nil)
17336 (calendar-view-holidays-initially-flag nil)
17337 (calendar-view-diary-initially-flag nil))
17338 (if (or (org-at-timestamp-p)
17339 (save-excursion
17340 (beginning-of-line 1)
17341 (looking-at (concat ".*" tsr))))
17342 (let ((d1 (time-to-days (current-time)))
17343 (d2 (time-to-days
17344 (org-time-string-to-time (match-string 1)))))
17345 (setq diff (- d2 d1))))
17346 (calendar)
17347 (calendar-goto-today)
17348 (if (and diff (not arg)) (calendar-forward-day diff))))
17350 (defun org-get-date-from-calendar ()
17351 "Return a list (month day year) of date at point in calendar."
17352 (with-current-buffer "*Calendar*"
17353 (save-match-data
17354 (calendar-cursor-to-date))))
17356 (defun org-date-from-calendar ()
17357 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17358 If there is already a time stamp at the cursor position, update it."
17359 (interactive)
17360 (if (org-at-timestamp-p t)
17361 (org-timestamp-change 0 'calendar)
17362 (let ((cal-date (org-get-date-from-calendar)))
17363 (org-insert-time-stamp
17364 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17366 (defcustom org-effort-durations
17367 `(("h" . 60)
17368 ("d" . ,(* 60 8))
17369 ("w" . ,(* 60 8 5))
17370 ("m" . ,(* 60 8 5 4))
17371 ("y" . ,(* 60 8 5 40)))
17372 "Conversion factor to minutes for an effort modifier.
17374 Each entry has the form (MODIFIER . MINUTES).
17376 In an effort string, a number followed by MODIFIER is multiplied
17377 by the specified number of MINUTES to obtain an effort in
17378 minutes.
17380 For example, if the value of this variable is ((\"hours\" . 60)), then an
17381 effort string \"2hours\" is equivalent to 120 minutes."
17382 :group 'org-agenda
17383 :version "24.1"
17384 :type '(alist :key-type (string :tag "Modifier")
17385 :value-type (number :tag "Minutes")))
17387 (defun org-minutes-to-clocksum-string (m)
17388 "Format number of minutes as a clocksum string.
17389 The format is determined by `org-time-clocksum-format',
17390 `org-time-clocksum-use-fractional' and
17391 `org-time-clocksum-fractional-format' and
17392 `org-time-clocksum-use-effort-durations'."
17393 (let ((clocksum "") h d w mo y fmt n)
17394 (setq h (if org-time-clocksum-use-effort-durations
17395 (cdr (assoc "h" org-effort-durations)) 60)
17396 d (if org-time-clocksum-use-effort-durations
17397 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17398 w (if org-time-clocksum-use-effort-durations
17399 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17400 mo (if org-time-clocksum-use-effort-durations
17401 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17402 y (if org-time-clocksum-use-effort-durations
17403 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17404 ;; fractional format
17405 (if org-time-clocksum-use-fractional
17406 (cond
17407 ;; single format string
17408 ((stringp org-time-clocksum-fractional-format)
17409 (format org-time-clocksum-fractional-format (/ m (float h))))
17410 ;; choice of fractional formats for different time units
17411 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17412 (> (/ (truncate m) (* y d h)) 0))
17413 (format fmt (/ m (* y d (float h)))))
17414 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17415 (> (/ (truncate m) (* mo d h)) 0))
17416 (format fmt (/ m (* mo d (float h)))))
17417 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17418 (> (/ (truncate m) (* w d h)) 0))
17419 (format fmt (/ m (* w d (float h)))))
17420 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17421 (> (/ (truncate m) (* d h)) 0))
17422 (format fmt (/ m (* d (float h)))))
17423 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17424 (> (/ (truncate m) h) 0))
17425 (format fmt (/ m (float h))))
17426 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17427 (format fmt m))
17428 ;; fall back to smallest time unit with a format
17429 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17430 (format fmt (/ m (float h))))
17431 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17432 (format fmt (/ m (* d (float h)))))
17433 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17434 (format fmt (/ m (* w d (float h)))))
17435 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17436 (format fmt (/ m (* mo d (float h)))))
17437 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17438 (format fmt (/ m (* y d (float h))))))
17439 ;; standard (non-fractional) format, with single format string
17440 (if (stringp org-time-clocksum-format)
17441 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17442 ;; separate formats components
17443 (and (setq fmt (plist-get org-time-clocksum-format :years))
17444 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17445 (plist-get org-time-clocksum-format :require-years))
17446 (setq clocksum (concat clocksum (format fmt n))
17447 m (- m (* n y d h))))
17448 (and (setq fmt (plist-get org-time-clocksum-format :months))
17449 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17450 (plist-get org-time-clocksum-format :require-months))
17451 (setq clocksum (concat clocksum (format fmt n))
17452 m (- m (* n mo d h))))
17453 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17454 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17455 (plist-get org-time-clocksum-format :require-weeks))
17456 (setq clocksum (concat clocksum (format fmt n))
17457 m (- m (* n w d h))))
17458 (and (setq fmt (plist-get org-time-clocksum-format :days))
17459 (or (> (setq n (/ (truncate m) (* d h))) 0)
17460 (plist-get org-time-clocksum-format :require-days))
17461 (setq clocksum (concat clocksum (format fmt n))
17462 m (- m (* n d h))))
17463 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17464 (or (> (setq n (/ (truncate m) h)) 0)
17465 (plist-get org-time-clocksum-format :require-hours))
17466 (setq clocksum (concat clocksum (format fmt n))
17467 m (- m (* n h))))
17468 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17469 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17470 (setq clocksum (concat clocksum (format fmt m))))
17471 ;; return formatted time duration
17472 clocksum))))
17474 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17475 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17476 "Org mode version 8.0")
17478 (defun org-hours-to-clocksum-string (n)
17479 (org-minutes-to-clocksum-string (* n 60)))
17481 (defun org-hh:mm-string-to-minutes (s)
17482 "Convert a string H:MM to a number of minutes.
17483 If the string is just a number, interpret it as minutes.
17484 In fact, the first hh:mm or number in the string will be taken,
17485 there can be extra stuff in the string.
17486 If no number is found, the return value is 0."
17487 (cond
17488 ((integerp s) s)
17489 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17490 (+ (* (string-to-number (match-string 1 s)) 60)
17491 (string-to-number (match-string 2 s))))
17492 ((string-match "\\([0-9]+\\)" s)
17493 (string-to-number (match-string 1 s)))
17494 (t 0)))
17496 (defcustom org-image-actual-width t
17497 "Should we use the actual width of images when inlining them?
17499 When set to `t', always use the image width.
17501 When set to a number, use imagemagick (when available) to set
17502 the image's width to this value.
17504 When set to a number in a list, try to get the width from any
17505 #+ATTR.* keyword if it matches a width specification like
17507 #+ATTR_HTML: :width 300px
17509 and fall back on that number if none is found.
17511 When set to nil, try to get the width from an #+ATTR.* keyword
17512 and fall back on the original width if none is found.
17514 This requires Emacs >= 24.1, build with imagemagick support."
17515 :group 'org-appearance
17516 :version "24.4"
17517 :package-version '(Org . "8.0")
17518 :type '(choice
17519 (const :tag "Use the image width" t)
17520 (integer :tag "Use a number of pixels")
17521 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17522 (const :tag "Use #+ATTR* or don't resize" nil)))
17524 (defcustom org-agenda-inhibit-startup nil
17525 "Inhibit startup when preparing agenda buffers.
17526 When this variable is `t' (the default), the initialization of
17527 the Org agenda buffers is inhibited: e.g. the visibility state
17528 is not set, the tables are not re-aligned, etc."
17529 :type 'boolean
17530 :version "24.3"
17531 :group 'org-agenda)
17533 (defun org-duration-string-to-minutes (s &optional output-to-string)
17534 "Convert a duration string S to minutes.
17536 A bare number is interpreted as minutes, modifiers can be set by
17537 customizing `org-effort-durations' (which see).
17539 Entries containing a colon are interpreted as H:MM by
17540 `org-hh:mm-string-to-minutes'."
17541 (let ((result 0)
17542 (re (concat "\\([0-9.]+\\) *\\("
17543 (regexp-opt (mapcar 'car org-effort-durations))
17544 "\\)")))
17545 (while (string-match re s)
17546 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17547 (string-to-number (match-string 1 s))))
17548 (setq s (replace-match "" nil t s)))
17549 (setq result (floor result))
17550 (incf result (org-hh:mm-string-to-minutes s))
17551 (if output-to-string (number-to-string result) result)))
17553 ;;;; Files
17555 (defun org-save-all-org-buffers ()
17556 "Save all Org-mode buffers without user confirmation."
17557 (interactive)
17558 (message "Saving all Org-mode buffers...")
17559 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17560 (when (featurep 'org-id) (org-id-locations-save))
17561 (message "Saving all Org-mode buffers... done"))
17563 (defun org-revert-all-org-buffers ()
17564 "Revert all Org-mode buffers.
17565 Prompt for confirmation when there are unsaved changes.
17566 Be sure you know what you are doing before letting this function
17567 overwrite your changes.
17569 This function is useful in a setup where one tracks org files
17570 with a version control system, to revert on one machine after pulling
17571 changes from another. I believe the procedure must be like this:
17573 1. M-x org-save-all-org-buffers
17574 2. Pull changes from the other machine, resolve conflicts
17575 3. M-x org-revert-all-org-buffers"
17576 (interactive)
17577 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17578 (error "Abort"))
17579 (save-excursion
17580 (save-window-excursion
17581 (mapc
17582 (lambda (b)
17583 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17584 (with-current-buffer b buffer-file-name))
17585 (org-pop-to-buffer-same-window b)
17586 (revert-buffer t 'no-confirm)))
17587 (buffer-list))
17588 (when (and (featurep 'org-id) org-id-track-globally)
17589 (org-id-locations-load)))))
17591 ;;;; Agenda files
17593 ;;;###autoload
17594 (defun org-switchb (&optional arg)
17595 "Switch between Org buffers.
17596 With one prefix argument, restrict available buffers to files.
17597 With two prefix arguments, restrict available buffers to agenda files.
17599 Defaults to `iswitchb' for buffer name completion.
17600 Set `org-completion-use-ido' to make it use ido instead."
17601 (interactive "P")
17602 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17603 ((equal arg '(16)) (org-buffer-list 'agenda))
17604 (t (org-buffer-list))))
17605 (org-completion-use-iswitchb org-completion-use-iswitchb)
17606 (org-completion-use-ido org-completion-use-ido))
17607 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17608 (setq org-completion-use-iswitchb t))
17609 (org-pop-to-buffer-same-window
17610 (org-icompleting-read "Org buffer: "
17611 (mapcar 'list (mapcar 'buffer-name blist))
17612 nil t))))
17614 ;;; Define some older names previously used for this functionality
17615 ;;;###autoload
17616 (defalias 'org-ido-switchb 'org-switchb)
17617 ;;;###autoload
17618 (defalias 'org-iswitchb 'org-switchb)
17620 (defun org-buffer-list (&optional predicate exclude-tmp)
17621 "Return a list of Org buffers.
17622 PREDICATE can be `export', `files' or `agenda'.
17624 export restrict the list to Export buffers.
17625 files restrict the list to buffers visiting Org files.
17626 agenda restrict the list to buffers visiting agenda files.
17628 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17629 (let* ((bfn nil)
17630 (agenda-files (and (eq predicate 'agenda)
17631 (mapcar 'file-truename (org-agenda-files t))))
17632 (filter
17633 (cond
17634 ((eq predicate 'files)
17635 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17636 ((eq predicate 'export)
17637 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17638 ((eq predicate 'agenda)
17639 (lambda (b)
17640 (with-current-buffer b
17641 (and (derived-mode-p 'org-mode)
17642 (setq bfn (buffer-file-name b))
17643 (member (file-truename bfn) agenda-files)))))
17644 (t (lambda (b) (with-current-buffer b
17645 (or (derived-mode-p 'org-mode)
17646 (string-match "\*Org .*Export"
17647 (buffer-name b)))))))))
17648 (delq nil
17649 (mapcar
17650 (lambda(b)
17651 (if (and (funcall filter b)
17652 (or (not exclude-tmp)
17653 (not (string-match "tmp" (buffer-name b)))))
17655 nil))
17656 (buffer-list)))))
17658 (defun org-agenda-files (&optional unrestricted archives)
17659 "Get the list of agenda files.
17660 Optional UNRESTRICTED means return the full list even if a restriction
17661 is currently in place.
17662 When ARCHIVES is t, include all archive files that are really being
17663 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17664 `org-agenda-archives-mode' is t."
17665 (let ((files
17666 (cond
17667 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17668 ((stringp org-agenda-files) (org-read-agenda-file-list))
17669 ((listp org-agenda-files) org-agenda-files)
17670 (t (error "Invalid value of `org-agenda-files'")))))
17671 (setq files (apply 'append
17672 (mapcar (lambda (f)
17673 (if (file-directory-p f)
17674 (directory-files
17675 f t org-agenda-file-regexp)
17676 (list f)))
17677 files)))
17678 (when org-agenda-skip-unavailable-files
17679 (setq files (delq nil
17680 (mapcar (function
17681 (lambda (file)
17682 (and (file-readable-p file) file)))
17683 files))))
17684 (when (or (eq archives t)
17685 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17686 (setq files (org-add-archive-files files)))
17687 files))
17689 (defun org-agenda-file-p (&optional file)
17690 "Return non-nil, if FILE is an agenda file.
17691 If FILE is omitted, use the file associated with the current
17692 buffer."
17693 (member (or file (buffer-file-name))
17694 (org-agenda-files t)))
17696 (defun org-edit-agenda-file-list ()
17697 "Edit the list of agenda files.
17698 Depending on setup, this either uses customize to edit the variable
17699 `org-agenda-files', or it visits the file that is holding the list. In the
17700 latter case, the buffer is set up in a way that saving it automatically kills
17701 the buffer and restores the previous window configuration."
17702 (interactive)
17703 (if (stringp org-agenda-files)
17704 (let ((cw (current-window-configuration)))
17705 (find-file org-agenda-files)
17706 (org-set-local 'org-window-configuration cw)
17707 (org-add-hook 'after-save-hook
17708 (lambda ()
17709 (set-window-configuration
17710 (prog1 org-window-configuration
17711 (kill-buffer (current-buffer))))
17712 (org-install-agenda-files-menu)
17713 (message "New agenda file list installed"))
17714 nil 'local)
17715 (message "%s" (substitute-command-keys
17716 "Edit list and finish with \\[save-buffer]")))
17717 (customize-variable 'org-agenda-files)))
17719 (defun org-store-new-agenda-file-list (list)
17720 "Set new value for the agenda file list and save it correctly."
17721 (if (stringp org-agenda-files)
17722 (let ((fe (org-read-agenda-file-list t)) b u)
17723 (while (setq b (find-buffer-visiting org-agenda-files))
17724 (kill-buffer b))
17725 (with-temp-file org-agenda-files
17726 (insert
17727 (mapconcat
17728 (lambda (f) ;; Keep un-expanded entries.
17729 (if (setq u (assoc f fe))
17730 (cdr u)
17732 list "\n")
17733 "\n")))
17734 (let ((org-mode-hook nil) (org-inhibit-startup t)
17735 (org-insert-mode-line-in-empty-file nil))
17736 (setq org-agenda-files list)
17737 (customize-save-variable 'org-agenda-files org-agenda-files))))
17739 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17740 "Read the list of agenda files from a file.
17741 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17742 filenames, used by `org-store-new-agenda-file-list' to write back
17743 un-expanded file names."
17744 (when (file-directory-p org-agenda-files)
17745 (error "`org-agenda-files' cannot be a single directory"))
17746 (when (stringp org-agenda-files)
17747 (with-temp-buffer
17748 (insert-file-contents org-agenda-files)
17749 (mapcar
17750 (lambda (f)
17751 (let ((e (expand-file-name (substitute-in-file-name f)
17752 org-directory)))
17753 (if pair-with-expansion
17754 (cons e f)
17755 e)))
17756 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17758 ;;;###autoload
17759 (defun org-cycle-agenda-files ()
17760 "Cycle through the files in `org-agenda-files'.
17761 If the current buffer visits an agenda file, find the next one in the list.
17762 If the current buffer does not, find the first agenda file."
17763 (interactive)
17764 (let* ((fs (org-agenda-files t))
17765 (files (append fs (list (car fs))))
17766 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17767 file)
17768 (unless files (error "No agenda files"))
17769 (catch 'exit
17770 (while (setq file (pop files))
17771 (if (equal (file-truename file) tcf)
17772 (when (car files)
17773 (find-file (car files))
17774 (throw 'exit t))))
17775 (find-file (car fs)))
17776 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17778 (defun org-agenda-file-to-front (&optional to-end)
17779 "Move/add the current file to the top of the agenda file list.
17780 If the file is not present in the list, it is added to the front. If it is
17781 present, it is moved there. With optional argument TO-END, add/move to the
17782 end of the list."
17783 (interactive "P")
17784 (let ((org-agenda-skip-unavailable-files nil)
17785 (file-alist (mapcar (lambda (x)
17786 (cons (file-truename x) x))
17787 (org-agenda-files t)))
17788 (ctf (file-truename
17789 (or buffer-file-name
17790 (error "Please save the current buffer to a file"))))
17791 x had)
17792 (setq x (assoc ctf file-alist) had x)
17794 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17795 (if to-end
17796 (setq file-alist (append (delq x file-alist) (list x)))
17797 (setq file-alist (cons x (delq x file-alist))))
17798 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17799 (org-install-agenda-files-menu)
17800 (message "File %s to %s of agenda file list"
17801 (if had "moved" "added") (if to-end "end" "front"))))
17803 (defun org-remove-file (&optional file)
17804 "Remove current file from the list of files in variable `org-agenda-files'.
17805 These are the files which are being checked for agenda entries.
17806 Optional argument FILE means use this file instead of the current."
17807 (interactive)
17808 (let* ((org-agenda-skip-unavailable-files nil)
17809 (file (or file buffer-file-name
17810 (error "Current buffer does not visit a file")))
17811 (true-file (file-truename file))
17812 (afile (abbreviate-file-name file))
17813 (files (delq nil (mapcar
17814 (lambda (x)
17815 (if (equal true-file
17816 (file-truename x))
17817 nil x))
17818 (org-agenda-files t)))))
17819 (if (not (= (length files) (length (org-agenda-files t))))
17820 (progn
17821 (org-store-new-agenda-file-list files)
17822 (org-install-agenda-files-menu)
17823 (message "Removed file: %s" afile))
17824 (message "File was not in list: %s (not removed)" afile))))
17826 (defun org-file-menu-entry (file)
17827 (vector file (list 'find-file file) t))
17829 (defun org-check-agenda-file (file)
17830 "Make sure FILE exists. If not, ask user what to do."
17831 (when (not (file-exists-p file))
17832 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17833 (abbreviate-file-name file))
17834 (let ((r (downcase (read-char-exclusive))))
17835 (cond
17836 ((equal r ?r)
17837 (org-remove-file file)
17838 (throw 'nextfile t))
17839 (t (error "Abort"))))))
17841 (defun org-get-agenda-file-buffer (file)
17842 "Get a buffer visiting FILE. If the buffer needs to be created, add
17843 it to the list of buffers which might be released later."
17844 (let ((buf (org-find-base-buffer-visiting file)))
17845 (if buf
17846 buf ; just return it
17847 ;; Make a new buffer and remember it
17848 (setq buf (find-file-noselect file))
17849 (if buf (push buf org-agenda-new-buffers))
17850 buf)))
17852 (defun org-release-buffers (blist)
17853 "Release all buffers in list, asking the user for confirmation when needed.
17854 When a buffer is unmodified, it is just killed. When modified, it is saved
17855 \(if the user agrees) and then killed."
17856 (let (buf file)
17857 (while (setq buf (pop blist))
17858 (setq file (buffer-file-name buf))
17859 (when (and (buffer-modified-p buf)
17860 file
17861 (y-or-n-p (format "Save file %s? " file)))
17862 (with-current-buffer buf (save-buffer)))
17863 (kill-buffer buf))))
17865 (defun org-agenda-prepare-buffers (files)
17866 "Create buffers for all agenda files, protect archived trees and comments."
17867 (interactive)
17868 (let ((pa '(:org-archived t))
17869 (pc '(:org-comment t))
17870 (pall '(:org-archived t :org-comment t))
17871 (inhibit-read-only t)
17872 (org-inhibit-startup org-agenda-inhibit-startup)
17873 (rea (concat ":" org-archive-tag ":"))
17874 file re org-tag-alist)
17875 (setq org-tag-alist-for-agenda nil
17876 org-tag-groups-alist-for-agenda nil)
17877 (save-excursion
17878 (save-restriction
17879 (while (setq file (pop files))
17880 (catch 'nextfile
17881 (if (bufferp file)
17882 (set-buffer file)
17883 (org-check-agenda-file file)
17884 (set-buffer (org-get-agenda-file-buffer file)))
17885 (widen)
17886 (org-set-regexps-and-options-for-tags)
17887 (org-refresh-category-properties)
17888 (org-refresh-properties org-effort-property 'org-effort)
17889 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17890 (setq org-todo-keywords-for-agenda
17891 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17892 (setq org-done-keywords-for-agenda
17893 (append org-done-keywords-for-agenda org-done-keywords))
17894 (setq org-todo-keyword-alist-for-agenda
17895 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17896 (setq org-drawers-for-agenda
17897 (append org-drawers-for-agenda org-drawers))
17898 (setq org-tag-alist-for-agenda
17899 (append org-tag-alist-for-agenda org-tag-alist))
17900 (if org-group-tags
17901 (setq org-tag-groups-alist-for-agenda
17902 (org-uniquify-alist
17903 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17904 (org-with-silent-modifications
17905 (save-excursion
17906 (remove-text-properties (point-min) (point-max) pall)
17907 (when org-agenda-skip-archived-trees
17908 (goto-char (point-min))
17909 (while (re-search-forward rea nil t)
17910 (if (org-at-heading-p t)
17911 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17912 (goto-char (point-min))
17913 (setq re (format org-heading-keyword-regexp-format
17914 org-comment-string))
17915 (while (re-search-forward re nil t)
17916 (add-text-properties
17917 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17918 (setq org-todo-keywords-for-agenda
17919 (org-uniquify org-todo-keywords-for-agenda))
17920 (setq org-todo-keyword-alist-for-agenda
17921 (org-uniquify org-todo-keyword-alist-for-agenda))))
17924 ;;;; CDLaTeX minor mode
17926 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17927 "Keymap for the minor `org-cdlatex-mode'.")
17929 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17930 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17931 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17932 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17933 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17935 (defvar org-cdlatex-texmathp-advice-is-done nil
17936 "Flag remembering if we have applied the advice to texmathp already.")
17938 (define-minor-mode org-cdlatex-mode
17939 "Toggle the minor `org-cdlatex-mode'.
17940 This mode supports entering LaTeX environment and math in LaTeX fragments
17941 in Org-mode.
17942 \\{org-cdlatex-mode-map}"
17943 nil " OCDL" nil
17944 (when org-cdlatex-mode
17945 (require 'cdlatex)
17946 (run-hooks 'cdlatex-mode-hook)
17947 (cdlatex-compute-tables))
17948 (unless org-cdlatex-texmathp-advice-is-done
17949 (setq org-cdlatex-texmathp-advice-is-done t)
17950 (defadvice texmathp (around org-math-always-on activate)
17951 "Always return t in org-mode buffers.
17952 This is because we want to insert math symbols without dollars even outside
17953 the LaTeX math segments. If Orgmode thinks that point is actually inside
17954 an embedded LaTeX fragment, let texmathp do its job.
17955 \\[org-cdlatex-mode-map]"
17956 (interactive)
17957 (let (p)
17958 (cond
17959 ((not (derived-mode-p 'org-mode)) ad-do-it)
17960 ((eq this-command 'cdlatex-math-symbol)
17961 (setq ad-return-value t
17962 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17964 (let ((p (org-inside-LaTeX-fragment-p)))
17965 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17966 (setq ad-return-value t
17967 texmathp-why '("Org-mode embedded math" . 0))
17968 (if p ad-do-it)))))))))
17970 (defun turn-on-org-cdlatex ()
17971 "Unconditionally turn on `org-cdlatex-mode'."
17972 (org-cdlatex-mode 1))
17974 (defun org-try-cdlatex-tab ()
17975 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17976 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17977 - inside a LaTeX fragment, or
17978 - after the first word in a line, where an abbreviation expansion could
17979 insert a LaTeX environment."
17980 (when org-cdlatex-mode
17981 (cond
17982 ;; Before any word on the line: No expansion possible.
17983 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17984 ;; Just after first word on the line: Expand it. Make sure it
17985 ;; cannot happen on headlines, though.
17986 ((save-excursion
17987 (skip-chars-backward "a-zA-Z0-9*")
17988 (skip-chars-backward " \t")
17989 (and (bolp) (not (org-at-heading-p))))
17990 (cdlatex-tab) t)
17991 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17993 (defun org-cdlatex-underscore-caret (&optional arg)
17994 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17995 Revert to the normal definition outside of these fragments."
17996 (interactive "P")
17997 (if (org-inside-LaTeX-fragment-p)
17998 (call-interactively 'cdlatex-sub-superscript)
17999 (let (org-cdlatex-mode)
18000 (call-interactively (key-binding (vector last-input-event))))))
18002 (defun org-cdlatex-math-modify (&optional arg)
18003 "Execute `cdlatex-math-modify' in LaTeX fragments.
18004 Revert to the normal definition outside of these fragments."
18005 (interactive "P")
18006 (if (org-inside-LaTeX-fragment-p)
18007 (call-interactively 'cdlatex-math-modify)
18008 (let (org-cdlatex-mode)
18009 (call-interactively (key-binding (vector last-input-event))))))
18013 ;;;; LaTeX fragments
18015 (defvar org-latex-regexps
18016 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18017 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18018 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18019 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18020 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18021 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18022 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18023 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18024 "Regular expressions for matching embedded LaTeX.")
18026 (defun org-inside-LaTeX-fragment-p ()
18027 "Test if point is inside a LaTeX fragment.
18028 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18029 sequence appearing also before point.
18030 Even though the matchers for math are configurable, this function assumes
18031 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18032 delimiters are skipped when they have been removed by customization.
18033 The return value is nil, or a cons cell with the delimiter and the
18034 position of this delimiter.
18036 This function does a reasonably good job, but can locally be fooled by
18037 for example currency specifications. For example it will assume being in
18038 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18039 fragments that are properly closed, but during editing, we have to live
18040 with the uncertainty caused by missing closing delimiters. This function
18041 looks only before point, not after."
18042 (catch 'exit
18043 (let ((pos (point))
18044 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18045 (lim (progn
18046 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18047 (point)))
18048 dd-on str (start 0) m re)
18049 (goto-char pos)
18050 (when dodollar
18051 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18052 re (nth 1 (assoc "$" org-latex-regexps)))
18053 (while (string-match re str start)
18054 (cond
18055 ((= (match-end 0) (length str))
18056 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18057 ((= (match-end 0) (- (length str) 5))
18058 (throw 'exit nil))
18059 (t (setq start (match-end 0))))))
18060 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18061 (goto-char pos)
18062 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18063 (and (match-beginning 2) (throw 'exit nil))
18064 ;; count $$
18065 (while (re-search-backward "\\$\\$" lim t)
18066 (setq dd-on (not dd-on)))
18067 (goto-char pos)
18068 (if dd-on (cons "$$" m))))))
18070 (defun org-inside-latex-macro-p ()
18071 "Is point inside a LaTeX macro or its arguments?"
18072 (save-match-data
18073 (org-in-regexp
18074 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18076 (defvar org-latex-fragment-image-overlays nil
18077 "List of overlays carrying the images of latex fragments.")
18078 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18080 (defun org-remove-latex-fragment-image-overlays ()
18081 "Remove all overlays with LaTeX fragment images in current buffer."
18082 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18083 (setq org-latex-fragment-image-overlays nil))
18085 (defun org-preview-latex-fragment (&optional subtree)
18086 "Preview the LaTeX fragment at point, or all locally or globally.
18087 If the cursor is in a LaTeX fragment, create the image and overlay
18088 it over the source code. If there is no fragment at point, display
18089 all fragments in the current text, from one headline to the next. With
18090 prefix SUBTREE, display all fragments in the current subtree. With a
18091 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18092 the cursor is before the first headline,
18093 display all fragments in the buffer.
18094 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18095 (interactive "P")
18096 (unless buffer-file-name
18097 (error "Can't preview LaTeX fragment in a non-file buffer"))
18098 (org-remove-latex-fragment-image-overlays)
18099 (save-excursion
18100 (save-restriction
18101 (let (beg end at msg)
18102 (cond
18103 ((or (equal subtree '(16))
18104 (not (save-excursion
18105 (re-search-backward org-outline-regexp-bol nil t))))
18106 (setq beg (point-min) end (point-max)
18107 msg "Creating images for buffer...%s"))
18108 ((equal subtree '(4))
18109 (org-back-to-heading)
18110 (setq beg (point) end (org-end-of-subtree t)
18111 msg "Creating images for subtree...%s"))
18113 (if (setq at (org-inside-LaTeX-fragment-p))
18114 (goto-char (max (point-min) (- (cdr at) 2)))
18115 (org-back-to-heading))
18116 (setq beg (point) end (progn (outline-next-heading) (point))
18117 msg (if at "Creating image...%s"
18118 "Creating images for entry...%s"))))
18119 (message msg "")
18120 (narrow-to-region beg end)
18121 (goto-char beg)
18122 (org-format-latex
18123 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18124 (file-name-nondirectory
18125 buffer-file-name)))
18126 default-directory 'overlays msg at 'forbuffer
18127 org-latex-create-formula-image-program)
18128 (message msg "done. Use `C-c C-c' to remove images.")))))
18130 (defun org-format-latex (prefix &optional dir overlays msg at
18131 forbuffer processing-type)
18132 "Replace LaTeX fragments with links to an image, and produce images.
18133 Some of the options can be changed using the variable
18134 `org-format-latex-options'."
18135 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18136 (let* ((prefixnodir (file-name-nondirectory prefix))
18137 (absprefix (expand-file-name prefix dir))
18138 (todir (file-name-directory absprefix))
18139 (opt org-format-latex-options)
18140 (optnew org-format-latex-options)
18141 (matchers (plist-get opt :matchers))
18142 (re-list org-latex-regexps)
18143 (cnt 0) txt hash link beg end re e checkdir
18144 string
18145 m n block-type block linkfile movefile ov)
18146 ;; Check the different regular expressions
18147 (while (setq e (pop re-list))
18148 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18149 block (if block-type "\n\n" ""))
18150 (when (member m matchers)
18151 (goto-char (point-min))
18152 (while (re-search-forward re nil t)
18153 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18154 (or (not overlays)
18155 (not (eq (get-char-property (match-beginning n)
18156 'org-overlay-type)
18157 'org-latex-overlay))))
18158 (cond
18159 ((eq processing-type 'verbatim))
18160 ((eq processing-type 'mathjax)
18161 ;; Prepare for MathJax processing.
18162 (setq string (match-string n))
18163 (when (member m '("$" "$1"))
18164 (save-excursion
18165 (delete-region (match-beginning n) (match-end n))
18166 (goto-char (match-beginning n))
18167 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18168 ((or (eq processing-type 'dvipng)
18169 (eq processing-type 'imagemagick))
18170 ;; Process to an image.
18171 (setq txt (match-string n)
18172 beg (match-beginning n) end (match-end n)
18173 cnt (1+ cnt))
18174 (let ((face (face-at-point))
18175 (fg (plist-get opt :foreground))
18176 (bg (plist-get opt :background))
18177 ;; Ensure full list is printed.
18178 print-length print-level)
18179 (when forbuffer
18180 ;; Get the colors from the face at point.
18181 (goto-char beg)
18182 (when (eq fg 'auto)
18183 (setq fg (face-attribute face :foreground nil 'default)))
18184 (when (eq bg 'auto)
18185 (setq bg (face-attribute face :background nil 'default)))
18186 (setq optnew (copy-sequence opt))
18187 (plist-put optnew :foreground fg)
18188 (plist-put optnew :background bg))
18189 (setq hash (sha1 (prin1-to-string
18190 (list org-format-latex-header
18191 org-latex-default-packages-alist
18192 org-latex-packages-alist
18193 org-format-latex-options
18194 forbuffer txt fg bg)))
18195 linkfile (format "%s_%s.png" prefix hash)
18196 movefile (format "%s_%s.png" absprefix hash)))
18197 (setq link (concat block "[[file:" linkfile "]]" block))
18198 (if msg (message msg cnt))
18199 (goto-char beg)
18200 (unless checkdir ; Ensure the directory exists.
18201 (setq checkdir t)
18202 (or (file-directory-p todir) (make-directory todir t)))
18203 (unless (file-exists-p movefile)
18204 (org-create-formula-image
18205 txt movefile optnew forbuffer processing-type))
18206 (if overlays
18207 (progn
18208 (mapc (lambda (o)
18209 (if (eq (overlay-get o 'org-overlay-type)
18210 'org-latex-overlay)
18211 (delete-overlay o)))
18212 (overlays-in beg end))
18213 (setq ov (make-overlay beg end))
18214 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18215 (if (featurep 'xemacs)
18216 (progn
18217 (overlay-put ov 'invisible t)
18218 (overlay-put
18219 ov 'end-glyph
18220 (make-glyph (vector 'png :file movefile))))
18221 (overlay-put
18222 ov 'display
18223 (list 'image :type 'png :file movefile :ascent 'center)))
18224 (push ov org-latex-fragment-image-overlays)
18225 (goto-char end))
18226 (delete-region beg end)
18227 (insert (org-add-props link
18228 (list 'org-latex-src
18229 (replace-regexp-in-string
18230 "\"" "" txt)
18231 'org-latex-src-embed-type
18232 (if block-type 'paragraph 'character))))))
18233 ((eq processing-type 'mathml)
18234 ;; Process to MathML
18235 (unless (save-match-data (org-format-latex-mathml-available-p))
18236 (error "LaTeX to MathML converter not configured"))
18237 (setq txt (match-string n)
18238 beg (match-beginning n) end (match-end n)
18239 cnt (1+ cnt))
18240 (if msg (message msg cnt))
18241 (goto-char beg)
18242 (delete-region beg end)
18243 (insert (org-format-latex-as-mathml
18244 txt block-type prefix dir)))
18246 (error "Unknown conversion type %s for latex fragments"
18247 processing-type)))))))))
18249 (defun org-create-math-formula (latex-frag &optional mathml-file)
18250 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18251 Use `org-latex-to-mathml-convert-command'. If the conversion is
18252 sucessful, return the portion between \"<math...> </math>\"
18253 elements otherwise return nil. When MATHML-FILE is specified,
18254 write the results in to that file. When invoked as an
18255 interactive command, prompt for LATEX-FRAG, with initial value
18256 set to the current active region and echo the results for user
18257 inspection."
18258 (interactive (list (let ((frag (when (org-region-active-p)
18259 (buffer-substring-no-properties
18260 (region-beginning) (region-end)))))
18261 (read-string "LaTeX Fragment: " frag nil frag))))
18262 (unless latex-frag (error "Invalid latex-frag"))
18263 (let* ((tmp-in-file (file-relative-name
18264 (make-temp-name (expand-file-name "ltxmathml-in"))))
18265 (ignore (write-region latex-frag nil tmp-in-file))
18266 (tmp-out-file (file-relative-name
18267 (make-temp-name (expand-file-name "ltxmathml-out"))))
18268 (cmd (format-spec
18269 org-latex-to-mathml-convert-command
18270 `((?j . ,(shell-quote-argument
18271 (expand-file-name org-latex-to-mathml-jar-file)))
18272 (?I . ,(shell-quote-argument tmp-in-file))
18273 (?o . ,(shell-quote-argument tmp-out-file)))))
18274 mathml shell-command-output)
18275 (when (org-called-interactively-p 'any)
18276 (unless (org-format-latex-mathml-available-p)
18277 (error "LaTeX to MathML converter not configured")))
18278 (message "Running %s" cmd)
18279 (setq shell-command-output (shell-command-to-string cmd))
18280 (setq mathml
18281 (when (file-readable-p tmp-out-file)
18282 (with-current-buffer (find-file-noselect tmp-out-file t)
18283 (goto-char (point-min))
18284 (when (re-search-forward
18285 (concat
18286 (regexp-quote
18287 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18288 "\\(.\\|\n\\)*"
18289 (regexp-quote "</math>")) nil t)
18290 (prog1 (match-string 0) (kill-buffer))))))
18291 (cond
18292 (mathml
18293 (setq mathml
18294 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18295 (when mathml-file
18296 (write-region mathml nil mathml-file))
18297 (when (org-called-interactively-p 'any)
18298 (message mathml)))
18299 ((message "LaTeX to MathML conversion failed")
18300 (message shell-command-output)))
18301 (delete-file tmp-in-file)
18302 (when (file-exists-p tmp-out-file)
18303 (delete-file tmp-out-file))
18304 mathml))
18306 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18307 prefix &optional dir)
18308 "Use `org-create-math-formula' but check local cache first."
18309 (let* ((absprefix (expand-file-name prefix dir))
18310 (print-length nil) (print-level nil)
18311 (formula-id (concat
18312 "formula-"
18313 (sha1
18314 (prin1-to-string
18315 (list latex-frag
18316 org-latex-to-mathml-convert-command)))))
18317 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18318 (formula-cache-dir (file-name-directory formula-cache)))
18320 (unless (file-directory-p formula-cache-dir)
18321 (make-directory formula-cache-dir t))
18323 (unless (file-exists-p formula-cache)
18324 (org-create-math-formula latex-frag formula-cache))
18326 (if (file-exists-p formula-cache)
18327 ;; Successful conversion. Return the link to MathML file.
18328 (org-add-props
18329 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18330 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18331 'org-latex-src-embed-type (if latex-frag-type
18332 'paragraph 'character)))
18333 ;; Failed conversion. Return the LaTeX fragment verbatim
18334 latex-frag)))
18336 (defun org-create-formula-image (string tofile options buffer &optional type)
18337 "Create an image from LaTeX source using dvipng or convert.
18338 This function calls either `org-create-formula-image-with-dvipng'
18339 or `org-create-formula-image-with-imagemagick' depending on the
18340 value of `org-latex-create-formula-image-program' or on the value
18341 of the optional TYPE variable.
18343 Note: ultimately these two function should be combined as they
18344 share a good deal of logic."
18345 (org-check-external-command
18346 "latex" "needed to convert LaTeX fragments to images")
18347 (funcall
18348 (case (or type org-latex-create-formula-image-program)
18349 ('dvipng
18350 (org-check-external-command
18351 "dvipng" "needed to convert LaTeX fragments to images")
18352 #'org-create-formula-image-with-dvipng)
18353 ('imagemagick
18354 (org-check-external-command
18355 "convert" "you need to install imagemagick")
18356 #'org-create-formula-image-with-imagemagick)
18357 (t (error
18358 "invalid value of `org-latex-create-formula-image-program'")))
18359 string tofile options buffer))
18361 (declare-function org-export--get-global-options "ox" (&optional backend))
18362 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18363 (defun org-create-formula--latex-header ()
18364 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18365 (org-latex-guess-inputenc
18366 (org-splice-latex-header
18367 org-format-latex-header
18368 org-latex-default-packages-alist
18369 org-latex-packages-alist t
18370 (plist-get
18371 (org-combine-plists
18372 (org-export--get-global-options 'latex)
18373 (org-export--get-inbuffer-options 'latex))
18374 :latex-header))))
18376 ;; This function borrows from Ganesh Swami's latex2png.el
18377 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18378 "This calls dvipng."
18379 (require 'ox-latex)
18380 (let* ((tmpdir (if (featurep 'xemacs)
18381 (temp-directory)
18382 temporary-file-directory))
18383 (texfilebase (make-temp-name
18384 (expand-file-name "orgtex" tmpdir)))
18385 (texfile (concat texfilebase ".tex"))
18386 (dvifile (concat texfilebase ".dvi"))
18387 (pngfile (concat texfilebase ".png"))
18388 (fnh (if (featurep 'xemacs)
18389 (font-height (face-font 'default))
18390 (face-attribute 'default :height nil)))
18391 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18392 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18393 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18394 "Black"))
18395 (bg (or (plist-get options (if buffer :background :html-background))
18396 "Transparent")))
18397 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18398 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18399 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18400 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18401 (let ((latex-header (org-create-formula--latex-header)))
18402 (with-temp-file texfile
18403 (insert latex-header)
18404 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18405 (let ((dir default-directory))
18406 (condition-case nil
18407 (progn
18408 (cd tmpdir)
18409 (call-process "latex" nil nil nil texfile))
18410 (error nil))
18411 (cd dir))
18412 (if (not (file-exists-p dvifile))
18413 (progn (message "Failed to create dvi file from %s" texfile) nil)
18414 (condition-case nil
18415 (if (featurep 'xemacs)
18416 (call-process "dvipng" nil nil nil
18417 "-fg" fg "-bg" bg
18418 "-T" "tight"
18419 "-o" pngfile
18420 dvifile)
18421 (call-process "dvipng" nil nil nil
18422 "-fg" fg "-bg" bg
18423 "-D" dpi
18424 ;;"-x" scale "-y" scale
18425 "-T" "tight"
18426 "-o" pngfile
18427 dvifile))
18428 (error nil))
18429 (if (not (file-exists-p pngfile))
18430 (if org-format-latex-signal-error
18431 (error "Failed to create png file from %s" texfile)
18432 (message "Failed to create png file from %s" texfile)
18433 nil)
18434 ;; Use the requested file name and clean up
18435 (copy-file pngfile tofile 'replace)
18436 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18437 (if (file-exists-p (concat texfilebase e))
18438 (delete-file (concat texfilebase e))))
18439 pngfile))))
18441 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18442 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18443 "This calls convert, which is included into imagemagick."
18444 (require 'ox-latex)
18445 (let* ((tmpdir (if (featurep 'xemacs)
18446 (temp-directory)
18447 temporary-file-directory))
18448 (texfilebase (make-temp-name
18449 (expand-file-name "orgtex" tmpdir)))
18450 (texfile (concat texfilebase ".tex"))
18451 (pdffile (concat texfilebase ".pdf"))
18452 (pngfile (concat texfilebase ".png"))
18453 (fnh (if (featurep 'xemacs)
18454 (font-height (face-font 'default))
18455 (face-attribute 'default :height nil)))
18456 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18457 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18458 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18459 "black"))
18460 (bg (or (plist-get options (if buffer :background :html-background))
18461 "white")))
18462 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18463 (setq fg (org-latex-color-format fg)))
18464 (if (eq bg 'default) (setq bg (org-latex-color :background))
18465 (setq bg (org-latex-color-format
18466 (if (string= bg "Transparent") "white" bg))))
18467 (let ((latex-header (org-create-formula--latex-header)))
18468 (with-temp-file texfile
18469 (insert latex-header)
18470 (insert "\n\\begin{document}\n"
18471 "\\definecolor{fg}{rgb}{" fg "}\n"
18472 "\\definecolor{bg}{rgb}{" bg "}\n"
18473 "\n\\pagecolor{bg}\n"
18474 "\n{\\color{fg}\n"
18475 string
18476 "\n}\n"
18477 "\n\\end{document}\n")))
18478 (org-latex-compile texfile t)
18479 (if (not (file-exists-p pdffile))
18480 (progn (message "Failed to create pdf file from %s" texfile) nil)
18481 (condition-case nil
18482 (if (featurep 'xemacs)
18483 (call-process "convert" nil nil nil
18484 "-density" "96"
18485 "-trim"
18486 "-antialias"
18487 pdffile
18488 "-quality" "100"
18489 ;; "-sharpen" "0x1.0"
18490 pngfile)
18491 (call-process "convert" nil nil nil
18492 "-density" dpi
18493 "-trim"
18494 "-antialias"
18495 pdffile
18496 "-quality" "100"
18497 ;; "-sharpen" "0x1.0"
18498 pngfile))
18499 (error nil))
18500 (if (not (file-exists-p pngfile))
18501 (if org-format-latex-signal-error
18502 (error "Failed to create png file from %s" texfile)
18503 (message "Failed to create png file from %s" texfile)
18504 nil)
18505 ;; Use the requested file name and clean up
18506 (copy-file pngfile tofile 'replace)
18507 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18508 (if (file-exists-p (concat texfilebase e))
18509 (delete-file (concat texfilebase e))))
18510 pngfile))))
18512 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18513 "Fill a LaTeX header template TPL.
18514 In the template, the following place holders will be recognized:
18516 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18517 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18518 [PACKAGES] \\usepackage statements for PKG
18519 [NO-PACKAGES] do not include PKG
18520 [EXTRA] the string EXTRA
18521 [NO-EXTRA] do not include EXTRA
18523 For backward compatibility, if both the positive and the negative place
18524 holder is missing, the positive one (without the \"NO-\") will be
18525 assumed to be present at the end of the template.
18526 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18527 EXTRA is a string.
18528 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18529 (let (rpl (end ""))
18530 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18531 (setq rpl (if (or (match-end 1) (not def-pkg))
18532 "" (org-latex-packages-to-string def-pkg snippets-p t))
18533 tpl (replace-match rpl t t tpl))
18534 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18536 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18537 (setq rpl (if (or (match-end 1) (not pkg))
18538 "" (org-latex-packages-to-string pkg snippets-p t))
18539 tpl (replace-match rpl t t tpl))
18540 (if pkg (setq end
18541 (concat end "\n"
18542 (org-latex-packages-to-string pkg snippets-p)))))
18544 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18545 (setq rpl (if (or (match-end 1) (not extra))
18546 "" (concat extra "\n"))
18547 tpl (replace-match rpl t t tpl))
18548 (if (and extra (string-match "\\S-" extra))
18549 (setq end (concat end "\n" extra))))
18551 (if (string-match "\\S-" end)
18552 (concat tpl "\n" end)
18553 tpl)))
18555 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18556 "Turn an alist of packages into a string with the \\usepackage macros."
18557 (setq pkg (mapconcat (lambda(p)
18558 (cond
18559 ((stringp p) p)
18560 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18561 (format "%% Package %s omitted" (cadr p)))
18562 ((equal "" (car p))
18563 (format "\\usepackage{%s}" (cadr p)))
18565 (format "\\usepackage[%s]{%s}"
18566 (car p) (cadr p)))))
18568 "\n"))
18569 (if newline (concat pkg "\n") pkg))
18571 (defun org-dvipng-color (attr)
18572 "Return a RGB color specification for dvipng."
18573 (apply 'format "rgb %s %s %s"
18574 (mapcar 'org-normalize-color
18575 (if (featurep 'xemacs)
18576 (color-rgb-components
18577 (face-property 'default
18578 (cond ((eq attr :foreground) 'foreground)
18579 ((eq attr :background) 'background))))
18580 (color-values (face-attribute 'default attr nil))))))
18582 (defun org-dvipng-color-format (color-name)
18583 "Convert COLOR-NAME to a RGB color value for dvipng."
18584 (apply 'format "rgb %s %s %s"
18585 (mapcar 'org-normalize-color
18586 (color-values color-name))))
18588 (defun org-latex-color (attr)
18589 "Return a RGB color for the LaTeX color package."
18590 (apply 'format "%s,%s,%s"
18591 (mapcar 'org-normalize-color
18592 (if (featurep 'xemacs)
18593 (color-rgb-components
18594 (face-property 'default
18595 (cond ((eq attr :foreground) 'foreground)
18596 ((eq attr :background) 'background))))
18597 (color-values (face-attribute 'default attr nil))))))
18599 (defun org-latex-color-format (color-name)
18600 "Convert COLOR-NAME to a RGB color value."
18601 (apply 'format "%s,%s,%s"
18602 (mapcar 'org-normalize-color
18603 (color-values color-name))))
18605 (defun org-normalize-color (value)
18606 "Return string to be used as color value for an RGB component."
18607 (format "%g" (/ value 65535.0)))
18611 ;; Image display
18613 (defvar org-inline-image-overlays nil)
18614 (make-variable-buffer-local 'org-inline-image-overlays)
18616 (defun org-toggle-inline-images (&optional include-linked)
18617 "Toggle the display of inline images.
18618 INCLUDE-LINKED is passed to `org-display-inline-images'."
18619 (interactive "P")
18620 (if org-inline-image-overlays
18621 (progn
18622 (org-remove-inline-images)
18623 (message "Inline image display turned off"))
18624 (org-display-inline-images include-linked)
18625 (if (and (org-called-interactively-p)
18626 org-inline-image-overlays)
18627 (message "%d images displayed inline"
18628 (length org-inline-image-overlays))
18629 (message "No images to display inline"))))
18631 (defun org-redisplay-inline-images ()
18632 "Refresh the display of inline images."
18633 (interactive)
18634 (if (not org-inline-image-overlays)
18635 (org-toggle-inline-images)
18636 (org-toggle-inline-images)
18637 (org-toggle-inline-images)))
18639 (defun org-display-inline-images (&optional include-linked refresh beg end)
18640 "Display inline images.
18641 Normally only links without a description part are inlined, because this
18642 is how it will work for export. When INCLUDE-LINKED is set, also links
18643 with a description part will be inlined. This can be nice for a quick
18644 look at those images, but it does not reflect what exported files will look
18645 like.
18646 When REFRESH is set, refresh existing images between BEG and END.
18647 This will create new image displays only if necessary.
18648 BEG and END default to the buffer boundaries."
18649 (interactive "P")
18650 (unless refresh
18651 (org-remove-inline-images)
18652 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18653 (save-excursion
18654 (save-restriction
18655 (widen)
18656 (setq beg (or beg (point-min)) end (or end (point-max)))
18657 (goto-char beg)
18658 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18659 (substring (org-image-file-name-regexp) 0 -2)
18660 "\\)\\]" (if include-linked "" "\\]")))
18661 (case-fold-search t)
18662 old file ov img type attrwidth width)
18663 (while (re-search-forward re end t)
18664 (setq old (get-char-property-and-overlay (match-beginning 1)
18665 'org-image-overlay)
18666 file (expand-file-name
18667 (concat (or (match-string 3) "") (match-string 4))))
18668 (when (image-type-available-p 'imagemagick)
18669 (setq attrwidth (if (or (listp org-image-actual-width)
18670 (null org-image-actual-width))
18671 (save-excursion
18672 (save-match-data
18673 (when (re-search-backward
18674 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18675 (save-excursion
18676 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18677 (string-to-number (match-string 1))))))
18678 width (cond ((eq org-image-actual-width t) nil)
18679 ((null org-image-actual-width) attrwidth)
18680 ((numberp org-image-actual-width)
18681 org-image-actual-width)
18682 ((listp org-image-actual-width)
18683 (or attrwidth (car org-image-actual-width))))
18684 type (if width 'imagemagick)))
18685 (when (file-exists-p file)
18686 (if (and (car-safe old) refresh)
18687 (image-refresh (overlay-get (cdr old) 'display))
18688 (setq img (save-match-data (create-image file type nil :width width)))
18689 (when img
18690 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18691 (overlay-put ov 'display img)
18692 (overlay-put ov 'face 'default)
18693 (overlay-put ov 'org-image-overlay t)
18694 (overlay-put ov 'modification-hooks
18695 (list 'org-display-inline-remove-overlay))
18696 (push ov org-inline-image-overlays)))))))))
18698 (define-obsolete-function-alias
18699 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18701 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18702 "Remove inline-display overlay if a corresponding region is modified."
18703 (let ((inhibit-modification-hooks t))
18704 (when (and ov after)
18705 (delete ov org-inline-image-overlays)
18706 (delete-overlay ov))))
18708 (defun org-remove-inline-images ()
18709 "Remove inline display of images."
18710 (interactive)
18711 (mapc 'delete-overlay org-inline-image-overlays)
18712 (setq org-inline-image-overlays nil))
18714 ;;;; Key bindings
18716 ;; Outline functions from `outline-mode-prefix-map'
18717 ;; that can be remapped in Org:
18718 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18719 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18720 (define-key org-mode-map [remap outline-forward-same-level]
18721 'org-forward-heading-same-level)
18722 (define-key org-mode-map [remap outline-backward-same-level]
18723 'org-backward-heading-same-level)
18724 (define-key org-mode-map [remap show-branches]
18725 'org-kill-note-or-show-branches)
18726 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18727 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18728 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18730 ;; Outline functions from `outline-mode-prefix-map' that can not
18731 ;; be remapped in Org:
18733 ;; - the column "key binding" shows whether the Outline function is still
18734 ;; available in Org mode on the same key that it has been bound to in
18735 ;; Outline mode:
18736 ;; - "overridden": key used for a different functionality in Org mode
18737 ;; - else: key still bound to the same Outline function in Org mode
18739 ;; | Outline function | key binding | Org replacement |
18740 ;; |------------------------------------+-------------+-----------------------|
18741 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18742 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18743 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18744 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18745 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18746 ;; | `show-entry' | overridden | no replacement |
18747 ;; | `show-children' | `C-c C-i' | visibility cycling |
18748 ;; | `show-branches' | `C-c C-k' | still same function |
18749 ;; | `show-subtree' | overridden | visibility cycling |
18750 ;; | `show-all' | overridden | no replacement |
18751 ;; | `hide-subtree' | overridden | visibility cycling |
18752 ;; | `hide-body' | overridden | no replacement |
18753 ;; | `hide-entry' | overridden | visibility cycling |
18754 ;; | `hide-leaves' | overridden | no replacement |
18755 ;; | `hide-sublevels' | overridden | no replacement |
18756 ;; | `hide-other' | overridden | no replacement |
18758 ;; Make `C-c C-x' a prefix key
18759 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18761 ;; TAB key with modifiers
18762 (org-defkey org-mode-map "\C-i" 'org-cycle)
18763 (org-defkey org-mode-map [(tab)] 'org-cycle)
18764 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18765 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18766 ;; The following line is necessary under Suse GNU/Linux
18767 (unless (featurep 'xemacs)
18768 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18769 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18770 (define-key org-mode-map [backtab] 'org-shifttab)
18772 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18773 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18774 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18776 ;; Cursor keys with modifiers
18777 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18778 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18779 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18780 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18782 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18783 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18784 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18785 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18787 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18788 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18789 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18790 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18792 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18793 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18794 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18795 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18797 ;; Babel keys
18798 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18799 (mapc (lambda (pair)
18800 (define-key org-babel-map (car pair) (cdr pair)))
18801 org-babel-key-bindings)
18803 ;;; Extra keys for tty access.
18804 ;; We only set them when really needed because otherwise the
18805 ;; menus don't show the simple keys
18807 (when (or org-use-extra-keys
18808 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18809 (not window-system))
18810 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18811 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18812 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18813 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18814 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18815 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18816 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18817 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18818 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18819 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18820 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18821 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18822 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18823 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18824 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18825 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18826 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18827 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18828 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18829 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18830 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18831 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18832 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18833 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18834 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18835 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18836 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18837 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18839 ;; All the other keys
18841 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18842 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18843 (if (boundp 'narrow-map)
18844 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18845 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18846 (if (boundp 'narrow-map)
18847 (org-defkey narrow-map "b" 'org-narrow-to-block)
18848 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18849 (if (boundp 'narrow-map)
18850 (org-defkey narrow-map "e" 'org-narrow-to-element)
18851 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18852 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18853 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18854 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18855 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18856 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18857 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18858 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18859 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18860 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18861 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18862 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18863 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18864 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18865 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18866 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18867 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18868 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18869 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18870 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18871 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18872 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18873 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18874 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18875 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18876 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18877 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18878 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18879 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18880 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18881 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18882 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18883 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18884 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18885 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18886 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18887 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18888 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18889 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18890 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18891 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18892 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18893 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18894 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18895 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18896 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18897 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18898 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18899 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18900 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18901 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18902 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18903 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18904 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18905 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18906 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18907 (org-defkey org-mode-map "\C-c^" 'org-sort)
18908 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18909 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18910 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18911 (org-defkey org-mode-map "\C-m" 'org-return)
18912 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18913 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18914 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18915 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18916 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18917 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18918 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18919 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18920 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18921 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18922 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18923 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18924 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18925 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18926 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18927 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18928 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18929 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18930 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18931 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18932 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18933 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18934 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18936 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18937 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18938 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18940 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18941 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18942 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18943 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18944 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18945 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18946 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18947 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18948 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18949 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18950 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18951 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18952 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18953 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18954 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18955 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18956 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18957 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18958 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18959 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18960 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18961 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18962 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18964 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18965 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18966 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18967 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18968 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18970 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18972 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18974 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18975 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18977 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18980 (when (featurep 'xemacs)
18981 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18984 (defconst org-speed-commands-default
18986 ("Outline Navigation")
18987 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18988 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18989 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18990 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18991 ("F" . org-next-block)
18992 ("B" . org-previous-block)
18993 ("u" . (org-speed-move-safe 'outline-up-heading))
18994 ("j" . org-goto)
18995 ("g" . (org-refile t))
18996 ("Outline Visibility")
18997 ("c" . org-cycle)
18998 ("C" . org-shifttab)
18999 (" " . org-display-outline-path)
19000 ("=" . org-columns)
19001 ("Outline Structure Editing")
19002 ("U" . org-shiftmetaup)
19003 ("D" . org-shiftmetadown)
19004 ("r" . org-metaright)
19005 ("l" . org-metaleft)
19006 ("R" . org-shiftmetaright)
19007 ("L" . org-shiftmetaleft)
19008 ("i" . (progn (forward-char 1) (call-interactively
19009 'org-insert-heading-respect-content)))
19010 ("^" . org-sort)
19011 ("w" . org-refile)
19012 ("a" . org-archive-subtree-default-with-confirmation)
19013 ("@" . org-mark-subtree)
19014 ("#" . org-toggle-comment)
19015 ("Clock Commands")
19016 ("I" . org-clock-in)
19017 ("O" . org-clock-out)
19018 ("Meta Data Editing")
19019 ("t" . org-todo)
19020 ("," . (org-priority))
19021 ("0" . (org-priority ?\ ))
19022 ("1" . (org-priority ?A))
19023 ("2" . (org-priority ?B))
19024 ("3" . (org-priority ?C))
19025 (":" . org-set-tags-command)
19026 ("e" . org-set-effort)
19027 ("E" . org-inc-effort)
19028 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19029 (org-entry-put (point) "APPT_WARNTIME" m)))
19030 ("Agenda Views etc")
19031 ("v" . org-agenda)
19032 ("/" . org-sparse-tree)
19033 ("Misc")
19034 ("o" . org-open-at-point)
19035 ("?" . org-speed-command-help)
19036 ("<" . (org-agenda-set-restriction-lock 'subtree))
19037 (">" . (org-agenda-remove-restriction-lock))
19039 "The default speed commands.")
19041 (defun org-print-speed-command (e)
19042 (if (> (length (car e)) 1)
19043 (progn
19044 (princ "\n")
19045 (princ (car e))
19046 (princ "\n")
19047 (princ (make-string (length (car e)) ?-))
19048 (princ "\n"))
19049 (princ (car e))
19050 (princ " ")
19051 (if (symbolp (cdr e))
19052 (princ (symbol-name (cdr e)))
19053 (prin1 (cdr e)))
19054 (princ "\n")))
19056 (defun org-speed-command-help ()
19057 "Show the available speed commands."
19058 (interactive)
19059 (if (not org-use-speed-commands)
19060 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19061 (with-output-to-temp-buffer "*Help*"
19062 (princ "User-defined Speed commands\n===========================\n")
19063 (mapc 'org-print-speed-command org-speed-commands-user)
19064 (princ "\n")
19065 (princ "Built-in Speed commands\n=======================\n")
19066 (mapc 'org-print-speed-command org-speed-commands-default))
19067 (with-current-buffer "*Help*"
19068 (setq truncate-lines t))))
19070 (defun org-speed-move-safe (cmd)
19071 "Execute CMD, but make sure that the cursor always ends up in a headline.
19072 If not, return to the original position and throw an error."
19073 (interactive)
19074 (let ((pos (point)))
19075 (call-interactively cmd)
19076 (unless (and (bolp) (org-at-heading-p))
19077 (goto-char pos)
19078 (error "Boundary reached while executing %s" cmd))))
19080 (defvar org-self-insert-command-undo-counter 0)
19082 (defvar org-table-auto-blank-field) ; defined in org-table.el
19083 (defvar org-speed-command nil)
19085 (define-obsolete-function-alias
19086 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19088 (defun org-speed-command-activate (keys)
19089 "Hook for activating single-letter speed commands.
19090 `org-speed-commands-default' specifies a minimal command set.
19091 Use `org-speed-commands-user' for further customization."
19092 (when (or (and (bolp) (looking-at org-outline-regexp))
19093 (and (functionp org-use-speed-commands)
19094 (funcall org-use-speed-commands)))
19095 (cdr (assoc keys (append org-speed-commands-user
19096 org-speed-commands-default)))))
19098 (define-obsolete-function-alias
19099 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19101 (defun org-babel-speed-command-activate (keys)
19102 "Hook for activating single-letter code block commands."
19103 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19104 (cdr (assoc keys org-babel-key-bindings))))
19106 (defcustom org-speed-command-hook
19107 '(org-speed-command-default-hook org-babel-speed-command-hook)
19108 "Hook for activating speed commands at strategic locations.
19109 Hook functions are called in sequence until a valid handler is
19110 found.
19112 Each hook takes a single argument, a user-pressed command key
19113 which is also a `self-insert-command' from the global map.
19115 Within the hook, examine the cursor position and the command key
19116 and return nil or a valid handler as appropriate. Handler could
19117 be one of an interactive command, a function, or a form.
19119 Set `org-use-speed-commands' to non-nil value to enable this
19120 hook. The default setting is `org-speed-command-activate'."
19121 :group 'org-structure
19122 :version "24.1"
19123 :type 'hook)
19125 (defun org-self-insert-command (N)
19126 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19127 If the cursor is in a table looking at whitespace, the whitespace is
19128 overwritten, and the table is not marked as requiring realignment."
19129 (interactive "p")
19130 (org-check-before-invisible-edit 'insert)
19131 (cond
19132 ((and org-use-speed-commands
19133 (setq org-speed-command
19134 (run-hook-with-args-until-success
19135 'org-speed-command-hook (this-command-keys))))
19136 (cond
19137 ((commandp org-speed-command)
19138 (setq this-command org-speed-command)
19139 (call-interactively org-speed-command))
19140 ((functionp org-speed-command)
19141 (funcall org-speed-command))
19142 ((and org-speed-command (listp org-speed-command))
19143 (eval org-speed-command))
19144 (t (let (org-use-speed-commands)
19145 (call-interactively 'org-self-insert-command)))))
19146 ((and
19147 (org-table-p)
19148 (progn
19149 ;; check if we blank the field, and if that triggers align
19150 (and (featurep 'org-table) org-table-auto-blank-field
19151 (member last-command
19152 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19153 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19154 ;; got extra space, this field does not determine column width
19155 (let (org-table-may-need-update) (org-table-blank-field))
19156 ;; no extra space, this field may determine column width
19157 (org-table-blank-field)))
19159 (eq N 1)
19160 (looking-at "[^|\n]* |"))
19161 (let (org-table-may-need-update)
19162 (goto-char (1- (match-end 0)))
19163 (backward-delete-char 1)
19164 (goto-char (match-beginning 0))
19165 (self-insert-command N)))
19167 (setq org-table-may-need-update t)
19168 (self-insert-command N)
19169 (org-fix-tags-on-the-fly)
19170 (if org-self-insert-cluster-for-undo
19171 (if (not (eq last-command 'org-self-insert-command))
19172 (setq org-self-insert-command-undo-counter 1)
19173 (if (>= org-self-insert-command-undo-counter 20)
19174 (setq org-self-insert-command-undo-counter 1)
19175 (and (> org-self-insert-command-undo-counter 0)
19176 buffer-undo-list (listp buffer-undo-list)
19177 (not (cadr buffer-undo-list)) ; remove nil entry
19178 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19179 (setq org-self-insert-command-undo-counter
19180 (1+ org-self-insert-command-undo-counter))))))))
19182 (defun org-check-before-invisible-edit (kind)
19183 "Check is editing if kind KIND would be dangerous with invisible text around.
19184 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19185 ;; First, try to get out of here as quickly as possible, to reduce overhead
19186 (if (and org-catch-invisible-edits
19187 (or (not (boundp 'visible-mode)) (not visible-mode))
19188 (or (get-char-property (point) 'invisible)
19189 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19190 ;; OK, we need to take a closer look
19191 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19192 (invisible-before-point (if (bobp) nil (get-char-property
19193 (1- (point)) 'invisible)))
19194 (border-and-ok-direction
19196 ;; Check if we are acting predictably before invisible text
19197 (and invisible-at-point (not invisible-before-point)
19198 (memq kind '(insert delete-backward)))
19199 ;; Check if we are acting predictably after invisible text
19200 ;; This works not well, and I have turned it off. It seems
19201 ;; better to always show and stop after invisible text.
19202 ;; (and (not invisible-at-point) invisible-before-point
19203 ;; (memq kind '(insert delete)))
19205 (when (or (memq invisible-at-point '(outline org-hide-block t))
19206 (memq invisible-before-point '(outline org-hide-block t)))
19207 (if (eq org-catch-invisible-edits 'error)
19208 (error "Editing in invisible areas is prohibited - make visible first"))
19209 (if (and org-custom-properties-overlays
19210 (y-or-n-p "Display invisible properties in this buffer? "))
19211 (org-toggle-custom-properties-visibility)
19212 ;; Make the area visible
19213 (save-excursion
19214 (if invisible-before-point
19215 (goto-char (previous-single-char-property-change
19216 (point) 'invisible)))
19217 (org-cycle))
19218 (cond
19219 ((eq org-catch-invisible-edits 'show)
19220 ;; That's it, we do the edit after showing
19221 (message
19222 "Unfolding invisible region around point before editing")
19223 (sit-for 1))
19224 ((and (eq org-catch-invisible-edits 'smart)
19225 border-and-ok-direction)
19226 (message "Unfolding invisible region around point before editing"))
19228 ;; Don't do the edit, make the user repeat it in full visibility
19229 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19231 (defun org-fix-tags-on-the-fly ()
19232 (when (and (equal (char-after (point-at-bol)) ?*)
19233 (org-at-heading-p))
19234 (org-align-tags-here org-tags-column)))
19236 (defun org-delete-backward-char (N)
19237 "Like `delete-backward-char', insert whitespace at field end in tables.
19238 When deleting backwards, in tables this function will insert whitespace in
19239 front of the next \"|\" separator, to keep the table aligned. The table will
19240 still be marked for re-alignment if the field did fill the entire column,
19241 because, in this case the deletion might narrow the column."
19242 (interactive "p")
19243 (save-match-data
19244 (org-check-before-invisible-edit 'delete-backward)
19245 (if (and (org-table-p)
19246 (eq N 1)
19247 (string-match "|" (buffer-substring (point-at-bol) (point)))
19248 (looking-at ".*?|"))
19249 (let ((pos (point))
19250 (noalign (looking-at "[^|\n\r]* |"))
19251 (c org-table-may-need-update))
19252 (backward-delete-char N)
19253 (if (not overwrite-mode)
19254 (progn
19255 (skip-chars-forward "^|")
19256 (insert " ")
19257 (goto-char (1- pos))))
19258 ;; noalign: if there were two spaces at the end, this field
19259 ;; does not determine the width of the column.
19260 (if noalign (setq org-table-may-need-update c)))
19261 (backward-delete-char N)
19262 (org-fix-tags-on-the-fly))))
19264 (defun org-delete-char (N)
19265 "Like `delete-char', but insert whitespace at field end in tables.
19266 When deleting characters, in tables this function will insert whitespace in
19267 front of the next \"|\" separator, to keep the table aligned. The table will
19268 still be marked for re-alignment if the field did fill the entire column,
19269 because, in this case the deletion might narrow the column."
19270 (interactive "p")
19271 (save-match-data
19272 (org-check-before-invisible-edit 'delete)
19273 (if (and (org-table-p)
19274 (not (bolp))
19275 (not (= (char-after) ?|))
19276 (eq N 1))
19277 (if (looking-at ".*?|")
19278 (let ((pos (point))
19279 (noalign (looking-at "[^|\n\r]* |"))
19280 (c org-table-may-need-update))
19281 (replace-match
19282 (concat (substring (match-string 0) 1 -1) " |") nil t)
19283 (goto-char pos)
19284 ;; noalign: if there were two spaces at the end, this field
19285 ;; does not determine the width of the column.
19286 (if noalign (setq org-table-may-need-update c)))
19287 (delete-char N))
19288 (delete-char N)
19289 (org-fix-tags-on-the-fly))))
19291 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19292 (put 'org-self-insert-command 'delete-selection t)
19293 (put 'orgtbl-self-insert-command 'delete-selection t)
19294 (put 'org-delete-char 'delete-selection 'supersede)
19295 (put 'org-delete-backward-char 'delete-selection 'supersede)
19296 (put 'org-yank 'delete-selection 'yank)
19298 ;; Make `flyspell-mode' delay after some commands
19299 (put 'org-self-insert-command 'flyspell-delayed t)
19300 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19301 (put 'org-delete-char 'flyspell-delayed t)
19302 (put 'org-delete-backward-char 'flyspell-delayed t)
19304 ;; Make pabbrev-mode expand after org-mode commands
19305 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19306 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19308 ;; How to do this: Measure non-white length of current string
19309 ;; If equal to column width, we should realign.
19311 (defun org-remap (map &rest commands)
19312 "In MAP, remap the functions given in COMMANDS.
19313 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19314 (let (new old)
19315 (while commands
19316 (setq old (pop commands) new (pop commands))
19317 (if (fboundp 'command-remapping)
19318 (org-defkey map (vector 'remap old) new)
19319 (substitute-key-definition old new map global-map)))))
19321 (defun org-transpose-words ()
19322 "Transpose words for Org.
19323 This uses the `org-mode-transpose-word-syntax-table' syntax
19324 table, which interprets characters in `org-emphasis-alist' as
19325 word constituants."
19326 (interactive)
19327 (with-syntax-table org-mode-transpose-word-syntax-table
19328 (call-interactively 'transpose-words)))
19329 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19331 (when (eq org-enable-table-editor 'optimized)
19332 ;; If the user wants maximum table support, we need to hijack
19333 ;; some standard editing functions
19334 (org-remap org-mode-map
19335 'self-insert-command 'org-self-insert-command
19336 'delete-char 'org-delete-char
19337 'delete-backward-char 'org-delete-backward-char)
19338 (org-defkey org-mode-map "|" 'org-force-self-insert))
19340 (defvar org-ctrl-c-ctrl-c-hook nil
19341 "Hook for functions attaching themselves to `C-c C-c'.
19343 This can be used to add additional functionality to the C-c C-c
19344 key which executes context-dependent commands. This hook is run
19345 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19346 run after the last test.
19348 Each function will be called with no arguments. The function
19349 must check if the context is appropriate for it to act. If yes,
19350 it should do its thing and then return a non-nil value. If the
19351 context is wrong, just do nothing and return nil.")
19353 (defvar org-ctrl-c-ctrl-c-final-hook nil
19354 "Hook for functions attaching themselves to `C-c C-c'.
19356 This can be used to add additional functionality to the C-c C-c
19357 key which executes context-dependent commands. This hook is run
19358 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19359 before the first test.
19361 Each function will be called with no arguments. The function
19362 must check if the context is appropriate for it to act. If yes,
19363 it should do its thing and then return a non-nil value. If the
19364 context is wrong, just do nothing and return nil.")
19366 (defvar org-tab-first-hook nil
19367 "Hook for functions to attach themselves to TAB.
19368 See `org-ctrl-c-ctrl-c-hook' for more information.
19369 This hook runs as the first action when TAB is pressed, even before
19370 `org-cycle' messes around with the `outline-regexp' to cater for
19371 inline tasks and plain list item folding.
19372 If any function in this hook returns t, any other actions that
19373 would have been caused by TAB (such as table field motion or visibility
19374 cycling) will not occur.")
19376 (defvar org-tab-after-check-for-table-hook nil
19377 "Hook for functions to attach themselves to TAB.
19378 See `org-ctrl-c-ctrl-c-hook' for more information.
19379 This hook runs after it has been established that the cursor is not in a
19380 table, but before checking if the cursor is in a headline or if global cycling
19381 should be done.
19382 If any function in this hook returns t, not other actions like visibility
19383 cycling will be done.")
19385 (defvar org-tab-after-check-for-cycling-hook nil
19386 "Hook for functions to attach themselves to TAB.
19387 See `org-ctrl-c-ctrl-c-hook' for more information.
19388 This hook runs after it has been established that not table field motion and
19389 not visibility should be done because of current context. This is probably
19390 the place where a package like yasnippets can hook in.")
19392 (defvar org-tab-before-tab-emulation-hook nil
19393 "Hook for functions to attach themselves to TAB.
19394 See `org-ctrl-c-ctrl-c-hook' for more information.
19395 This hook runs after every other options for TAB have been exhausted, but
19396 before indentation and \t insertion takes place.")
19398 (defvar org-metaleft-hook nil
19399 "Hook for functions attaching themselves to `M-left'.
19400 See `org-ctrl-c-ctrl-c-hook' for more information.")
19401 (defvar org-metaright-hook nil
19402 "Hook for functions attaching themselves to `M-right'.
19403 See `org-ctrl-c-ctrl-c-hook' for more information.")
19404 (defvar org-metaup-hook nil
19405 "Hook for functions attaching themselves to `M-up'.
19406 See `org-ctrl-c-ctrl-c-hook' for more information.")
19407 (defvar org-metadown-hook nil
19408 "Hook for functions attaching themselves to `M-down'.
19409 See `org-ctrl-c-ctrl-c-hook' for more information.")
19410 (defvar org-shiftmetaleft-hook nil
19411 "Hook for functions attaching themselves to `M-S-left'.
19412 See `org-ctrl-c-ctrl-c-hook' for more information.")
19413 (defvar org-shiftmetaright-hook nil
19414 "Hook for functions attaching themselves to `M-S-right'.
19415 See `org-ctrl-c-ctrl-c-hook' for more information.")
19416 (defvar org-shiftmetaup-hook nil
19417 "Hook for functions attaching themselves to `M-S-up'.
19418 See `org-ctrl-c-ctrl-c-hook' for more information.")
19419 (defvar org-shiftmetadown-hook nil
19420 "Hook for functions attaching themselves to `M-S-down'.
19421 See `org-ctrl-c-ctrl-c-hook' for more information.")
19422 (defvar org-metareturn-hook nil
19423 "Hook for functions attaching themselves to `M-RET'.
19424 See `org-ctrl-c-ctrl-c-hook' for more information.")
19425 (defvar org-shiftup-hook nil
19426 "Hook for functions attaching themselves to `S-up'.
19427 See `org-ctrl-c-ctrl-c-hook' for more information.")
19428 (defvar org-shiftup-final-hook nil
19429 "Hook for functions attaching themselves to `S-up'.
19430 This one runs after all other options except shift-select have been excluded.
19431 See `org-ctrl-c-ctrl-c-hook' for more information.")
19432 (defvar org-shiftdown-hook nil
19433 "Hook for functions attaching themselves to `S-down'.
19434 See `org-ctrl-c-ctrl-c-hook' for more information.")
19435 (defvar org-shiftdown-final-hook nil
19436 "Hook for functions attaching themselves to `S-down'.
19437 This one runs after all other options except shift-select have been excluded.
19438 See `org-ctrl-c-ctrl-c-hook' for more information.")
19439 (defvar org-shiftleft-hook nil
19440 "Hook for functions attaching themselves to `S-left'.
19441 See `org-ctrl-c-ctrl-c-hook' for more information.")
19442 (defvar org-shiftleft-final-hook nil
19443 "Hook for functions attaching themselves to `S-left'.
19444 This one runs after all other options except shift-select have been excluded.
19445 See `org-ctrl-c-ctrl-c-hook' for more information.")
19446 (defvar org-shiftright-hook nil
19447 "Hook for functions attaching themselves to `S-right'.
19448 See `org-ctrl-c-ctrl-c-hook' for more information.")
19449 (defvar org-shiftright-final-hook nil
19450 "Hook for functions attaching themselves to `S-right'.
19451 This one runs after all other options except shift-select have been excluded.
19452 See `org-ctrl-c-ctrl-c-hook' for more information.")
19454 (defun org-modifier-cursor-error ()
19455 "Throw an error, a modified cursor command was applied in wrong context."
19456 (error "This command is active in special context like tables, headlines or items"))
19458 (defun org-shiftselect-error ()
19459 "Throw an error because Shift-Cursor command was applied in wrong context."
19460 (if (and (boundp 'shift-select-mode) shift-select-mode)
19461 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19462 (error "This command works only in special context like headlines or timestamps")))
19464 (defun org-call-for-shift-select (cmd)
19465 (let ((this-command-keys-shift-translated t))
19466 (call-interactively cmd)))
19468 (defun org-shifttab (&optional arg)
19469 "Global visibility cycling or move to previous table field.
19470 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19471 on context.
19472 See the individual commands for more information."
19473 (interactive "P")
19474 (cond
19475 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19476 ((integerp arg)
19477 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19478 (message "Content view to level: %d" arg)
19479 (org-content (prefix-numeric-value arg2))
19480 (setq org-cycle-global-status 'overview)))
19481 (t (call-interactively 'org-global-cycle))))
19483 (defun org-shiftmetaleft ()
19484 "Promote subtree or delete table column.
19485 Calls `org-promote-subtree', `org-outdent-item-tree', or
19486 `org-table-delete-column', depending on context. See the
19487 individual commands for more information."
19488 (interactive)
19489 (cond
19490 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19491 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19492 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19493 ((if (not (org-region-active-p)) (org-at-item-p)
19494 (save-excursion (goto-char (region-beginning))
19495 (org-at-item-p)))
19496 (call-interactively 'org-outdent-item-tree))
19497 (t (org-modifier-cursor-error))))
19499 (defun org-shiftmetaright ()
19500 "Demote subtree or insert table column.
19501 Calls `org-demote-subtree', `org-indent-item-tree', or
19502 `org-table-insert-column', depending on context. See the
19503 individual commands for more information."
19504 (interactive)
19505 (cond
19506 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19507 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19508 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19509 ((if (not (org-region-active-p)) (org-at-item-p)
19510 (save-excursion (goto-char (region-beginning))
19511 (org-at-item-p)))
19512 (call-interactively 'org-indent-item-tree))
19513 (t (org-modifier-cursor-error))))
19515 (defun org-shiftmetaup (&optional arg)
19516 "Move subtree up or kill table row.
19517 Calls `org-move-subtree-up' or `org-table-kill-row' or
19518 `org-move-item-up' or `org-timestamp-up', depending on context.
19519 See the individual commands for more information."
19520 (interactive "P")
19521 (cond
19522 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19523 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19524 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19525 ((org-at-item-p) (call-interactively 'org-move-item-up))
19526 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19527 (call-interactively 'org-timestamp-up)))
19528 (t (call-interactively 'org-drag-line-backward))))
19530 (defun org-shiftmetadown (&optional arg)
19531 "Move subtree down or insert table row.
19532 Calls `org-move-subtree-down' or `org-table-insert-row' or
19533 `org-move-item-down' 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-shiftmetadown-hook))
19538 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19539 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19540 ((org-at-item-p) (call-interactively 'org-move-item-down))
19541 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19542 (call-interactively 'org-timestamp-down)))
19543 (t (call-interactively 'org-drag-line-forward))))
19545 (defsubst org-hidden-tree-error ()
19546 (error
19547 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19549 (defun org-metaleft (&optional arg)
19550 "Promote heading or move table column to left.
19551 Calls `org-do-promote' or `org-table-move-column', depending on context.
19552 With no specific context, calls the Emacs default `backward-word'.
19553 See the individual commands for more information."
19554 (interactive "P")
19555 (cond
19556 ((run-hook-with-args-until-success 'org-metaleft-hook))
19557 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19558 ((org-with-limited-levels
19559 (or (org-at-heading-p)
19560 (and (org-region-active-p)
19561 (save-excursion
19562 (goto-char (region-beginning))
19563 (org-at-heading-p)))))
19564 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19565 (call-interactively 'org-do-promote))
19566 ;; At an inline task.
19567 ((org-at-heading-p)
19568 (call-interactively 'org-inlinetask-promote))
19569 ((or (org-at-item-p)
19570 (and (org-region-active-p)
19571 (save-excursion
19572 (goto-char (region-beginning))
19573 (org-at-item-p))))
19574 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19575 (call-interactively 'org-outdent-item))
19576 (t (call-interactively 'backward-word))))
19578 (defun org-metaright (&optional arg)
19579 "Demote a subtree, a list item or move table column to right.
19580 In front of a drawer or a block keyword, indent it correctly.
19581 With no specific context, calls the Emacs default `forward-word'.
19582 See the individual commands for more information."
19583 (interactive "P")
19584 (cond
19585 ((run-hook-with-args-until-success 'org-metaright-hook))
19586 ((org-at-table-p) (call-interactively 'org-table-move-column))
19587 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19588 ((org-at-block-p) (call-interactively 'org-indent-block))
19589 ((org-with-limited-levels
19590 (or (org-at-heading-p)
19591 (and (org-region-active-p)
19592 (save-excursion
19593 (goto-char (region-beginning))
19594 (org-at-heading-p)))))
19595 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19596 (call-interactively 'org-do-demote))
19597 ;; At an inline task.
19598 ((org-at-heading-p)
19599 (call-interactively 'org-inlinetask-demote))
19600 ((or (org-at-item-p)
19601 (and (org-region-active-p)
19602 (save-excursion
19603 (goto-char (region-beginning))
19604 (org-at-item-p))))
19605 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19606 (call-interactively 'org-indent-item))
19607 (t (call-interactively 'forward-word))))
19609 (defun org-check-for-hidden (what)
19610 "Check if there are hidden headlines/items in the current visual line.
19611 WHAT can be either `headlines' or `items'. If the current line is
19612 an outline or item heading and it has a folded subtree below it,
19613 this function returns t, nil otherwise."
19614 (let ((re (cond
19615 ((eq what 'headlines) org-outline-regexp-bol)
19616 ((eq what 'items) (org-item-beginning-re))
19617 (t (error "This should not happen"))))
19618 beg end)
19619 (save-excursion
19620 (catch 'exit
19621 (unless (org-region-active-p)
19622 (setq beg (point-at-bol))
19623 (beginning-of-line 2)
19624 (while (and (not (eobp)) ;; this is like `next-line'
19625 (get-char-property (1- (point)) 'invisible))
19626 (beginning-of-line 2))
19627 (setq end (point))
19628 (goto-char beg)
19629 (goto-char (point-at-eol))
19630 (setq end (max end (point)))
19631 (while (re-search-forward re end t)
19632 (if (get-char-property (match-beginning 0) 'invisible)
19633 (throw 'exit t))))
19634 nil))))
19636 (defun org-metaup (&optional arg)
19637 "Move subtree up or move table row up.
19638 Calls `org-move-subtree-up' or `org-table-move-row' or
19639 `org-move-item-up', depending on context. See the individual commands
19640 for more information."
19641 (interactive "P")
19642 (cond
19643 ((run-hook-with-args-until-success 'org-metaup-hook))
19644 ((org-region-active-p)
19645 (let* ((a (min (region-beginning) (region-end)))
19646 (b (1- (max (region-beginning) (region-end))))
19647 (c (save-excursion (goto-char a)
19648 (move-beginning-of-line 0)))
19649 (d (save-excursion (goto-char a)
19650 (move-end-of-line 0) (point))))
19651 (transpose-regions a b c d)
19652 (goto-char c)))
19653 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19654 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19655 ((org-at-item-p) (call-interactively 'org-move-item-up))
19656 (t (org-drag-element-backward))))
19658 (defun org-metadown (&optional arg)
19659 "Move subtree down or move table row down.
19660 Calls `org-move-subtree-down' or `org-table-move-row' or
19661 `org-move-item-down', depending on context. See the individual
19662 commands for more information."
19663 (interactive "P")
19664 (cond
19665 ((run-hook-with-args-until-success 'org-metadown-hook))
19666 ((org-region-active-p)
19667 (let* ((a (min (region-beginning) (region-end)))
19668 (b (max (region-beginning) (region-end)))
19669 (c (save-excursion (goto-char b)
19670 (move-beginning-of-line 1)))
19671 (d (save-excursion (goto-char b)
19672 (move-end-of-line 1) (1+ (point)))))
19673 (transpose-regions a b c d)
19674 (goto-char d)))
19675 ((org-at-table-p) (call-interactively 'org-table-move-row))
19676 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19677 ((org-at-item-p) (call-interactively 'org-move-item-down))
19678 (t (org-drag-element-forward))))
19680 (defun org-shiftup (&optional arg)
19681 "Increase item in timestamp or increase priority of current headline.
19682 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19683 depending on context. See the individual commands for more information."
19684 (interactive "P")
19685 (cond
19686 ((run-hook-with-args-until-success 'org-shiftup-hook))
19687 ((and org-support-shift-select (org-region-active-p))
19688 (org-call-for-shift-select 'previous-line))
19689 ((org-at-timestamp-p t)
19690 (call-interactively (if org-edit-timestamp-down-means-later
19691 'org-timestamp-down 'org-timestamp-up)))
19692 ((and (not (eq org-support-shift-select 'always))
19693 org-enable-priority-commands
19694 (org-at-heading-p))
19695 (call-interactively 'org-priority-up))
19696 ((and (not org-support-shift-select) (org-at-item-p))
19697 (call-interactively 'org-previous-item))
19698 ((org-clocktable-try-shift 'up arg))
19699 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19700 (org-support-shift-select
19701 (org-call-for-shift-select 'previous-line))
19702 (t (org-shiftselect-error))))
19704 (defun org-shiftdown (&optional arg)
19705 "Decrease item in timestamp or decrease priority of current headline.
19706 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19707 depending on context. See the individual commands for more information."
19708 (interactive "P")
19709 (cond
19710 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19711 ((and org-support-shift-select (org-region-active-p))
19712 (org-call-for-shift-select 'next-line))
19713 ((org-at-timestamp-p t)
19714 (call-interactively (if org-edit-timestamp-down-means-later
19715 'org-timestamp-up 'org-timestamp-down)))
19716 ((and (not (eq org-support-shift-select 'always))
19717 org-enable-priority-commands
19718 (org-at-heading-p))
19719 (call-interactively 'org-priority-down))
19720 ((and (not org-support-shift-select) (org-at-item-p))
19721 (call-interactively 'org-next-item))
19722 ((org-clocktable-try-shift 'down arg))
19723 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19724 (org-support-shift-select
19725 (org-call-for-shift-select 'next-line))
19726 (t (org-shiftselect-error))))
19728 (defun org-shiftright (&optional arg)
19729 "Cycle the thing at point or in the current line, depending on context.
19730 Depending on context, this does one of the following:
19732 - switch a timestamp at point one day into the future
19733 - on a headline, switch to the next TODO keyword.
19734 - on an item, switch entire list to the next bullet type
19735 - on a property line, switch to the next allowed value
19736 - on a clocktable definition line, move time block into the future"
19737 (interactive "P")
19738 (cond
19739 ((run-hook-with-args-until-success 'org-shiftright-hook))
19740 ((and org-support-shift-select (org-region-active-p))
19741 (org-call-for-shift-select 'forward-char))
19742 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19743 ((and (not (eq org-support-shift-select 'always))
19744 (org-at-heading-p))
19745 (let ((org-inhibit-logging
19746 (not org-treat-S-cursor-todo-selection-as-state-change))
19747 (org-inhibit-blocking
19748 (not org-treat-S-cursor-todo-selection-as-state-change)))
19749 (org-call-with-arg 'org-todo 'right)))
19750 ((or (and org-support-shift-select
19751 (not (eq org-support-shift-select 'always))
19752 (org-at-item-bullet-p))
19753 (and (not org-support-shift-select) (org-at-item-p)))
19754 (org-call-with-arg 'org-cycle-list-bullet nil))
19755 ((and (not (eq org-support-shift-select 'always))
19756 (org-at-property-p))
19757 (call-interactively 'org-property-next-allowed-value))
19758 ((org-clocktable-try-shift 'right arg))
19759 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19760 (org-support-shift-select
19761 (org-call-for-shift-select 'forward-char))
19762 (t (org-shiftselect-error))))
19764 (defun org-shiftleft (&optional arg)
19765 "Cycle the thing at point or in the current line, depending on context.
19766 Depending on context, this does one of the following:
19768 - switch a timestamp at point one day into the past
19769 - on a headline, switch to the previous TODO keyword.
19770 - on an item, switch entire list to the previous bullet type
19771 - on a property line, switch to the previous allowed value
19772 - on a clocktable definition line, move time block into the past"
19773 (interactive "P")
19774 (cond
19775 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19776 ((and org-support-shift-select (org-region-active-p))
19777 (org-call-for-shift-select 'backward-char))
19778 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19779 ((and (not (eq org-support-shift-select 'always))
19780 (org-at-heading-p))
19781 (let ((org-inhibit-logging
19782 (not org-treat-S-cursor-todo-selection-as-state-change))
19783 (org-inhibit-blocking
19784 (not org-treat-S-cursor-todo-selection-as-state-change)))
19785 (org-call-with-arg 'org-todo 'left)))
19786 ((or (and org-support-shift-select
19787 (not (eq org-support-shift-select 'always))
19788 (org-at-item-bullet-p))
19789 (and (not org-support-shift-select) (org-at-item-p)))
19790 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19791 ((and (not (eq org-support-shift-select 'always))
19792 (org-at-property-p))
19793 (call-interactively 'org-property-previous-allowed-value))
19794 ((org-clocktable-try-shift 'left arg))
19795 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19796 (org-support-shift-select
19797 (org-call-for-shift-select 'backward-char))
19798 (t (org-shiftselect-error))))
19800 (defun org-shiftcontrolright ()
19801 "Switch to next TODO set."
19802 (interactive)
19803 (cond
19804 ((and org-support-shift-select (org-region-active-p))
19805 (org-call-for-shift-select 'forward-word))
19806 ((and (not (eq org-support-shift-select 'always))
19807 (org-at-heading-p))
19808 (org-call-with-arg 'org-todo 'nextset))
19809 (org-support-shift-select
19810 (org-call-for-shift-select 'forward-word))
19811 (t (org-shiftselect-error))))
19813 (defun org-shiftcontrolleft ()
19814 "Switch to previous TODO set."
19815 (interactive)
19816 (cond
19817 ((and org-support-shift-select (org-region-active-p))
19818 (org-call-for-shift-select 'backward-word))
19819 ((and (not (eq org-support-shift-select 'always))
19820 (org-at-heading-p))
19821 (org-call-with-arg 'org-todo 'previousset))
19822 (org-support-shift-select
19823 (org-call-for-shift-select 'backward-word))
19824 (t (org-shiftselect-error))))
19826 (defun org-shiftcontrolup (&optional n)
19827 "Change timestamps synchronously up in CLOCK log lines.
19828 Optional argument N tells to change by that many units."
19829 (interactive "P")
19830 (cond ((and (not org-support-shift-select)
19831 (org-at-clock-log-p)
19832 (org-at-timestamp-p t))
19833 (org-clock-timestamps-up n))
19834 (t (org-shiftselect-error))))
19836 (defun org-shiftcontroldown (&optional n)
19837 "Change timestamps synchronously down in CLOCK log lines.
19838 Optional argument N tells to change by that many units."
19839 (interactive "P")
19840 (cond ((and (not org-support-shift-select)
19841 (org-at-clock-log-p)
19842 (org-at-timestamp-p t))
19843 (org-clock-timestamps-down n))
19844 (t (org-shiftselect-error))))
19846 (defun org-ctrl-c-ret ()
19847 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19848 (interactive)
19849 (cond
19850 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19851 (t (call-interactively 'org-insert-heading))))
19853 (defun org-find-visible ()
19854 (let ((s (point)))
19855 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19856 (get-char-property s 'invisible)))
19858 (defun org-find-invisible ()
19859 (let ((s (point)))
19860 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19861 (not (get-char-property s 'invisible))))
19864 (defun org-copy-visible (beg end)
19865 "Copy the visible parts of the region."
19866 (interactive "r")
19867 (let (snippets s)
19868 (save-excursion
19869 (save-restriction
19870 (narrow-to-region beg end)
19871 (setq s (goto-char (point-min)))
19872 (while (not (= (point) (point-max)))
19873 (goto-char (org-find-invisible))
19874 (push (buffer-substring s (point)) snippets)
19875 (setq s (goto-char (org-find-visible))))))
19876 (kill-new (apply 'concat (nreverse snippets)))))
19878 (defun org-copy-special ()
19879 "Copy region in table or copy current subtree.
19880 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19881 See the individual commands for more information."
19882 (interactive)
19883 (call-interactively
19884 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19886 (defun org-cut-special ()
19887 "Cut region in table or cut current subtree.
19888 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19889 See the individual commands for more information."
19890 (interactive)
19891 (call-interactively
19892 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19894 (defun org-paste-special (arg)
19895 "Paste rectangular region into table, or past subtree relative to level.
19896 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19897 See the individual commands for more information."
19898 (interactive "P")
19899 (if (org-at-table-p)
19900 (org-table-paste-rectangle)
19901 (org-paste-subtree arg)))
19903 (defsubst org-in-fixed-width-region-p ()
19904 "Is point in a fixed-width region?"
19905 (save-match-data
19906 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19908 (defun org-edit-special (&optional arg)
19909 "Call a special editor for the element at point.
19910 When at a table, call the formula editor with `org-table-edit-formulas'.
19911 When in a source code block, call `org-edit-src-code'.
19912 When in a fixed-width region, call `org-edit-fixed-width-region'.
19913 When at an #+INCLUDE keyword, visit the included file.
19914 On a link, call `ffap' to visit the link at point.
19915 Otherwise, return a user error."
19916 (interactive)
19917 (let ((element (org-element-at-point)))
19918 (assert (not buffer-read-only) nil
19919 "Buffer is read-only: %s" (buffer-name))
19920 (case (org-element-type element)
19921 (src-block
19922 (if (not arg) (org-edit-src-code)
19923 (let* ((info (org-babel-get-src-block-info))
19924 (lang (nth 0 info))
19925 (params (nth 2 info))
19926 (session (cdr (assq :session params))))
19927 (if (not session) (org-edit-src-code)
19928 ;; At a src-block with a session and function called with
19929 ;; an ARG: switch to the buffer related to the inferior
19930 ;; process.
19931 (funcall (intern (concat "org-babel-prep-session:" lang))
19932 session params)))))
19933 (keyword
19934 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19935 (find-file
19936 (org-remove-double-quotes
19937 (car (org-split-string (org-element-property :value element)))))
19938 (user-error "No special environment to edit here")))
19939 (table
19940 (if (eq (org-element-property :type element) 'table.el)
19941 (org-edit-src-code)
19942 (call-interactively 'org-table-edit-formulas)))
19943 ;; Only Org tables contain `table-row' type elements.
19944 (table-row (call-interactively 'org-table-edit-formulas))
19945 ((example-block export-block) (org-edit-src-code))
19946 (fixed-width (org-edit-fixed-width-region))
19947 (otherwise
19948 ;; No notable element at point. Though, we may be at a link,
19949 ;; which is an object. Thus, scan deeper.
19950 (if (eq (org-element-type (org-element-context element)) 'link)
19951 (call-interactively 'ffap)
19952 (user-error "No special environment to edit here"))))))
19954 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19955 (defun org-ctrl-c-ctrl-c (&optional arg)
19956 "Set tags in headline, or update according to changed information at point.
19958 This command does many different things, depending on context:
19960 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19961 this is what we do.
19963 - If the cursor is on a statistics cookie, update it.
19965 - If the cursor is in a headline, prompt for tags and insert them
19966 into the current line, aligned to `org-tags-column'. When called
19967 with prefix arg, realign all tags in the current buffer.
19969 - If the cursor is in one of the special #+KEYWORD lines, this
19970 triggers scanning the buffer for these lines and updating the
19971 information.
19973 - If the cursor is inside a table, realign the table. This command
19974 works even if the automatic table editor has been turned off.
19976 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19977 the entire table.
19979 - If the cursor is at a footnote reference or definition, jump to
19980 the corresponding definition or references, respectively.
19982 - If the cursor is a the beginning of a dynamic block, update it.
19984 - If the current buffer is a capture buffer, close note and file it.
19986 - If the cursor is on a <<<target>>>, update radio targets and
19987 corresponding links in this buffer.
19989 - If the cursor is on a numbered item in a plain list, renumber the
19990 ordered list.
19992 - If the cursor is on a checkbox, toggle it.
19994 - If the cursor is on a code block, evaluate it. The variable
19995 `org-confirm-babel-evaluate' can be used to control prompting
19996 before code block evaluation, by default every code block
19997 evaluation requires confirmation. Code block evaluation can be
19998 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19999 (interactive "P")
20000 (cond
20001 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20002 org-occur-highlights
20003 org-latex-fragment-image-overlays)
20004 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20005 (org-remove-occur-highlights)
20006 (org-remove-latex-fragment-image-overlays)
20007 (message "Temporary highlights/overlays removed from current buffer"))
20008 ((and (local-variable-p 'org-finish-function (current-buffer))
20009 (fboundp org-finish-function))
20010 (funcall org-finish-function))
20011 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20013 (let* ((context (org-element-context)) (type (org-element-type context)))
20014 ;; Test if point is within a blank line.
20015 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20016 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20017 (user-error "C-c C-c can do nothing useful at this location"))
20018 ;; For convenience: at the first line of a paragraph on the
20019 ;; same line as an item, apply function on that item instead.
20020 (when (eq type 'paragraph)
20021 (let ((parent (org-element-property :parent context)))
20022 (when (and (eq (org-element-type parent) 'item)
20023 (= (point-at-bol) (org-element-property :begin parent)))
20024 (setq context parent type 'item))))
20025 ;; Act according to type of element or object at point.
20026 (case type
20027 (clock (org-clock-update-time-maybe))
20028 (dynamic-block
20029 (save-excursion
20030 (goto-char (org-element-property :post-affiliated context))
20031 (org-update-dblock)))
20032 (footnote-definition
20033 (goto-char (org-element-property :post-affiliated context))
20034 (call-interactively 'org-footnote-action))
20035 (footnote-reference (call-interactively 'org-footnote-action))
20036 ((headline inlinetask)
20037 (save-excursion (goto-char (org-element-property :begin context))
20038 (call-interactively 'org-set-tags)))
20039 (item
20040 ;; At an item: a double C-u set checkbox to "[-]"
20041 ;; unconditionally, whereas a single one will toggle its
20042 ;; presence. Without an universal argument, if the item
20043 ;; has a checkbox, toggle it. Otherwise repair the list.
20044 (let* ((box (org-element-property :checkbox context))
20045 (struct (org-element-property :structure context))
20046 (old-struct (copy-tree struct))
20047 (parents (org-list-parents-alist struct))
20048 (prevs (org-list-prevs-alist struct))
20049 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20050 (org-list-set-checkbox
20051 (org-element-property :begin context) struct
20052 (cond ((equal arg '(16)) "[-]")
20053 ((and (not box) (equal arg '(4))) "[ ]")
20054 ((or (not box) (equal arg '(4))) nil)
20055 ((eq box 'on) "[ ]")
20056 (t "[X]")))
20057 ;; Mimic `org-list-write-struct' but with grabbing
20058 ;; a return value from `org-list-struct-fix-box'.
20059 (org-list-struct-fix-ind struct parents 2)
20060 (org-list-struct-fix-item-end struct)
20061 (org-list-struct-fix-bul struct prevs)
20062 (org-list-struct-fix-ind struct parents)
20063 (let ((block-item
20064 (org-list-struct-fix-box struct parents prevs orderedp)))
20065 (if (and box (equal struct old-struct))
20066 (if (equal arg '(16))
20067 (message "Checkboxes already reset")
20068 (user-error "Cannot toggle this checkbox: %s"
20069 (if (eq box 'on)
20070 "all subitems checked"
20071 "unchecked subitems")))
20072 (org-list-struct-apply-struct struct old-struct)
20073 (org-update-checkbox-count-maybe))
20074 (when block-item
20075 (message "Checkboxes were removed due to empty box at line %d"
20076 (org-current-line block-item))))))
20077 (keyword
20078 (let ((org-inhibit-startup-visibility-stuff t)
20079 (org-startup-align-all-tables nil))
20080 (when (boundp 'org-table-coordinate-overlays)
20081 (mapc 'delete-overlay org-table-coordinate-overlays)
20082 (setq org-table-coordinate-overlays nil))
20083 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20084 (message "Local setup has been refreshed"))
20085 (plain-list
20086 ;; At a plain list, with a double C-u argument, set
20087 ;; checkboxes of each item to "[-]", whereas a single one
20088 ;; will toggle their presence according to the state of the
20089 ;; first item in the list. Without an argument, repair the
20090 ;; list.
20091 (let* ((begin (org-element-property :contents-begin context))
20092 (struct (org-element-property :structure context))
20093 (old-struct (copy-tree struct))
20094 (first-box (save-excursion
20095 (goto-char begin)
20096 (looking-at org-list-full-item-re)
20097 (match-string-no-properties 3)))
20098 (new-box (cond ((equal arg '(16)) "[-]")
20099 ((equal arg '(4)) (unless first-box "[ ]"))
20100 ((equal first-box "[X]") "[ ]")
20101 (t "[X]"))))
20102 (cond
20103 (arg
20104 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20105 (org-list-get-all-items
20106 begin struct (org-list-prevs-alist struct))))
20107 ((and first-box (eq (point) begin))
20108 ;; For convenience, when point is at bol on the first
20109 ;; item of the list and no argument is provided, simply
20110 ;; toggle checkbox of that item, if any.
20111 (org-list-set-checkbox begin struct new-box)))
20112 (org-list-write-struct
20113 struct (org-list-parents-alist struct) old-struct)
20114 (org-update-checkbox-count-maybe)
20115 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
20116 ((property-drawer node-property)
20117 (call-interactively 'org-property-action))
20118 ((radio-target target)
20119 (call-interactively 'org-update-radio-target-regexp))
20120 (statistics-cookie
20121 (call-interactively 'org-update-statistics-cookies))
20122 ((table table-cell table-row)
20123 ;; At a table, recalculate every field and align it. Also
20124 ;; send the table if necessary. If the table has
20125 ;; a `table.el' type, just give up. At a table row or
20126 ;; cell, maybe recalculate line but always align table.
20127 (if (eq (org-element-property :type context) 'table.el)
20128 (message "Use C-c ' to edit table.el tables")
20129 (let ((org-enable-table-editor t))
20130 (if (or (eq type 'table)
20131 ;; Check if point is at a TBLFM line.
20132 (and (eq type 'table-row)
20133 (= (point) (org-element-property :end context))))
20134 (save-excursion
20135 (goto-char (org-element-property :contents-begin context))
20136 (org-call-with-arg 'org-table-recalculate (or arg t))
20137 (orgtbl-send-table 'maybe))
20138 (org-table-maybe-eval-formula)
20139 (cond (arg (call-interactively 'org-table-recalculate))
20140 ((org-table-maybe-recalculate-line))
20141 (t (org-table-align)))))))
20142 (timestamp (org-timestamp-change 0 'day))
20143 (otherwise
20144 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20145 (user-error
20146 "C-c C-c can do nothing useful at this location")))))))))
20148 (defun org-mode-restart ()
20149 "Restart Org-mode, to scan again for special lines.
20150 Also updates the keyword regular expressions."
20151 (interactive)
20152 (org-mode)
20153 (message "Org-mode restarted"))
20155 (defun org-kill-note-or-show-branches ()
20156 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20157 (interactive)
20158 (if (not org-finish-function)
20159 (progn
20160 (hide-subtree)
20161 (call-interactively 'show-branches))
20162 (let ((org-note-abort t))
20163 (funcall org-finish-function))))
20165 (defun org-return (&optional indent)
20166 "Goto next table row or insert a newline.
20167 Calls `org-table-next-row' or `newline', depending on context.
20168 See the individual commands for more information."
20169 (interactive)
20170 (let (org-ts-what)
20171 (cond
20172 ((or (bobp) (org-in-src-block-p))
20173 (if indent (newline-and-indent) (newline)))
20174 ((org-at-table-p)
20175 (org-table-justify-field-maybe)
20176 (call-interactively 'org-table-next-row))
20177 ;; when `newline-and-indent' is called within a list, make sure
20178 ;; text moved stays inside the item.
20179 ((and (org-in-item-p) indent)
20180 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20181 (progn
20182 (save-match-data (newline))
20183 (org-indent-line-to (length (match-string 0))))
20184 (let ((ind (org-get-indentation)))
20185 (newline)
20186 (if (org-looking-back org-list-end-re)
20187 (org-indent-line)
20188 (org-indent-line-to ind)))))
20189 ((and org-return-follows-link
20190 (org-at-timestamp-p t)
20191 (not (eq org-ts-what 'after)))
20192 (org-follow-timestamp-link))
20193 ((and org-return-follows-link
20194 (let ((tprop (get-text-property (point) 'face)))
20195 (or (eq tprop 'org-link)
20196 (and (listp tprop) (memq 'org-link tprop)))))
20197 (call-interactively 'org-open-at-point))
20198 ((and (org-at-heading-p)
20199 (looking-at
20200 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20201 (org-show-entry)
20202 (end-of-line 1)
20203 (newline))
20204 (t (if indent (newline-and-indent) (newline))))))
20206 (defun org-return-indent ()
20207 "Goto next table row or insert a newline and indent.
20208 Calls `org-table-next-row' or `newline-and-indent', depending on
20209 context. See the individual commands for more information."
20210 (interactive)
20211 (org-return t))
20213 (defun org-ctrl-c-star ()
20214 "Compute table, or change heading status of lines.
20215 Calls `org-table-recalculate' or `org-toggle-heading',
20216 depending on context."
20217 (interactive)
20218 (cond
20219 ((org-at-table-p)
20220 (call-interactively 'org-table-recalculate))
20222 ;; Convert all lines in region to list items
20223 (call-interactively 'org-toggle-heading))))
20225 (defun org-ctrl-c-minus ()
20226 "Insert separator line in table or modify bullet status of line.
20227 Also turns a plain line or a region of lines into list items.
20228 Calls `org-table-insert-hline', `org-toggle-item', or
20229 `org-cycle-list-bullet', depending on context."
20230 (interactive)
20231 (cond
20232 ((org-at-table-p)
20233 (call-interactively 'org-table-insert-hline))
20234 ((org-region-active-p)
20235 (call-interactively 'org-toggle-item))
20236 ((org-in-item-p)
20237 (call-interactively 'org-cycle-list-bullet))
20239 (call-interactively 'org-toggle-item))))
20241 (defun org-toggle-item (arg)
20242 "Convert headings or normal lines to items, items to normal lines.
20243 If there is no active region, only the current line is considered.
20245 If the first non blank line in the region is a headline, convert
20246 all headlines to items, shifting text accordingly.
20248 If it is an item, convert all items to normal lines.
20250 If it is normal text, change region into a list of items.
20251 With a prefix argument ARG, change the region in a single item."
20252 (interactive "P")
20253 (let ((shift-text
20254 (function
20255 ;; Shift text in current section to IND, from point to END.
20256 ;; The function leaves point to END line.
20257 (lambda (ind end)
20258 (let ((min-i 1000) (end (copy-marker end)))
20259 ;; First determine the minimum indentation (MIN-I) of
20260 ;; the text.
20261 (save-excursion
20262 (catch 'exit
20263 (while (< (point) end)
20264 (let ((i (org-get-indentation)))
20265 (cond
20266 ;; Skip blank lines and inline tasks.
20267 ((looking-at "^[ \t]*$"))
20268 ((looking-at org-outline-regexp-bol))
20269 ;; We can't find less than 0 indentation.
20270 ((zerop i) (throw 'exit (setq min-i 0)))
20271 ((< i min-i) (setq min-i i))))
20272 (forward-line))))
20273 ;; Then indent each line so that a line indented to
20274 ;; MIN-I becomes indented to IND. Ignore blank lines
20275 ;; and inline tasks in the process.
20276 (let ((delta (- ind min-i)))
20277 (while (< (point) end)
20278 (unless (or (looking-at "^[ \t]*$")
20279 (looking-at org-outline-regexp-bol))
20280 (org-indent-line-to (+ (org-get-indentation) delta)))
20281 (forward-line)))))))
20282 (skip-blanks
20283 (function
20284 ;; Return beginning of first non-blank line, starting from
20285 ;; line at POS.
20286 (lambda (pos)
20287 (save-excursion
20288 (goto-char pos)
20289 (skip-chars-forward " \r\t\n")
20290 (point-at-bol)))))
20291 beg end)
20292 ;; Determine boundaries of changes.
20293 (if (org-region-active-p)
20294 (setq beg (funcall skip-blanks (region-beginning))
20295 end (copy-marker (region-end)))
20296 (setq beg (funcall skip-blanks (point-at-bol))
20297 end (copy-marker (point-at-eol))))
20298 ;; Depending on the starting line, choose an action on the text
20299 ;; between BEG and END.
20300 (org-with-limited-levels
20301 (save-excursion
20302 (goto-char beg)
20303 (cond
20304 ;; Case 1. Start at an item: de-itemize. Note that it only
20305 ;; happens when a region is active: `org-ctrl-c-minus'
20306 ;; would call `org-cycle-list-bullet' otherwise.
20307 ((org-at-item-p)
20308 (while (< (point) end)
20309 (when (org-at-item-p)
20310 (skip-chars-forward " \t")
20311 (delete-region (point) (match-end 0)))
20312 (forward-line)))
20313 ;; Case 2. Start at an heading: convert to items.
20314 ((org-at-heading-p)
20315 (let* ((bul (org-list-bullet-string "-"))
20316 (bul-len (length bul))
20317 ;; Indentation of the first heading. It should be
20318 ;; relative to the indentation of its parent, if any.
20319 (start-ind (save-excursion
20320 (cond
20321 ((not org-adapt-indentation) 0)
20322 ((not (outline-previous-heading)) 0)
20323 (t (length (match-string 0))))))
20324 ;; Level of first heading. Further headings will be
20325 ;; compared to it to determine hierarchy in the list.
20326 (ref-level (org-reduced-level (org-outline-level))))
20327 (while (< (point) end)
20328 (let* ((level (org-reduced-level (org-outline-level)))
20329 (delta (max 0 (- level ref-level))))
20330 ;; If current headline is less indented than the first
20331 ;; one, set it as reference, in order to preserve
20332 ;; subtrees.
20333 (when (< level ref-level) (setq ref-level level))
20334 (replace-match bul t t)
20335 (org-indent-line-to (+ start-ind (* delta bul-len)))
20336 ;; Ensure all text down to END (or SECTION-END) belongs
20337 ;; to the newly created item.
20338 (let ((section-end (save-excursion
20339 (or (outline-next-heading) (point)))))
20340 (forward-line)
20341 (funcall shift-text
20342 (+ start-ind (* (1+ delta) bul-len))
20343 (min end section-end)))))))
20344 ;; Case 3. Normal line with ARG: make the first line of region
20345 ;; an item, and shift indentation of others lines to
20346 ;; set them as item's body.
20347 (arg (let* ((bul (org-list-bullet-string "-"))
20348 (bul-len (length bul))
20349 (ref-ind (org-get-indentation)))
20350 (skip-chars-forward " \t")
20351 (insert bul)
20352 (forward-line)
20353 (while (< (point) end)
20354 ;; Ensure that lines less indented than first one
20355 ;; still get included in item body.
20356 (funcall shift-text
20357 (+ ref-ind bul-len)
20358 (min end (save-excursion (or (outline-next-heading)
20359 (point)))))
20360 (forward-line))))
20361 ;; Case 4. Normal line without ARG: turn each non-item line
20362 ;; into an item.
20364 (while (< (point) end)
20365 (unless (or (org-at-heading-p) (org-at-item-p))
20366 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20367 (replace-match
20368 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20369 (forward-line))))))))
20371 (defun org-toggle-heading (&optional nstars)
20372 "Convert headings to normal text, or items or text to headings.
20373 If there is no active region, only convert the current line.
20375 With a \\[universal-argument] prefix, convert the whole list at
20376 point into heading.
20378 In a region:
20380 - If the first non blank line is a headline, remove the stars
20381 from all headlines in the region.
20383 - If it is a normal line, turn each and every normal line (i.e.,
20384 not an heading or an item) in the region into headings. If you
20385 want to convert only the first line of this region, use one
20386 universal prefix argument.
20388 - If it is a plain list item, turn all plain list items into headings.
20390 When converting a line into a heading, the number of stars is chosen
20391 such that the lines become children of the current entry. However,
20392 when a numeric prefix argument is given, its value determines the
20393 number of stars to add."
20394 (interactive "P")
20395 (let ((skip-blanks
20396 (function
20397 ;; Return beginning of first non-blank line, starting from
20398 ;; line at POS.
20399 (lambda (pos)
20400 (save-excursion
20401 (goto-char pos)
20402 (while (org-at-comment-p) (forward-line))
20403 (skip-chars-forward " \r\t\n")
20404 (point-at-bol)))))
20405 beg end toggled)
20406 ;; Determine boundaries of changes. If a universal prefix has
20407 ;; been given, put the list in a region. If region ends at a bol,
20408 ;; do not consider the last line to be in the region.
20410 (when (and current-prefix-arg (org-at-item-p))
20411 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20412 (org-mark-element))
20414 (if (org-region-active-p)
20415 (setq beg (funcall skip-blanks (region-beginning))
20416 end (copy-marker (save-excursion
20417 (goto-char (region-end))
20418 (if (bolp) (point) (point-at-eol)))))
20419 (setq beg (funcall skip-blanks (point-at-bol))
20420 end (copy-marker (point-at-eol))))
20421 ;; Ensure inline tasks don't count as headings.
20422 (org-with-limited-levels
20423 (save-excursion
20424 (goto-char beg)
20425 (cond
20426 ;; Case 1. Started at an heading: de-star headings.
20427 ((org-at-heading-p)
20428 (while (< (point) end)
20429 (when (org-at-heading-p t)
20430 (looking-at org-outline-regexp) (replace-match "")
20431 (setq toggled t))
20432 (forward-line)))
20433 ;; Case 2. Started at an item: change items into headlines.
20434 ;; One star will be added by `org-list-to-subtree'.
20435 ((org-at-item-p)
20436 (let* ((stars (make-string
20437 ;; subtract the star that will be added again by
20438 ;; `org-list-to-subtree'
20439 (if (numberp nstars) (1- nstars)
20440 (or (org-current-level) 0))
20441 ?*))
20442 (add-stars
20443 (cond (nstars "") ; stars from prefix only
20444 ((equal stars "") "") ; before first heading
20445 (org-odd-levels-only "*") ; inside heading, odd
20446 (t "")))) ; inside heading, oddeven
20447 (while (< (point) end)
20448 (when (org-at-item-p)
20449 ;; Pay attention to cases when region ends before list.
20450 (let* ((struct (org-list-struct))
20451 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20452 (save-restriction
20453 (narrow-to-region (point) list-end)
20454 (insert
20455 (org-list-to-subtree
20456 (org-list-parse-list t)
20457 '(:istart (concat stars add-stars (funcall get-stars depth))
20458 :icount (concat stars add-stars (funcall get-stars depth)))))))
20459 (setq toggled t))
20460 (forward-line))))
20461 ;; Case 3. Started at normal text: make every line an heading,
20462 ;; skipping headlines and items.
20463 (t (let* ((stars
20464 (make-string
20465 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20466 (add-stars
20467 (cond (nstars "") ; stars from prefix only
20468 ((equal stars "") "*") ; before first heading
20469 (org-odd-levels-only "**") ; inside heading, odd
20470 (t "*"))) ; inside heading, oddeven
20471 (rpl (concat stars add-stars " "))
20472 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20473 (while (< (point) (if (equal nstars '(4)) lend end))
20474 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20475 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20476 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20477 (forward-line)))))))
20478 (unless toggled (message "Cannot toggle heading from here"))))
20480 (defun org-meta-return (&optional arg)
20481 "Insert a new heading or wrap a region in a table.
20482 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20483 See the individual commands for more information."
20484 (interactive "P")
20485 (cond
20486 ((run-hook-with-args-until-success 'org-metareturn-hook))
20487 ((or (org-at-drawer-p) (org-at-property-p))
20488 (newline-and-indent))
20489 ((org-at-table-p)
20490 (call-interactively 'org-table-wrap-region))
20491 (t (call-interactively 'org-insert-heading))))
20493 ;;; Menu entries
20495 (defsubst org-in-subtree-not-table-p ()
20496 "Are we in a subtree and not in a table?"
20497 (and (not (org-before-first-heading-p))
20498 (not (org-at-table-p))))
20500 ;; Define the Org-mode menus
20501 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20502 '("Tbl"
20503 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20504 ["Next Field" org-cycle (org-at-table-p)]
20505 ["Previous Field" org-shifttab (org-at-table-p)]
20506 ["Next Row" org-return (org-at-table-p)]
20507 "--"
20508 ["Blank Field" org-table-blank-field (org-at-table-p)]
20509 ["Edit Field" org-table-edit-field (org-at-table-p)]
20510 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20511 "--"
20512 ("Column"
20513 ["Move Column Left" org-metaleft (org-at-table-p)]
20514 ["Move Column Right" org-metaright (org-at-table-p)]
20515 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20516 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20517 ("Row"
20518 ["Move Row Up" org-metaup (org-at-table-p)]
20519 ["Move Row Down" org-metadown (org-at-table-p)]
20520 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20521 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20522 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20523 "--"
20524 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20525 ("Rectangle"
20526 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20527 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20528 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20529 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20530 "--"
20531 ("Calculate"
20532 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20533 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20534 ["Edit Formulas" org-edit-special (org-at-table-p)]
20535 "--"
20536 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20537 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20538 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20539 "--"
20540 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20541 "--"
20542 ["Sum Column/Rectangle" org-table-sum
20543 (or (org-at-table-p) (org-region-active-p))]
20544 ["Which Column?" org-table-current-column (org-at-table-p)])
20545 ["Debug Formulas"
20546 org-table-toggle-formula-debugger
20547 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20548 ["Show Col/Row Numbers"
20549 org-table-toggle-coordinate-overlays
20550 :style toggle
20551 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20552 "--"
20553 ["Create" org-table-create (and (not (org-at-table-p))
20554 org-enable-table-editor)]
20555 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20556 ["Import from File" org-table-import (not (org-at-table-p))]
20557 ["Export to File" org-table-export (org-at-table-p)]
20558 "--"
20559 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20561 (easy-menu-define org-org-menu org-mode-map "Org menu"
20562 '("Org"
20563 ("Show/Hide"
20564 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20565 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20566 ["Sparse Tree..." org-sparse-tree t]
20567 ["Reveal Context" org-reveal t]
20568 ["Show All" show-all t]
20569 "--"
20570 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20571 "--"
20572 ["New Heading" org-insert-heading t]
20573 ("Navigate Headings"
20574 ["Up" outline-up-heading t]
20575 ["Next" outline-next-visible-heading t]
20576 ["Previous" outline-previous-visible-heading t]
20577 ["Next Same Level" outline-forward-same-level t]
20578 ["Previous Same Level" outline-backward-same-level t]
20579 "--"
20580 ["Jump" org-goto t])
20581 ("Edit Structure"
20582 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20583 "--"
20584 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20585 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20586 "--"
20587 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20588 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20589 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20590 "--"
20591 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20592 "--"
20593 ["Copy visible text" org-copy-visible t]
20594 "--"
20595 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20596 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20597 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20598 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20599 "--"
20600 ["Sort Region/Children" org-sort t]
20601 "--"
20602 ["Convert to odd levels" org-convert-to-odd-levels t]
20603 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20604 ("Editing"
20605 ["Emphasis..." org-emphasize t]
20606 ["Edit Source Example" org-edit-special t]
20607 "--"
20608 ["Footnote new/jump" org-footnote-action t]
20609 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20610 ("Archive"
20611 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20612 "--"
20613 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20614 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20615 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20617 "--"
20618 ("Hyperlinks"
20619 ["Store Link (Global)" org-store-link t]
20620 ["Find existing link to here" org-occur-link-in-agenda-files t]
20621 ["Insert Link" org-insert-link t]
20622 ["Follow Link" org-open-at-point t]
20623 "--"
20624 ["Next link" org-next-link t]
20625 ["Previous link" org-previous-link t]
20626 "--"
20627 ["Descriptive Links"
20628 org-toggle-link-display
20629 :style radio
20630 :selected org-descriptive-links
20632 ["Literal Links"
20633 org-toggle-link-display
20634 :style radio
20635 :selected (not org-descriptive-links)])
20636 "--"
20637 ("TODO Lists"
20638 ["TODO/DONE/-" org-todo t]
20639 ("Select keyword"
20640 ["Next keyword" org-shiftright (org-at-heading-p)]
20641 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20642 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20643 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20644 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20645 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20646 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20647 "--"
20648 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20649 :selected org-enforce-todo-dependencies :style toggle :active t]
20650 "Settings for tree at point"
20651 ["Do Children sequentially" org-toggle-ordered-property :style radio
20652 :selected (org-entry-get nil "ORDERED")
20653 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20654 ["Do Children parallel" org-toggle-ordered-property :style radio
20655 :selected (not (org-entry-get nil "ORDERED"))
20656 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20657 "--"
20658 ["Set Priority" org-priority t]
20659 ["Priority Up" org-shiftup t]
20660 ["Priority Down" org-shiftdown t]
20661 "--"
20662 ["Get news from all feeds" org-feed-update-all t]
20663 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20664 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20665 ("TAGS and Properties"
20666 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20667 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20668 "--"
20669 ["Set property" org-set-property (not (org-before-first-heading-p))]
20670 ["Column view of properties" org-columns t]
20671 ["Insert Column View DBlock" org-insert-columns-dblock t])
20672 ("Dates and Scheduling"
20673 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20674 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20675 ("Change Date"
20676 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20677 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20678 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20679 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20680 ["Compute Time Range" org-evaluate-time-range t]
20681 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20682 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20683 "--"
20684 ["Custom time format" org-toggle-time-stamp-overlays
20685 :style radio :selected org-display-custom-times]
20686 "--"
20687 ["Goto Calendar" org-goto-calendar t]
20688 ["Date from Calendar" org-date-from-calendar t]
20689 "--"
20690 ["Start/Restart Timer" org-timer-start t]
20691 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20692 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20693 ["Insert Timer String" org-timer t]
20694 ["Insert Timer Item" org-timer-item t])
20695 ("Logging work"
20696 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20697 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20698 ["Clock out" org-clock-out t]
20699 ["Clock cancel" org-clock-cancel t]
20700 "--"
20701 ["Mark as default task" org-clock-mark-default-task t]
20702 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20703 ["Goto running clock" org-clock-goto t]
20704 "--"
20705 ["Display times" org-clock-display t]
20706 ["Create clock table" org-clock-report t]
20707 "--"
20708 ["Record DONE time"
20709 (progn (setq org-log-done (not org-log-done))
20710 (message "Switching to %s will %s record a timestamp"
20711 (car org-done-keywords)
20712 (if org-log-done "automatically" "not")))
20713 :style toggle :selected org-log-done])
20714 "--"
20715 ["Agenda Command..." org-agenda t]
20716 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20717 ("File List for Agenda")
20718 ("Special views current file"
20719 ["TODO Tree" org-show-todo-tree t]
20720 ["Check Deadlines" org-check-deadlines t]
20721 ["Timeline" org-timeline t]
20722 ["Tags/Property tree" org-match-sparse-tree t])
20723 "--"
20724 ["Export/Publish..." org-export-dispatch t]
20725 ("LaTeX"
20726 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20727 :selected org-cdlatex-mode]
20728 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20729 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20730 ["Modify math symbol" org-cdlatex-math-modify
20731 (org-inside-LaTeX-fragment-p)]
20732 ["Insert citation" org-reftex-citation t]
20733 "--"
20734 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20735 "--"
20736 ("MobileOrg"
20737 ["Push Files and Views" org-mobile-push t]
20738 ["Get Captured and Flagged" org-mobile-pull t]
20739 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20740 "--"
20741 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20742 "--"
20743 ("Documentation"
20744 ["Show Version" org-version t]
20745 ["Info Documentation" org-info t])
20746 ("Customize"
20747 ["Browse Org Group" org-customize t]
20748 "--"
20749 ["Expand This Menu" org-create-customize-menu
20750 (fboundp 'customize-menu-create)])
20751 ["Send bug report" org-submit-bug-report t]
20752 "--"
20753 ("Refresh/Reload"
20754 ["Refresh setup current buffer" org-mode-restart t]
20755 ["Reload Org (after update)" org-reload t]
20756 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20759 (defun org-info (&optional node)
20760 "Read documentation for Org-mode in the info system.
20761 With optional NODE, go directly to that node."
20762 (interactive)
20763 (info (format "(org)%s" (or node ""))))
20765 ;;;###autoload
20766 (defun org-submit-bug-report ()
20767 "Submit a bug report on Org-mode via mail.
20769 Don't hesitate to report any problems or inaccurate documentation.
20771 If you don't have setup sending mail from (X)Emacs, please copy the
20772 output buffer into your mail program, as it gives us important
20773 information about your Org-mode version and configuration."
20774 (interactive)
20775 (require 'reporter)
20776 (org-load-modules-maybe)
20777 (org-require-autoloaded-modules)
20778 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20779 (reporter-submit-bug-report
20780 "emacs-orgmode@gnu.org"
20781 (org-version nil 'full)
20782 (let (list)
20783 (save-window-excursion
20784 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20785 (delete-other-windows)
20786 (erase-buffer)
20787 (insert "You are about to submit a bug report to the Org-mode mailing list.
20789 We would like to add your full Org-mode and Outline configuration to the
20790 bug report. This greatly simplifies the work of the maintainer and
20791 other experts on the mailing list.
20793 HOWEVER, some variables you have customized may contain private
20794 information. The names of customers, colleagues, or friends, might
20795 appear in the form of file names, tags, todo states, or search strings.
20796 If you answer yes to the prompt, you might want to check and remove
20797 such private information before sending the email.")
20798 (add-text-properties (point-min) (point-max) '(face org-warning))
20799 (when (yes-or-no-p "Include your Org-mode configuration ")
20800 (mapatoms
20801 (lambda (v)
20802 (and (boundp v)
20803 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20804 (or (and (symbol-value v)
20805 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20806 (and
20807 (get v 'custom-type) (get v 'standard-value)
20808 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20809 (push v list)))))
20810 (kill-buffer (get-buffer "*Warn about privacy*"))
20811 list))
20812 nil nil
20813 "Remember to cover the basics, that is, what you expected to happen and
20814 what in fact did happen. You don't know how to make a good report? See
20816 http://orgmode.org/manual/Feedback.html#Feedback
20818 Your bug report will be posted to the Org-mode mailing list.
20819 ------------------------------------------------------------------------")
20820 (save-excursion
20821 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20822 (replace-match "\\1Bug: \\3 [\\2]")))))
20825 (defun org-install-agenda-files-menu ()
20826 (let ((bl (buffer-list)))
20827 (save-excursion
20828 (while bl
20829 (set-buffer (pop bl))
20830 (if (derived-mode-p 'org-mode) (setq bl nil)))
20831 (when (derived-mode-p 'org-mode)
20832 (easy-menu-change
20833 '("Org") "File List for Agenda"
20834 (append
20835 (list
20836 ["Edit File List" (org-edit-agenda-file-list) t]
20837 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20838 ["Remove Current File from List" org-remove-file t]
20839 ["Cycle through agenda files" org-cycle-agenda-files t]
20840 ["Occur in all agenda files" org-occur-in-agenda-files t]
20841 "--")
20842 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20844 ;;;; Documentation
20846 (defun org-require-autoloaded-modules ()
20847 (interactive)
20848 (mapc 'require
20849 '(org-agenda org-archive org-attach org-clock org-colview org-id
20850 org-remember org-table org-timer)))
20852 ;;;###autoload
20853 (defun org-reload (&optional uncompiled)
20854 "Reload all org lisp files.
20855 With prefix arg UNCOMPILED, load the uncompiled versions."
20856 (interactive "P")
20857 (require 'loadhist)
20858 (let* ((org-dir (org-find-library-dir "org"))
20859 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20860 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20861 (remove-re (mapconcat 'identity
20862 (mapcar (lambda (f) (concat "^" f "$"))
20863 (list (if (featurep 'xemacs)
20864 "org-colview"
20865 "org-colview-xemacs")
20866 "org" "org-loaddefs" "org-version"))
20867 "\\|"))
20868 (feats (delete-dups
20869 (mapcar 'file-name-sans-extension
20870 (mapcar 'file-name-nondirectory
20871 (delq nil
20872 (mapcar 'feature-file
20873 features))))))
20874 (lfeat (append
20875 (sort
20876 (setq feats
20877 (delq nil (mapcar
20878 (lambda (f)
20879 (if (and (string-match feature-re f)
20880 (not (string-match remove-re f)))
20881 f nil))
20882 feats)))
20883 'string-lessp)
20884 (list "org-version" "org")))
20885 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20886 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20887 load-uncore load-misses)
20888 (setq load-misses
20889 (delq 't
20890 (mapcar (lambda (f)
20891 (or (org-load-noerror-mustsuffix (concat org-dir f))
20892 (and (string= org-dir contrib-dir)
20893 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20894 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20895 (add-to-list 'load-uncore f 'append)
20898 lfeat)))
20899 (if load-uncore
20900 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20901 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20902 (if load-misses
20903 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20904 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20905 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20907 ;;;###autoload
20908 (defun org-customize ()
20909 "Call the customize function with org as argument."
20910 (interactive)
20911 (org-load-modules-maybe)
20912 (org-require-autoloaded-modules)
20913 (customize-browse 'org))
20915 (defun org-create-customize-menu ()
20916 "Create a full customization menu for Org-mode, insert it into the menu."
20917 (interactive)
20918 (org-load-modules-maybe)
20919 (org-require-autoloaded-modules)
20920 (if (fboundp 'customize-menu-create)
20921 (progn
20922 (easy-menu-change
20923 '("Org") "Customize"
20924 `(["Browse Org group" org-customize t]
20925 "--"
20926 ,(customize-menu-create 'org)
20927 ["Set" Custom-set t]
20928 ["Save" Custom-save t]
20929 ["Reset to Current" Custom-reset-current t]
20930 ["Reset to Saved" Custom-reset-saved t]
20931 ["Reset to Standard Settings" Custom-reset-standard t]))
20932 (message "\"Org\"-menu now contains full customization menu"))
20933 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20935 ;;;; Miscellaneous stuff
20937 ;;; Generally useful functions
20939 (defun org-get-at-bol (property)
20940 "Get text property PROPERTY at beginning of line."
20941 (get-text-property (point-at-bol) property))
20943 (defun org-find-text-property-in-string (prop s)
20944 "Return the first non-nil value of property PROP in string S."
20945 (or (get-text-property 0 prop s)
20946 (get-text-property (or (next-single-property-change 0 prop s) 0)
20947 prop s)))
20949 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20950 "Display the given MESSAGE as a warning."
20951 (if (fboundp 'display-warning)
20952 (display-warning 'org message
20953 (if (featurep 'xemacs) 'warning :warning))
20954 (let ((buf (get-buffer-create "*Org warnings*")))
20955 (with-current-buffer buf
20956 (goto-char (point-max))
20957 (insert "Warning (Org): " message)
20958 (unless (bolp)
20959 (newline)))
20960 (display-buffer buf)
20961 (sit-for 0))))
20963 (defun org-eval (form)
20964 "Eval FORM and return result."
20965 (condition-case error
20966 (eval form)
20967 (error (format "%%![Error: %s]" error))))
20969 (defun org-in-clocktable-p ()
20970 "Check if the cursor is in a clocktable."
20971 (let ((pos (point)) start)
20972 (save-excursion
20973 (end-of-line 1)
20974 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20975 (setq start (match-beginning 0))
20976 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20977 (>= (match-end 0) pos)
20978 start))))
20980 (defun org-in-commented-line ()
20981 "Is point in a line starting with `#'?"
20982 (equal (char-after (point-at-bol)) ?#))
20984 (defun org-in-indented-comment-line ()
20985 "Is point in a line starting with `#' after some white space?"
20986 (save-excursion
20987 (save-match-data
20988 (goto-char (point-at-bol))
20989 (looking-at "[ \t]*#"))))
20991 (defun org-in-verbatim-emphasis ()
20992 (save-match-data
20993 (and (org-in-regexp org-emph-re 2)
20994 (>= (point) (match-beginning 3))
20995 (<= (point) (match-end 4))
20996 (member (match-string 3) '("=" "~")))))
20998 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20999 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21000 (if (and marker (marker-buffer marker)
21001 (buffer-live-p (marker-buffer marker)))
21002 (progn
21003 (org-pop-to-buffer-same-window (marker-buffer marker))
21004 (if (or (> marker (point-max)) (< marker (point-min)))
21005 (widen))
21006 (goto-char marker)
21007 (org-show-context 'org-goto))
21008 (if bookmark
21009 (bookmark-jump bookmark)
21010 (error "Cannot find location"))))
21012 (defun org-quote-csv-field (s)
21013 "Quote field for inclusion in CSV material."
21014 (if (string-match "[\",]" s)
21015 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21018 (defun org-force-self-insert (N)
21019 "Needed to enforce self-insert under remapping."
21020 (interactive "p")
21021 (self-insert-command N))
21023 (defun org-string-width (s)
21024 "Compute width of string, ignoring invisible characters.
21025 This ignores character with invisibility property `org-link', and also
21026 characters with property `org-cwidth', because these will become invisible
21027 upon the next fontification round."
21028 (let (b l)
21029 (when (or (eq t buffer-invisibility-spec)
21030 (assq 'org-link buffer-invisibility-spec))
21031 (while (setq b (text-property-any 0 (length s)
21032 'invisible 'org-link s))
21033 (setq s (concat (substring s 0 b)
21034 (substring s (or (next-single-property-change
21035 b 'invisible s) (length s)))))))
21036 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21037 (setq s (concat (substring s 0 b)
21038 (substring s (or (next-single-property-change
21039 b 'org-cwidth s) (length s))))))
21040 (setq l (string-width s) b -1)
21041 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21042 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21045 (defun org-shorten-string (s maxlength)
21046 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21047 If the string is shorter or has length MAXLENGTH, just return the
21048 original string. If it is longer, the functions finds a space in the
21049 string, breaks this string off at that locations and adds three dots
21050 as ellipsis. Including the ellipsis, the string will not be longer
21051 than MAXLENGTH. If finding a good breaking point in the string does
21052 not work, the string is just chopped off in the middle of a word
21053 if necessary."
21054 (if (<= (length s) maxlength)
21056 (let* ((n (max (- maxlength 4) 1))
21057 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21058 (if (string-match re s)
21059 (concat (match-string 1 s) "...")
21060 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21062 (defun org-get-indentation (&optional line)
21063 "Get the indentation of the current line, interpreting tabs.
21064 When LINE is given, assume it represents a line and compute its indentation."
21065 (if line
21066 (if (string-match "^ *" (org-remove-tabs line))
21067 (match-end 0))
21068 (save-excursion
21069 (beginning-of-line 1)
21070 (skip-chars-forward " \t")
21071 (current-column))))
21073 (defun org-get-string-indentation (s)
21074 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21075 (let ((n -1) (i 0) (w tab-width) c)
21076 (catch 'exit
21077 (while (< (setq n (1+ n)) (length s))
21078 (setq c (aref s n))
21079 (cond ((= c ?\ ) (setq i (1+ i)))
21080 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21081 (t (throw 'exit t)))))
21084 (defun org-remove-tabs (s &optional width)
21085 "Replace tabulators in S with spaces.
21086 Assumes that s is a single line, starting in column 0."
21087 (setq width (or width tab-width))
21088 (while (string-match "\t" s)
21089 (setq s (replace-match
21090 (make-string
21091 (- (* width (/ (+ (match-beginning 0) width) width))
21092 (match-beginning 0)) ?\ )
21093 t t s)))
21096 (defun org-fix-indentation (line ind)
21097 "Fix indentation in LINE.
21098 IND is a cons cell with target and minimum indentation.
21099 If the current indentation in LINE is smaller than the minimum,
21100 leave it alone. If it is larger than ind, set it to the target."
21101 (let* ((l (org-remove-tabs line))
21102 (i (org-get-indentation l))
21103 (i1 (car ind)) (i2 (cdr ind)))
21104 (if (>= i i2) (setq l (substring line i2)))
21105 (if (> i1 0)
21106 (concat (make-string i1 ?\ ) l)
21107 l)))
21109 (defun org-remove-indentation (code &optional n)
21110 "Remove the maximum common indentation from the lines in CODE.
21111 N may optionally be the number of spaces to remove."
21112 (with-temp-buffer
21113 (insert code)
21114 (org-do-remove-indentation n)
21115 (buffer-string)))
21117 (defun org-do-remove-indentation (&optional n)
21118 "Remove the maximum common indentation from the buffer."
21119 (untabify (point-min) (point-max))
21120 (let ((min 10000) re)
21121 (if n
21122 (setq min n)
21123 (goto-char (point-min))
21124 (while (re-search-forward "^ *[^ \n]" nil t)
21125 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21126 (unless (or (= min 0) (= min 10000))
21127 (setq re (format "^ \\{%d\\}" min))
21128 (goto-char (point-min))
21129 (while (re-search-forward re nil t)
21130 (replace-match "")
21131 (end-of-line 1))
21132 min)))
21134 (defun org-fill-template (template alist)
21135 "Find each %key of ALIST in TEMPLATE and replace it."
21136 (let ((case-fold-search nil)
21137 entry key value)
21138 (setq alist (sort (copy-sequence alist)
21139 (lambda (a b) (< (length (car a)) (length (car b))))))
21140 (while (setq entry (pop alist))
21141 (setq template
21142 (replace-regexp-in-string
21143 (concat "%" (regexp-quote (car entry)))
21144 (or (cdr entry) "") template t t)))
21145 template))
21147 (defun org-base-buffer (buffer)
21148 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21149 (if (not buffer)
21150 buffer
21151 (or (buffer-base-buffer buffer)
21152 buffer)))
21154 (defun org-trim (s)
21155 "Remove whitespace at beginning and end of string."
21156 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21157 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21160 (defun org-wrap (string &optional width lines)
21161 "Wrap string to either a number of lines, or a width in characters.
21162 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21163 that costs. If there is a word longer than WIDTH, the text is actually
21164 wrapped to the length of that word.
21165 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21166 many lines, whatever width that takes.
21167 The return value is a list of lines, without newlines at the end."
21168 (let* ((words (org-split-string string "[ \t\n]+"))
21169 (maxword (apply 'max (mapcar 'org-string-width words)))
21170 w ll)
21171 (cond (width
21172 (org-do-wrap words (max maxword width)))
21173 (lines
21174 (setq w maxword)
21175 (setq ll (org-do-wrap words maxword))
21176 (if (<= (length ll) lines)
21178 (setq ll words)
21179 (while (> (length ll) lines)
21180 (setq w (1+ w))
21181 (setq ll (org-do-wrap words w)))
21182 ll))
21183 (t (error "Cannot wrap this")))))
21185 (defun org-do-wrap (words width)
21186 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21187 (let (lines line)
21188 (while words
21189 (setq line (pop words))
21190 (while (and words (< (+ (length line) (length (car words))) width))
21191 (setq line (concat line " " (pop words))))
21192 (setq lines (push line lines)))
21193 (nreverse lines)))
21195 (defun org-split-string (string &optional separators)
21196 "Splits STRING into substrings at SEPARATORS.
21197 No empty strings are returned if there are matches at the beginning
21198 and end of string."
21199 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21200 (start 0)
21201 notfirst
21202 (list nil))
21203 (while (and (string-match rexp string
21204 (if (and notfirst
21205 (= start (match-beginning 0))
21206 (< start (length string)))
21207 (1+ start) start))
21208 (< (match-beginning 0) (length string)))
21209 (setq notfirst t)
21210 (or (eq (match-beginning 0) 0)
21211 (and (eq (match-beginning 0) (match-end 0))
21212 (eq (match-beginning 0) start))
21213 (setq list
21214 (cons (substring string start (match-beginning 0))
21215 list)))
21216 (setq start (match-end 0)))
21217 (or (eq start (length string))
21218 (setq list
21219 (cons (substring string start)
21220 list)))
21221 (nreverse list)))
21223 (defun org-quote-vert (s)
21224 "Replace \"|\" with \"\\vert\"."
21225 (while (string-match "|" s)
21226 (setq s (replace-match "\\vert" t t s)))
21229 (defun org-uuidgen-p (s)
21230 "Is S an ID created by UUIDGEN?"
21231 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21233 (defun org-in-src-block-p (&optional inside)
21234 "Whether point is in a code source block.
21235 When INSIDE is non-nil, don't consider we are within a src block
21236 when point is at #+BEGIN_SRC or #+END_SRC."
21237 (let ((case-fold-search t) ov)
21238 (or (and (setq ov (overlays-at (point)))
21239 (memq 'org-block-background
21240 (overlay-properties (car ov))))
21241 (and (not inside)
21242 (save-match-data
21243 (save-excursion
21244 (beginning-of-line)
21245 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21247 (defun org-context ()
21248 "Return a list of contexts of the current cursor position.
21249 If several contexts apply, all are returned.
21250 Each context entry is a list with a symbol naming the context, and
21251 two positions indicating start and end of the context. Possible
21252 contexts are:
21254 :headline anywhere in a headline
21255 :headline-stars on the leading stars in a headline
21256 :todo-keyword on a TODO keyword (including DONE) in a headline
21257 :tags on the TAGS in a headline
21258 :priority on the priority cookie in a headline
21259 :item on the first line of a plain list item
21260 :item-bullet on the bullet/number of a plain list item
21261 :checkbox on the checkbox in a plain list item
21262 :table in an org-mode table
21263 :table-special on a special filed in a table
21264 :table-table in a table.el table
21265 :clocktable in a clocktable
21266 :src-block in a source block
21267 :link on a hyperlink
21268 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21269 :target on a <<target>>
21270 :radio-target on a <<<radio-target>>>
21271 :latex-fragment on a LaTeX fragment
21272 :latex-preview on a LaTeX fragment with overlaid preview image
21274 This function expects the position to be visible because it uses font-lock
21275 faces as a help to recognize the following contexts: :table-special, :link,
21276 and :keyword."
21277 (let* ((f (get-text-property (point) 'face))
21278 (faces (if (listp f) f (list f)))
21279 (case-fold-search t)
21280 (p (point)) clist o)
21281 ;; First the large context
21282 (cond
21283 ((org-at-heading-p t)
21284 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21285 (when (progn
21286 (beginning-of-line 1)
21287 (looking-at org-todo-line-tags-regexp))
21288 (push (org-point-in-group p 1 :headline-stars) clist)
21289 (push (org-point-in-group p 2 :todo-keyword) clist)
21290 (push (org-point-in-group p 4 :tags) clist))
21291 (goto-char p)
21292 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21293 (if (looking-at "\\[#[A-Z0-9]\\]")
21294 (push (org-point-in-group p 0 :priority) clist)))
21296 ((org-at-item-p)
21297 (push (org-point-in-group p 2 :item-bullet) clist)
21298 (push (list :item (point-at-bol)
21299 (save-excursion (org-end-of-item) (point)))
21300 clist)
21301 (and (org-at-item-checkbox-p)
21302 (push (org-point-in-group p 0 :checkbox) clist)))
21304 ((org-at-table-p)
21305 (push (list :table (org-table-begin) (org-table-end)) clist)
21306 (if (memq 'org-formula faces)
21307 (push (list :table-special
21308 (previous-single-property-change p 'face)
21309 (next-single-property-change p 'face)) clist)))
21310 ((org-at-table-p 'any)
21311 (push (list :table-table) clist)))
21312 (goto-char p)
21314 (let ((case-fold-search t))
21315 ;; New the "medium" contexts: clocktables, source blocks
21316 (cond ((org-in-clocktable-p)
21317 (push (list :clocktable
21318 (and (or (looking-at "#\\+BEGIN: clocktable")
21319 (search-backward "#+BEGIN: clocktable" nil t))
21320 (match-beginning 0))
21321 (and (re-search-forward "#\\+END:?" nil t)
21322 (match-end 0))) clist))
21323 ((org-in-src-block-p)
21324 (push (list :src-block
21325 (and (or (looking-at "#\\+BEGIN_SRC")
21326 (search-backward "#+BEGIN_SRC" nil t))
21327 (match-beginning 0))
21328 (and (search-forward "#+END_SRC" nil t)
21329 (match-beginning 0))) clist))))
21330 (goto-char p)
21332 ;; Now the small context
21333 (cond
21334 ((org-at-timestamp-p)
21335 (push (org-point-in-group p 0 :timestamp) clist))
21336 ((memq 'org-link faces)
21337 (push (list :link
21338 (previous-single-property-change p 'face)
21339 (next-single-property-change p 'face)) clist))
21340 ((memq 'org-special-keyword faces)
21341 (push (list :keyword
21342 (previous-single-property-change p 'face)
21343 (next-single-property-change p 'face)) clist))
21344 ((org-at-target-p)
21345 (push (org-point-in-group p 0 :target) clist)
21346 (goto-char (1- (match-beginning 0)))
21347 (if (looking-at org-radio-target-regexp)
21348 (push (org-point-in-group p 0 :radio-target) clist))
21349 (goto-char p))
21350 ((setq o (car (delq nil
21351 (mapcar
21352 (lambda (x)
21353 (if (memq x org-latex-fragment-image-overlays) x))
21354 (overlays-at (point))))))
21355 (push (list :latex-fragment
21356 (overlay-start o) (overlay-end o)) clist)
21357 (push (list :latex-preview
21358 (overlay-start o) (overlay-end o)) clist))
21359 ((org-inside-LaTeX-fragment-p)
21360 ;; FIXME: positions wrong.
21361 (push (list :latex-fragment (point) (point)) clist)))
21363 (setq clist (nreverse (delq nil clist)))
21364 clist))
21366 ;; FIXME: Compare with at-regexp-p Do we need both?
21367 (defun org-in-regexp (re &optional nlines visually)
21368 "Check if point is inside a match of regexp.
21369 Normally only the current line is checked, but you can include NLINES extra
21370 lines both before and after point into the search.
21371 If VISUALLY is set, require that the cursor is not after the match but
21372 really on, so that the block visually is on the match."
21373 (catch 'exit
21374 (let ((pos (point))
21375 (eol (point-at-eol (+ 1 (or nlines 0))))
21376 (inc (if visually 1 0)))
21377 (save-excursion
21378 (beginning-of-line (- 1 (or nlines 0)))
21379 (while (re-search-forward re eol t)
21380 (if (and (<= (match-beginning 0) pos)
21381 (>= (+ inc (match-end 0)) pos))
21382 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21384 (defun org-at-regexp-p (regexp)
21385 "Is point inside a match of REGEXP in the current line?"
21386 (catch 'exit
21387 (save-excursion
21388 (let ((pos (point)) (end (point-at-eol)))
21389 (beginning-of-line 1)
21390 (while (re-search-forward regexp end t)
21391 (if (and (<= (match-beginning 0) pos)
21392 (>= (match-end 0) pos))
21393 (throw 'exit t)))
21394 nil))))
21396 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21397 "Non-nil when point is between matches of START-RE and END-RE.
21399 Also return a non-nil value when point is on one of the matches.
21401 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21402 buffer positions. Default values are the positions of headlines
21403 surrounding the point.
21405 The functions returns a cons cell whose car (resp. cdr) is the
21406 position before START-RE (resp. after END-RE)."
21407 (save-match-data
21408 (let ((pos (point))
21409 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21410 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21411 beg end)
21412 (save-excursion
21413 ;; Point is on a block when on START-RE or if START-RE can be
21414 ;; found before it...
21415 (and (or (org-at-regexp-p start-re)
21416 (re-search-backward start-re limit-up t))
21417 (setq beg (match-beginning 0))
21418 ;; ... and END-RE after it...
21419 (goto-char (match-end 0))
21420 (re-search-forward end-re limit-down t)
21421 (> (setq end (match-end 0)) pos)
21422 ;; ... without another START-RE in-between.
21423 (goto-char (match-beginning 0))
21424 (not (re-search-backward start-re (1+ beg) t))
21425 ;; Return value.
21426 (cons beg end))))))
21428 (defun org-in-block-p (names)
21429 "Non-nil when point belongs to a block whose name belongs to NAMES.
21431 NAMES is a list of strings containing names of blocks.
21433 Return first block name matched, or nil. Beware that in case of
21434 nested blocks, the returned name may not belong to the closest
21435 block from point."
21436 (save-match-data
21437 (catch 'exit
21438 (let ((case-fold-search t)
21439 (lim-up (save-excursion (outline-previous-heading)))
21440 (lim-down (save-excursion (outline-next-heading))))
21441 (mapc (lambda (name)
21442 (let ((n (regexp-quote name)))
21443 (when (org-between-regexps-p
21444 (concat "^[ \t]*#\\+begin_" n)
21445 (concat "^[ \t]*#\\+end_" n)
21446 lim-up lim-down)
21447 (throw 'exit n))))
21448 names))
21449 nil)))
21451 (defun org-occur-in-agenda-files (regexp &optional nlines)
21452 "Call `multi-occur' with buffers for all agenda files."
21453 (interactive "sOrg-files matching: \np")
21454 (let* ((files (org-agenda-files))
21455 (tnames (mapcar 'file-truename files))
21456 (extra org-agenda-text-search-extra-files)
21458 (when (eq (car extra) 'agenda-archives)
21459 (setq extra (cdr extra))
21460 (setq files (org-add-archive-files files)))
21461 (while (setq f (pop extra))
21462 (unless (member (file-truename f) tnames)
21463 (add-to-list 'files f 'append)
21464 (add-to-list 'tnames (file-truename f) 'append)))
21465 (multi-occur
21466 (mapcar (lambda (x)
21467 (with-current-buffer
21468 (or (get-file-buffer x) (find-file-noselect x))
21469 (widen)
21470 (current-buffer)))
21471 files)
21472 regexp)))
21474 (if (boundp 'occur-mode-find-occurrence-hook)
21475 ;; Emacs 23
21476 (add-hook 'occur-mode-find-occurrence-hook
21477 (lambda ()
21478 (when (derived-mode-p 'org-mode)
21479 (org-reveal))))
21480 ;; Emacs 22
21481 (defadvice occur-mode-goto-occurrence
21482 (after org-occur-reveal activate)
21483 (and (derived-mode-p 'org-mode) (org-reveal)))
21484 (defadvice occur-mode-goto-occurrence-other-window
21485 (after org-occur-reveal activate)
21486 (and (derived-mode-p 'org-mode) (org-reveal)))
21487 (defadvice occur-mode-display-occurrence
21488 (after org-occur-reveal activate)
21489 (when (derived-mode-p 'org-mode)
21490 (let ((pos (occur-mode-find-occurrence)))
21491 (with-current-buffer (marker-buffer pos)
21492 (save-excursion
21493 (goto-char pos)
21494 (org-reveal)))))))
21496 (defun org-occur-link-in-agenda-files ()
21497 "Create a link and search for it in the agendas.
21498 The link is not stored in `org-stored-links', it is just created
21499 for the search purpose."
21500 (interactive)
21501 (let ((link (condition-case nil
21502 (org-store-link nil)
21503 (error "Unable to create a link to here"))))
21504 (org-occur-in-agenda-files (regexp-quote link))))
21506 (defun org-reverse-string (string)
21507 "Return the reverse of STRING."
21508 (apply 'string (reverse (string-to-list string))))
21510 (defun org-uniquify (list)
21511 "Remove duplicate elements from LIST."
21512 (let (res)
21513 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21514 res))
21516 (defun org-uniquify-alist (alist)
21517 "Merge duplicate elements of an alist.
21519 For example, in this alist:
21521 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21522 => '((a 1 3) (b 2))
21524 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21525 (let (rtn)
21526 (mapc
21527 (lambda (e)
21528 (let (n)
21529 (if (not (assoc (car e) rtn))
21530 (push e rtn)
21531 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21532 (setq rtn (assq-delete-all (car e) rtn))
21533 (push n rtn))))
21534 alist)
21535 rtn))
21537 (defun org-delete-all (elts list)
21538 "Remove all elements in ELTS from LIST."
21539 (while elts
21540 (setq list (delete (pop elts) list)))
21541 list)
21543 (defun org-count (cl-item cl-seq)
21544 "Count the number of occurrences of ITEM in SEQ.
21545 Taken from `count' in cl-seq.el with all keyword arguments removed."
21546 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21547 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21548 (while (< cl-start cl-end)
21549 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21550 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21551 (setq cl-start (1+ cl-start)))
21552 cl-count))
21554 (defun org-remove-if (predicate seq)
21555 "Remove everything from SEQ that fulfills PREDICATE."
21556 (let (res e)
21557 (while seq
21558 (setq e (pop seq))
21559 (if (not (funcall predicate e)) (push e res)))
21560 (nreverse res)))
21562 (defun org-remove-if-not (predicate seq)
21563 "Remove everything from SEQ that does not fulfill PREDICATE."
21564 (let (res e)
21565 (while seq
21566 (setq e (pop seq))
21567 (if (funcall predicate e) (push e res)))
21568 (nreverse res)))
21570 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21571 "Reduce two-argument FUNCTION across SEQ.
21572 Taken from `reduce' in cl-seq.el with all keyword arguments but
21573 \":initial-value\" removed."
21574 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21575 (cadr (memq :initial-value cl-keys)))
21576 (cl-seq (pop cl-seq))
21577 (t (funcall cl-func)))))
21578 (while cl-seq
21579 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21580 cl-accum))
21582 (defun org-back-over-empty-lines ()
21583 "Move backwards over whitespace, to the beginning of the first empty line.
21584 Returns the number of empty lines passed."
21585 (let ((pos (point)))
21586 (if (cdr (assoc 'heading org-blank-before-new-entry))
21587 (skip-chars-backward " \t\n\r")
21588 (unless (eobp)
21589 (forward-line -1)))
21590 (beginning-of-line 2)
21591 (goto-char (min (point) pos))
21592 (count-lines (point) pos)))
21594 (defun org-skip-whitespace ()
21595 (skip-chars-forward " \t\n\r"))
21597 (defun org-point-in-group (point group &optional context)
21598 "Check if POINT is in match-group GROUP.
21599 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21600 match. If the match group does not exist or point is not inside it,
21601 return nil."
21602 (and (match-beginning group)
21603 (>= point (match-beginning group))
21604 (<= point (match-end group))
21605 (if context
21606 (list context (match-beginning group) (match-end group))
21607 t)))
21609 (defun org-switch-to-buffer-other-window (&rest args)
21610 "Switch to buffer in a second window on the current frame.
21611 In particular, do not allow pop-up frames.
21612 Returns the newly created buffer."
21613 (org-no-popups
21614 (apply 'switch-to-buffer-other-window args)))
21616 (defun org-combine-plists (&rest plists)
21617 "Create a single property list from all plists in PLISTS.
21618 The process starts by copying the first list, and then setting properties
21619 from the other lists. Settings in the last list are the most significant
21620 ones and overrule settings in the other lists."
21621 (let ((rtn (copy-sequence (pop plists)))
21622 p v ls)
21623 (while plists
21624 (setq ls (pop plists))
21625 (while ls
21626 (setq p (pop ls) v (pop ls))
21627 (setq rtn (plist-put rtn p v))))
21628 rtn))
21630 (defun org-replace-escapes (string table)
21631 "Replace %-escapes in STRING with values in TABLE.
21632 TABLE is an association list with keys like \"%a\" and string values.
21633 The sequences in STRING may contain normal field width and padding information,
21634 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21635 so values can contain further %-escapes if they are define later in TABLE."
21636 (let ((tbl (copy-alist table))
21637 (case-fold-search nil)
21638 (pchg 0)
21639 e re rpl)
21640 (while (setq e (pop tbl))
21641 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21642 (when (and (cdr e) (string-match re (cdr e)))
21643 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21644 (safe "SREF"))
21645 (add-text-properties 0 3 (list 'sref sref) safe)
21646 (setcdr e (replace-match safe t t (cdr e)))))
21647 (while (string-match re string)
21648 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21649 (cdr e)))
21650 (setq string (replace-match rpl t t string))))
21651 (while (setq pchg (next-property-change pchg string))
21652 (let ((sref (get-text-property pchg 'sref string)))
21653 (when (and sref (string-match "SREF" string pchg))
21654 (setq string (replace-match sref t t string)))))
21655 string))
21657 (defun org-sublist (list start end)
21658 "Return a section of LIST, from START to END.
21659 Counting starts at 1."
21660 (let (rtn (c start))
21661 (setq list (nthcdr (1- start) list))
21662 (while (and list (<= c end))
21663 (push (pop list) rtn)
21664 (setq c (1+ c)))
21665 (nreverse rtn)))
21667 (defun org-find-base-buffer-visiting (file)
21668 "Like `find-buffer-visiting' but always return the base buffer and
21669 not an indirect buffer."
21670 (let ((buf (or (get-file-buffer file)
21671 (find-buffer-visiting file))))
21672 (if buf
21673 (or (buffer-base-buffer buf) buf)
21674 nil)))
21676 (defun org-image-file-name-regexp (&optional extensions)
21677 "Return regexp matching the file names of images.
21678 If EXTENSIONS is given, only match these."
21679 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21680 (image-file-name-regexp)
21681 (let ((image-file-name-extensions
21682 (or extensions
21683 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21684 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21685 (concat "\\."
21686 (regexp-opt (nconc (mapcar 'upcase
21687 image-file-name-extensions)
21688 image-file-name-extensions)
21690 "\\'"))))
21692 (defun org-file-image-p (file &optional extensions)
21693 "Return non-nil if FILE is an image."
21694 (save-match-data
21695 (string-match (org-image-file-name-regexp extensions) file)))
21697 (defun org-get-cursor-date (&optional with-time)
21698 "Return the date at cursor in as a time.
21699 This works in the calendar and in the agenda, anywhere else it just
21700 returns the current time.
21701 If WITH-TIME is non-nil, returns the time of the event at point (in
21702 the agenda) or the current time of the day."
21703 (let (date day defd tp tm hod mod)
21704 (when with-time
21705 (setq tp (get-text-property (point) 'time))
21706 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21707 (setq hod (string-to-number (match-string 1 tp))
21708 mod (string-to-number (match-string 2 tp))))
21709 (or tp (setq hod (nth 2 (decode-time (current-time)))
21710 mod (nth 1 (decode-time (current-time))))))
21711 (cond
21712 ((eq major-mode 'calendar-mode)
21713 (setq date (calendar-cursor-to-date)
21714 defd (encode-time 0 (or mod 0) (or hod 0)
21715 (nth 1 date) (nth 0 date) (nth 2 date))))
21716 ((eq major-mode 'org-agenda-mode)
21717 (setq day (get-text-property (point) 'day))
21718 (if day
21719 (setq date (calendar-gregorian-from-absolute day)
21720 defd (encode-time 0 (or mod 0) (or hod 0)
21721 (nth 1 date) (nth 0 date) (nth 2 date))))))
21722 (or defd (current-time))))
21724 (defun org-mark-subtree (&optional up)
21725 "Mark the current subtree.
21726 This puts point at the start of the current subtree, and mark at
21727 the end. If a numeric prefix UP is given, move up into the
21728 hierarchy of headlines by UP levels before marking the subtree."
21729 (interactive "P")
21730 (org-with-limited-levels
21731 (cond ((org-at-heading-p) (beginning-of-line))
21732 ((org-before-first-heading-p) (error "Not in a subtree"))
21733 (t (outline-previous-visible-heading 1))))
21734 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21735 (if (org-called-interactively-p 'any)
21736 (call-interactively 'org-mark-element)
21737 (org-mark-element)))
21740 ;;; Indentation
21742 (defun org-indent-line ()
21743 "Indent line depending on context."
21744 (interactive)
21745 (let* ((pos (point))
21746 (itemp (org-at-item-p))
21747 (case-fold-search t)
21748 (org-drawer-regexp (or org-drawer-regexp "\000"))
21749 (inline-task-p (and (featurep 'org-inlinetask)
21750 (org-inlinetask-in-task-p)))
21751 (inline-re (and inline-task-p
21752 (org-inlinetask-outline-regexp)))
21753 column)
21754 (if (and orgstruct-is-++ (eq pos (point)))
21755 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21756 (indent-according-to-mode))
21757 (beginning-of-line 1)
21758 (cond
21759 ;; Headings
21760 ((looking-at org-outline-regexp) (setq column 0))
21761 ;; Footnote definition
21762 ((looking-at org-footnote-definition-re) (setq column 0))
21763 ;; Literal examples
21764 ((looking-at "[ \t]*:\\( \\|$\\)")
21765 (setq column (org-get-indentation))) ; do nothing
21766 ;; Lists
21767 ((ignore-errors (goto-char (org-in-item-p)))
21768 (setq column (if itemp
21769 (org-get-indentation)
21770 (org-list-item-body-column (point))))
21771 (goto-char pos))
21772 ;; Drawers
21773 ((and (looking-at "[ \t]*:END:")
21774 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21775 (save-excursion
21776 (goto-char (1- (match-beginning 1)))
21777 (setq column (current-column))))
21778 ;; Special blocks
21779 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21780 (save-excursion
21781 (re-search-backward
21782 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21783 (setq column (org-get-indentation (match-string 0))))
21784 ((and (not (looking-at "[ \t]*#\\+begin_"))
21785 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21786 (save-excursion
21787 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21788 (setq column
21789 (cond ((equal (downcase (match-string 1)) "src")
21790 ;; src blocks: let `org-edit-src-exit' handle them
21791 (org-get-indentation))
21792 ((equal (downcase (match-string 1)) "example")
21793 (max (org-get-indentation)
21794 (org-get-indentation (match-string 0))))
21796 (org-get-indentation (match-string 0))))))
21797 ;; This line has nothing special, look at the previous relevant
21798 ;; line to compute indentation
21800 (beginning-of-line 0)
21801 (while (and (not (bobp))
21802 (not (looking-at org-table-line-regexp))
21803 (not (looking-at org-drawer-regexp))
21804 ;; When point started in an inline task, do not move
21805 ;; above task starting line.
21806 (not (and inline-task-p (looking-at inline-re)))
21807 ;; Skip drawers, blocks, empty lines, verbatim,
21808 ;; comments, tables, footnotes definitions, lists,
21809 ;; inline tasks.
21810 (or (and (looking-at "[ \t]*:END:")
21811 (re-search-backward org-drawer-regexp nil t))
21812 (and (looking-at "[ \t]*#\\+end_")
21813 (re-search-backward "[ \t]*#\\+begin_"nil t))
21814 (looking-at "[ \t]*[\n:#|]")
21815 (looking-at org-footnote-definition-re)
21816 (and (ignore-errors (goto-char (org-in-item-p)))
21817 (goto-char
21818 (org-list-get-top-point (org-list-struct))))
21819 (and (not inline-task-p)
21820 (featurep 'org-inlinetask)
21821 (org-inlinetask-in-task-p)
21822 (or (org-inlinetask-goto-beginning) t))))
21823 (beginning-of-line 0))
21824 (cond
21825 ;; There was an heading above.
21826 ((looking-at "\\*+[ \t]+")
21827 (if (not org-adapt-indentation)
21828 (setq column 0)
21829 (goto-char (match-end 0))
21830 (setq column (current-column))))
21831 ;; A drawer had started and is unfinished
21832 ((looking-at org-drawer-regexp)
21833 (goto-char (1- (match-beginning 1)))
21834 (setq column (current-column)))
21835 ;; Else, nothing noticeable found: get indentation and go on.
21836 (t (setq column (org-get-indentation))))))
21837 ;; Now apply indentation and move cursor accordingly
21838 (goto-char pos)
21839 (if (<= (current-column) (current-indentation))
21840 (org-indent-line-to column)
21841 (save-excursion (org-indent-line-to column)))
21842 ;; Special polishing for properties, see `org-property-format'
21843 (setq column (current-column))
21844 (beginning-of-line 1)
21845 (if (looking-at
21846 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21847 (replace-match (concat (match-string 1)
21848 (format org-property-format
21849 (match-string 2) (match-string 3)))
21850 t t))
21851 (org-move-to-column column))))
21853 (defun org-indent-drawer ()
21854 "Indent the drawer at point."
21855 (interactive)
21856 (let ((p (point))
21857 (e (and (save-excursion (re-search-forward ":END:" nil t))
21858 (match-end 0)))
21859 (folded
21860 (save-excursion
21861 (end-of-line)
21862 (when (overlays-at (point))
21863 (member 'invisible (overlay-properties
21864 (car (overlays-at (point)))))))))
21865 (when folded (org-cycle))
21866 (indent-for-tab-command)
21867 (while (and (move-beginning-of-line 2) (< (point) e))
21868 (indent-for-tab-command))
21869 (goto-char p)
21870 (when folded (org-cycle)))
21871 (message "Drawer at point indented"))
21873 (defun org-indent-block ()
21874 "Indent the block at point."
21875 (interactive)
21876 (let ((p (point))
21877 (case-fold-search t)
21878 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21879 (match-end 0)))
21880 (folded
21881 (save-excursion
21882 (end-of-line)
21883 (when (overlays-at (point))
21884 (member 'invisible (overlay-properties
21885 (car (overlays-at (point)))))))))
21886 (when folded (org-cycle))
21887 (indent-for-tab-command)
21888 (while (and (move-beginning-of-line 2) (< (point) e))
21889 (indent-for-tab-command))
21890 (goto-char p)
21891 (when folded (org-cycle)))
21892 (message "Block at point indented"))
21894 (defun org-indent-region (start end)
21895 "Indent region."
21896 (interactive "r")
21897 (save-excursion
21898 (let ((line-end (org-current-line end)))
21899 (goto-char start)
21900 (while (< (org-current-line) line-end)
21901 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21902 (t (call-interactively 'org-indent-line)))
21903 (move-beginning-of-line 2)))))
21906 ;;; Filling
21908 ;; We use our own fill-paragraph and auto-fill functions.
21910 ;; `org-fill-paragraph' relies on adaptive filling and context
21911 ;; checking. Appropriate `fill-prefix' is computed with
21912 ;; `org-adaptive-fill-function'.
21914 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21915 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21916 ;; `org-adaptive-fill-function' value. Internally,
21917 ;; `org-comment-line-break-function' breaks the line.
21919 ;; `org-setup-filling' installs filling and auto-filling related
21920 ;; variables during `org-mode' initialization.
21922 (defun org-setup-filling ()
21923 (interactive)
21924 ;; Prevent auto-fill from inserting unwanted new items.
21925 (when (boundp 'fill-nobreak-predicate)
21926 (org-set-local
21927 'fill-nobreak-predicate
21928 (org-uniquify
21929 (append fill-nobreak-predicate
21930 '(org-fill-paragraph-separate-nobreak-p
21931 org-fill-line-break-nobreak-p
21932 org-fill-paragraph-with-timestamp-nobreak-p)))))
21933 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21934 (org-set-local 'auto-fill-inhibit-regexp nil)
21935 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21936 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21937 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21939 (defvar org-element-paragraph-separate) ; org-element.el
21940 (defun org-fill-paragraph-separate-nobreak-p ()
21941 "Non-nil when a line break at point would insert a new item."
21942 (looking-at (substring org-element-paragraph-separate 1)))
21944 (defun org-fill-line-break-nobreak-p ()
21945 "Non-nil when a line break at point would create an Org line break."
21946 (save-excursion
21947 (skip-chars-backward "[ \t]")
21948 (skip-chars-backward "\\\\")
21949 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21951 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21952 "Non-nil when a line break at point would insert a new item."
21953 (and (org-at-timestamp-p t)
21954 (not (looking-at org-ts-regexp-both))))
21956 (declare-function message-in-body-p "message" ())
21957 (defvar orgtbl-line-start-regexp) ; From org-table.el
21958 (defun org-adaptive-fill-function ()
21959 "Compute a fill prefix for the current line.
21960 Return fill prefix, as a string, or nil if current line isn't
21961 meant to be filled."
21962 (let (prefix)
21963 (catch 'exit
21964 (when (derived-mode-p 'message-mode)
21965 (save-excursion
21966 (beginning-of-line)
21967 (cond ((or (not (message-in-body-p))
21968 (looking-at orgtbl-line-start-regexp))
21969 (throw 'exit nil))
21970 ((looking-at message-cite-prefix-regexp)
21971 (throw 'exit (match-string-no-properties 0)))
21972 ((looking-at org-outline-regexp)
21973 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21974 (org-with-wide-buffer
21975 (let* ((p (line-beginning-position))
21976 (element (save-excursion (beginning-of-line)
21977 (org-element-at-point)))
21978 (type (org-element-type element))
21979 (post-affiliated (org-element-property :post-affiliated element)))
21980 (unless (and post-affiliated (< p post-affiliated))
21981 (case type
21982 (comment (looking-at "[ \t]*# ?") (match-string 0))
21983 (footnote-definition "")
21984 ((item plain-list)
21985 (make-string (org-list-item-body-column
21986 (or post-affiliated
21987 (org-element-property :begin element)))
21988 ? ))
21989 (paragraph
21990 ;; Fill prefix is usually the same as the current line,
21991 ;; except if the paragraph is at the beginning of an item.
21992 (let ((parent (org-element-property :parent element)))
21993 (cond ((eq (org-element-type parent) 'item)
21994 (make-string (org-list-item-body-column
21995 (org-element-property :begin parent))
21996 ? ))
21997 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21998 (match-string 0))
21999 (t ""))))
22000 (comment-block
22001 ;; Only fill contents if P is within block boundaries.
22002 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22003 (forward-line)
22004 (point)))
22005 (cend (save-excursion
22006 (goto-char (org-element-property :end element))
22007 (skip-chars-backward " \r\t\n")
22008 (line-beginning-position))))
22009 (when (and (>= p cbeg) (< p cend))
22010 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22011 (match-string 0)
22012 "")))))))))))
22014 (declare-function message-goto-body "message" ())
22015 (defvar message-cite-prefix-regexp) ; From message.el
22016 (defun org-fill-paragraph (&optional justify)
22017 "Fill element at point, when applicable.
22019 This function only applies to comment blocks, comments, example
22020 blocks and paragraphs. Also, as a special case, re-align table
22021 when point is at one.
22023 If JUSTIFY is non-nil (interactively, with prefix argument),
22024 justify as well. If `sentence-end-double-space' is non-nil, then
22025 period followed by one space does not end a sentence, so don't
22026 break a line there. The variable `fill-column' controls the
22027 width for filling.
22029 For convenience, when point is at a plain list, an item or
22030 a footnote definition, try to fill the first paragraph within."
22031 (interactive)
22032 (if (and (derived-mode-p 'message-mode)
22033 (or (not (message-in-body-p))
22034 (save-excursion (move-beginning-of-line 1)
22035 (looking-at message-cite-prefix-regexp))))
22036 ;; First ensure filling is correct in message-mode.
22037 (let ((fill-paragraph-function
22038 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22039 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22040 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22041 (paragraph-separate
22042 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22043 (fill-paragraph nil))
22044 (with-syntax-table org-mode-transpose-word-syntax-table
22045 ;; Move to end of line in order to get the first paragraph
22046 ;; within a plain list or a footnote definition.
22047 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22048 ;; First check if point is in a blank line at the beginning of
22049 ;; the buffer. In that case, ignore filling.
22050 (case (org-element-type element)
22051 ;; Use major mode filling function is src blocks.
22052 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22053 ;; Align Org tables, leave table.el tables as-is.
22054 (table-row (org-table-align) t)
22055 (table
22056 (when (eq (org-element-property :type element) 'org)
22057 (org-table-align))
22059 (paragraph
22060 ;; Paragraphs may contain `line-break' type objects.
22061 (let ((beg (max (point-min)
22062 (org-element-property :contents-begin element)))
22063 (end (min (point-max)
22064 (org-element-property :contents-end element))))
22065 ;; Do nothing if point is at an affiliated keyword.
22066 (if (< (line-end-position) beg) t
22067 (when (derived-mode-p 'message-mode)
22068 ;; In `message-mode', do not fill following citation
22069 ;; in current paragraph nor text before message body.
22070 (let ((body-start (save-excursion (message-goto-body))))
22071 (when body-start (setq beg (max body-start beg))))
22072 (when (save-excursion
22073 (re-search-forward
22074 (concat "^" message-cite-prefix-regexp) end t))
22075 (setq end (match-beginning 0))))
22076 ;; Fill paragraph, taking line breaks into account.
22077 ;; For that, slice the paragraph using line breaks as
22078 ;; separators, and fill the parts in reverse order to
22079 ;; avoid messing with markers.
22080 (save-excursion
22081 (goto-char end)
22082 (mapc
22083 (lambda (pos)
22084 (fill-region-as-paragraph pos (point) justify)
22085 (goto-char pos))
22086 ;; Find the list of ending positions for line breaks
22087 ;; in the current paragraph. Add paragraph
22088 ;; beginning to include first slice.
22089 (nreverse
22090 (cons beg
22091 (org-element-map
22092 (org-element--parse-objects
22093 beg end nil (org-element-restriction 'paragraph))
22094 'line-break
22095 (lambda (lb) (org-element-property :end lb)))))))
22096 t)))
22097 ;; Contents of `comment-block' type elements should be
22098 ;; filled as plain text, but only if point is within block
22099 ;; markers.
22100 (comment-block
22101 (let* ((case-fold-search t)
22102 (beg (save-excursion
22103 (goto-char (org-element-property :begin element))
22104 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22105 (forward-line)
22106 (point)))
22107 (end (save-excursion
22108 (goto-char (org-element-property :end element))
22109 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22110 (line-beginning-position))))
22111 (when (and (>= (point) beg) (< (point) end))
22112 (fill-region-as-paragraph
22113 (save-excursion
22114 (end-of-line)
22115 (re-search-backward "^[ \t]*$" beg 'move)
22116 (line-beginning-position))
22117 (save-excursion
22118 (beginning-of-line)
22119 (re-search-forward "^[ \t]*$" end 'move)
22120 (line-beginning-position))
22121 justify)))
22123 ;; Fill comments.
22124 (comment (fill-comment-paragraph justify))
22125 ;; Ignore every other element.
22126 (otherwise t))))))
22128 (defun org-auto-fill-function ()
22129 "Auto-fill function."
22130 ;; Check if auto-filling is meaningful.
22131 (let ((fc (current-fill-column)))
22132 (when (and fc (> (current-column) fc))
22133 (let* ((fill-prefix (org-adaptive-fill-function))
22134 ;; Enforce empty fill prefix, if required. Otherwise, it
22135 ;; will be computed again.
22136 (adaptive-fill-mode (not (equal fill-prefix ""))))
22137 (when fill-prefix (do-auto-fill))))))
22139 (defun org-comment-line-break-function (&optional soft)
22140 "Break line at point and indent, continuing comment if within one.
22141 The inserted newline is marked hard if variable
22142 `use-hard-newlines' is true, unless optional argument SOFT is
22143 non-nil."
22144 (if soft (insert-and-inherit ?\n) (newline 1))
22145 (save-excursion (forward-char -1) (delete-horizontal-space))
22146 (delete-horizontal-space)
22147 (indent-to-left-margin)
22148 (insert-before-markers-and-inherit fill-prefix))
22151 ;;; Comments
22153 ;; Org comments syntax is quite complex. It requires the entire line
22154 ;; to be just a comment. Also, even with the right syntax at the
22155 ;; beginning of line, some some elements (i.e. verse-block or
22156 ;; example-block) don't accept comments. Usual Emacs comment commands
22157 ;; cannot cope with those requirements. Therefore, Org replaces them.
22159 ;; Org still relies on `comment-dwim', but cannot trust
22160 ;; `comment-only-p'. So, `comment-region-function' and
22161 ;; `uncomment-region-function' both point
22162 ;; to`org-comment-or-uncomment-region'. Eventually,
22163 ;; `org-insert-comment' takes care of insertion of comments at the
22164 ;; beginning of line.
22166 ;; `org-setup-comments-handling' install comments related variables
22167 ;; during `org-mode' initialization.
22169 (defun org-setup-comments-handling ()
22170 (interactive)
22171 (org-set-local 'comment-use-syntax nil)
22172 (org-set-local 'comment-start "# ")
22173 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22174 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22175 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22176 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22178 (defun org-insert-comment ()
22179 "Insert an empty comment above current line.
22180 If the line is empty, insert comment at its beginning."
22181 (beginning-of-line)
22182 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22183 (org-indent-line)
22184 (insert "# "))
22186 (defvar comment-empty-lines) ; From newcomment.el.
22187 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22188 "Comment or uncomment each non-blank line in the region.
22189 Uncomment each non-blank line between BEG and END if it only
22190 contains commented lines. Otherwise, comment them."
22191 (save-restriction
22192 ;; Restrict region
22193 (narrow-to-region (save-excursion (goto-char beg)
22194 (skip-chars-forward " \r\t\n" end)
22195 (line-beginning-position))
22196 (save-excursion (goto-char end)
22197 (skip-chars-backward " \r\t\n" beg)
22198 (line-end-position)))
22199 (let ((uncommentp
22200 ;; UNCOMMENTP is non-nil when every non blank line between
22201 ;; BEG and END is a comment.
22202 (save-excursion
22203 (goto-char (point-min))
22204 (while (and (not (eobp))
22205 (let ((element (org-element-at-point)))
22206 (and (eq (org-element-type element) 'comment)
22207 (goto-char (min (point-max)
22208 (org-element-property
22209 :end element)))))))
22210 (eobp))))
22211 (if uncommentp
22212 ;; Only blank lines and comments in region: uncomment it.
22213 (save-excursion
22214 (goto-char (point-min))
22215 (while (not (eobp))
22216 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22217 (replace-match "" nil nil nil 1))
22218 (forward-line)))
22219 ;; Comment each line in region.
22220 (let ((min-indent (point-max)))
22221 ;; First find the minimum indentation across all lines.
22222 (save-excursion
22223 (goto-char (point-min))
22224 (while (and (not (eobp)) (not (zerop min-indent)))
22225 (unless (looking-at "[ \t]*$")
22226 (setq min-indent (min min-indent (current-indentation))))
22227 (forward-line)))
22228 ;; Then loop over all lines.
22229 (save-excursion
22230 (goto-char (point-min))
22231 (while (not (eobp))
22232 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22233 ;; Don't get fooled by invisible text (e.g. link path)
22234 ;; when moving to column MIN-INDENT.
22235 (let ((buffer-invisibility-spec nil))
22236 (org-move-to-column min-indent t))
22237 (insert comment-start))
22238 (forward-line))))))))
22241 ;;; Planning
22243 ;; This section contains tools to operate on timestamp objects, as
22244 ;; returned by, e.g. `org-element-context'.
22246 (defun org-timestamp-has-time-p (timestamp)
22247 "Non-nil when TIMESTAMP has a time specified."
22248 (org-element-property :hour-start timestamp))
22250 (defun org-timestamp-format (timestamp format &optional end utc)
22251 "Format a TIMESTAMP element into a string.
22253 FORMAT is a format specifier to be passed to
22254 `format-time-string'.
22256 When optional argument END is non-nil, use end of date-range or
22257 time-range, if possible.
22259 When optional argument UTC is non-nil, time will be expressed as
22260 Universal Time."
22261 (format-time-string
22262 format
22263 (apply 'encode-time
22264 (cons 0
22265 (mapcar
22266 (lambda (prop) (or (org-element-property prop timestamp) 0))
22267 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22268 '(:minute-start :hour-start :day-start :month-start
22269 :year-start)))))
22270 utc))
22272 (defun org-timestamp-split-range (timestamp &optional end)
22273 "Extract a timestamp object from a date or time range.
22275 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22276 the end of the range. Otherwise, extract its start.
22278 Return a new timestamp object sharing the same parent as
22279 TIMESTAMP."
22280 (let ((type (org-element-property :type timestamp)))
22281 (if (memq type '(active inactive diary)) timestamp
22282 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22283 ;; Set new type.
22284 (org-element-put-property
22285 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22286 ;; Copy start properties over end properties if END is
22287 ;; non-nil. Otherwise, copy end properties over `start' ones.
22288 (let ((p-alist '((:minute-start . :minute-end)
22289 (:hour-start . :hour-end)
22290 (:day-start . :day-end)
22291 (:month-start . :month-end)
22292 (:year-start . :year-end))))
22293 (dolist (p-cell p-alist)
22294 (org-element-put-property
22295 split-ts
22296 (funcall (if end 'car 'cdr) p-cell)
22297 (org-element-property
22298 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22299 ;; Eventually refresh `:raw-value'.
22300 (org-element-put-property split-ts :raw-value nil)
22301 (org-element-put-property
22302 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22304 (defun org-timestamp-translate (timestamp &optional boundary)
22305 "Apply `org-translate-time' on a TIMESTAMP object.
22306 When optional argument BOUNDARY is non-nil, it is either the
22307 symbol `start' or `end'. In this case, only translate the
22308 starting or ending part of TIMESTAMP if it is a date or time
22309 range. Otherwise, translate both parts."
22310 (if (and (not boundary)
22311 (memq (org-element-property :type timestamp)
22312 '(active-range inactive-range)))
22313 (concat
22314 (org-translate-time
22315 (org-element-property :raw-value
22316 (org-timestamp-split-range timestamp)))
22317 "--"
22318 (org-translate-time
22319 (org-element-property :raw-value
22320 (org-timestamp-split-range timestamp t))))
22321 (org-translate-time
22322 (org-element-property
22323 :raw-value
22324 (if (not boundary) timestamp
22325 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22329 ;;; Other stuff.
22331 (defun org-toggle-fixed-width-section (arg)
22332 "Toggle the fixed-width export.
22333 If there is no active region, the QUOTE keyword at the current headline is
22334 inserted or removed. When present, it causes the text between this headline
22335 and the next to be exported as fixed-width text, and unmodified.
22336 If there is an active region, this command adds or removes a colon as the
22337 first character of this line. If the first character of a line is a colon,
22338 this line is also exported in fixed-width font."
22339 (interactive "P")
22340 (let* ((cc 0)
22341 (regionp (org-region-active-p))
22342 (beg (if regionp (region-beginning) (point)))
22343 (end (if regionp (region-end)))
22344 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22345 (case-fold-search nil)
22346 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22347 off)
22348 (if regionp
22349 (save-excursion
22350 (goto-char beg)
22351 (setq cc (current-column))
22352 (beginning-of-line 1)
22353 (setq off (looking-at re))
22354 (while (> nlines 0)
22355 (setq nlines (1- nlines))
22356 (beginning-of-line 1)
22357 (cond
22358 (arg
22359 (org-move-to-column cc t)
22360 (insert ": \n")
22361 (forward-line -1))
22362 ((and off (looking-at re))
22363 (replace-match "" t t nil 1))
22364 ((not off) (org-move-to-column cc t) (insert ": ")))
22365 (forward-line 1)))
22366 (save-excursion
22367 (org-back-to-heading)
22368 (cond
22369 ((looking-at (format org-heading-keyword-regexp-format
22370 org-quote-string))
22371 (goto-char (match-end 1))
22372 (looking-at (concat " +" org-quote-string))
22373 (replace-match "" t t)
22374 (when (eolp) (insert " ")))
22375 ((looking-at org-outline-regexp)
22376 (goto-char (match-end 0))
22377 (insert org-quote-string " ")))))))
22379 (defun org-reftex-citation ()
22380 "Use reftex-citation to insert a citation into the buffer.
22381 This looks for a line like
22383 #+BIBLIOGRAPHY: foo plain option:-d
22385 and derives from it that foo.bib is the bibliography file relevant
22386 for this document. It then installs the necessary environment for RefTeX
22387 to work in this buffer and calls `reftex-citation' to insert a citation
22388 into the buffer.
22390 Export of such citations to both LaTeX and HTML is handled by the contributed
22391 package org-exp-bibtex by Taru Karttunen."
22392 (interactive)
22393 (let ((reftex-docstruct-symbol 'rds)
22394 (reftex-cite-format "\\cite{%l}")
22395 rds bib)
22396 (save-excursion
22397 (save-restriction
22398 (widen)
22399 (let ((case-fold-search t)
22400 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22401 (if (not (save-excursion
22402 (or (re-search-forward re nil t)
22403 (re-search-backward re nil t))))
22404 (error "No bibliography defined in file")
22405 (setq bib (concat (match-string 1) ".bib")
22406 rds (list (list 'bib bib)))))))
22407 (call-interactively 'reftex-citation)))
22409 ;;;; Functions extending outline functionality
22411 (defun org-beginning-of-line (&optional arg)
22412 "Go to the beginning of the current line. If that is invisible, continue
22413 to a visible line beginning. This makes the function of C-a more intuitive.
22414 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22415 first attempt, and only move to after the tags when the cursor is already
22416 beyond the end of the headline."
22417 (interactive "P")
22418 (let ((pos (point))
22419 (special (if (consp org-special-ctrl-a/e)
22420 (car org-special-ctrl-a/e)
22421 org-special-ctrl-a/e))
22422 refpos)
22423 (if (org-bound-and-true-p visual-line-mode)
22424 (beginning-of-visual-line 1)
22425 (beginning-of-line 1))
22426 (if (and arg (fboundp 'move-beginning-of-line))
22427 (call-interactively 'move-beginning-of-line)
22428 (if (bobp)
22430 (backward-char 1)
22431 (if (org-truely-invisible-p)
22432 (while (and (not (bobp)) (org-truely-invisible-p))
22433 (backward-char 1)
22434 (beginning-of-line 1))
22435 (forward-char 1))))
22436 (when special
22437 (cond
22438 ((and (looking-at org-complex-heading-regexp)
22439 (= (char-after (match-end 1)) ?\ ))
22440 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22441 (point-at-eol)))
22442 (goto-char
22443 (if (eq special t)
22444 (cond ((> pos refpos) refpos)
22445 ((= pos (point)) refpos)
22446 (t (point)))
22447 (cond ((> pos (point)) (point))
22448 ((not (eq last-command this-command)) (point))
22449 (t refpos)))))
22450 ((org-at-item-p)
22451 ;; Being at an item and not looking at an the item means point
22452 ;; was previously moved to beginning of a visual line, which
22453 ;; doesn't contain the item. Therefore, do nothing special,
22454 ;; just stay here.
22455 (when (looking-at org-list-full-item-re)
22456 ;; Set special position at first white space character after
22457 ;; bullet, and check-box, if any.
22458 (let ((after-bullet
22459 (let ((box (match-end 3)))
22460 (if (not box) (match-end 1)
22461 (let ((after (char-after box)))
22462 (if (and after (= after ? )) (1+ box) box))))))
22463 ;; Special case: Move point to special position when
22464 ;; currently after it or at beginning of line.
22465 (if (eq special t)
22466 (when (or (> pos after-bullet) (= (point) pos))
22467 (goto-char after-bullet))
22468 ;; Reversed case: Move point to special position when
22469 ;; point was already at beginning of line and command is
22470 ;; repeated.
22471 (when (and (= (point) pos) (eq last-command this-command))
22472 (goto-char after-bullet))))))))
22473 (org-no-warnings
22474 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22476 (defun org-end-of-line (&optional arg)
22477 "Go to the end of the line.
22478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22479 tags on the first attempt, and only move to after the tags when
22480 the cursor is already beyond the end of the headline."
22481 (interactive "P")
22482 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22483 org-special-ctrl-a/e))
22484 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22485 'end-of-visual-line)
22486 ((fboundp 'move-end-of-line) 'move-end-of-line)
22487 (t 'end-of-line))))
22488 (if (or (not special) arg) (call-interactively move-fun)
22489 (let* ((element (save-excursion (beginning-of-line)
22490 (org-element-at-point)))
22491 (type (org-element-type element)))
22492 (cond
22493 ((memq type '(headline inlinetask))
22494 (let ((pos (point)))
22495 (beginning-of-line 1)
22496 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22497 (if (eq special t)
22498 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22499 (goto-char (match-beginning 1))
22500 (goto-char (match-end 0)))
22501 (if (or (< pos (match-end 0))
22502 (not (eq this-command last-command)))
22503 (goto-char (match-end 0))
22504 (goto-char (match-beginning 1))))
22505 (call-interactively move-fun))))
22506 ((org-element-property :hiddenp element)
22507 ;; If element is hidden, `move-end-of-line' would put point
22508 ;; after it. Use `end-of-line' to stay on current line.
22509 (call-interactively 'end-of-line))
22510 (t (call-interactively move-fun)))))
22511 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22513 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22514 (define-key org-mode-map "\C-e" 'org-end-of-line)
22516 (defun org-backward-sentence (&optional arg)
22517 "Go to beginning of sentence, or beginning of table field.
22518 This will call `backward-sentence' or `org-table-beginning-of-field',
22519 depending on context."
22520 (interactive "P")
22521 (cond
22522 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22523 (t (call-interactively 'backward-sentence))))
22525 (defun org-forward-sentence (&optional arg)
22526 "Go to end of sentence, or end of table field.
22527 This will call `forward-sentence' or `org-table-end-of-field',
22528 depending on context."
22529 (interactive "P")
22530 (cond
22531 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22532 (t (call-interactively 'forward-sentence))))
22534 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22535 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22537 (defun org-kill-line (&optional arg)
22538 "Kill line, to tags or end of line."
22539 (interactive "P")
22540 (cond
22541 ((or (not org-special-ctrl-k)
22542 (bolp)
22543 (not (org-at-heading-p)))
22544 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22545 org-ctrl-k-protect-subtree)
22546 (if (or (eq org-ctrl-k-protect-subtree 'error)
22547 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22548 (error "C-k aborted - would kill hidden subtree")))
22549 (call-interactively
22550 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22551 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22552 (kill-region (point) (match-beginning 1))
22553 (org-set-tags nil t))
22554 (t (kill-region (point) (point-at-eol)))))
22556 (define-key org-mode-map "\C-k" 'org-kill-line)
22558 (defun org-yank (&optional arg)
22559 "Yank. If the kill is a subtree, treat it specially.
22560 This command will look at the current kill and check if is a single
22561 subtree, or a series of subtrees[1]. If it passes the test, and if the
22562 cursor is at the beginning of a line or after the stars of a currently
22563 empty headline, then the yank is handled specially. How exactly depends
22564 on the value of the following variables, both set by default.
22566 org-yank-folded-subtrees
22567 When set, the subtree(s) will be folded after insertion, but only
22568 if doing so would now swallow text after the yanked text.
22570 org-yank-adjusted-subtrees
22571 When set, the subtree will be promoted or demoted in order to
22572 fit into the local outline tree structure, which means that the level
22573 will be adjusted so that it becomes the smaller one of the two
22574 *visible* surrounding headings.
22576 Any prefix to this command will cause `yank' to be called directly with
22577 no special treatment. In particular, a simple \\[universal-argument] prefix \
22578 will just
22579 plainly yank the text as it is.
22581 \[1] The test checks if the first non-white line is a heading
22582 and if there are no other headings with fewer stars."
22583 (interactive "P")
22584 (org-yank-generic 'yank arg))
22586 (defun org-yank-generic (command arg)
22587 "Perform some yank-like command.
22589 This function implements the behavior described in the `org-yank'
22590 documentation. However, it has been generalized to work for any
22591 interactive command with similar behavior."
22593 ;; pretend to be command COMMAND
22594 (setq this-command command)
22596 (if arg
22597 (call-interactively command)
22599 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22600 (and (org-kill-is-subtree-p)
22601 (or (bolp)
22602 (and (looking-at "[ \t]*$")
22603 (string-match
22604 "\\`\\*+\\'"
22605 (buffer-substring (point-at-bol) (point)))))))
22606 swallowp)
22607 (cond
22608 ((and subtreep org-yank-folded-subtrees)
22609 (let ((beg (point))
22610 end)
22611 (if (and subtreep org-yank-adjusted-subtrees)
22612 (org-paste-subtree nil nil 'for-yank)
22613 (call-interactively command))
22615 (setq end (point))
22616 (goto-char beg)
22617 (when (and (bolp) subtreep
22618 (not (setq swallowp
22619 (org-yank-folding-would-swallow-text beg end))))
22620 (org-with-limited-levels
22621 (or (looking-at org-outline-regexp)
22622 (re-search-forward org-outline-regexp-bol end t))
22623 (while (and (< (point) end) (looking-at org-outline-regexp))
22624 (hide-subtree)
22625 (org-cycle-show-empty-lines 'folded)
22626 (condition-case nil
22627 (outline-forward-same-level 1)
22628 (error (goto-char end))))))
22629 (when swallowp
22630 (message
22631 "Inserted text not folded because that would swallow text"))
22633 (goto-char end)
22634 (skip-chars-forward " \t\n\r")
22635 (beginning-of-line 1)
22636 (push-mark beg 'nomsg)))
22637 ((and subtreep org-yank-adjusted-subtrees)
22638 (let ((beg (point-at-bol)))
22639 (org-paste-subtree nil nil 'for-yank)
22640 (push-mark beg 'nomsg)))
22642 (call-interactively command))))))
22644 (defun org-yank-folding-would-swallow-text (beg end)
22645 "Would hide-subtree at BEG swallow any text after END?"
22646 (let (level)
22647 (org-with-limited-levels
22648 (save-excursion
22649 (goto-char beg)
22650 (when (or (looking-at org-outline-regexp)
22651 (re-search-forward org-outline-regexp-bol end t))
22652 (setq level (org-outline-level)))
22653 (goto-char end)
22654 (skip-chars-forward " \t\r\n\v\f")
22655 (if (or (eobp)
22656 (and (bolp) (looking-at org-outline-regexp)
22657 (<= (org-outline-level) level)))
22658 nil ; Nothing would be swallowed
22659 t))))) ; something would swallow
22661 (define-key org-mode-map "\C-y" 'org-yank)
22663 (defun org-truely-invisible-p ()
22664 "Check if point is at a character currently not visible.
22665 This version does not only check the character property, but also
22666 `visible-mode'."
22667 ;; Early versions of noutline don't have `outline-invisible-p'.
22668 (if (org-bound-and-true-p visible-mode)
22670 (outline-invisible-p)))
22672 (defun org-invisible-p2 ()
22673 "Check if point is at a character currently not visible."
22674 (save-excursion
22675 (if (and (eolp) (not (bobp))) (backward-char 1))
22676 ;; Early versions of noutline don't have `outline-invisible-p'.
22677 (outline-invisible-p)))
22679 (defun org-back-to-heading (&optional invisible-ok)
22680 "Call `outline-back-to-heading', but provide a better error message."
22681 (condition-case nil
22682 (outline-back-to-heading invisible-ok)
22683 (error (error "Before first headline at position %d in buffer %s"
22684 (point) (current-buffer)))))
22686 (defun org-before-first-heading-p ()
22687 "Before first heading?"
22688 (save-excursion
22689 (end-of-line)
22690 (null (re-search-backward org-outline-regexp-bol nil t))))
22692 (defun org-at-heading-p (&optional ignored)
22693 (outline-on-heading-p t))
22694 ;; Compatibility alias with Org versions < 7.8.03
22695 (defalias 'org-on-heading-p 'org-at-heading-p)
22697 (defun org-at-comment-p nil
22698 "Is cursor in a line starting with a # character?"
22699 (save-excursion
22700 (beginning-of-line)
22701 (looking-at "^#")))
22703 (defun org-at-drawer-p nil
22704 "Is cursor at a drawer keyword?"
22705 (save-excursion
22706 (move-beginning-of-line 1)
22707 (looking-at org-drawer-regexp)))
22709 (defun org-at-block-p nil
22710 "Is cursor at a block keyword?"
22711 (save-excursion
22712 (move-beginning-of-line 1)
22713 (looking-at org-block-regexp)))
22715 (defun org-point-at-end-of-empty-headline ()
22716 "If point is at the end of an empty headline, return t, else nil.
22717 If the heading only contains a TODO keyword, it is still still considered
22718 empty."
22719 (and (looking-at "[ \t]*$")
22720 (when org-todo-line-regexp
22721 (save-excursion
22722 (beginning-of-line 1)
22723 (let ((case-fold-search nil))
22724 (looking-at org-todo-line-regexp)
22725 (string= (match-string 3) ""))))))
22727 (defun org-at-heading-or-item-p ()
22728 (or (org-at-heading-p) (org-at-item-p)))
22730 (defun org-at-target-p ()
22731 (or (org-in-regexp org-radio-target-regexp)
22732 (org-in-regexp org-target-regexp)))
22733 ;; Compatibility alias with Org versions < 7.8.03
22734 (defalias 'org-on-target-p 'org-at-target-p)
22736 (defun org-up-heading-all (arg)
22737 "Move to the heading line of which the present line is a subheading.
22738 This function considers both visible and invisible heading lines.
22739 With argument, move up ARG levels."
22740 (if (fboundp 'outline-up-heading-all)
22741 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22742 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22744 (defun org-up-heading-safe ()
22745 "Move to the heading line of which the present line is a subheading.
22746 This version will not throw an error. It will return the level of the
22747 headline found, or nil if no higher level is found.
22749 Also, this function will be a lot faster than `outline-up-heading',
22750 because it relies on stars being the outline starters. This can really
22751 make a significant difference in outlines with very many siblings."
22752 (let (start-level re)
22753 (org-back-to-heading t)
22754 (setq start-level (funcall outline-level))
22755 (if (equal start-level 1)
22757 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22758 (if (re-search-backward re nil t)
22759 (funcall outline-level)))))
22761 (defun org-first-sibling-p ()
22762 "Is this heading the first child of its parents?"
22763 (interactive)
22764 (let ((re org-outline-regexp-bol)
22765 level l)
22766 (unless (org-at-heading-p t)
22767 (error "Not at a heading"))
22768 (setq level (funcall outline-level))
22769 (save-excursion
22770 (if (not (re-search-backward re nil t))
22772 (setq l (funcall outline-level))
22773 (< l level)))))
22775 (defun org-goto-sibling (&optional previous)
22776 "Goto the next sibling, even if it is invisible.
22777 When PREVIOUS is set, go to the previous sibling instead. Returns t
22778 when a sibling was found. When none is found, return nil and don't
22779 move point."
22780 (let ((fun (if previous 're-search-backward 're-search-forward))
22781 (pos (point))
22782 (re org-outline-regexp-bol)
22783 level l)
22784 (when (condition-case nil (org-back-to-heading t) (error nil))
22785 (setq level (funcall outline-level))
22786 (catch 'exit
22787 (or previous (forward-char 1))
22788 (while (funcall fun re nil t)
22789 (setq l (funcall outline-level))
22790 (when (< l level) (goto-char pos) (throw 'exit nil))
22791 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22792 (goto-char pos)
22793 nil))))
22795 (defun org-show-siblings ()
22796 "Show all siblings of the current headline."
22797 (save-excursion
22798 (while (org-goto-sibling) (org-flag-heading nil)))
22799 (save-excursion
22800 (while (org-goto-sibling 'previous)
22801 (org-flag-heading nil))))
22803 (defun org-goto-first-child ()
22804 "Goto the first child, even if it is invisible.
22805 Return t when a child was found. Otherwise don't move point and
22806 return nil."
22807 (let (level (pos (point)) (re org-outline-regexp-bol))
22808 (when (condition-case nil (org-back-to-heading t) (error nil))
22809 (setq level (outline-level))
22810 (forward-char 1)
22811 (if (and (re-search-forward re nil t) (> (outline-level) level))
22812 (progn (goto-char (match-beginning 0)) t)
22813 (goto-char pos) nil))))
22815 (defun org-show-hidden-entry ()
22816 "Show an entry where even the heading is hidden."
22817 (save-excursion
22818 (org-show-entry)))
22820 (defun org-flag-heading (flag &optional entry)
22821 "Flag the current heading. FLAG non-nil means make invisible.
22822 When ENTRY is non-nil, show the entire entry."
22823 (save-excursion
22824 (org-back-to-heading t)
22825 ;; Check if we should show the entire entry
22826 (if entry
22827 (progn
22828 (org-show-entry)
22829 (save-excursion
22830 (and (outline-next-heading)
22831 (org-flag-heading nil))))
22832 (outline-flag-region (max (point-min) (1- (point)))
22833 (save-excursion (outline-end-of-heading) (point))
22834 flag))))
22836 (defun org-get-next-sibling ()
22837 "Move to next heading of the same level, and return point.
22838 If there is no such heading, return nil.
22839 This is like outline-next-sibling, but invisible headings are ok."
22840 (let ((level (funcall outline-level)))
22841 (outline-next-heading)
22842 (while (and (not (eobp)) (> (funcall outline-level) level))
22843 (outline-next-heading))
22844 (if (or (eobp) (< (funcall outline-level) level))
22846 (point))))
22848 (defun org-get-last-sibling ()
22849 "Move to previous heading of the same level, and return point.
22850 If there is no such heading, return nil."
22851 (let ((opoint (point))
22852 (level (funcall outline-level)))
22853 (outline-previous-heading)
22854 (when (and (/= (point) opoint) (outline-on-heading-p t))
22855 (while (and (> (funcall outline-level) level)
22856 (not (bobp)))
22857 (outline-previous-heading))
22858 (if (< (funcall outline-level) level)
22860 (point)))))
22862 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22863 "Goto to the end of a subtree."
22864 ;; This contains an exact copy of the original function, but it uses
22865 ;; `org-back-to-heading', to make it work also in invisible
22866 ;; trees. And is uses an invisible-ok argument.
22867 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22868 ;; Furthermore, when used inside Org, finding the end of a large subtree
22869 ;; with many children and grandchildren etc, this can be much faster
22870 ;; than the outline version.
22871 (org-back-to-heading invisible-ok)
22872 (let ((first t)
22873 (level (funcall outline-level)))
22874 (if (and (derived-mode-p 'org-mode) (< level 1000))
22875 ;; A true heading (not a plain list item), in Org-mode
22876 ;; This means we can easily find the end by looking
22877 ;; only for the right number of stars. Using a regexp to do
22878 ;; this is so much faster than using a Lisp loop.
22879 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22880 (forward-char 1)
22881 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22882 ;; something else, do it the slow way
22883 (while (and (not (eobp))
22884 (or first (> (funcall outline-level) level)))
22885 (setq first nil)
22886 (outline-next-heading)))
22887 (unless to-heading
22888 (if (memq (preceding-char) '(?\n ?\^M))
22889 (progn
22890 ;; Go to end of line before heading
22891 (forward-char -1)
22892 (if (memq (preceding-char) '(?\n ?\^M))
22893 ;; leave blank line before heading
22894 (forward-char -1))))))
22895 (point))
22897 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22898 "Use Org version in org-mode, for dramatic speed-up."
22899 (if (derived-mode-p 'org-mode)
22900 (progn
22901 (org-end-of-subtree nil t)
22902 (unless (eobp) (backward-char 1)))
22903 ad-do-it))
22905 (defun org-end-of-meta-data-and-drawers ()
22906 "Jump to the first text after meta data and drawers in the current entry.
22907 This will move over empty lines, lines with planning time stamps,
22908 clocking lines, and drawers."
22909 (org-back-to-heading t)
22910 (let ((end (save-excursion (outline-next-heading) (point)))
22911 (re (concat "\\(" org-drawer-regexp "\\)"
22912 "\\|" "[ \t]*" org-keyword-time-regexp)))
22913 (forward-line 1)
22914 (while (re-search-forward re end t)
22915 (if (not (match-end 1))
22916 ;; empty or planning line
22917 (forward-line 1)
22918 ;; a drawer, find the end
22919 (re-search-forward "^[ \t]*:END:" end 'move)
22920 (forward-line 1)))
22921 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22922 (point)))
22924 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22925 "Move forward to the ARG'th subheading at same level as this one.
22926 Stop at the first and last subheadings of a superior heading.
22927 Normally this only looks at visible headings, but when INVISIBLE-OK is
22928 non-nil it will also look at invisible ones."
22929 (interactive "p")
22930 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22931 (if (and arg (< arg 0))
22932 (goto-char (point-min))
22933 (outline-next-heading))
22934 (org-at-heading-p)
22935 (let ((level (- (match-end 0) (match-beginning 0) 1))
22936 (f (if (and arg (< arg 0))
22937 're-search-backward
22938 're-search-forward))
22939 (count (if arg (abs arg) 1))
22940 (result (point)))
22941 (forward-char (if (and arg (< arg 0)) -1 1))
22942 (while (and (> count 0)
22943 (funcall f org-outline-regexp-bol nil 'move))
22944 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22945 (cond ((< l level) (setq count 0))
22946 ((and (= l level)
22947 (or invisible-ok
22948 (progn
22949 (goto-char (line-beginning-position))
22950 (not (outline-invisible-p)))))
22951 (setq count (1- count))
22952 (when (eq l level)
22953 (setq result (point)))))))
22954 (goto-char result))
22955 (beginning-of-line 1)))
22957 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22958 "Move backward to the ARG'th subheading at same level as this one.
22959 Stop at the first and last subheadings of a superior heading."
22960 (interactive "p")
22961 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22963 (defun org-next-block (arg &optional backward block-regexp)
22964 "Jump to the next block.
22965 With a prefix argument ARG, jump forward ARG many source blocks.
22966 When BACKWARD is non-nil, jump to the previous block.
22967 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22968 (interactive "p")
22969 (let ((re (or block-regexp org-block-regexp))
22970 (re-search-fn (or (and backward 're-search-backward)
22971 're-search-forward)))
22972 (if (looking-at re) (forward-char 1))
22973 (condition-case nil
22974 (funcall re-search-fn re nil nil arg)
22975 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22976 (goto-char (match-beginning 0)) (org-show-context)))
22978 (defun org-previous-block (arg &optional block-regexp)
22979 "Jump to the previous block.
22980 With a prefix argument ARG, jump backward ARG many source blocks.
22981 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22982 (interactive "p")
22983 (org-next-block arg t block-regexp))
22985 (defun org-forward-element ()
22986 "Move forward by one element.
22987 Move to the next element at the same level, when possible."
22988 (interactive)
22989 (cond ((eobp) (user-error "Cannot move further down"))
22990 ((org-with-limited-levels (org-at-heading-p))
22991 (let ((origin (point)))
22992 (goto-char (org-end-of-subtree nil t))
22993 (unless (org-with-limited-levels (org-at-heading-p))
22994 (goto-char origin)
22995 (user-error "Cannot move further down"))))
22997 (let* ((elem (org-element-at-point))
22998 (end (org-element-property :end elem))
22999 (parent (org-element-property :parent elem)))
23000 (if (and parent (= (org-element-property :contents-end parent) end))
23001 (goto-char (org-element-property :end parent))
23002 (goto-char end))))))
23004 (defun org-backward-element ()
23005 "Move backward by one element.
23006 Move to the previous element at the same level, when possible."
23007 (interactive)
23008 (cond ((bobp) (user-error "Cannot move further up"))
23009 ((org-with-limited-levels (org-at-heading-p))
23010 ;; At a headline, move to the previous one, if any, or stay
23011 ;; here.
23012 (let ((origin (point)))
23013 (org-with-limited-levels (org-backward-heading-same-level 1))
23014 ;; When current headline has no sibling above, move to its
23015 ;; parent.
23016 (when (= (point) origin)
23017 (or (org-with-limited-levels (org-up-heading-safe))
23018 (progn (goto-char origin)
23019 (user-error "Cannot move further up"))))))
23021 (let* ((trail (org-element-at-point 'keep-trail))
23022 (elem (car trail))
23023 (prev-elem (nth 1 trail))
23024 (beg (org-element-property :begin elem)))
23025 (cond
23026 ;; Move to beginning of current element if point isn't
23027 ;; there already.
23028 ((/= (point) beg) (goto-char beg))
23029 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23030 ((org-before-first-heading-p) (goto-char (point-min)))
23031 (t (org-back-to-heading)))))))
23033 (defun org-up-element ()
23034 "Move to upper element."
23035 (interactive)
23036 (if (org-with-limited-levels (org-at-heading-p))
23037 (unless (org-up-heading-safe) (error "No surrounding element"))
23038 (let* ((elem (org-element-at-point))
23039 (parent (org-element-property :parent elem)))
23040 (if parent (goto-char (org-element-property :begin parent))
23041 (if (org-with-limited-levels (org-before-first-heading-p))
23042 (error "No surrounding element")
23043 (org-with-limited-levels (org-back-to-heading)))))))
23045 (defvar org-element-greater-elements)
23046 (defun org-down-element ()
23047 "Move to inner element."
23048 (interactive)
23049 (let ((element (org-element-at-point)))
23050 (cond
23051 ((memq (org-element-type element) '(plain-list table))
23052 (goto-char (org-element-property :contents-begin element))
23053 (forward-char))
23054 ((memq (org-element-type element) org-element-greater-elements)
23055 ;; If contents are hidden, first disclose them.
23056 (when (org-element-property :hiddenp element) (org-cycle))
23057 (goto-char (or (org-element-property :contents-begin element)
23058 (error "No content for this element"))))
23059 (t (error "No inner element")))))
23061 (defun org-drag-element-backward ()
23062 "Move backward element at point."
23063 (interactive)
23064 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23065 (let* ((trail (org-element-at-point 'keep-trail))
23066 (elem (car trail))
23067 (prev-elem (nth 1 trail)))
23068 ;; Error out if no previous element or previous element is
23069 ;; a parent of the current one.
23070 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23071 (error "Cannot drag element backward")
23072 (let ((pos (point)))
23073 (org-element-swap-A-B prev-elem elem)
23074 (goto-char (+ (org-element-property :begin prev-elem)
23075 (- pos (org-element-property :begin elem)))))))))
23077 (defun org-drag-element-forward ()
23078 "Move forward element at point."
23079 (interactive)
23080 (let* ((pos (point))
23081 (elem (org-element-at-point)))
23082 (when (= (point-max) (org-element-property :end elem))
23083 (error "Cannot drag element forward"))
23084 (goto-char (org-element-property :end elem))
23085 (let ((next-elem (org-element-at-point)))
23086 (when (or (org-element-nested-p elem next-elem)
23087 (and (eq (org-element-type next-elem) 'headline)
23088 (not (eq (org-element-type elem) 'headline))))
23089 (goto-char pos)
23090 (error "Cannot drag element forward"))
23091 ;; Compute new position of point: it's shifted by NEXT-ELEM
23092 ;; body's length (without final blanks) and by the length of
23093 ;; blanks between ELEM and NEXT-ELEM.
23094 (let ((size-next (- (save-excursion
23095 (goto-char (org-element-property :end next-elem))
23096 (skip-chars-backward " \r\t\n")
23097 (forward-line)
23098 ;; Small correction if buffer doesn't end
23099 ;; with a newline character.
23100 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23101 (org-element-property :begin next-elem)))
23102 (size-blank (- (org-element-property :end elem)
23103 (save-excursion
23104 (goto-char (org-element-property :end elem))
23105 (skip-chars-backward " \r\t\n")
23106 (forward-line)
23107 (point)))))
23108 (org-element-swap-A-B elem next-elem)
23109 (goto-char (+ pos size-next size-blank))))))
23111 (defun org-drag-line-forward (arg)
23112 "Drag the line at point ARG lines forward."
23113 (interactive "p")
23114 (dotimes (n (abs arg))
23115 (let ((c (current-column)))
23116 (if (< 0 arg)
23117 (progn
23118 (beginning-of-line 2)
23119 (transpose-lines 1)
23120 (beginning-of-line 0))
23121 (transpose-lines 1)
23122 (beginning-of-line -1))
23123 (org-move-to-column c))))
23125 (defun org-drag-line-backward (arg)
23126 "Drag the line at point ARG lines backward."
23127 (interactive "p")
23128 (org-drag-line-forward (- arg)))
23130 (defun org-mark-element ()
23131 "Put point at beginning of this element, mark at end.
23133 Interactively, if this command is repeated or (in Transient Mark
23134 mode) if the mark is active, it marks the next element after the
23135 ones already marked."
23136 (interactive)
23137 (let (deactivate-mark)
23138 (if (and (org-called-interactively-p 'any)
23139 (or (and (eq last-command this-command) (mark t))
23140 (and transient-mark-mode mark-active)))
23141 (set-mark
23142 (save-excursion
23143 (goto-char (mark))
23144 (goto-char (org-element-property :end (org-element-at-point)))))
23145 (let ((element (org-element-at-point)))
23146 (end-of-line)
23147 (push-mark (org-element-property :end element) t t)
23148 (goto-char (org-element-property :begin element))))))
23150 (defun org-narrow-to-element ()
23151 "Narrow buffer to current element."
23152 (interactive)
23153 (let ((elem (org-element-at-point)))
23154 (cond
23155 ((eq (car elem) 'headline)
23156 (narrow-to-region
23157 (org-element-property :begin elem)
23158 (org-element-property :end elem)))
23159 ((memq (car elem) org-element-greater-elements)
23160 (narrow-to-region
23161 (org-element-property :contents-begin elem)
23162 (org-element-property :contents-end elem)))
23164 (narrow-to-region
23165 (org-element-property :begin elem)
23166 (org-element-property :end elem))))))
23168 (defun org-transpose-element ()
23169 "Transpose current and previous elements, keeping blank lines between.
23170 Point is moved after both elements."
23171 (interactive)
23172 (org-skip-whitespace)
23173 (let ((end (org-element-property :end (org-element-at-point))))
23174 (org-drag-element-backward)
23175 (goto-char end)))
23177 (defun org-unindent-buffer ()
23178 "Un-indent the visible part of the buffer.
23179 Relative indentation (between items, inside blocks, etc.) isn't
23180 modified."
23181 (interactive)
23182 (unless (eq major-mode 'org-mode)
23183 (error "Cannot un-indent a buffer not in Org mode"))
23184 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23185 unindent-tree ; For byte-compiler.
23186 (unindent-tree
23187 (function
23188 (lambda (contents)
23189 (mapc
23190 (lambda (element)
23191 (if (memq (org-element-type element) '(headline section))
23192 (funcall unindent-tree (org-element-contents element))
23193 (save-excursion
23194 (save-restriction
23195 (narrow-to-region
23196 (org-element-property :begin element)
23197 (org-element-property :end element))
23198 (org-do-remove-indentation)))))
23199 (reverse contents))))))
23200 (funcall unindent-tree (org-element-contents parse-tree))))
23202 (defun org-show-subtree ()
23203 "Show everything after this heading at deeper levels."
23204 (interactive)
23205 (outline-flag-region
23206 (point)
23207 (save-excursion
23208 (org-end-of-subtree t t))
23209 nil))
23211 (defun org-show-entry ()
23212 "Show the body directly following this heading.
23213 Show the heading too, if it is currently invisible."
23214 (interactive)
23215 (save-excursion
23216 (condition-case nil
23217 (progn
23218 (org-back-to-heading t)
23219 (outline-flag-region
23220 (max (point-min) (1- (point)))
23221 (save-excursion
23222 (if (re-search-forward
23223 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23224 (match-beginning 1)
23225 (point-max)))
23226 nil)
23227 (org-cycle-hide-drawers 'children))
23228 (error nil))))
23230 (defun org-make-options-regexp (kwds &optional extra)
23231 "Make a regular expression for keyword lines."
23232 (concat
23233 "^#\\+\\("
23234 (mapconcat 'regexp-quote kwds "\\|")
23235 (if extra (concat "\\|" extra))
23236 "\\):[ \t]*\\(.*\\)"))
23238 ;; Make isearch reveal the necessary context
23239 (defun org-isearch-end ()
23240 "Reveal context after isearch exits."
23241 (when isearch-success ; only if search was successful
23242 (if (featurep 'xemacs)
23243 ;; Under XEmacs, the hook is run in the correct place,
23244 ;; we directly show the context.
23245 (org-show-context 'isearch)
23246 ;; In Emacs the hook runs *before* restoring the overlays.
23247 ;; So we have to use a one-time post-command-hook to do this.
23248 ;; (Emacs 22 has a special variable, see function `org-mode')
23249 (unless (and (boundp 'isearch-mode-end-hook-quit)
23250 isearch-mode-end-hook-quit)
23251 ;; Only when the isearch was not quitted.
23252 (org-add-hook 'post-command-hook 'org-isearch-post-command
23253 'append 'local)))
23254 (org-fix-ellipsis-at-bol)))
23256 (defun org-isearch-post-command ()
23257 "Remove self from hook, and show context."
23258 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23259 (org-show-context 'isearch))
23262 ;;;; Integration with and fixes for other packages
23264 ;;; Imenu support
23266 (defvar org-imenu-markers nil
23267 "All markers currently used by Imenu.")
23268 (make-variable-buffer-local 'org-imenu-markers)
23270 (defun org-imenu-new-marker (&optional pos)
23271 "Return a new marker for use by Imenu, and remember the marker."
23272 (let ((m (make-marker)))
23273 (move-marker m (or pos (point)))
23274 (push m org-imenu-markers)
23277 (defun org-imenu-get-tree ()
23278 "Produce the index for Imenu."
23279 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23280 (setq org-imenu-markers nil)
23281 (let* ((n org-imenu-depth)
23282 (re (concat "^" (org-get-limited-outline-regexp)))
23283 (subs (make-vector (1+ n) nil))
23284 (last-level 0)
23285 m level head0 head)
23286 (save-excursion
23287 (save-restriction
23288 (widen)
23289 (goto-char (point-max))
23290 (while (re-search-backward re nil t)
23291 (setq level (org-reduced-level (funcall outline-level)))
23292 (when (and (<= level n)
23293 (looking-at org-complex-heading-regexp)
23294 (setq head0 (org-match-string-no-properties 4)))
23295 (setq head (org-link-display-format head0)
23296 m (org-imenu-new-marker))
23297 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23298 (if (>= level last-level)
23299 (push (cons head m) (aref subs level))
23300 (push (cons head (aref subs (1+ level))) (aref subs level))
23301 (loop for i from (1+ level) to n do (aset subs i nil)))
23302 (setq last-level level)))))
23303 (aref subs 1)))
23305 (eval-after-load "imenu"
23306 '(progn
23307 (add-hook 'imenu-after-jump-hook
23308 (lambda ()
23309 (if (derived-mode-p 'org-mode)
23310 (org-show-context 'org-goto))))))
23312 (defun org-link-display-format (link)
23313 "Replace a link with its the description.
23314 If there is no description, use the link target."
23315 (save-match-data
23316 (if (string-match org-bracket-link-analytic-regexp link)
23317 (replace-match (if (match-end 5)
23318 (match-string 5 link)
23319 (concat (match-string 1 link)
23320 (match-string 3 link)))
23321 nil t link)
23322 link)))
23324 (defun org-toggle-link-display ()
23325 "Toggle the literal or descriptive display of links."
23326 (interactive)
23327 (if org-descriptive-links
23328 (progn (org-remove-from-invisibility-spec '(org-link))
23329 (org-restart-font-lock)
23330 (setq org-descriptive-links nil))
23331 (progn (add-to-invisibility-spec '(org-link))
23332 (org-restart-font-lock)
23333 (setq org-descriptive-links t))))
23335 ;; Speedbar support
23337 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23338 "Overlay marking the agenda restriction line in speedbar.")
23339 (overlay-put org-speedbar-restriction-lock-overlay
23340 'face 'org-agenda-restriction-lock)
23341 (overlay-put org-speedbar-restriction-lock-overlay
23342 'help-echo "Agendas are currently limited to this item.")
23343 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23345 (defun org-speedbar-set-agenda-restriction ()
23346 "Restrict future agenda commands to the location at point in speedbar.
23347 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23348 (interactive)
23349 (require 'org-agenda)
23350 (let (p m tp np dir txt)
23351 (cond
23352 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23353 'org-imenu t))
23354 (setq m (get-text-property p 'org-imenu-marker))
23355 (with-current-buffer (marker-buffer m)
23356 (goto-char m)
23357 (org-agenda-set-restriction-lock 'subtree)))
23358 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23359 'speedbar-function 'speedbar-find-file))
23360 (setq tp (previous-single-property-change
23361 (1+ p) 'speedbar-function)
23362 np (next-single-property-change
23363 tp 'speedbar-function)
23364 dir (speedbar-line-directory)
23365 txt (buffer-substring-no-properties (or tp (point-min))
23366 (or np (point-max))))
23367 (with-current-buffer (find-file-noselect
23368 (let ((default-directory dir))
23369 (expand-file-name txt)))
23370 (unless (derived-mode-p 'org-mode)
23371 (error "Cannot restrict to non-Org-mode file"))
23372 (org-agenda-set-restriction-lock 'file)))
23373 (t (error "Don't know how to restrict Org-mode's agenda")))
23374 (move-overlay org-speedbar-restriction-lock-overlay
23375 (point-at-bol) (point-at-eol))
23376 (setq current-prefix-arg nil)
23377 (org-agenda-maybe-redo)))
23379 (eval-after-load "speedbar"
23380 '(progn
23381 (speedbar-add-supported-extension ".org")
23382 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23383 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23384 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23385 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23386 (add-hook 'speedbar-visiting-tag-hook
23387 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23389 ;;; Fixes and Hacks for problems with other packages
23391 ;; Make flyspell not check words in links, to not mess up our keymap
23392 (defvar org-element-affiliated-keywords) ; From org-element.el
23393 (defvar org-element-block-name-alist) ; From org-element.el
23394 (defun org-mode-flyspell-verify ()
23395 "Don't let flyspell put overlays at active buttons, or on
23396 {todo,all-time,additional-option-like}-keywords."
23397 (let ((pos (max (1- (point)) (point-min)))
23398 (word (thing-at-point 'word)))
23399 (and (not (get-text-property pos 'keymap))
23400 (not (get-text-property pos 'org-no-flyspell))
23401 (not (member word org-todo-keywords-1))
23402 (not (member word org-all-time-keywords))
23403 (not (member word org-options-keywords))
23404 (not (member word (mapcar 'car org-startup-options)))
23405 (not (member-ignore-case word org-element-affiliated-keywords))
23406 (not (member-ignore-case word (org-get-export-keywords)))
23407 (not (member-ignore-case
23408 word (mapcar 'car org-element-block-name-alist)))
23409 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23411 (defun org-remove-flyspell-overlays-in (beg end)
23412 "Remove flyspell overlays in region."
23413 (and (org-bound-and-true-p flyspell-mode)
23414 (fboundp 'flyspell-delete-region-overlays)
23415 (flyspell-delete-region-overlays beg end))
23416 (add-text-properties beg end '(org-no-flyspell t)))
23418 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23419 (eval-after-load "bookmark"
23420 '(if (boundp 'bookmark-after-jump-hook)
23421 ;; We can use the hook
23422 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23423 ;; Hook not available, use advice
23424 (defadvice bookmark-jump (after org-make-visible activate)
23425 "Make the position visible."
23426 (org-bookmark-jump-unhide))))
23428 ;; Make sure saveplace shows the location if it was hidden
23429 (eval-after-load "saveplace"
23430 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23431 "Make the position visible."
23432 (org-bookmark-jump-unhide)))
23434 ;; Make sure ecb shows the location if it was hidden
23435 (eval-after-load "ecb"
23436 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23437 "Make hierarchy visible when jumping into location from ECB tree buffer."
23438 (if (derived-mode-p 'org-mode)
23439 (org-show-context))))
23441 (defun org-bookmark-jump-unhide ()
23442 "Unhide the current position, to show the bookmark location."
23443 (and (derived-mode-p 'org-mode)
23444 (or (outline-invisible-p)
23445 (save-excursion (goto-char (max (point-min) (1- (point))))
23446 (outline-invisible-p)))
23447 (org-show-context 'bookmark-jump)))
23449 ;; Make session.el ignore our circular variable
23450 (eval-after-load "session"
23451 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23453 ;;;; Experimental code
23455 (defun org-closed-in-range ()
23456 "Sparse tree of items closed in a certain time range.
23457 Still experimental, may disappear in the future."
23458 (interactive)
23459 ;; Get the time interval from the user.
23460 (let* ((time1 (org-float-time
23461 (org-read-date nil 'to-time nil "Starting date: ")))
23462 (time2 (org-float-time
23463 (org-read-date nil 'to-time nil "End date:")))
23464 ;; callback function
23465 (callback (lambda ()
23466 (let ((time
23467 (org-float-time
23468 (apply 'encode-time
23469 (org-parse-time-string
23470 (match-string 1))))))
23471 ;; check if time in interval
23472 (and (>= time time1) (<= time time2))))))
23473 ;; make tree, check each match with the callback
23474 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23476 ;;;; Finish up
23478 (provide 'org)
23480 (run-hooks 'org-load-hook)
23482 ;;; org.el ends here