ox-rss.el: Fix keys descriptions in `org-export-define-derived-backend'
[org-mode.git] / lisp / org.el
bloba1fa315da65b69a327957ec0c1b4549cd9c39d02
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-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (declare-function org-element--parse-objects "org-element"
139 (beg end acc restriction))
140 (declare-function org-element-at-point "org-element" (&optional keep-trail))
141 (declare-function org-element-contents "org-element" (element))
142 (declare-function org-element-context "org-element" (&optional element))
143 (declare-function org-element-interpret-data "org-element"
144 (data &optional parent))
145 (declare-function org-element-map "org-element"
146 (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-parse-buffer "org-element"
149 (&optional granularity visible-only))
150 (declare-function org-element-property "org-element" (property element))
151 (declare-function org-element-put-property "org-element"
152 (element property value))
153 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
154 (declare-function org-element--parse-objects "org-element"
155 (beg end acc restriction))
156 (declare-function org-element-parse-buffer "org-element"
157 (&optional granularity visible-only))
158 (declare-function org-element-restriction "org-element" (element))
159 (declare-function org-element-type "org-element" (element))
161 ;; load languages based on value of `org-babel-load-languages'
162 (defvar org-babel-load-languages)
164 ;;;###autoload
165 (defun org-babel-do-load-languages (sym value)
166 "Load the languages defined in `org-babel-load-languages'."
167 (set-default sym value)
168 (mapc (lambda (pair)
169 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
170 (if active
171 (progn
172 (require (intern (concat "ob-" lang))))
173 (progn
174 (funcall 'fmakunbound
175 (intern (concat "org-babel-execute:" lang)))
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-expand-body:" lang)))))))
178 org-babel-load-languages))
180 (defcustom org-babel-load-languages '((emacs-lisp . t))
181 "Languages which can be evaluated in Org-mode buffers.
182 This list can be used to load support for any of the languages
183 below, note that each language will depend on a different set of
184 system executables and/or Emacs modes. When a language is
185 \"loaded\", then code blocks in that language can be evaluated
186 with `org-babel-execute-src-block' bound by default to C-c
187 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
188 be set to remove code block evaluation from the C-c C-c
189 keybinding. By default only Emacs Lisp (which has no
190 requirements) is loaded."
191 :group 'org-babel
192 :set 'org-babel-do-load-languages
193 :version "24.1"
194 :type '(alist :tag "Babel Languages"
195 :key-type
196 (choice
197 (const :tag "Awk" awk)
198 (const :tag "C" C)
199 (const :tag "R" R)
200 (const :tag "Asymptote" asymptote)
201 (const :tag "Calc" calc)
202 (const :tag "Clojure" clojure)
203 (const :tag "CSS" css)
204 (const :tag "Ditaa" ditaa)
205 (const :tag "Dot" dot)
206 (const :tag "Emacs Lisp" emacs-lisp)
207 (const :tag "Fortran" fortran)
208 (const :tag "Gnuplot" gnuplot)
209 (const :tag "Haskell" haskell)
210 (const :tag "IO" io)
211 (const :tag "Java" java)
212 (const :tag "Javascript" js)
213 (const :tag "LaTeX" latex)
214 (const :tag "Ledger" ledger)
215 (const :tag "Lilypond" lilypond)
216 (const :tag "Lisp" lisp)
217 (const :tag "Makefile" makefile)
218 (const :tag "Maxima" maxima)
219 (const :tag "Matlab" matlab)
220 (const :tag "Mscgen" mscgen)
221 (const :tag "Ocaml" ocaml)
222 (const :tag "Octave" octave)
223 (const :tag "Org" org)
224 (const :tag "Perl" perl)
225 (const :tag "Pico Lisp" picolisp)
226 (const :tag "PlantUML" plantuml)
227 (const :tag "Python" python)
228 (const :tag "Ruby" ruby)
229 (const :tag "Sass" sass)
230 (const :tag "Scala" scala)
231 (const :tag "Scheme" scheme)
232 (const :tag "Screen" screen)
233 (const :tag "Shell Script" sh)
234 (const :tag "Shen" shen)
235 (const :tag "Sql" sql)
236 (const :tag "Sqlite" sqlite))
237 :value-type (boolean :tag "Activate" :value t)))
239 ;;;; Customization variables
240 (defcustom org-clone-delete-id nil
241 "Remove ID property of clones of a subtree.
242 When non-nil, clones of a subtree don't inherit the ID property.
243 Otherwise they inherit the ID property with a new unique
244 identifier."
245 :type 'boolean
246 :version "24.1"
247 :group 'org-id)
249 ;;; Version
250 (org-check-version)
252 ;;;###autoload
253 (defun org-version (&optional here full message)
254 "Show the org-mode version in the echo area.
255 With prefix argument HERE, insert it at point.
256 When FULL is non-nil, use a verbose version string.
257 When MESSAGE is non-nil, display a message with the version."
258 (interactive "P")
259 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
260 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
261 (load-suffixes (list ".el"))
262 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
263 (org-trash (or
264 (and (fboundp 'org-release) (fboundp 'org-git-version))
265 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
266 (load-suffixes save-load-suffixes)
267 (org-version (org-release))
268 (git-version (org-git-version))
269 (version (format "Org-mode version %s (%s @ %s)"
270 org-version
271 git-version
272 (if org-install-dir
273 (if (string= org-dir org-install-dir)
274 org-install-dir
275 (concat "mixed installation! " org-install-dir " and " org-dir))
276 "org-loaddefs.el can not be found!")))
277 (_version (if full version org-version)))
278 (if (org-called-interactively-p 'interactive)
279 (if here
280 (insert version)
281 (message version))
282 (if message (message _version))
283 _version)))
285 (defconst org-version (org-version))
287 ;;; Compatibility constants
289 ;;; The custom variables
291 (defgroup org nil
292 "Outline-based notes management and organizer."
293 :tag "Org"
294 :group 'outlines
295 :group 'calendar)
297 (defcustom org-mode-hook nil
298 "Mode hook for Org-mode, run after the mode was turned on."
299 :group 'org
300 :type 'hook)
302 (defcustom org-load-hook nil
303 "Hook that is run after org.el has been loaded."
304 :group 'org
305 :type 'hook)
307 (defcustom org-log-buffer-setup-hook nil
308 "Hook that is run after an Org log buffer is created."
309 :group 'org
310 :version "24.1"
311 :type 'hook)
313 (defvar org-modules) ; defined below
314 (defvar org-modules-loaded nil
315 "Have the modules been loaded already?")
317 (defun org-load-modules-maybe (&optional force)
318 "Load all extensions listed in `org-modules'."
319 (when (or force (not org-modules-loaded))
320 (mapc (lambda (ext)
321 (condition-case nil (require ext)
322 (error (message "Problems while trying to load feature `%s'" ext))))
323 org-modules)
324 (setq org-modules-loaded t)))
326 (defun org-set-modules (var value)
327 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
328 (set var value)
329 (when (featurep 'org)
330 (org-load-modules-maybe 'force)))
332 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
333 "Modules that should always be loaded together with org.el.
335 If a description starts with <C>, the file is not part of Emacs
336 and loading it will require that you have downloaded and properly
337 installed the Org mode distribution.
339 You can also use this system to load external packages (i.e. neither Org
340 core modules, nor modules from the CONTRIB directory). Just add symbols
341 to the end of the list. If the package is called org-xyz.el, then you need
342 to add the symbol `xyz', and the package must have a call to:
344 \(provide 'org-xyz)
346 For export specific modules, see also `org-export-backends'."
347 :group 'org
348 :set 'org-set-modules
349 :version "24.4"
350 :package-version '(Org . "8.0")
351 :type
352 '(set :greedy t
353 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
354 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
355 (const :tag " crypt: Encryption of subtrees" org-crypt)
356 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
357 (const :tag " docview: Links to doc-view buffers" org-docview)
358 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
359 (const :tag " id: Global IDs for identifying entries" org-id)
360 (const :tag " info: Links to Info nodes" org-info)
361 (const :tag " habit: Track your consistency with habits" org-habit)
362 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
363 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
364 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " mouse: Additional mouse support" org-mouse)
370 (const :tag "C vm: Links to VM folders/messages" org-vm)
371 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
372 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
373 (const :tag "C mew: Links to Mew folders/messages" org-mew)
374 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
375 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
376 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
377 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
378 (const :tag "C collector: Collect properties into tables" org-collector)
379 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
380 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
381 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
382 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
383 (const :tag "C eval: Include command output as text" org-eval)
384 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
385 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
386 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
387 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
388 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
390 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
392 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
393 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
394 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
395 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
396 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
397 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
398 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
399 (const :tag "C mtags: Support for muse-like tags" org-mtags)
400 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
401 (const :tag "C registry: A registry for Org-mode links" org-registry)
402 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
403 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
404 (const :tag "C secretary: Team management with org-mode" org-secretary)
405 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
406 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
407 (const :tag "C track: Keep up with Org-mode development" org-track)
408 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
409 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
410 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
412 (defvar org-export-registered-backends) ; From ox.el
413 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
414 (defcustom org-export-backends '(ascii html icalendar latex)
415 "List of export back-ends that should be always available.
417 If a description starts with <C>, the file is not part of Emacs
418 and loading it will require that you have downloaded and properly
419 installed the Org mode distribution.
421 Unlike to `org-modules', libraries in this list will not be
422 loaded along with Org, but only once the export framework is
423 needed.
425 This variable needs to be set before org.el is loaded. If you
426 need to make a change while Emacs is running, use the customize
427 interface or run the following code, where VALUE stands for the
428 new value of the variable, after updating it:
430 \(progn
431 \(setq org-export-registered-backends
432 \(org-remove-if-not
433 \(lambda (backend)
434 \(or (memq backend val)
435 \(catch 'parentp
436 \(mapc
437 \(lambda (b)
438 \(and (org-export-derived-backend-p b (car backend))
439 \(throw 'parentp t)))
440 val)
441 nil)))
442 org-export-registered-backends))
443 \(let ((new-list (mapcar 'car org-export-registered-backends)))
444 \(dolist (backend val)
445 \(cond
446 \((not (load (format \"ox-%s\" backend) t t))
447 \(message \"Problems while trying to load export back-end `%s'\"
448 backend))
449 \((not (memq backend new-list)) (push backend new-list))))
450 \(set-default var new-list)))
452 Adding a back-end to this list will also pull the back-end it
453 depends on, if any."
454 :group 'org
455 :group 'org-export
456 :version "24.4"
457 :package-version '(Org . "8.0")
458 :initialize 'custom-initialize-set
459 :set (lambda (var val)
460 (if (not (featurep 'ox)) (set-default var val)
461 ;; Any back-end not required anymore (not present in VAL and not
462 ;; a parent of any back-end in the new value) is removed from the
463 ;; list of registered back-ends.
464 (setq org-export-registered-backends
465 (org-remove-if-not
466 (lambda (backend)
467 (or (memq backend val)
468 (catch 'parentp
469 (mapc
470 (lambda (b)
471 (and (org-export-derived-backend-p b (car backend))
472 (throw 'parentp t)))
473 val)
474 nil)))
475 org-export-registered-backends))
476 ;; Now build NEW-LIST of both new back-ends and required
477 ;; parents.
478 (let ((new-list (mapcar 'car org-export-registered-backends)))
479 (dolist (backend val)
480 (cond
481 ((not (load (format "ox-%s" backend) t t))
482 (message "Problems while trying to load export back-end `%s'"
483 backend))
484 ((not (memq backend new-list)) (push backend new-list))))
485 ;; Set VAR to that list with fixed dependencies.
486 (set-default var new-list))))
487 :type '(set :greedy t
488 (const :tag " ascii Export buffer to ASCII format" ascii)
489 (const :tag " beamer Export buffer to Beamer presentation" beamer)
490 (const :tag " html Export buffer to HTML format" html)
491 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
492 (const :tag " latex Export buffer to LaTeX format" latex)
493 (const :tag " man Export buffer to MAN format" man)
494 (const :tag " md Export buffer to Markdown format" md)
495 (const :tag " odt Export buffer to ODT format" odt)
496 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
497 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
498 (const :tag "C deck Export buffer to deck.js presentations" deck)
499 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
500 (const :tag "C groff Export buffer to Groff format" groff)
501 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
502 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
503 (const :tag "C s5 Export buffer to s5 presentations" s5)
504 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
506 (eval-after-load 'ox
507 '(mapc
508 (lambda (backend)
509 (condition-case nil (require (intern (format "ox-%s" backend)))
510 (error (message "Problems while trying to load export back-end `%s'"
511 backend))))
512 org-export-backends))
514 (defcustom org-support-shift-select nil
515 "Non-nil means make shift-cursor commands select text when possible.
517 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
518 start selecting a region, or enlarge regions started in this way.
519 In Org-mode, in special contexts, these same keys are used for
520 other purposes, important enough to compete with shift selection.
521 Org tries to balance these needs by supporting `shift-select-mode'
522 outside these special contexts, under control of this variable.
524 The default of this variable is nil, to avoid confusing behavior. Shifted
525 cursor keys will then execute Org commands in the following contexts:
526 - on a headline, changing TODO state (left/right) and priority (up/down)
527 - on a time stamp, changing the time
528 - in a plain list item, changing the bullet type
529 - in a property definition line, switching between allowed values
530 - in the BEGIN line of a clock table (changing the time block).
531 Outside these contexts, the commands will throw an error.
533 When this variable is t and the cursor is not in a special
534 context, Org-mode will support shift-selection for making and
535 enlarging regions. To make this more effective, the bullet
536 cycling will no longer happen anywhere in an item line, but only
537 if the cursor is exactly on the bullet.
539 If you set this variable to the symbol `always', then the keys
540 will not be special in headlines, property lines, and item lines,
541 to make shift selection work there as well. If this is what you
542 want, you can use the following alternative commands: `C-c C-t'
543 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
544 can be used to switch TODO sets, `C-c -' to cycle item bullet
545 types, and properties can be edited by hand or in column view.
547 However, when the cursor is on a timestamp, shift-cursor commands
548 will still edit the time stamp - this is just too good to give up.
550 XEmacs user should have this variable set to nil, because
551 `shift-select-mode' is in Emacs 23 or later only."
552 :group 'org
553 :type '(choice
554 (const :tag "Never" nil)
555 (const :tag "When outside special context" t)
556 (const :tag "Everywhere except timestamps" always)))
558 (defcustom org-loop-over-headlines-in-active-region nil
559 "Shall some commands act upon headlines in the active region?
561 When set to `t', some commands will be performed in all headlines
562 within the active region.
564 When set to `start-level', some commands will be performed in all
565 headlines within the active region, provided that these headlines
566 are of the same level than the first one.
568 When set to a string, those commands will be performed on the
569 matching headlines within the active region. Such string must be
570 a tags/property/todo match as it is used in the agenda tags view.
572 The list of commands is: `org-schedule', `org-deadline',
573 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
574 `org-archive-to-archive-sibling'. The archiving commands skip
575 already archived entries."
576 :type '(choice (const :tag "Don't loop" nil)
577 (const :tag "All headlines in active region" t)
578 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
579 (string :tag "Tags/Property/Todo matcher"))
580 :version "24.1"
581 :group 'org-todo
582 :group 'org-archive)
584 (defgroup org-startup nil
585 "Options concerning startup of Org-mode."
586 :tag "Org Startup"
587 :group 'org)
589 (defcustom org-startup-folded t
590 "Non-nil means entering Org-mode will switch to OVERVIEW.
591 This can also be configured on a per-file basis by adding one of
592 the following lines anywhere in the buffer:
594 #+STARTUP: fold (or `overview', this is equivalent)
595 #+STARTUP: nofold (or `showall', this is equivalent)
596 #+STARTUP: content
597 #+STARTUP: showeverything
599 By default, this option is ignored when Org opens agenda files
600 for the first time. If you want the agenda to honor the startup
601 option, set `org-agenda-inhibit-startup' to nil."
602 :group 'org-startup
603 :type '(choice
604 (const :tag "nofold: show all" nil)
605 (const :tag "fold: overview" t)
606 (const :tag "content: all headlines" content)
607 (const :tag "show everything, even drawers" showeverything)))
609 (defcustom org-startup-truncated t
610 "Non-nil means entering Org-mode will set `truncate-lines'.
611 This is useful since some lines containing links can be very long and
612 uninteresting. Also tables look terrible when wrapped."
613 :group 'org-startup
614 :type 'boolean)
616 (defcustom org-startup-indented nil
617 "Non-nil means turn on `org-indent-mode' on startup.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: indent
622 #+STARTUP: noindent"
623 :group 'org-structure
624 :type '(choice
625 (const :tag "Not" nil)
626 (const :tag "Globally (slow on startup in large files)" t)))
628 (defcustom org-use-sub-superscripts t
629 "Non-nil means interpret \"_\" and \"^\" for display.
630 When this option is turned on, you can use TeX-like syntax for sub- and
631 superscripts. Several characters after \"_\" or \"^\" will be
632 considered as a single item - so grouping with {} is normally not
633 needed. For example, the following things will be parsed as single
634 sub- or superscripts.
636 10^24 or 10^tau several digits will be considered 1 item.
637 10^-12 or 10^-tau a leading sign with digits or a word
638 x^2-y^3 will be read as x^2 - y^3, because items are
639 terminated by almost any nonword/nondigit char.
640 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
642 Still, ambiguity is possible - so when in doubt use {} to enclose
643 the sub/superscript. If you set this variable to the symbol
644 `{}', the braces are *required* in order to trigger
645 interpretations as sub/superscript. This can be helpful in
646 documents that need \"_\" frequently in plain text."
647 :group 'org-startup
648 :version "24.1"
649 :type '(choice
650 (const :tag "Always interpret" t)
651 (const :tag "Only with braces" {})
652 (const :tag "Never interpret" nil)))
654 (defcustom org-startup-with-beamer-mode nil
655 "Non-nil means turn on `org-beamer-mode' on startup.
656 This can also be configured on a per-file basis by adding one of
657 the following lines anywhere in the buffer:
659 #+STARTUP: beamer"
660 :group 'org-startup
661 :version "24.1"
662 :type 'boolean)
664 (defcustom org-startup-align-all-tables nil
665 "Non-nil means align all tables when visiting a file.
666 This is useful when the column width in tables is forced with <N> cookies
667 in table fields. Such tables will look correct only after the first re-align.
668 This can also be configured on a per-file basis by adding one of
669 the following lines anywhere in the buffer:
670 #+STARTUP: align
671 #+STARTUP: noalign"
672 :group 'org-startup
673 :type 'boolean)
675 (defcustom org-startup-with-inline-images nil
676 "Non-nil means show inline images when loading a new Org file.
677 This can also be configured on a per-file basis by adding one of
678 the following lines anywhere in the buffer:
679 #+STARTUP: inlineimages
680 #+STARTUP: noinlineimages"
681 :group 'org-startup
682 :version "24.1"
683 :type 'boolean)
685 (defcustom org-startup-with-latex-preview nil
686 "Non-nil means preview LaTeX fragments when loading a new Org file.
688 This can also be configured on a per-file basis by adding one of
689 the followinglines anywhere in the buffer:
690 #+STARTUP: latexpreview
691 #+STARTUP: nolatexpreview"
692 :group 'org-startup
693 :version "24.4"
694 :package-version '(Org . "8.0")
695 :type 'boolean)
697 (defcustom org-insert-mode-line-in-empty-file nil
698 "Non-nil means insert the first line setting Org-mode in empty files.
699 When the function `org-mode' is called interactively in an empty file, this
700 normally means that the file name does not automatically trigger Org-mode.
701 To ensure that the file will always be in Org-mode in the future, a
702 line enforcing Org-mode will be inserted into the buffer, if this option
703 has been set."
704 :group 'org-startup
705 :type 'boolean)
707 (defcustom org-replace-disputed-keys nil
708 "Non-nil means use alternative key bindings for some keys.
709 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
710 These keys are also used by other packages like shift-selection-mode'
711 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
712 If you want to use Org-mode together with one of these other modes,
713 or more generally if you would like to move some Org-mode commands to
714 other keys, set this variable and configure the keys with the variable
715 `org-disputed-keys'.
717 This option is only relevant at load-time of Org-mode, and must be set
718 *before* org.el is loaded. Changing it requires a restart of Emacs to
719 become effective."
720 :group 'org-startup
721 :type 'boolean)
723 (defcustom org-use-extra-keys nil
724 "Non-nil means use extra key sequence definitions for certain commands.
725 This happens automatically if you run XEmacs or if `window-system'
726 is nil. This variable lets you do the same manually. You must
727 set it before loading org.
729 Example: on Carbon Emacs 22 running graphically, with an external
730 keyboard on a Powerbook, the default way of setting M-left might
731 not work for either Alt or ESC. Setting this variable will make
732 it work for ESC."
733 :group 'org-startup
734 :type 'boolean)
736 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
738 (defcustom org-disputed-keys
739 '(([(shift up)] . [(meta p)])
740 ([(shift down)] . [(meta n)])
741 ([(shift left)] . [(meta -)])
742 ([(shift right)] . [(meta +)])
743 ([(control shift right)] . [(meta shift +)])
744 ([(control shift left)] . [(meta shift -)]))
745 "Keys for which Org-mode and other modes compete.
746 This is an alist, cars are the default keys, second element specifies
747 the alternative to use when `org-replace-disputed-keys' is t.
749 Keys can be specified in any syntax supported by `define-key'.
750 The value of this option takes effect only at Org-mode's startup,
751 therefore you'll have to restart Emacs to apply it after changing."
752 :group 'org-startup
753 :type 'alist)
755 (defun org-key (key)
756 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
757 Or return the original if not disputed.
758 Also apply the translations defined in `org-xemacs-key-equivalents'."
759 (when org-replace-disputed-keys
760 (let* ((nkey (key-description key))
761 (x (org-find-if (lambda (x)
762 (equal (key-description (car x)) nkey))
763 org-disputed-keys)))
764 (setq key (if x (cdr x) key))))
765 (when (featurep 'xemacs)
766 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
767 key)
769 (defun org-find-if (predicate seq)
770 (catch 'exit
771 (while seq
772 (if (funcall predicate (car seq))
773 (throw 'exit (car seq))
774 (pop seq)))))
776 (defun org-defkey (keymap key def)
777 "Define a key, possibly translated, as returned by `org-key'."
778 (define-key keymap (org-key key) def))
780 (defcustom org-ellipsis nil
781 "The ellipsis to use in the Org-mode outline.
782 When nil, just use the standard three dots. When a string, use that instead,
783 When a face, use the standard 3 dots, but with the specified face.
784 The change affects only Org-mode (which will then use its own display table).
785 Changing this requires executing `M-x org-mode' in a buffer to become
786 effective."
787 :group 'org-startup
788 :type '(choice (const :tag "Default" nil)
789 (face :tag "Face" :value org-warning)
790 (string :tag "String" :value "...#")))
792 (defvar org-display-table nil
793 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
795 (defgroup org-keywords nil
796 "Keywords in Org-mode."
797 :tag "Org Keywords"
798 :group 'org)
800 (defcustom org-deadline-string "DEADLINE:"
801 "String to mark deadline entries.
802 A deadline is this string, followed by a time stamp. Should be a word,
803 terminated by a colon. You can insert a schedule keyword and
804 a timestamp with \\[org-deadline].
805 Changes become only effective after restarting Emacs."
806 :group 'org-keywords
807 :type 'string)
809 (defcustom org-scheduled-string "SCHEDULED:"
810 "String to mark scheduled TODO entries.
811 A schedule is this string, followed by a time stamp. Should be a word,
812 terminated by a colon. You can insert a schedule keyword and
813 a timestamp with \\[org-schedule].
814 Changes become only effective after restarting Emacs."
815 :group 'org-keywords
816 :type 'string)
818 (defcustom org-closed-string "CLOSED:"
819 "String used as the prefix for timestamps logging closing a TODO entry."
820 :group 'org-keywords
821 :type 'string)
823 (defcustom org-clock-string "CLOCK:"
824 "String used as prefix for timestamps clocking work hours on an item."
825 :group 'org-keywords
826 :type 'string)
828 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
829 org-scheduled-string "\\|"
830 org-deadline-string "\\|"
831 org-closed-string "\\|"
832 org-clock-string "\\)")
833 "Matches a line with planning or clock info.")
835 (defcustom org-comment-string "COMMENT"
836 "Entries starting with this keyword will never be exported.
837 An entry can be toggled between COMMENT and normal with
838 \\[org-toggle-comment].
839 Changes become only effective after restarting Emacs."
840 :group 'org-keywords
841 :type 'string)
843 (defcustom org-quote-string "QUOTE"
844 "Entries starting with this keyword will be exported in fixed-width font.
845 Quoting applies only to the text in the entry following the headline, and does
846 not extend beyond the next headline, even if that is lower level.
847 An entry can be toggled between QUOTE and normal with
848 \\[org-toggle-fixed-width-section]."
849 :group 'org-keywords
850 :type 'string)
852 (defconst org-repeat-re
853 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
854 "Regular expression for specifying repeated events.
855 After a match, group 1 contains the repeat expression.")
857 (defgroup org-structure nil
858 "Options concerning the general structure of Org-mode files."
859 :tag "Org Structure"
860 :group 'org)
862 (defgroup org-reveal-location nil
863 "Options about how to make context of a location visible."
864 :tag "Org Reveal Location"
865 :group 'org-structure)
867 (defconst org-context-choice
868 '(choice
869 (const :tag "Always" t)
870 (const :tag "Never" nil)
871 (repeat :greedy t :tag "Individual contexts"
872 (cons
873 (choice :tag "Context"
874 (const agenda)
875 (const org-goto)
876 (const occur-tree)
877 (const tags-tree)
878 (const link-search)
879 (const mark-goto)
880 (const bookmark-jump)
881 (const isearch)
882 (const default))
883 (boolean))))
884 "Contexts for the reveal options.")
886 (defcustom org-show-hierarchy-above '((default . t))
887 "Non-nil means show full hierarchy when revealing a location.
888 Org-mode often shows locations in an org-mode file which might have
889 been invisible before. When this is set, the hierarchy of headings
890 above the exposed location is shown.
891 Turning this off for example for sparse trees makes them very compact.
892 Instead of t, this can also be an alist specifying this option for different
893 contexts. Valid contexts are
894 agenda when exposing an entry from the agenda
895 org-goto when using the command `org-goto' on key C-c C-j
896 occur-tree when using the command `org-occur' on key C-c /
897 tags-tree when constructing a sparse tree based on tags matches
898 link-search when exposing search matches associated with a link
899 mark-goto when exposing the jump goal of a mark
900 bookmark-jump when exposing a bookmark location
901 isearch when exiting from an incremental search
902 default default for all contexts not set explicitly"
903 :group 'org-reveal-location
904 :type org-context-choice)
906 (defcustom org-show-following-heading '((default . nil))
907 "Non-nil means show following heading when revealing a location.
908 Org-mode often shows locations in an org-mode file which might have
909 been invisible before. When this is set, the heading following the
910 match is shown.
911 Turning this off for example for sparse trees makes them very compact,
912 but makes it harder to edit the location of the match. In such a case,
913 use the command \\[org-reveal] to show more context.
914 Instead of t, this can also be an alist specifying this option for different
915 contexts. See `org-show-hierarchy-above' for valid contexts."
916 :group 'org-reveal-location
917 :type org-context-choice)
919 (defcustom org-show-siblings '((default . nil) (isearch t))
920 "Non-nil means show all sibling heading when revealing a location.
921 Org-mode often shows locations in an org-mode file which might have
922 been invisible before. When this is set, the sibling of the current entry
923 heading are all made visible. If `org-show-hierarchy-above' is t,
924 the same happens on each level of the hierarchy above the current entry.
926 By default this is on for the isearch context, off for all other contexts.
927 Turning this off for example for sparse trees makes them very compact,
928 but makes it harder to edit the location of the match. In such a case,
929 use the command \\[org-reveal] to show more context.
930 Instead of t, this can also be an alist specifying this option for different
931 contexts. See `org-show-hierarchy-above' for valid contexts."
932 :group 'org-reveal-location
933 :type org-context-choice)
935 (defcustom org-show-entry-below '((default . nil))
936 "Non-nil means show the entry below a headline when revealing a location.
937 Org-mode often shows locations in an org-mode file which might have
938 been invisible before. When this is set, the text below the headline that is
939 exposed is also shown.
941 By default this is off for all contexts.
942 Instead of t, this can also be an alist specifying this option for different
943 contexts. See `org-show-hierarchy-above' for valid contexts."
944 :group 'org-reveal-location
945 :type org-context-choice)
947 (defcustom org-indirect-buffer-display 'other-window
948 "How should indirect tree buffers be displayed?
949 This applies to indirect buffers created with the commands
950 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
951 Valid values are:
952 current-window Display in the current window
953 other-window Just display in another window.
954 dedicated-frame Create one new frame, and re-use it each time.
955 new-frame Make a new frame each time. Note that in this case
956 previously-made indirect buffers are kept, and you need to
957 kill these buffers yourself."
958 :group 'org-structure
959 :group 'org-agenda-windows
960 :type '(choice
961 (const :tag "In current window" current-window)
962 (const :tag "In current frame, other window" other-window)
963 (const :tag "Each time a new frame" new-frame)
964 (const :tag "One dedicated frame" dedicated-frame)))
966 (defcustom org-use-speed-commands nil
967 "Non-nil means activate single letter commands at beginning of a headline.
968 This may also be a function to test for appropriate locations where speed
969 commands should be active."
970 :group 'org-structure
971 :type '(choice
972 (const :tag "Never" nil)
973 (const :tag "At beginning of headline stars" t)
974 (function)))
976 (defcustom org-speed-commands-user nil
977 "Alist of additional speed commands.
978 This list will be checked before `org-speed-commands-default'
979 when the variable `org-use-speed-commands' is non-nil
980 and when the cursor is at the beginning of a headline.
981 The car if each entry is a string with a single letter, which must
982 be assigned to `self-insert-command' in the global map.
983 The cdr is either a command to be called interactively, a function
984 to be called, or a form to be evaluated.
985 An entry that is just a list with a single string will be interpreted
986 as a descriptive headline that will be added when listing the speed
987 commands in the Help buffer using the `?' speed command."
988 :group 'org-structure
989 :type '(repeat :value ("k" . ignore)
990 (choice :value ("k" . ignore)
991 (list :tag "Descriptive Headline" (string :tag "Headline"))
992 (cons :tag "Letter and Command"
993 (string :tag "Command letter")
994 (choice
995 (function)
996 (sexp))))))
998 (defgroup org-cycle nil
999 "Options concerning visibility cycling in Org-mode."
1000 :tag "Org Cycle"
1001 :group 'org-structure)
1003 (defcustom org-cycle-skip-children-state-if-no-children t
1004 "Non-nil means skip CHILDREN state in entries that don't have any."
1005 :group 'org-cycle
1006 :type 'boolean)
1008 (defcustom org-cycle-max-level nil
1009 "Maximum level which should still be subject to visibility cycling.
1010 Levels higher than this will, for cycling, be treated as text, not a headline.
1011 When `org-odd-levels-only' is set, a value of N in this variable actually
1012 means 2N-1 stars as the limiting headline.
1013 When nil, cycle all levels.
1014 Note that the limiting level of cycling is also influenced by
1015 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1016 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1017 than its value."
1018 :group 'org-cycle
1019 :type '(choice
1020 (const :tag "No limit" nil)
1021 (integer :tag "Maximum level")))
1023 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1024 "Names of drawers. Drawers are not opened by cycling on the headline above.
1025 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1026 this:
1027 :DRAWERNAME:
1028 .....
1029 :END:
1030 The drawer \"PROPERTIES\" is special for capturing properties through
1031 the property API.
1033 Drawers can be defined on the per-file basis with a line like:
1035 #+DRAWERS: HIDDEN STATE PROPERTIES"
1036 :group 'org-structure
1037 :group 'org-cycle
1038 :type '(repeat (string :tag "Drawer Name")))
1040 (defcustom org-hide-block-startup nil
1041 "Non-nil means entering Org-mode will fold all blocks.
1042 This can also be set in on a per-file basis with
1044 #+STARTUP: hideblocks
1045 #+STARTUP: showblocks"
1046 :group 'org-startup
1047 :group 'org-cycle
1048 :type 'boolean)
1050 (defcustom org-cycle-global-at-bob nil
1051 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1052 This makes it possible to do global cycling without having to use S-TAB or
1053 \\[universal-argument] TAB. For this special case to work, the first line
1054 of the buffer must not be a headline -- it may be empty or some other text.
1055 When used in this way, `org-cycle-hook' is disabled temporarily to make
1056 sure the cursor stays at the beginning of the buffer. When this option is
1057 nil, don't do anything special at the beginning of the buffer."
1058 :group 'org-cycle
1059 :type 'boolean)
1061 (defcustom org-cycle-level-after-item/entry-creation t
1062 "Non-nil means cycle entry level or item indentation in new empty entries.
1064 When the cursor is at the end of an empty headline, i.e., with only stars
1065 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1066 and then all possible ancestor states, before returning to the original state.
1067 This makes data entry extremely fast: M-RET to create a new headline,
1068 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1070 When the cursor is at the end of an empty plain list item, one TAB will
1071 make it a subitem, two or more tabs will back up to make this an item
1072 higher up in the item hierarchy."
1073 :group 'org-cycle
1074 :type 'boolean)
1076 (defcustom org-cycle-emulate-tab t
1077 "Where should `org-cycle' emulate TAB.
1078 nil Never
1079 white Only in completely white lines
1080 whitestart Only at the beginning of lines, before the first non-white char
1081 t Everywhere except in headlines
1082 exc-hl-bol Everywhere except at the start of a headline
1083 If TAB is used in a place where it does not emulate TAB, the current subtree
1084 visibility is cycled."
1085 :group 'org-cycle
1086 :type '(choice (const :tag "Never" nil)
1087 (const :tag "Only in completely white lines" white)
1088 (const :tag "Before first char in a line" whitestart)
1089 (const :tag "Everywhere except in headlines" t)
1090 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1093 (defcustom org-cycle-separator-lines 2
1094 "Number of empty lines needed to keep an empty line between collapsed trees.
1095 If you leave an empty line between the end of a subtree and the following
1096 headline, this empty line is hidden when the subtree is folded.
1097 Org-mode will leave (exactly) one empty line visible if the number of
1098 empty lines is equal or larger to the number given in this variable.
1099 So the default 2 means at least 2 empty lines after the end of a subtree
1100 are needed to produce free space between a collapsed subtree and the
1101 following headline.
1103 If the number is negative, and the number of empty lines is at least -N,
1104 all empty lines are shown.
1106 Special case: when 0, never leave empty lines in collapsed view."
1107 :group 'org-cycle
1108 :type 'integer)
1109 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1111 (defcustom org-pre-cycle-hook nil
1112 "Hook that is run before visibility cycling is happening.
1113 The function(s) in this hook must accept a single argument which indicates
1114 the new state that will be set right after running this hook. The
1115 argument is a symbol. Before a global state change, it can have the values
1116 `overview', `content', or `all'. Before a local state change, it can have
1117 the values `folded', `children', or `subtree'."
1118 :group 'org-cycle
1119 :type 'hook)
1121 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1122 org-cycle-hide-drawers
1123 org-cycle-hide-inline-tasks
1124 org-cycle-show-empty-lines
1125 org-optimize-window-after-visibility-change)
1126 "Hook that is run after `org-cycle' has changed the buffer visibility.
1127 The function(s) in this hook must accept a single argument which indicates
1128 the new state that was set by the most recent `org-cycle' command. The
1129 argument is a symbol. After a global state change, it can have the values
1130 `overview', `contents', or `all'. After a local state change, it can have
1131 the values `folded', `children', or `subtree'."
1132 :group 'org-cycle
1133 :type 'hook)
1135 (defgroup org-edit-structure nil
1136 "Options concerning structure editing in Org-mode."
1137 :tag "Org Edit Structure"
1138 :group 'org-structure)
1140 (defcustom org-odd-levels-only nil
1141 "Non-nil means skip even levels and only use odd levels for the outline.
1142 This has the effect that two stars are being added/taken away in
1143 promotion/demotion commands. It also influences how levels are
1144 handled by the exporters.
1145 Changing it requires restart of `font-lock-mode' to become effective
1146 for fontification also in regions already fontified.
1147 You may also set this on a per-file basis by adding one of the following
1148 lines to the buffer:
1150 #+STARTUP: odd
1151 #+STARTUP: oddeven"
1152 :group 'org-edit-structure
1153 :group 'org-appearance
1154 :type 'boolean)
1156 (defcustom org-adapt-indentation t
1157 "Non-nil means adapt indentation to outline node level.
1159 When this variable is set, Org assumes that you write outlines by
1160 indenting text in each node to align with the headline (after the stars).
1161 The following issues are influenced by this variable:
1163 - When this is set and the *entire* text in an entry is indented, the
1164 indentation is increased by one space in a demotion command, and
1165 decreased by one in a promotion command. If any line in the entry
1166 body starts with text at column 0, indentation is not changed at all.
1168 - Property drawers and planning information is inserted indented when
1169 this variable s set. When nil, they will not be indented.
1171 - TAB indents a line relative to context. The lines below a headline
1172 will be indented when this variable is set.
1174 Note that this is all about true indentation, by adding and removing
1175 space characters. See also `org-indent.el' which does level-dependent
1176 indentation in a virtual way, i.e. at display time in Emacs."
1177 :group 'org-edit-structure
1178 :type 'boolean)
1180 (defcustom org-special-ctrl-a/e nil
1181 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1183 When t, `C-a' will bring back the cursor to the beginning of the
1184 headline text, i.e. after the stars and after a possible TODO
1185 keyword. In an item, this will be the position after bullet and
1186 check-box, if any. When the cursor is already at that position,
1187 another `C-a' will bring it to the beginning of the line.
1189 `C-e' will jump to the end of the headline, ignoring the presence
1190 of tags in the headline. A second `C-e' will then jump to the
1191 true end of the line, after any tags. This also means that, when
1192 this variable is non-nil, `C-e' also will never jump beyond the
1193 end of the heading of a folded section, i.e. not after the
1194 ellipses.
1196 When set to the symbol `reversed', the first `C-a' or `C-e' works
1197 normally, going to the true line boundary first. Only a directly
1198 following, identical keypress will bring the cursor to the
1199 special positions.
1201 This may also be a cons cell where the behavior for `C-a' and
1202 `C-e' is set separately."
1203 :group 'org-edit-structure
1204 :type '(choice
1205 (const :tag "off" nil)
1206 (const :tag "on: after stars/bullet and before tags first" t)
1207 (const :tag "reversed: true line boundary first" reversed)
1208 (cons :tag "Set C-a and C-e separately"
1209 (choice :tag "Special C-a"
1210 (const :tag "off" nil)
1211 (const :tag "on: after stars/bullet first" t)
1212 (const :tag "reversed: before stars/bullet first" reversed))
1213 (choice :tag "Special C-e"
1214 (const :tag "off" nil)
1215 (const :tag "on: before tags first" t)
1216 (const :tag "reversed: after tags first" reversed)))))
1217 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1219 (defcustom org-special-ctrl-k nil
1220 "Non-nil means `C-k' will behave specially in headlines.
1221 When nil, `C-k' will call the default `kill-line' command.
1222 When t, the following will happen while the cursor is in the headline:
1224 - When the cursor is at the beginning of a headline, kill the entire
1225 line and possible the folded subtree below the line.
1226 - When in the middle of the headline text, kill the headline up to the tags.
1227 - When after the headline text, kill the tags."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-ctrl-k-protect-subtree nil
1232 "Non-nil means, do not delete a hidden subtree with C-k.
1233 When set to the symbol `error', simply throw an error when C-k is
1234 used to kill (part-of) a headline that has hidden text behind it.
1235 Any other non-nil value will result in a query to the user, if it is
1236 OK to kill that hidden subtree. When nil, kill without remorse."
1237 :group 'org-edit-structure
1238 :version "24.1"
1239 :type '(choice
1240 (const :tag "Do not protect hidden subtrees" nil)
1241 (const :tag "Protect hidden subtrees with a security query" t)
1242 (const :tag "Never kill a hidden subtree with C-k" error)))
1244 (defcustom org-catch-invisible-edits nil
1245 "Check if in invisible region before inserting or deleting a character.
1246 Valid values are:
1248 nil Do not check, so just do invisible edits.
1249 error Throw an error and do nothing.
1250 show Make point visible, and do the requested edit.
1251 show-and-error Make point visible, then throw an error and abort the edit.
1252 smart Make point visible, and do insertion/deletion if it is
1253 adjacent to visible text and the change feels predictable.
1254 Never delete a previously invisible character or add in the
1255 middle or right after an invisible region. Basically, this
1256 allows insertion and backward-delete right before ellipses.
1257 FIXME: maybe in this case we should not even show?"
1258 :group 'org-edit-structure
1259 :version "24.1"
1260 :type '(choice
1261 (const :tag "Do not check" nil)
1262 (const :tag "Throw error when trying to edit" error)
1263 (const :tag "Unhide, but do not do the edit" show-and-error)
1264 (const :tag "Show invisible part and do the edit" show)
1265 (const :tag "Be smart and do the right thing" smart)))
1267 (defcustom org-yank-folded-subtrees t
1268 "Non-nil means when yanking subtrees, fold them.
1269 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1270 it starts with a heading and all other headings in it are either children
1271 or siblings, then fold all the subtrees. However, do this only if no
1272 text after the yank would be swallowed into a folded tree by this action."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-yank-adjusted-subtrees nil
1277 "Non-nil means when yanking subtrees, adjust the level.
1278 With this setting, `org-paste-subtree' is used to insert the subtree, see
1279 this function for details."
1280 :group 'org-edit-structure
1281 :type 'boolean)
1283 (defcustom org-M-RET-may-split-line '((default . t))
1284 "Non-nil means M-RET will split the line at the cursor position.
1285 When nil, it will go to the end of the line before making a
1286 new line.
1287 You may also set this option in a different way for different
1288 contexts. Valid contexts are:
1290 headline when creating a new headline
1291 item when creating a new item
1292 table in a table field
1293 default the value to be used for all contexts not explicitly
1294 customized"
1295 :group 'org-structure
1296 :group 'org-table
1297 :type '(choice
1298 (const :tag "Always" t)
1299 (const :tag "Never" nil)
1300 (repeat :greedy t :tag "Individual contexts"
1301 (cons
1302 (choice :tag "Context"
1303 (const headline)
1304 (const item)
1305 (const table)
1306 (const default))
1307 (boolean)))))
1310 (defcustom org-insert-heading-respect-content nil
1311 "Non-nil means insert new headings after the current subtree.
1312 When nil, the new heading is created directly after the current line.
1313 The commands \\[org-insert-heading-respect-content] and
1314 \\[org-insert-todo-heading-respect-content] turn this variable on
1315 for the duration of the command."
1316 :group 'org-structure
1317 :type 'boolean)
1319 (defcustom org-blank-before-new-entry '((heading . auto)
1320 (plain-list-item . auto))
1321 "Should `org-insert-heading' leave a blank line before new heading/item?
1322 The value is an alist, with `heading' and `plain-list-item' as CAR,
1323 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1324 which case Org will look at the surrounding headings/items and try to
1325 make an intelligent decision whether to insert a blank line or not.
1327 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1328 set, the setting here is ignored and no empty line is inserted, to avoid
1329 breaking the list structure."
1330 :group 'org-edit-structure
1331 :type '(list
1332 (cons (const heading)
1333 (choice (const :tag "Never" nil)
1334 (const :tag "Always" t)
1335 (const :tag "Auto" auto)))
1336 (cons (const plain-list-item)
1337 (choice (const :tag "Never" nil)
1338 (const :tag "Always" t)
1339 (const :tag "Auto" auto)))))
1341 (defcustom org-insert-heading-hook nil
1342 "Hook being run after inserting a new heading."
1343 :group 'org-edit-structure
1344 :type 'hook)
1346 (defcustom org-enable-fixed-width-editor t
1347 "Non-nil means lines starting with \":\" are treated as fixed-width.
1348 This currently only means they are never auto-wrapped.
1349 When nil, such lines will be treated like ordinary lines.
1350 See also the QUOTE keyword."
1351 :group 'org-edit-structure
1352 :type 'boolean)
1354 (defcustom org-goto-auto-isearch t
1355 "Non-nil means typing characters in `org-goto' starts incremental search.
1356 When nil, you can use these keybindings to navigate the buffer:
1358 q Quit the org-goto interface
1359 n Go to the next visible heading
1360 p Go to the previous visible heading
1361 f Go one heading forward on same level
1362 b Go one heading backward on same level
1363 u Go one heading up"
1364 :group 'org-edit-structure
1365 :type 'boolean)
1367 (defgroup org-sparse-trees nil
1368 "Options concerning sparse trees in Org-mode."
1369 :tag "Org Sparse Trees"
1370 :group 'org-structure)
1372 (defcustom org-highlight-sparse-tree-matches t
1373 "Non-nil means highlight all matches that define a sparse tree.
1374 The highlights will automatically disappear the next time the buffer is
1375 changed by an edit command."
1376 :group 'org-sparse-trees
1377 :type 'boolean)
1379 (defcustom org-remove-highlights-with-change t
1380 "Non-nil means any change to the buffer will remove temporary highlights.
1381 Such highlights are created by `org-occur' and `org-clock-display'.
1382 When nil, `C-c C-c needs to be used to get rid of the highlights.
1383 The highlights created by `org-preview-latex-fragment' always need
1384 `C-c C-c' to be removed."
1385 :group 'org-sparse-trees
1386 :group 'org-time
1387 :type 'boolean)
1390 (defcustom org-occur-hook '(org-first-headline-recenter)
1391 "Hook that is run after `org-occur' has constructed a sparse tree.
1392 This can be used to recenter the window to show as much of the structure
1393 as possible."
1394 :group 'org-sparse-trees
1395 :type 'hook)
1397 (defgroup org-imenu-and-speedbar nil
1398 "Options concerning imenu and speedbar in Org-mode."
1399 :tag "Org Imenu and Speedbar"
1400 :group 'org-structure)
1402 (defcustom org-imenu-depth 2
1403 "The maximum level for Imenu access to Org-mode headlines.
1404 This also applied for speedbar access."
1405 :group 'org-imenu-and-speedbar
1406 :type 'integer)
1408 (defgroup org-table nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table"
1411 :group 'org)
1413 (defcustom org-enable-table-editor 'optimized
1414 "Non-nil means lines starting with \"|\" are handled by the table editor.
1415 When nil, such lines will be treated like ordinary lines.
1417 When equal to the symbol `optimized', the table editor will be optimized to
1418 do the following:
1419 - Automatic overwrite mode in front of whitespace in table fields.
1420 This makes the structure of the table stay in tact as long as the edited
1421 field does not exceed the column width.
1422 - Minimize the number of realigns. Normally, the table is aligned each time
1423 TAB or RET are pressed to move to another field. With optimization this
1424 happens only if changes to a field might have changed the column width.
1425 Optimization requires replacing the functions `self-insert-command',
1426 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1427 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1428 very good at guessing when a re-align will be necessary, but you can always
1429 force one with \\[org-ctrl-c-ctrl-c].
1431 If you would like to use the optimized version in Org-mode, but the
1432 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1434 This variable can be used to turn on and off the table editor during a session,
1435 but in order to toggle optimization, a restart is required.
1437 See also the variable `org-table-auto-blank-field'."
1438 :group 'org-table
1439 :type '(choice
1440 (const :tag "off" nil)
1441 (const :tag "on" t)
1442 (const :tag "on, optimized" optimized)))
1444 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1445 (version<= emacs-version "24.1"))
1446 "Non-nil means cluster self-insert commands for undo when possible.
1447 If this is set, then, like in the Emacs command loop, 20 consecutive
1448 characters will be undone together.
1449 This is configurable, because there is some impact on typing performance."
1450 :group 'org-table
1451 :type 'boolean)
1453 (defcustom org-table-tab-recognizes-table.el t
1454 "Non-nil means TAB will automatically notice a table.el table.
1455 When it sees such a table, it moves point into it and - if necessary -
1456 calls `table-recognize-table'."
1457 :group 'org-table-editing
1458 :type 'boolean)
1460 (defgroup org-link nil
1461 "Options concerning links in Org-mode."
1462 :tag "Org Link"
1463 :group 'org)
1465 (defvar org-link-abbrev-alist-local nil
1466 "Buffer-local version of `org-link-abbrev-alist', which see.
1467 The value of this is taken from the #+LINK lines.")
1468 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1470 (defcustom org-link-abbrev-alist nil
1471 "Alist of link abbreviations.
1472 The car of each element is a string, to be replaced at the start of a link.
1473 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1474 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1476 [[linkkey:tag][description]]
1478 The 'linkkey' must be a word word, starting with a letter, followed
1479 by letters, numbers, '-' or '_'.
1481 If REPLACE is a string, the tag will simply be appended to create the link.
1482 If the string contains \"%s\", the tag will be inserted there. If the string
1483 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1484 at that point (see the function `url-hexify-string'). If the string contains
1485 the specifier \"%(my-function)\", then the custom function `my-function' will
1486 be invoked: this function takes the tag as its only argument and must return
1487 a string.
1489 REPLACE may also be a function that will be called with the tag as the
1490 only argument to create the link, which should be returned as a string.
1492 See the manual for examples."
1493 :group 'org-link
1494 :type '(repeat
1495 (cons
1496 (string :tag "Protocol")
1497 (choice
1498 (string :tag "Format")
1499 (function)))))
1501 (defcustom org-descriptive-links t
1502 "Non-nil means Org will display descriptive links.
1503 E.g. [[http://orgmode.org][Org website]] will be displayed as
1504 \"Org Website\", hiding the link itself and just displaying its
1505 description. When set to `nil', Org will display the full links
1506 literally.
1508 You can interactively set the value of this variable by calling
1509 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1510 :group 'org-link
1511 :type 'boolean)
1513 (defcustom org-link-file-path-type 'adaptive
1514 "How the path name in file links should be stored.
1515 Valid values are:
1517 relative Relative to the current directory, i.e. the directory of the file
1518 into which the link is being inserted.
1519 absolute Absolute path, if possible with ~ for home directory.
1520 noabbrev Absolute path, no abbreviation of home directory.
1521 adaptive Use relative path for files in the current directory and sub-
1522 directories of it. For other files, use an absolute path."
1523 :group 'org-link
1524 :type '(choice
1525 (const relative)
1526 (const absolute)
1527 (const noabbrev)
1528 (const adaptive)))
1530 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1531 "Types of links that should be activated in Org-mode files.
1532 This is a list of symbols, each leading to the activation of a certain link
1533 type. In principle, it does not hurt to turn on most link types - there may
1534 be a small gain when turning off unused link types. The types are:
1536 bracket The recommended [[link][description]] or [[link]] links with hiding.
1537 angle Links in angular brackets that may contain whitespace like
1538 <bbdb:Carsten Dominik>.
1539 plain Plain links in normal text, no whitespace, like http://google.com.
1540 radio Text that is matched by a radio target, see manual for details.
1541 tag Tag settings in a headline (link to tag search).
1542 date Time stamps (link to calendar).
1543 footnote Footnote labels.
1545 Changing this variable requires a restart of Emacs to become effective."
1546 :group 'org-link
1547 :type '(set :greedy t
1548 (const :tag "Double bracket links" bracket)
1549 (const :tag "Angular bracket links" angle)
1550 (const :tag "Plain text links" plain)
1551 (const :tag "Radio target matches" radio)
1552 (const :tag "Tags" tag)
1553 (const :tag "Timestamps" date)
1554 (const :tag "Footnotes" footnote)))
1556 (defcustom org-make-link-description-function nil
1557 "Function to use for generating link descriptions from links.
1558 When nil, the link location will be used. This function must take
1559 two parameters: the first one is the link, the second one is the
1560 description generated by `org-insert-link'. The function should
1561 return the description to use."
1562 :group 'org-link
1563 :type 'function)
1565 (defgroup org-link-store nil
1566 "Options concerning storing links in Org-mode."
1567 :tag "Org Store Link"
1568 :group 'org-link)
1570 (defcustom org-url-hexify-p t
1571 "When non-nil, hexify URL when creating a link."
1572 :type 'boolean
1573 :version "24.3"
1574 :group 'org-link-store)
1576 (defcustom org-email-link-description-format "Email %c: %.30s"
1577 "Format of the description part of a link to an email or usenet message.
1578 The following %-escapes will be replaced by corresponding information:
1580 %F full \"From\" field
1581 %f name, taken from \"From\" field, address if no name
1582 %T full \"To\" field
1583 %t first name in \"To\" field, address if no name
1584 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1585 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1586 %s subject
1587 %d date
1588 %m message-id.
1590 You may use normal field width specification between the % and the letter.
1591 This is for example useful to limit the length of the subject.
1593 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1594 :group 'org-link-store
1595 :type 'string)
1597 (defcustom org-from-is-user-regexp
1598 (let (r1 r2)
1599 (when (and user-mail-address (not (string= user-mail-address "")))
1600 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1601 (when (and user-full-name (not (string= user-full-name "")))
1602 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1603 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1604 "Regexp matched against the \"From:\" header of an email or usenet message.
1605 It should match if the message is from the user him/herself."
1606 :group 'org-link-store
1607 :type 'regexp)
1609 (defcustom org-context-in-file-links t
1610 "Non-nil means file links from `org-store-link' contain context.
1611 A search string will be added to the file name with :: as separator and
1612 used to find the context when the link is activated by the command
1613 `org-open-at-point'. When this option is t, the entire active region
1614 will be placed in the search string of the file link. If set to a
1615 positive integer, only the first n lines of context will be stored.
1617 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1618 negates this setting for the duration of the command."
1619 :group 'org-link-store
1620 :type '(choice boolean integer))
1622 (defcustom org-keep-stored-link-after-insertion nil
1623 "Non-nil means keep link in list for entire session.
1625 The command `org-store-link' adds a link pointing to the current
1626 location to an internal list. These links accumulate during a session.
1627 The command `org-insert-link' can be used to insert links into any
1628 Org-mode file (offering completion for all stored links). When this
1629 option is nil, every link which has been inserted once using \\[org-insert-link]
1630 will be removed from the list, to make completing the unused links
1631 more efficient."
1632 :group 'org-link-store
1633 :type 'boolean)
1635 (defgroup org-link-follow nil
1636 "Options concerning following links in Org-mode."
1637 :tag "Org Follow Link"
1638 :group 'org-link)
1640 (defcustom org-link-translation-function nil
1641 "Function to translate links with different syntax to Org syntax.
1642 This can be used to translate links created for example by the Planner
1643 or emacs-wiki packages to Org syntax.
1644 The function must accept two parameters, a TYPE containing the link
1645 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1646 which is everything after the link protocol. It should return a cons
1647 with possibly modified values of type and path.
1648 Org contains a function for this, so if you set this variable to
1649 `org-translate-link-from-planner', you should be able follow many
1650 links created by planner."
1651 :group 'org-link-follow
1652 :type 'function)
1654 (defcustom org-follow-link-hook nil
1655 "Hook that is run after a link has been followed."
1656 :group 'org-link-follow
1657 :type 'hook)
1659 (defcustom org-tab-follows-link nil
1660 "Non-nil means on links TAB will follow the link.
1661 Needs to be set before org.el is loaded.
1662 This really should not be used, it does not make sense, and the
1663 implementation is bad."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-return-follows-link nil
1668 "Non-nil means on links RET will follow the link.
1669 In tables, the special behavior of RET has precedence."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mouse-1-follows-link
1674 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1675 "Non-nil means mouse-1 on a link will follow the link.
1676 A longer mouse click will still set point. Does not work on XEmacs.
1677 Needs to be set before org.el is loaded."
1678 :group 'org-link-follow
1679 :type 'boolean)
1681 (defcustom org-mark-ring-length 4
1682 "Number of different positions to be recorded in the ring.
1683 Changing this requires a restart of Emacs to work correctly."
1684 :group 'org-link-follow
1685 :type 'integer)
1687 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1688 "Non-nil means internal links in Org files must exactly match a headline.
1689 When nil, the link search tries to match a phrase with all words
1690 in the search text."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type '(choice
1694 (const :tag "Use fuzzy text search" nil)
1695 (const :tag "Match only exact headline" t)
1696 (const :tag "Match exact headline or query to create it"
1697 query-to-create)))
1699 (defcustom org-link-frame-setup
1700 '((vm . vm-visit-folder-other-frame)
1701 (vm-imap . vm-visit-imap-folder-other-frame)
1702 (gnus . org-gnus-no-new-news)
1703 (file . find-file-other-window)
1704 (wl . wl-other-frame))
1705 "Setup the frame configuration for following links.
1706 When following a link with Emacs, it may often be useful to display
1707 this link in another window or frame. This variable can be used to
1708 set this up for the different types of links.
1709 For VM, use any of
1710 `vm-visit-folder'
1711 `vm-visit-folder-other-window'
1712 `vm-visit-folder-other-frame'
1713 For Gnus, use any of
1714 `gnus'
1715 `gnus-other-frame'
1716 `org-gnus-no-new-news'
1717 For FILE, use any of
1718 `find-file'
1719 `find-file-other-window'
1720 `find-file-other-frame'
1721 For Wanderlust use any of
1722 `wl'
1723 `wl-other-frame'
1724 For the calendar, use the variable `calendar-setup'.
1725 For BBDB, it is currently only possible to display the matches in
1726 another window."
1727 :group 'org-link-follow
1728 :type '(list
1729 (cons (const vm)
1730 (choice
1731 (const vm-visit-folder)
1732 (const vm-visit-folder-other-window)
1733 (const vm-visit-folder-other-frame)))
1734 (cons (const gnus)
1735 (choice
1736 (const gnus)
1737 (const gnus-other-frame)
1738 (const org-gnus-no-new-news)))
1739 (cons (const file)
1740 (choice
1741 (const find-file)
1742 (const find-file-other-window)
1743 (const find-file-other-frame)))
1744 (cons (const wl)
1745 (choice
1746 (const wl)
1747 (const wl-other-frame)))))
1749 (defcustom org-display-internal-link-with-indirect-buffer nil
1750 "Non-nil means use indirect buffer to display infile links.
1751 Activating internal links (from one location in a file to another location
1752 in the same file) normally just jumps to the location. When the link is
1753 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1754 is displayed in
1755 another window. When this option is set, the other window actually displays
1756 an indirect buffer clone of the current buffer, to avoid any visibility
1757 changes to the current buffer."
1758 :group 'org-link-follow
1759 :type 'boolean)
1761 (defcustom org-open-non-existing-files nil
1762 "Non-nil means `org-open-file' will open non-existing files.
1763 When nil, an error will be generated.
1764 This variable applies only to external applications because they
1765 might choke on non-existing files. If the link is to a file that
1766 will be opened in Emacs, the variable is ignored."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-open-directory-means-index-dot-org nil
1771 "Non-nil means a link to a directory really means to index.org.
1772 When nil, following a directory link will run dired or open a finder/explorer
1773 window on that directory."
1774 :group 'org-link-follow
1775 :type 'boolean)
1777 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1778 "Function and arguments to call for following mailto links.
1779 This is a list with the first element being a Lisp function, and the
1780 remaining elements being arguments to the function. In string arguments,
1781 %a will be replaced by the address, and %s will be replaced by the subject
1782 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1783 :group 'org-link-follow
1784 :type '(choice
1785 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1786 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1787 (const :tag "message-mail" (message-mail "%a" "%s"))
1788 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1790 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1791 "Non-nil means ask for confirmation before executing shell links.
1792 Shell links can be dangerous: just think about a link
1794 [[shell:rm -rf ~/*][Google Search]]
1796 This link would show up in your Org-mode document as \"Google Search\",
1797 but really it would remove your entire home directory.
1798 Therefore we advise against setting this variable to nil.
1799 Just change it to `y-or-n-p' if you want to confirm with a
1800 single keystroke rather than having to type \"yes\"."
1801 :group 'org-link-follow
1802 :type '(choice
1803 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1804 (const :tag "with y-or-n (faster)" y-or-n-p)
1805 (const :tag "no confirmation (dangerous)" nil)))
1806 (put 'org-confirm-shell-link-function
1807 'safe-local-variable
1808 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1810 (defcustom org-confirm-shell-link-not-regexp ""
1811 "A regexp to skip confirmation for shell links."
1812 :group 'org-link-follow
1813 :version "24.1"
1814 :type 'regexp)
1816 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1817 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1818 Elisp links can be dangerous: just think about a link
1820 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1822 This link would show up in your Org-mode document as \"Google Search\",
1823 but really it would remove your entire home directory.
1824 Therefore we advise against setting this variable to nil.
1825 Just change it to `y-or-n-p' if you want to confirm with a
1826 single keystroke rather than having to type \"yes\"."
1827 :group 'org-link-follow
1828 :type '(choice
1829 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1830 (const :tag "with y-or-n (faster)" y-or-n-p)
1831 (const :tag "no confirmation (dangerous)" nil)))
1832 (put 'org-confirm-shell-link-function
1833 'safe-local-variable
1834 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1836 (defcustom org-confirm-elisp-link-not-regexp ""
1837 "A regexp to skip confirmation for Elisp links."
1838 :group 'org-link-follow
1839 :version "24.1"
1840 :type 'regexp)
1842 (defconst org-file-apps-defaults-gnu
1843 '((remote . emacs)
1844 (system . mailcap)
1845 (t . mailcap))
1846 "Default file applications on a UNIX or GNU/Linux system.
1847 See `org-file-apps'.")
1849 (defconst org-file-apps-defaults-macosx
1850 '((remote . emacs)
1851 (t . "open %s")
1852 (system . "open %s")
1853 ("ps.gz" . "gv %s")
1854 ("eps.gz" . "gv %s")
1855 ("dvi" . "xdvi %s")
1856 ("fig" . "xfig %s"))
1857 "Default file applications on a MacOS X system.
1858 The system \"open\" is known as a default, but we use X11 applications
1859 for some files for which the OS does not have a good default.
1860 See `org-file-apps'.")
1862 (defconst org-file-apps-defaults-windowsnt
1863 (list
1864 '(remote . emacs)
1865 (cons t
1866 (list (if (featurep 'xemacs)
1867 'mswindows-shell-execute
1868 'w32-shell-execute)
1869 "open" 'file))
1870 (cons 'system
1871 (list (if (featurep 'xemacs)
1872 'mswindows-shell-execute
1873 'w32-shell-execute)
1874 "open" 'file)))
1875 "Default file applications on a Windows NT system.
1876 The system \"open\" is used for most files.
1877 See `org-file-apps'.")
1879 (defcustom org-file-apps
1881 (auto-mode . emacs)
1882 ("\\.mm\\'" . default)
1883 ("\\.x?html?\\'" . default)
1884 ("\\.pdf\\'" . default)
1886 "External applications for opening `file:path' items in a document.
1887 Org-mode uses system defaults for different file types, but
1888 you can use this variable to set the application for a given file
1889 extension. The entries in this list are cons cells where the car identifies
1890 files and the cdr the corresponding command. Possible values for the
1891 file identifier are
1892 \"string\" A string as a file identifier can be interpreted in different
1893 ways, depending on its contents:
1895 - Alphanumeric characters only:
1896 Match links with this file extension.
1897 Example: (\"pdf\" . \"evince %s\")
1898 to open PDFs with evince.
1900 - Regular expression: Match links where the
1901 filename matches the regexp. If you want to
1902 use groups here, use shy groups.
1904 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1905 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1906 to open *.html and *.xhtml with firefox.
1908 - Regular expression which contains (non-shy) groups:
1909 Match links where the whole link, including \"::\", and
1910 anything after that, matches the regexp.
1911 In a custom command string, %1, %2, etc. are replaced with
1912 the parts of the link that were matched by the groups.
1913 For backwards compatibility, if a command string is given
1914 that does not use any of the group matches, this case is
1915 handled identically to the second one (i.e. match against
1916 file name only).
1917 In a custom lisp form, you can access the group matches with
1918 (match-string n link).
1920 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1921 to open [[file:document.pdf::5]] with evince at page 5.
1923 `directory' Matches a directory
1924 `remote' Matches a remote file, accessible through tramp or efs.
1925 Remote files most likely should be visited through Emacs
1926 because external applications cannot handle such paths.
1927 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1928 so all files Emacs knows how to handle. Using this with
1929 command `emacs' will open most files in Emacs. Beware that this
1930 will also open html files inside Emacs, unless you add
1931 (\"html\" . default) to the list as well.
1932 t Default for files not matched by any of the other options.
1933 `system' The system command to open files, like `open' on Windows
1934 and Mac OS X, and mailcap under GNU/Linux. This is the command
1935 that will be selected if you call `C-c C-o' with a double
1936 \\[universal-argument] \\[universal-argument] prefix.
1938 Possible values for the command are:
1939 `emacs' The file will be visited by the current Emacs process.
1940 `default' Use the default application for this file type, which is the
1941 association for t in the list, most likely in the system-specific
1942 part.
1943 This can be used to overrule an unwanted setting in the
1944 system-specific variable.
1945 `system' Use the system command for opening files, like \"open\".
1946 This command is specified by the entry whose car is `system'.
1947 Most likely, the system-specific version of this variable
1948 does define this command, but you can overrule/replace it
1949 here.
1950 string A command to be executed by a shell; %s will be replaced
1951 by the path to the file.
1952 sexp A Lisp form which will be evaluated. The file path will
1953 be available in the Lisp variable `file'.
1954 For more examples, see the system specific constants
1955 `org-file-apps-defaults-macosx'
1956 `org-file-apps-defaults-windowsnt'
1957 `org-file-apps-defaults-gnu'."
1958 :group 'org-link-follow
1959 :type '(repeat
1960 (cons (choice :value ""
1961 (string :tag "Extension")
1962 (const :tag "System command to open files" system)
1963 (const :tag "Default for unrecognized files" t)
1964 (const :tag "Remote file" remote)
1965 (const :tag "Links to a directory" directory)
1966 (const :tag "Any files that have Emacs modes"
1967 auto-mode))
1968 (choice :value ""
1969 (const :tag "Visit with Emacs" emacs)
1970 (const :tag "Use default" default)
1971 (const :tag "Use the system command" system)
1972 (string :tag "Command")
1973 (sexp :tag "Lisp form")))))
1975 (defcustom org-doi-server-url "http://dx.doi.org/"
1976 "The URL of the DOI server."
1977 :type 'string
1978 :version "24.3"
1979 :group 'org-link-follow)
1981 (defgroup org-refile nil
1982 "Options concerning refiling entries in Org-mode."
1983 :tag "Org Refile"
1984 :group 'org)
1986 (defcustom org-directory "~/org"
1987 "Directory with org files.
1988 This is just a default location to look for Org files. There is no need
1989 at all to put your files into this directory. It is only used in the
1990 following situations:
1992 1. When a capture template specifies a target file that is not an
1993 absolute path. The path will then be interpreted relative to
1994 `org-directory'
1995 2. When a capture note is filed away in an interactive way (when exiting the
1996 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1997 with `org-directory' as the default path."
1998 :group 'org-refile
1999 :group 'org-remember
2000 :group 'org-capture
2001 :type 'directory)
2003 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2004 "Default target for storing notes.
2005 Used as a fall back file for org-remember.el and org-capture.el, for
2006 templates that do not specify a target file."
2007 :group 'org-refile
2008 :group 'org-remember
2009 :group 'org-capture
2010 :type '(choice
2011 (const :tag "Default from remember-data-file" nil)
2012 file))
2014 (defcustom org-goto-interface 'outline
2015 "The default interface to be used for `org-goto'.
2016 Allowed values are:
2017 outline The interface shows an outline of the relevant file
2018 and the correct heading is found by moving through
2019 the outline or by searching with incremental search.
2020 outline-path-completion Headlines in the current buffer are offered via
2021 completion. This is the interface also used by
2022 the refile command."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Outline" outline)
2026 (const :tag "Outline-path-completion" outline-path-completion)))
2028 (defcustom org-goto-max-level 5
2029 "Maximum target level when running `org-goto' with refile interface."
2030 :group 'org-refile
2031 :type 'integer)
2033 (defcustom org-reverse-note-order nil
2034 "Non-nil means store new notes at the beginning of a file or entry.
2035 When nil, new notes will be filed to the end of a file or entry.
2036 This can also be a list with cons cells of regular expressions that
2037 are matched against file names, and values."
2038 :group 'org-remember
2039 :group 'org-capture
2040 :group 'org-refile
2041 :type '(choice
2042 (const :tag "Reverse always" t)
2043 (const :tag "Reverse never" nil)
2044 (repeat :tag "By file name regexp"
2045 (cons regexp boolean))))
2047 (defcustom org-log-refile nil
2048 "Information to record when a task is refiled.
2050 Possible values are:
2052 nil Don't add anything
2053 time Add a time stamp to the task
2054 note Prompt for a note and add it with template `org-log-note-headings'
2056 This option can also be set with on a per-file-basis with
2058 #+STARTUP: nologrefile
2059 #+STARTUP: logrefile
2060 #+STARTUP: lognoterefile
2062 You can have local logging settings for a subtree by setting the LOGGING
2063 property to one or more of these keywords.
2065 When bulk-refiling from the agenda, the value `note' is forbidden and
2066 will temporarily be changed to `time'."
2067 :group 'org-refile
2068 :group 'org-progress
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "No logging" nil)
2072 (const :tag "Record timestamp" time)
2073 (const :tag "Record timestamp with note." note)))
2075 (defcustom org-refile-targets nil
2076 "Targets for refiling entries with \\[org-refile].
2077 This is a list of cons cells. Each cell contains:
2078 - a specification of the files to be considered, either a list of files,
2079 or a symbol whose function or variable value will be used to retrieve
2080 a file name or a list of file names. If you use `org-agenda-files' for
2081 that, all agenda files will be scanned for targets. Nil means consider
2082 headings in the current buffer.
2083 - A specification of how to find candidate refile targets. This may be
2084 any of:
2085 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2086 This tag has to be present in all target headlines, inheritance will
2087 not be considered.
2088 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2089 todo keyword.
2090 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2091 headlines that are refiling targets.
2092 - a cons cell (:level . N). Any headline of level N is considered a target.
2093 Note that, when `org-odd-levels-only' is set, level corresponds to
2094 order in hierarchy, not to the number of stars.
2095 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2096 Note that, when `org-odd-levels-only' is set, level corresponds to
2097 order in hierarchy, not to the number of stars.
2099 Each element of this list generates a set of possible targets.
2100 The union of these sets is presented (with completion) to
2101 the user by `org-refile'.
2103 You can set the variable `org-refile-target-verify-function' to a function
2104 to verify each headline found by the simple criteria above.
2106 When this variable is nil, all top-level headlines in the current buffer
2107 are used, equivalent to the value `((nil . (:level . 1))'."
2108 :group 'org-refile
2109 :type '(repeat
2110 (cons
2111 (choice :value org-agenda-files
2112 (const :tag "All agenda files" org-agenda-files)
2113 (const :tag "Current buffer" nil)
2114 (function) (variable) (file))
2115 (choice :tag "Identify target headline by"
2116 (cons :tag "Specific tag" (const :value :tag) (string))
2117 (cons :tag "TODO keyword" (const :value :todo) (string))
2118 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2119 (cons :tag "Level number" (const :value :level) (integer))
2120 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2122 (defcustom org-refile-target-verify-function nil
2123 "Function to verify if the headline at point should be a refile target.
2124 The function will be called without arguments, with point at the
2125 beginning of the headline. It should return t and leave point
2126 where it is if the headline is a valid target for refiling.
2128 If the target should not be selected, the function must return nil.
2129 In addition to this, it may move point to a place from where the search
2130 should be continued. For example, the function may decide that the entire
2131 subtree of the current entry should be excluded and move point to the end
2132 of the subtree."
2133 :group 'org-refile
2134 :type 'function)
2136 (defcustom org-refile-use-cache nil
2137 "Non-nil means cache refile targets to speed up the process.
2138 The cache for a particular file will be updated automatically when
2139 the buffer has been killed, or when any of the marker used for flagging
2140 refile targets no longer points at a live buffer.
2141 If you have added new entries to a buffer that might themselves be targets,
2142 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2143 find that easier, `C-u C-u C-u C-c C-w'."
2144 :group 'org-refile
2145 :version "24.1"
2146 :type 'boolean)
2148 (defcustom org-refile-use-outline-path nil
2149 "Non-nil means provide refile targets as paths.
2150 So a level 3 headline will be available as level1/level2/level3.
2152 When the value is `file', also include the file name (without directory)
2153 into the path. In this case, you can also stop the completion after
2154 the file name, to get entries inserted as top level in the file.
2156 When `full-file-path', include the full file path."
2157 :group 'org-refile
2158 :type '(choice
2159 (const :tag "Not" nil)
2160 (const :tag "Yes" t)
2161 (const :tag "Start with file name" file)
2162 (const :tag "Start with full file path" full-file-path)))
2164 (defcustom org-outline-path-complete-in-steps t
2165 "Non-nil means complete the outline path in hierarchical steps.
2166 When Org-mode uses the refile interface to select an outline path
2167 \(see variable `org-refile-use-outline-path'), the completion of
2168 the path can be done is a single go, or if can be done in steps down
2169 the headline hierarchy. Going in steps is probably the best if you
2170 do not use a special completion package like `ido' or `icicles'.
2171 However, when using these packages, going in one step can be very
2172 fast, while still showing the whole path to the entry."
2173 :group 'org-refile
2174 :type 'boolean)
2176 (defcustom org-refile-allow-creating-parent-nodes nil
2177 "Non-nil means allow to create new nodes as refile targets.
2178 New nodes are then created by adding \"/new node name\" to the completion
2179 of an existing node. When the value of this variable is `confirm',
2180 new node creation must be confirmed by the user (recommended)
2181 When nil, the completion must match an existing entry.
2183 Note that, if the new heading is not seen by the criteria
2184 listed in `org-refile-targets', multiple instances of the same
2185 heading would be created by trying again to file under the new
2186 heading."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Never" nil)
2190 (const :tag "Always" t)
2191 (const :tag "Prompt for confirmation" confirm)))
2193 (defcustom org-refile-active-region-within-subtree nil
2194 "Non-nil means also refile active region within a subtree.
2196 By default `org-refile' doesn't allow refiling regions if they
2197 don't contain a set of subtrees, but it might be convenient to
2198 do so sometimes: in that case, the first line of the region is
2199 converted to a headline before refiling."
2200 :group 'org-refile
2201 :version "24.1"
2202 :type 'boolean)
2204 (defgroup org-todo nil
2205 "Options concerning TODO items in Org-mode."
2206 :tag "Org TODO"
2207 :group 'org)
2209 (defgroup org-progress nil
2210 "Options concerning Progress logging in Org-mode."
2211 :tag "Org Progress"
2212 :group 'org-time)
2214 (defvar org-todo-interpretation-widgets
2215 '((:tag "Sequence (cycling hits every state)" sequence)
2216 (:tag "Type (cycling directly to DONE)" type))
2217 "The available interpretation symbols for customizing `org-todo-keywords'.
2218 Interested libraries should add to this list.")
2220 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2221 "List of TODO entry keyword sequences and their interpretation.
2222 \\<org-mode-map>This is a list of sequences.
2224 Each sequence starts with a symbol, either `sequence' or `type',
2225 indicating if the keywords should be interpreted as a sequence of
2226 action steps, or as different types of TODO items. The first
2227 keywords are states requiring action - these states will select a headline
2228 for inclusion into the global TODO list Org-mode produces. If one of
2229 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2230 signify that no further action is necessary. If \"|\" is not found,
2231 the last keyword is treated as the only DONE state of the sequence.
2233 The command \\[org-todo] cycles an entry through these states, and one
2234 additional state where no keyword is present. For details about this
2235 cycling, see the manual.
2237 TODO keywords and interpretation can also be set on a per-file basis with
2238 the special #+SEQ_TODO and #+TYP_TODO lines.
2240 Each keyword can optionally specify a character for fast state selection
2241 \(in combination with the variable `org-use-fast-todo-selection')
2242 and specifiers for state change logging, using the same syntax that
2243 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2244 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2245 indicates to record a time stamp each time this state is selected.
2247 Each keyword may also specify if a timestamp or a note should be
2248 recorded when entering or leaving the state, by adding additional
2249 characters in the parenthesis after the keyword. This looks like this:
2250 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2251 record only the time of the state change. With X and Y being either
2252 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2253 Y when leaving the state if and only if the *target* state does not
2254 define X. You may omit any of the fast-selection key or X or /Y,
2255 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2257 For backward compatibility, this variable may also be just a list
2258 of keywords. In this case the interpretation (sequence or type) will be
2259 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2260 :group 'org-todo
2261 :group 'org-keywords
2262 :type '(choice
2263 (repeat :tag "Old syntax, just keywords"
2264 (string :tag "Keyword"))
2265 (repeat :tag "New syntax"
2266 (cons
2267 (choice
2268 :tag "Interpretation"
2269 ;;Quick and dirty way to see
2270 ;;`org-todo-interpretations'. This takes the
2271 ;;place of item arguments
2272 :convert-widget
2273 (lambda (widget)
2274 (widget-put widget
2275 :args (mapcar
2276 #'(lambda (x)
2277 (widget-convert
2278 (cons 'const x)))
2279 org-todo-interpretation-widgets))
2280 widget))
2281 (repeat
2282 (string :tag "Keyword"))))))
2284 (defvar org-todo-keywords-1 nil
2285 "All TODO and DONE keywords active in a buffer.")
2286 (make-variable-buffer-local 'org-todo-keywords-1)
2287 (defvar org-todo-keywords-for-agenda nil)
2288 (defvar org-done-keywords-for-agenda nil)
2289 (defvar org-drawers-for-agenda nil)
2290 (defvar org-todo-keyword-alist-for-agenda nil)
2291 (defvar org-tag-alist-for-agenda nil)
2292 (defvar org-agenda-contributing-files nil)
2293 (defvar org-not-done-keywords nil)
2294 (make-variable-buffer-local 'org-not-done-keywords)
2295 (defvar org-done-keywords nil)
2296 (make-variable-buffer-local 'org-done-keywords)
2297 (defvar org-todo-heads nil)
2298 (make-variable-buffer-local 'org-todo-heads)
2299 (defvar org-todo-sets nil)
2300 (make-variable-buffer-local 'org-todo-sets)
2301 (defvar org-todo-log-states nil)
2302 (make-variable-buffer-local 'org-todo-log-states)
2303 (defvar org-todo-kwd-alist nil)
2304 (make-variable-buffer-local 'org-todo-kwd-alist)
2305 (defvar org-todo-key-alist nil)
2306 (make-variable-buffer-local 'org-todo-key-alist)
2307 (defvar org-todo-key-trigger nil)
2308 (make-variable-buffer-local 'org-todo-key-trigger)
2310 (defcustom org-todo-interpretation 'sequence
2311 "Controls how TODO keywords are interpreted.
2312 This variable is in principle obsolete and is only used for
2313 backward compatibility, if the interpretation of todo keywords is
2314 not given already in `org-todo-keywords'. See that variable for
2315 more information."
2316 :group 'org-todo
2317 :group 'org-keywords
2318 :type '(choice (const sequence)
2319 (const type)))
2321 (defcustom org-use-fast-todo-selection t
2322 "Non-nil means use the fast todo selection scheme with C-c C-t.
2323 This variable describes if and under what circumstances the cycling
2324 mechanism for TODO keywords will be replaced by a single-key, direct
2325 selection scheme.
2327 When nil, fast selection is never used.
2329 When the symbol `prefix', it will be used when `org-todo' is called
2330 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2331 `C-u t' in an agenda buffer.
2333 When t, fast selection is used by default. In this case, the prefix
2334 argument forces cycling instead.
2336 In all cases, the special interface is only used if access keys have
2337 actually been assigned by the user, i.e. if keywords in the configuration
2338 are followed by a letter in parenthesis, like TODO(t)."
2339 :group 'org-todo
2340 :type '(choice
2341 (const :tag "Never" nil)
2342 (const :tag "By default" t)
2343 (const :tag "Only with C-u C-c C-t" prefix)))
2345 (defcustom org-provide-todo-statistics t
2346 "Non-nil means update todo statistics after insert and toggle.
2347 ALL-HEADLINES means update todo statistics by including headlines
2348 with no TODO keyword as well, counting them as not done.
2349 A list of TODO keywords means the same, but skip keywords that are
2350 not in this list.
2352 When this is set, todo statistics is updated in the parent of the
2353 current entry each time a todo state is changed."
2354 :group 'org-todo
2355 :type '(choice
2356 (const :tag "Yes, only for TODO entries" t)
2357 (const :tag "Yes, including all entries" 'all-headlines)
2358 (repeat :tag "Yes, for TODOs in this list"
2359 (string :tag "TODO keyword"))
2360 (other :tag "No TODO statistics" nil)))
2362 (defcustom org-hierarchical-todo-statistics t
2363 "Non-nil means TODO statistics covers just direct children.
2364 When nil, all entries in the subtree are considered.
2365 This has only an effect if `org-provide-todo-statistics' is set.
2366 To set this to nil for only a single subtree, use a COOKIE_DATA
2367 property and include the word \"recursive\" into the value."
2368 :group 'org-todo
2369 :type 'boolean)
2371 (defcustom org-after-todo-state-change-hook nil
2372 "Hook which is run after the state of a TODO item was changed.
2373 The new state (a string with a TODO keyword, or nil) is available in the
2374 Lisp variable `org-state'."
2375 :group 'org-todo
2376 :type 'hook)
2378 (defvar org-blocker-hook nil
2379 "Hook for functions that are allowed to block a state change.
2381 Functions in this hook should not modify the buffer.
2382 Each function gets as its single argument a property list,
2383 see `org-trigger-hook' for more information about this list.
2385 If any of the functions in this hook returns nil, the state change
2386 is blocked.")
2388 (defvar org-trigger-hook nil
2389 "Hook for functions that are triggered by a state change.
2391 Each function gets as its single argument a property list with at
2392 least the following elements:
2394 (:type type-of-change :position pos-at-entry-start
2395 :from old-state :to new-state)
2397 Depending on the type, more properties may be present.
2399 This mechanism is currently implemented for:
2401 TODO state changes
2402 ------------------
2403 :type todo-state-change
2404 :from previous state (keyword as a string), or nil, or a symbol
2405 'todo' or 'done', to indicate the general type of state.
2406 :to new state, like in :from")
2408 (defcustom org-enforce-todo-dependencies nil
2409 "Non-nil means undone TODO entries will block switching the parent to DONE.
2410 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2411 be blocked if any prior sibling is not yet done.
2412 Finally, if the parent is blocked because of ordered siblings of its own,
2413 the child will also be blocked."
2414 :set (lambda (var val)
2415 (set var val)
2416 (if val
2417 (add-hook 'org-blocker-hook
2418 'org-block-todo-from-children-or-siblings-or-parent)
2419 (remove-hook 'org-blocker-hook
2420 'org-block-todo-from-children-or-siblings-or-parent)))
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-enforce-todo-checkbox-dependencies nil
2425 "Non-nil means unchecked boxes will block switching the parent to DONE.
2426 When this is nil, checkboxes have no influence on switching TODO states.
2427 When non-nil, you first need to check off all check boxes before the TODO
2428 entry can be switched to DONE.
2429 This variable needs to be set before org.el is loaded, and you need to
2430 restart Emacs after a change to make the change effective. The only way
2431 to change is while Emacs is running is through the customize interface."
2432 :set (lambda (var val)
2433 (set var val)
2434 (if val
2435 (add-hook 'org-blocker-hook
2436 'org-block-todo-from-checkboxes)
2437 (remove-hook 'org-blocker-hook
2438 'org-block-todo-from-checkboxes)))
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-insert-todo-heading-as-state-change nil
2443 "Non-nil means inserting a TODO heading is treated as state change.
2444 So when the command \\[org-insert-todo-heading] is used, state change
2445 logging will apply if appropriate. When nil, the new TODO item will
2446 be inserted directly, and no logging will take place."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2451 "Non-nil means switching TODO states with S-cursor counts as state change.
2452 This is the default behavior. However, setting this to nil allows a
2453 convenient way to select a TODO state and bypass any logging associated
2454 with that."
2455 :group 'org-todo
2456 :type 'boolean)
2458 (defcustom org-todo-state-tags-triggers nil
2459 "Tag changes that should be triggered by TODO state changes.
2460 This is a list. Each entry is
2462 (state-change (tag . flag) .......)
2464 State-change can be a string with a state, and empty string to indicate the
2465 state that has no TODO keyword, or it can be one of the symbols `todo'
2466 or `done', meaning any not-done or done state, respectively."
2467 :group 'org-todo
2468 :group 'org-tags
2469 :type '(repeat
2470 (cons (choice :tag "When changing to"
2471 (const :tag "Not-done state" todo)
2472 (const :tag "Done state" done)
2473 (string :tag "State"))
2474 (repeat
2475 (cons :tag "Tag action"
2476 (string :tag "Tag")
2477 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2479 (defcustom org-log-done nil
2480 "Information to record when a task moves to the DONE state.
2482 Possible values are:
2484 nil Don't add anything, just change the keyword
2485 time Add a time stamp to the task
2486 note Prompt for a note and add it with template `org-log-note-headings'
2488 This option can also be set with on a per-file-basis with
2490 #+STARTUP: nologdone
2491 #+STARTUP: logdone
2492 #+STARTUP: lognotedone
2494 You can have local logging settings for a subtree by setting the LOGGING
2495 property to one or more of these keywords."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "No logging" nil)
2500 (const :tag "Record CLOSED timestamp" time)
2501 (const :tag "Record CLOSED timestamp with note." note)))
2503 ;; Normalize old uses of org-log-done.
2504 (cond
2505 ((eq org-log-done t) (setq org-log-done 'time))
2506 ((and (listp org-log-done) (memq 'done org-log-done))
2507 (setq org-log-done 'note)))
2509 (defcustom org-log-reschedule nil
2510 "Information to record when the scheduling date of a tasks is modified.
2512 Possible values are:
2514 nil Don't add anything, just change the date
2515 time Add a time stamp to the task
2516 note Prompt for a note and add it with template `org-log-note-headings'
2518 This option can also be set with on a per-file-basis with
2520 #+STARTUP: nologreschedule
2521 #+STARTUP: logreschedule
2522 #+STARTUP: lognotereschedule"
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "No logging" nil)
2527 (const :tag "Record timestamp" time)
2528 (const :tag "Record timestamp with note." note)))
2530 (defcustom org-log-redeadline nil
2531 "Information to record when the deadline date of a tasks is modified.
2533 Possible values are:
2535 nil Don't add anything, just change the date
2536 time Add a time stamp to the task
2537 note Prompt for a note and add it with template `org-log-note-headings'
2539 This option can also be set with on a per-file-basis with
2541 #+STARTUP: nologredeadline
2542 #+STARTUP: logredeadline
2543 #+STARTUP: lognoteredeadline
2545 You can have local logging settings for a subtree by setting the LOGGING
2546 property to one or more of these keywords."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type '(choice
2550 (const :tag "No logging" nil)
2551 (const :tag "Record timestamp" time)
2552 (const :tag "Record timestamp with note." note)))
2554 (defcustom org-log-note-clock-out nil
2555 "Non-nil means record a note when clocking out of an item.
2556 This can also be configured on a per-file basis by adding one of
2557 the following lines anywhere in the buffer:
2559 #+STARTUP: lognoteclock-out
2560 #+STARTUP: nolognoteclock-out"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-done-with-time t
2566 "Non-nil means the CLOSED time stamp will contain date and time.
2567 When nil, only the date will be recorded."
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-log-note-headings
2572 '((done . "CLOSING NOTE %t")
2573 (state . "State %-12s from %-12S %t")
2574 (note . "Note taken on %t")
2575 (reschedule . "Rescheduled from %S on %t")
2576 (delschedule . "Not scheduled, was %S on %t")
2577 (redeadline . "New deadline from %S on %t")
2578 (deldeadline . "Removed deadline, was %S on %t")
2579 (refile . "Refiled on %t")
2580 (clock-out . ""))
2581 "Headings for notes added to entries.
2582 The value is an alist, with the car being a symbol indicating the note
2583 context, and the cdr is the heading to be used. The heading may also be the
2584 empty string.
2585 %t in the heading will be replaced by a time stamp.
2586 %T will be an active time stamp instead the default inactive one
2587 %d will be replaced by a short-format time stamp.
2588 %D will be replaced by an active short-format time stamp.
2589 %s will be replaced by the new TODO state, in double quotes.
2590 %S will be replaced by the old TODO state, in double quotes.
2591 %u will be replaced by the user name.
2592 %U will be replaced by the full user name.
2594 In fact, it is not a good idea to change the `state' entry, because
2595 agenda log mode depends on the format of these entries."
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type '(list :greedy t
2599 (cons (const :tag "Heading when closing an item" done) string)
2600 (cons (const :tag
2601 "Heading when changing todo state (todo sequence only)"
2602 state) string)
2603 (cons (const :tag "Heading when just taking a note" note) string)
2604 (cons (const :tag "Heading when clocking out" clock-out) string)
2605 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2606 (cons (const :tag "Heading when rescheduling" reschedule) string)
2607 (cons (const :tag "Heading when changing deadline" redeadline) string)
2608 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2609 (cons (const :tag "Heading when refiling" refile) string)))
2611 (unless (assq 'note org-log-note-headings)
2612 (push '(note . "%t") org-log-note-headings))
2614 (defcustom org-log-into-drawer nil
2615 "Non-nil means insert state change notes and time stamps into a drawer.
2616 When nil, state changes notes will be inserted after the headline and
2617 any scheduling and clock lines, but not inside a drawer.
2619 The value of this variable should be the name of the drawer to use.
2620 LOGBOOK is proposed as the default drawer for this purpose, you can
2621 also set this to a string to define the drawer of your choice.
2623 A value of t is also allowed, representing \"LOGBOOK\".
2625 A value of t or nil can also be set with on a per-file-basis with
2627 #+STARTUP: logdrawer
2628 #+STARTUP: nologdrawer
2630 If this variable is set, `org-log-state-notes-insert-after-drawers'
2631 will be ignored.
2633 You can set the property LOG_INTO_DRAWER to overrule this setting for
2634 a subtree."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(choice
2638 (const :tag "Not into a drawer" nil)
2639 (const :tag "LOGBOOK" t)
2640 (string :tag "Other")))
2642 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2644 (defun org-log-into-drawer ()
2645 "Return the value of `org-log-into-drawer', but let properties overrule.
2646 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2647 used instead of the default value."
2648 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2649 (cond
2650 ((not p) org-log-into-drawer)
2651 ((equal p "nil") nil)
2652 ((equal p "t") "LOGBOOK")
2653 (t p))))
2655 (defcustom org-log-state-notes-insert-after-drawers nil
2656 "Non-nil means insert state change notes after any drawers in entry.
2657 Only the drawers that *immediately* follow the headline and the
2658 deadline/scheduled line are skipped.
2659 When nil, insert notes right after the heading and perhaps the line
2660 with deadline/scheduling if present.
2662 This variable will have no effect if `org-log-into-drawer' is
2663 set."
2664 :group 'org-todo
2665 :group 'org-progress
2666 :type 'boolean)
2668 (defcustom org-log-states-order-reversed t
2669 "Non-nil means the latest state note will be directly after heading.
2670 When nil, the state change notes will be ordered according to time.
2672 This option can also be set with on a per-file-basis with
2674 #+STARTUP: logstatesreversed
2675 #+STARTUP: nologstatesreversed"
2676 :group 'org-todo
2677 :group 'org-progress
2678 :type 'boolean)
2680 (defcustom org-todo-repeat-to-state nil
2681 "The TODO state to which a repeater should return the repeating task.
2682 By default this is the first task in a TODO sequence, or the previous state
2683 in a TODO_TYP set. But you can specify another task here.
2684 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2685 :group 'org-todo
2686 :version "24.1"
2687 :type '(choice (const :tag "Head of sequence" nil)
2688 (string :tag "Specific state")))
2690 (defcustom org-log-repeat 'time
2691 "Non-nil means record moving through the DONE state when triggering repeat.
2692 An auto-repeating task is immediately switched back to TODO when
2693 marked DONE. If you are not logging state changes (by adding \"@\"
2694 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2695 record a closing note, there will be no record of the task moving
2696 through DONE. This variable forces taking a note anyway.
2698 nil Don't force a record
2699 time Record a time stamp
2700 note Prompt for a note and add it with template `org-log-note-headings'
2702 This option can also be set with on a per-file-basis with
2704 #+STARTUP: nologrepeat
2705 #+STARTUP: logrepeat
2706 #+STARTUP: lognoterepeat
2708 You can have local logging settings for a subtree by setting the LOGGING
2709 property to one or more of these keywords."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type '(choice
2713 (const :tag "Don't force a record" nil)
2714 (const :tag "Force recording the DONE state" time)
2715 (const :tag "Force recording a note with the DONE state" note)))
2718 (defgroup org-priorities nil
2719 "Priorities in Org-mode."
2720 :tag "Org Priorities"
2721 :group 'org-todo)
2723 (defcustom org-enable-priority-commands t
2724 "Non-nil means priority commands are active.
2725 When nil, these commands will be disabled, so that you never accidentally
2726 set a priority."
2727 :group 'org-priorities
2728 :type 'boolean)
2730 (defcustom org-highest-priority ?A
2731 "The highest priority of TODO items. A character like ?A, ?B etc.
2732 Must have a smaller ASCII number than `org-lowest-priority'."
2733 :group 'org-priorities
2734 :type 'character)
2736 (defcustom org-lowest-priority ?C
2737 "The lowest priority of TODO items. A character like ?A, ?B etc.
2738 Must have a larger ASCII number than `org-highest-priority'."
2739 :group 'org-priorities
2740 :type 'character)
2742 (defcustom org-default-priority ?B
2743 "The default priority of TODO items.
2744 This is the priority an item gets if no explicit priority is given.
2745 When starting to cycle on an empty priority the first step in the cycle
2746 depends on `org-priority-start-cycle-with-default'. The resulting first
2747 step priority must not exceed the range from `org-highest-priority' to
2748 `org-lowest-priority' which means that `org-default-priority' has to be
2749 in this range exclusive or inclusive the range boundaries. Else the
2750 first step refuses to set the default and the second will fall back
2751 to (depending on the command used) the highest or lowest priority."
2752 :group 'org-priorities
2753 :type 'character)
2755 (defcustom org-priority-start-cycle-with-default t
2756 "Non-nil means start with default priority when starting to cycle.
2757 When this is nil, the first step in the cycle will be (depending on the
2758 command used) one higher or lower than the default priority.
2759 See also `org-default-priority'."
2760 :group 'org-priorities
2761 :type 'boolean)
2763 (defcustom org-get-priority-function nil
2764 "Function to extract the priority from a string.
2765 The string is normally the headline. If this is nil Org computes the
2766 priority from the priority cookie like [#A] in the headline. It returns
2767 an integer, increasing by 1000 for each priority level.
2768 The user can set a different function here, which should take a string
2769 as an argument and return the numeric priority."
2770 :group 'org-priorities
2771 :version "24.1"
2772 :type 'function)
2774 (defgroup org-time nil
2775 "Options concerning time stamps and deadlines in Org-mode."
2776 :tag "Org Time"
2777 :group 'org)
2779 (defcustom org-insert-labeled-timestamps-at-point nil
2780 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2781 When nil, these labeled time stamps are forces into the second line of an
2782 entry, just after the headline. When scheduling from the global TODO list,
2783 the time stamp will always be forced into the second line."
2784 :group 'org-time
2785 :type 'boolean)
2787 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2788 "Formats for `format-time-string' which are used for time stamps.
2789 It is not recommended to change this constant.")
2791 (defcustom org-time-stamp-rounding-minutes '(0 5)
2792 "Number of minutes to round time stamps to.
2793 These are two values, the first applies when first creating a time stamp.
2794 The second applies when changing it with the commands `S-up' and `S-down'.
2795 When changing the time stamp, this means that it will change in steps
2796 of N minutes, as given by the second value.
2798 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2799 numbers should be factors of 60, so for example 5, 10, 15.
2801 When this is larger than 1, you can still force an exact time stamp by using
2802 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2803 and by using a prefix arg to `S-up/down' to specify the exact number
2804 of minutes to shift."
2805 :group 'org-time
2806 :get #'(lambda (var) ; Make sure both elements are there
2807 (if (integerp (default-value var))
2808 (list (default-value var) 5)
2809 (default-value var)))
2810 :type '(list
2811 (integer :tag "when inserting times")
2812 (integer :tag "when modifying times")))
2814 ;; Normalize old customizations of this variable.
2815 (when (integerp org-time-stamp-rounding-minutes)
2816 (setq org-time-stamp-rounding-minutes
2817 (list org-time-stamp-rounding-minutes
2818 org-time-stamp-rounding-minutes)))
2820 (defcustom org-display-custom-times nil
2821 "Non-nil means overlay custom formats over all time stamps.
2822 The formats are defined through the variable `org-time-stamp-custom-formats'.
2823 To turn this on on a per-file basis, insert anywhere in the file:
2824 #+STARTUP: customtime"
2825 :group 'org-time
2826 :set 'set-default
2827 :type 'sexp)
2828 (make-variable-buffer-local 'org-display-custom-times)
2830 (defcustom org-time-stamp-custom-formats
2831 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2832 "Custom formats for time stamps. See `format-time-string' for the syntax.
2833 These are overlaid over the default ISO format if the variable
2834 `org-display-custom-times' is set. Time like %H:%M should be at the
2835 end of the second format. The custom formats are also honored by export
2836 commands, if custom time display is turned on at the time of export."
2837 :group 'org-time
2838 :type 'sexp)
2840 (defun org-time-stamp-format (&optional long inactive)
2841 "Get the right format for a time string."
2842 (let ((f (if long (cdr org-time-stamp-formats)
2843 (car org-time-stamp-formats))))
2844 (if inactive
2845 (concat "[" (substring f 1 -1) "]")
2846 f)))
2848 (defcustom org-time-clocksum-format
2849 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2850 "The format string used when creating CLOCKSUM lines.
2851 This is also used when Org mode generates a time duration.
2853 The value can be a single format string containing two
2854 %-sequences, which will be filled with the number of hours and
2855 minutes in that order.
2857 Alternatively, the value can be a plist associating any of the
2858 keys :years, :months, :weeks, :days, :hours or :minutes with
2859 format strings. The time duration is formatted using only the
2860 time components that are needed and concatenating the results.
2861 If a time unit in absent, it falls back to the next smallest
2862 unit.
2864 The keys :require-years, :require-months, :require-days,
2865 :require-weeks, :require-hours, :require-minutes are also
2866 meaningful. A non-nil value for these keys indicates that the
2867 corresponding time component should always be included, even if
2868 its value is 0.
2871 For example,
2873 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2874 :require-minutes t)
2876 means durations longer than a day will be expressed in days,
2877 hours and minutes, and durations less than a day will always be
2878 expressed in hours and minutes (even for durations less than an
2879 hour).
2881 The value
2883 \(:days \"%dd\" :minutes \"%dm\")
2885 means durations longer than a day will be expressed in days and
2886 minutes, and durations less than a day will be expressed entirely
2887 in minutes (even for durations longer than an hour)."
2888 :group 'org-time
2889 :group 'org-clock
2890 :version "24.4"
2891 :package-version '(Org . "8.0")
2892 :type '(choice (string :tag "Format string")
2893 (set :tag "Plist"
2894 (group :inline t (const :tag "Years" :years)
2895 (string :tag "Format string"))
2896 (group :inline t
2897 (const :tag "Always show years" :require-years)
2898 (const t))
2899 (group :inline t (const :tag "Months" :months)
2900 (string :tag "Format string"))
2901 (group :inline t
2902 (const :tag "Always show months" :require-months)
2903 (const t))
2904 (group :inline t (const :tag "Weeks" :weeks)
2905 (string :tag "Format string"))
2906 (group :inline t
2907 (const :tag "Always show weeks" :require-weeks)
2908 (const t))
2909 (group :inline t (const :tag "Days" :days)
2910 (string :tag "Format string"))
2911 (group :inline t
2912 (const :tag "Always show days" :require-days)
2913 (const t))
2914 (group :inline t (const :tag "Hours" :hours)
2915 (string :tag "Format string"))
2916 (group :inline t
2917 (const :tag "Always show hours" :require-hours)
2918 (const t))
2919 (group :inline t (const :tag "Minutes" :minutes)
2920 (string :tag "Format string"))
2921 (group :inline t
2922 (const :tag "Always show minutes" :require-minutes)
2923 (const t)))))
2925 (defcustom org-time-clocksum-use-fractional nil
2926 "When non-nil, \\[org-clock-display] uses fractional times.
2927 See `org-time-clocksum-format' for more on time clock formats."
2928 :group 'org-time
2929 :group 'org-clock
2930 :version "24.3"
2931 :type 'boolean)
2933 (defcustom org-time-clocksum-use-effort-durations nil
2934 "When non-nil, \\[org-clock-display] uses effort durations.
2935 E.g. by default, one day is considered to be a 8 hours effort,
2936 so a task that has been clocked for 16 hours will be displayed
2937 as during 2 days in the clock display or in the clocktable.
2939 See `org-effort-durations' on how to set effort durations
2940 and `org-time-clocksum-format' for more on time clock formats."
2941 :group 'org-time
2942 :group 'org-clock
2943 :version "24.4"
2944 :package-version '(Org . "8.0")
2945 :type 'boolean)
2947 (defcustom org-time-clocksum-fractional-format "%.2f"
2948 "The format string used when creating CLOCKSUM lines,
2949 or when Org mode generates a time duration, if
2950 `org-time-clocksum-use-fractional' is enabled.
2952 The value can be a single format string containing one
2953 %-sequence, which will be filled with the number of hours as
2954 a float.
2956 Alternatively, the value can be a plist associating any of the
2957 keys :years, :months, :weeks, :days, :hours or :minutes with
2958 a format string. The time duration is formatted using the
2959 largest time unit which gives a non-zero integer part. If all
2960 specified formats have zero integer part, the smallest time unit
2961 is used."
2962 :group 'org-time
2963 :type '(choice (string :tag "Format string")
2964 (set (group :inline t (const :tag "Years" :years)
2965 (string :tag "Format string"))
2966 (group :inline t (const :tag "Months" :months)
2967 (string :tag "Format string"))
2968 (group :inline t (const :tag "Weeks" :weeks)
2969 (string :tag "Format string"))
2970 (group :inline t (const :tag "Days" :days)
2971 (string :tag "Format string"))
2972 (group :inline t (const :tag "Hours" :hours)
2973 (string :tag "Format string"))
2974 (group :inline t (const :tag "Minutes" :minutes)
2975 (string :tag "Format string")))))
2977 (defcustom org-deadline-warning-days 14
2978 "Number of days before expiration during which a deadline becomes active.
2979 This variable governs the display in sparse trees and in the agenda.
2980 When 0 or negative, it means use this number (the absolute value of it)
2981 even if a deadline has a different individual lead time specified.
2983 Custom commands can set this variable in the options section."
2984 :group 'org-time
2985 :group 'org-agenda-daily/weekly
2986 :type 'integer)
2988 (defcustom org-scheduled-delay-days 0
2989 "Number of days before a scheduled item becomes active.
2990 This variable governs the display in sparse trees and in the agenda.
2991 The default value (i.e. 0) means: don't delay scheduled item.
2992 When negative, it means use this number (the absolute value of it)
2993 even if a scheduled item has a different individual delay time
2994 specified.
2996 Custom commands can set this variable in the options section."
2997 :group 'org-time
2998 :group 'org-agenda-daily/weekly
2999 :version "24.4"
3000 :package-version '(Org . "8.0")
3001 :type 'integer)
3003 (defcustom org-read-date-prefer-future t
3004 "Non-nil means assume future for incomplete date input from user.
3005 This affects the following situations:
3006 1. The user gives a month but not a year.
3007 For example, if it is April and you enter \"feb 2\", this will be read
3008 as Feb 2, *next* year. \"May 5\", however, will be this year.
3009 2. The user gives a day, but no month.
3010 For example, if today is the 15th, and you enter \"3\", Org-mode will
3011 read this as the third of *next* month. However, if you enter \"17\",
3012 it will be considered as *this* month.
3014 If you set this variable to the symbol `time', then also the following
3015 will work:
3017 3. If the user gives a time.
3018 If the time is before now, it will be interpreted as tomorrow.
3020 Currently none of this works for ISO week specifications.
3022 When this option is nil, the current day, month and year will always be
3023 used as defaults.
3025 See also `org-agenda-jump-prefer-future'."
3026 :group 'org-time
3027 :type '(choice
3028 (const :tag "Never" nil)
3029 (const :tag "Check month and day" t)
3030 (const :tag "Check month, day, and time" time)))
3032 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3033 "Should the agenda jump command prefer the future for incomplete dates?
3034 The default is to do the same as configured in `org-read-date-prefer-future'.
3035 But you can also set a deviating value here.
3036 This may t or nil, or the symbol `org-read-date-prefer-future'."
3037 :group 'org-agenda
3038 :group 'org-time
3039 :version "24.1"
3040 :type '(choice
3041 (const :tag "Use org-read-date-prefer-future"
3042 org-read-date-prefer-future)
3043 (const :tag "Never" nil)
3044 (const :tag "Always" t)))
3046 (defcustom org-read-date-force-compatible-dates t
3047 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3049 Depending on the system Emacs is running on, certain dates cannot
3050 be represented with the type used internally to represent time.
3051 Dates between 1970-1-1 and 2038-1-1 can always be represented
3052 correctly. Some systems allow for earlier dates, some for later,
3053 some for both. One way to find out it to insert any date into an
3054 Org buffer, putting the cursor on the year and hitting S-up and
3055 S-down to test the range.
3057 When this variable is set to t, the date/time prompt will not let
3058 you specify dates outside the 1970-2037 range, so it is certain that
3059 these dates will work in whatever version of Emacs you are
3060 running, and also that you can move a file from one Emacs implementation
3061 to another. WHenever Org is forcing the year for you, it will display
3062 a message and beep.
3064 When this variable is nil, Org will check if the date is
3065 representable in the specific Emacs implementation you are using.
3066 If not, it will force a year, usually the current year, and beep
3067 to remind you. Currently this setting is not recommended because
3068 the likelihood that you will open your Org files in an Emacs that
3069 has limited date range is not negligible.
3071 A workaround for this problem is to use diary sexp dates for time
3072 stamps outside of this range."
3073 :group 'org-time
3074 :version "24.1"
3075 :type 'boolean)
3077 (defcustom org-read-date-display-live t
3078 "Non-nil means display current interpretation of date prompt live.
3079 This display will be in an overlay, in the minibuffer."
3080 :group 'org-time
3081 :type 'boolean)
3083 (defcustom org-read-date-popup-calendar t
3084 "Non-nil means pop up a calendar when prompting for a date.
3085 In the calendar, the date can be selected with mouse-1. However, the
3086 minibuffer will also be active, and you can simply enter the date as well.
3087 When nil, only the minibuffer will be available."
3088 :group 'org-time
3089 :type 'boolean)
3090 (org-defvaralias 'org-popup-calendar-for-date-prompt
3091 'org-read-date-popup-calendar)
3093 (make-obsolete-variable
3094 'org-read-date-minibuffer-setup-hook
3095 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3096 (defcustom org-read-date-minibuffer-setup-hook nil
3097 "Hook to be used to set up keys for the date/time interface.
3098 Add key definitions to `minibuffer-local-map', which will be a
3099 temporary copy.
3101 WARNING: This option is obsolete, you should use
3102 `org-read-date-minibuffer-local-map' to set up keys."
3103 :group 'org-time
3104 :type 'hook)
3106 (defcustom org-extend-today-until 0
3107 "The hour when your day really ends. Must be an integer.
3108 This has influence for the following applications:
3109 - When switching the agenda to \"today\". It it is still earlier than
3110 the time given here, the day recognized as TODAY is actually yesterday.
3111 - When a date is read from the user and it is still before the time given
3112 here, the current date and time will be assumed to be yesterday, 23:59.
3113 Also, timestamps inserted in capture templates follow this rule.
3115 IMPORTANT: This is a feature whose implementation is and likely will
3116 remain incomplete. Really, it is only here because past midnight seems to
3117 be the favorite working time of John Wiegley :-)"
3118 :group 'org-time
3119 :type 'integer)
3121 (defcustom org-use-effective-time nil
3122 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3123 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3124 \"effective time\" of any timestamps between midnight and 8am will be
3125 23:59 of the previous day."
3126 :group 'org-time
3127 :version "24.1"
3128 :type 'boolean)
3130 (defcustom org-use-last-clock-out-time-as-effective-time nil
3131 "When non-nil, use the last clock out time for `org-todo'.
3132 Note that this option has precedence over the combined use of
3133 `org-use-effective-time' and `org-extend-today-until'."
3134 :group 'org-time
3135 :version "24.4"
3136 :package-version '(Org . "8.0")
3137 :type 'boolean)
3139 (defcustom org-edit-timestamp-down-means-later nil
3140 "Non-nil means S-down will increase the time in a time stamp.
3141 When nil, S-up will increase."
3142 :group 'org-time
3143 :type 'boolean)
3145 (defcustom org-calendar-follow-timestamp-change t
3146 "Non-nil means make the calendar window follow timestamp changes.
3147 When a timestamp is modified and the calendar window is visible, it will be
3148 moved to the new date."
3149 :group 'org-time
3150 :type 'boolean)
3152 (defgroup org-tags nil
3153 "Options concerning tags in Org-mode."
3154 :tag "Org Tags"
3155 :group 'org)
3157 (defcustom org-tag-alist nil
3158 "List of tags allowed in Org-mode files.
3159 When this list is nil, Org-mode will base TAG input on what is already in the
3160 buffer.
3161 The value of this variable is an alist, the car of each entry must be a
3162 keyword as a string, the cdr may be a character that is used to select
3163 that tag through the fast-tag-selection interface.
3164 See the manual for details."
3165 :group 'org-tags
3166 :type '(repeat
3167 (choice
3168 (cons (string :tag "Tag name")
3169 (character :tag "Access char"))
3170 (list :tag "Start radio group"
3171 (const :startgroup)
3172 (option (string :tag "Group description")))
3173 (list :tag "End radio group"
3174 (const :endgroup)
3175 (option (string :tag "Group description")))
3176 (const :tag "New line" (:newline)))))
3178 (defcustom org-tag-persistent-alist nil
3179 "List of tags that will always appear in all Org-mode files.
3180 This is in addition to any in buffer settings or customizations
3181 of `org-tag-alist'.
3182 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3183 The value of this variable is an alist, the car of each entry must be a
3184 keyword as a string, the cdr may be a character that is used to select
3185 that tag through the fast-tag-selection interface.
3186 See the manual for details.
3187 To disable these tags on a per-file basis, insert anywhere in the file:
3188 #+STARTUP: noptag"
3189 :group 'org-tags
3190 :type '(repeat
3191 (choice
3192 (cons (string :tag "Tag name")
3193 (character :tag "Access char"))
3194 (const :tag "Start radio group" (:startgroup))
3195 (const :tag "End radio group" (:endgroup))
3196 (const :tag "New line" (:newline)))))
3198 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3199 "If non-nil, always offer completion for all tags of all agenda files.
3200 Instead of customizing this variable directly, you might want to
3201 set it locally for capture buffers, because there no list of
3202 tags in that file can be created dynamically (there are none).
3204 (add-hook 'org-capture-mode-hook
3205 (lambda ()
3206 (set (make-local-variable
3207 'org-complete-tags-always-offer-all-agenda-tags)
3208 t)))"
3209 :group 'org-tags
3210 :version "24.1"
3211 :type 'boolean)
3213 (defvar org-file-tags nil
3214 "List of tags that can be inherited by all entries in the file.
3215 The tags will be inherited if the variable `org-use-tag-inheritance'
3216 says they should be.
3217 This variable is populated from #+FILETAGS lines.")
3219 (defcustom org-use-fast-tag-selection 'auto
3220 "Non-nil means use fast tag selection scheme.
3221 This is a special interface to select and deselect tags with single keys.
3222 When nil, fast selection is never used.
3223 When the symbol `auto', fast selection is used if and only if selection
3224 characters for tags have been configured, either through the variable
3225 `org-tag-alist' or through a #+TAGS line in the buffer.
3226 When t, fast selection is always used and selection keys are assigned
3227 automatically if necessary."
3228 :group 'org-tags
3229 :type '(choice
3230 (const :tag "Always" t)
3231 (const :tag "Never" nil)
3232 (const :tag "When selection characters are configured" 'auto)))
3234 (defcustom org-fast-tag-selection-single-key nil
3235 "Non-nil means fast tag selection exits after first change.
3236 When nil, you have to press RET to exit it.
3237 During fast tag selection, you can toggle this flag with `C-c'.
3238 This variable can also have the value `expert'. In this case, the window
3239 displaying the tags menu is not even shown, until you press C-c again."
3240 :group 'org-tags
3241 :type '(choice
3242 (const :tag "No" nil)
3243 (const :tag "Yes" t)
3244 (const :tag "Expert" expert)))
3246 (defvar org-fast-tag-selection-include-todo nil
3247 "Non-nil means fast tags selection interface will also offer TODO states.
3248 This is an undocumented feature, you should not rely on it.")
3250 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3251 "The column to which tags should be indented in a headline.
3252 If this number is positive, it specifies the column. If it is negative,
3253 it means that the tags should be flushright to that column. For example,
3254 -80 works well for a normal 80 character screen.
3255 When 0, place tags directly after headline text, with only one space in
3256 between."
3257 :group 'org-tags
3258 :type 'integer)
3260 (defcustom org-auto-align-tags t
3261 "Non-nil keeps tags aligned when modifying headlines.
3262 Some operations (i.e. demoting) change the length of a headline and
3263 therefore shift the tags around. With this option turned on, after
3264 each such operation the tags are again aligned to `org-tags-column'."
3265 :group 'org-tags
3266 :type 'boolean)
3268 (defcustom org-use-tag-inheritance t
3269 "Non-nil means tags in levels apply also for sublevels.
3270 When nil, only the tags directly given in a specific line apply there.
3271 This may also be a list of tags that should be inherited, or a regexp that
3272 matches tags that should be inherited. Additional control is possible
3273 with the variable `org-tags-exclude-from-inheritance' which gives an
3274 explicit list of tags to be excluded from inheritance, even if the value of
3275 `org-use-tag-inheritance' would select it for inheritance.
3277 If this option is t, a match early-on in a tree can lead to a large
3278 number of matches in the subtree when constructing the agenda or creating
3279 a sparse tree. If you only want to see the first match in a tree during
3280 a search, check out the variable `org-tags-match-list-sublevels'."
3281 :group 'org-tags
3282 :type '(choice
3283 (const :tag "Not" nil)
3284 (const :tag "Always" t)
3285 (repeat :tag "Specific tags" (string :tag "Tag"))
3286 (regexp :tag "Tags matched by regexp")))
3288 (defcustom org-tags-exclude-from-inheritance nil
3289 "List of tags that should never be inherited.
3290 This is a way to exclude a few tags from inheritance. For way to do
3291 the opposite, to actively allow inheritance for selected tags,
3292 see the variable `org-use-tag-inheritance'."
3293 :group 'org-tags
3294 :type '(repeat (string :tag "Tag")))
3296 (defun org-tag-inherit-p (tag)
3297 "Check if TAG is one that should be inherited."
3298 (cond
3299 ((member tag org-tags-exclude-from-inheritance) nil)
3300 ((eq org-use-tag-inheritance t) t)
3301 ((not org-use-tag-inheritance) nil)
3302 ((stringp org-use-tag-inheritance)
3303 (string-match org-use-tag-inheritance tag))
3304 ((listp org-use-tag-inheritance)
3305 (member tag org-use-tag-inheritance))
3306 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3308 (defcustom org-tags-match-list-sublevels t
3309 "Non-nil means list also sublevels of headlines matching a search.
3310 This variable applies to tags/property searches, and also to stuck
3311 projects because this search is based on a tags match as well.
3313 When set to the symbol `indented', sublevels are indented with
3314 leading dots.
3316 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3317 the sublevels of a headline matching a tag search often also match
3318 the same search. Listing all of them can create very long lists.
3319 Setting this variable to nil causes subtrees of a match to be skipped.
3321 This variable is semi-obsolete and probably should always be true. It
3322 is better to limit inheritance to certain tags using the variables
3323 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3324 :group 'org-tags
3325 :type '(choice
3326 (const :tag "No, don't list them" nil)
3327 (const :tag "Yes, do list them" t)
3328 (const :tag "List them, indented with leading dots" indented)))
3330 (defcustom org-tags-sort-function nil
3331 "When set, tags are sorted using this function as a comparator."
3332 :group 'org-tags
3333 :type '(choice
3334 (const :tag "No sorting" nil)
3335 (const :tag "Alphabetical" string<)
3336 (const :tag "Reverse alphabetical" string>)
3337 (function :tag "Custom function" nil)))
3339 (defvar org-tags-history nil
3340 "History of minibuffer reads for tags.")
3341 (defvar org-last-tags-completion-table nil
3342 "The last used completion table for tags.")
3343 (defvar org-after-tags-change-hook nil
3344 "Hook that is run after the tags in a line have changed.")
3346 (defgroup org-properties nil
3347 "Options concerning properties in Org-mode."
3348 :tag "Org Properties"
3349 :group 'org)
3351 (defcustom org-property-format "%-10s %s"
3352 "How property key/value pairs should be formatted by `indent-line'.
3353 When `indent-line' hits a property definition, it will format the line
3354 according to this format, mainly to make sure that the values are
3355 lined-up with respect to each other."
3356 :group 'org-properties
3357 :type 'string)
3359 (defcustom org-properties-postprocess-alist nil
3360 "Alist of properties and functions to adjust inserted values.
3361 Elements of this alist must be of the form
3363 ([string] [function])
3365 where [string] must be a property name and [function] must be a
3366 lambda expression: this lambda expression must take one argument,
3367 the value to adjust, and return the new value as a string.
3369 For example, this element will allow the property \"Remaining\"
3370 to be updated wrt the relation between the \"Effort\" property
3371 and the clock summary:
3373 ((\"Remaining\" (lambda(value)
3374 (let ((clocksum (org-clock-sum-current-item))
3375 (effort (org-duration-string-to-minutes
3376 (org-entry-get (point) \"Effort\"))))
3377 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3378 :group 'org-properties
3379 :version "24.1"
3380 :type '(alist :key-type (string :tag "Property")
3381 :value-type (function :tag "Function")))
3383 (defcustom org-use-property-inheritance nil
3384 "Non-nil means properties apply also for sublevels.
3386 This setting is chiefly used during property searches. Turning it on can
3387 cause significant overhead when doing a search, which is why it is not
3388 on by default.
3390 When nil, only the properties directly given in the current entry count.
3391 When t, every property is inherited. The value may also be a list of
3392 properties that should have inheritance, or a regular expression matching
3393 properties that should be inherited.
3395 However, note that some special properties use inheritance under special
3396 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3397 and the properties ending in \"_ALL\" when they are used as descriptor
3398 for valid values of a property.
3400 Note for programmers:
3401 When querying an entry with `org-entry-get', you can control if inheritance
3402 should be used. By default, `org-entry-get' looks only at the local
3403 properties. You can request inheritance by setting the inherit argument
3404 to t (to force inheritance) or to `selective' (to respect the setting
3405 in this variable)."
3406 :group 'org-properties
3407 :type '(choice
3408 (const :tag "Not" nil)
3409 (const :tag "Always" t)
3410 (repeat :tag "Specific properties" (string :tag "Property"))
3411 (regexp :tag "Properties matched by regexp")))
3413 (defun org-property-inherit-p (property)
3414 "Check if PROPERTY is one that should be inherited."
3415 (cond
3416 ((eq org-use-property-inheritance t) t)
3417 ((not org-use-property-inheritance) nil)
3418 ((stringp org-use-property-inheritance)
3419 (string-match org-use-property-inheritance property))
3420 ((listp org-use-property-inheritance)
3421 (member property org-use-property-inheritance))
3422 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3424 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3425 "The default column format, if no other format has been defined.
3426 This variable can be set on the per-file basis by inserting a line
3428 #+COLUMNS: %25ITEM ....."
3429 :group 'org-properties
3430 :type 'string)
3432 (defcustom org-columns-ellipses ".."
3433 "The ellipses to be used when a field in column view is truncated.
3434 When this is the empty string, as many characters as possible are shown,
3435 but then there will be no visual indication that the field has been truncated.
3436 When this is a string of length N, the last N characters of a truncated
3437 field are replaced by this string. If the column is narrower than the
3438 ellipses string, only part of the ellipses string will be shown."
3439 :group 'org-properties
3440 :type 'string)
3442 (defcustom org-columns-modify-value-for-display-function nil
3443 "Function that modifies values for display in column view.
3444 For example, it can be used to cut out a certain part from a time stamp.
3445 The function must take 2 arguments:
3447 column-title The title of the column (*not* the property name)
3448 value The value that should be modified.
3450 The function should return the value that should be displayed,
3451 or nil if the normal value should be used."
3452 :group 'org-properties
3453 :type 'function)
3455 (defcustom org-effort-property "Effort"
3456 "The property that is being used to keep track of effort estimates.
3457 Effort estimates given in this property need to have the format H:MM."
3458 :group 'org-properties
3459 :group 'org-progress
3460 :type '(string :tag "Property"))
3462 (defconst org-global-properties-fixed
3463 '(("VISIBILITY_ALL" . "folded children content all")
3464 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3465 "List of property/value pairs that can be inherited by any entry.
3467 These are fixed values, for the preset properties. The user variable
3468 that can be used to add to this list is `org-global-properties'.
3470 The entries in this list are cons cells where the car is a property
3471 name and cdr is a string with the value. If the value represents
3472 multiple items like an \"_ALL\" property, separate the items by
3473 spaces.")
3475 (defcustom org-global-properties nil
3476 "List of property/value pairs that can be inherited by any entry.
3478 This list will be combined with the constant `org-global-properties-fixed'.
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.
3483 You can set buffer-local values for the same purpose in the variable
3484 `org-file-properties' this by adding lines like
3486 #+PROPERTY: NAME VALUE"
3487 :group 'org-properties
3488 :type '(repeat
3489 (cons (string :tag "Property")
3490 (string :tag "Value"))))
3492 (defvar org-file-properties nil
3493 "List of property/value pairs that can be inherited by any entry.
3494 Valid for the current buffer.
3495 This variable is populated from #+PROPERTY lines.")
3496 (make-variable-buffer-local 'org-file-properties)
3498 (defgroup org-agenda nil
3499 "Options concerning agenda views in Org-mode."
3500 :tag "Org Agenda"
3501 :group 'org)
3503 (defvar org-category nil
3504 "Variable used by org files to set a category for agenda display.
3505 Such files should use a file variable to set it, for example
3507 # -*- mode: org; org-category: \"ELisp\"
3509 or contain a special line
3511 #+CATEGORY: ELisp
3513 If the file does not specify a category, then file's base name
3514 is used instead.")
3515 (make-variable-buffer-local 'org-category)
3516 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3518 (defcustom org-agenda-files nil
3519 "The files to be used for agenda display.
3520 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3521 \\[org-remove-file]. You can also use customize to edit the list.
3523 If an entry is a directory, all files in that directory that are matched by
3524 `org-agenda-file-regexp' will be part of the file list.
3526 If the value of the variable is not a list but a single file name, then
3527 the list of agenda files is actually stored and maintained in that file, one
3528 agenda file per line. In this file paths can be given relative to
3529 `org-directory'. Tilde expansion and environment variable substitution
3530 are also made."
3531 :group 'org-agenda
3532 :type '(choice
3533 (repeat :tag "List of files and directories" file)
3534 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3536 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3537 "Regular expression to match files for `org-agenda-files'.
3538 If any element in the list in that variable contains a directory instead
3539 of a normal file, all files in that directory that are matched by this
3540 regular expression will be included."
3541 :group 'org-agenda
3542 :type 'regexp)
3544 (defcustom org-agenda-text-search-extra-files nil
3545 "List of extra files to be searched by text search commands.
3546 These files will be search in addition to the agenda files by the
3547 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3548 Note that these files will only be searched for text search commands,
3549 not for the other agenda views like todo lists, tag searches or the weekly
3550 agenda. This variable is intended to list notes and possibly archive files
3551 that should also be searched by these two commands.
3552 In fact, if the first element in the list is the symbol `agenda-archives',
3553 than all archive files of all agenda files will be added to the search
3554 scope."
3555 :group 'org-agenda
3556 :type '(set :greedy t
3557 (const :tag "Agenda Archives" agenda-archives)
3558 (repeat :inline t (file))))
3560 (org-defvaralias 'org-agenda-multi-occur-extra-files
3561 'org-agenda-text-search-extra-files)
3563 (defcustom org-agenda-skip-unavailable-files nil
3564 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3565 A nil value means to remove them, after a query, from the list."
3566 :group 'org-agenda
3567 :type 'boolean)
3569 (defcustom org-calendar-to-agenda-key [?c]
3570 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3571 The command `org-calendar-goto-agenda' will be bound to this key. The
3572 default is the character `c' because then `c' can be used to switch back and
3573 forth between agenda and calendar."
3574 :group 'org-agenda
3575 :type 'sexp)
3577 (defcustom org-calendar-insert-diary-entry-key [?i]
3578 "The key to be installed in `calendar-mode-map' for adding diary entries.
3579 This option is irrelevant until `org-agenda-diary-file' has been configured
3580 to point to an Org-mode file. When that is the case, the command
3581 `org-agenda-diary-entry' will be bound to the key given here, by default
3582 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3583 if you want to continue doing this, you need to change this to a different
3584 key."
3585 :group 'org-agenda
3586 :type 'sexp)
3588 (defcustom org-agenda-diary-file 'diary-file
3589 "File to which to add new entries with the `i' key in agenda and calendar.
3590 When this is the symbol `diary-file', the functionality in the Emacs
3591 calendar will be used to add entries to the `diary-file'. But when this
3592 points to a file, `org-agenda-diary-entry' will be used instead."
3593 :group 'org-agenda
3594 :type '(choice
3595 (const :tag "The standard Emacs diary file" diary-file)
3596 (file :tag "Special Org file diary entries")))
3598 (eval-after-load "calendar"
3599 '(progn
3600 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3601 'org-calendar-goto-agenda)
3602 (add-hook 'calendar-mode-hook
3603 (lambda ()
3604 (unless (eq org-agenda-diary-file 'diary-file)
3605 (define-key calendar-mode-map
3606 org-calendar-insert-diary-entry-key
3607 'org-agenda-diary-entry))))))
3609 (defgroup org-latex nil
3610 "Options for embedding LaTeX code into Org-mode."
3611 :tag "Org LaTeX"
3612 :group 'org)
3614 (defcustom org-format-latex-options
3615 '(:foreground default :background default :scale 1.0
3616 :html-foreground "Black" :html-background "Transparent"
3617 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3618 "Options for creating images from LaTeX fragments.
3619 This is a property list with the following properties:
3620 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3621 `default' means use the foreground of the default face.
3622 `auto' means use the foreground from the text face.
3623 :background the background color, or \"Transparent\".
3624 `default' means use the background of the default face.
3625 `auto' means use the background from the text face.
3626 :scale a scaling factor for the size of the images, to get more pixels
3627 :html-foreground, :html-background, :html-scale
3628 the same numbers for HTML export.
3629 :matchers a list indicating which matchers should be used to
3630 find LaTeX fragments. Valid members of this list are:
3631 \"begin\" find environments
3632 \"$1\" find single characters surrounded by $.$
3633 \"$\" find math expressions surrounded by $...$
3634 \"$$\" find math expressions surrounded by $$....$$
3635 \"\\(\" find math expressions surrounded by \\(...\\)
3636 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3637 :group 'org-latex
3638 :type 'plist)
3640 (defcustom org-format-latex-signal-error t
3641 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3642 When nil, just push out a message."
3643 :group 'org-latex
3644 :version "24.1"
3645 :type 'boolean)
3647 (defcustom org-latex-to-mathml-jar-file nil
3648 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3649 Use this to specify additional executable file say a jar file.
3651 When using MathToWeb as the converter, specify the full-path to
3652 your mathtoweb.jar file."
3653 :group 'org-latex
3654 :version "24.1"
3655 :type '(choice
3656 (const :tag "None" nil)
3657 (file :tag "JAR file" :must-match t)))
3659 (defcustom org-latex-to-mathml-convert-command nil
3660 "Command to convert LaTeX fragments to MathML.
3661 Replace format-specifiers in the command as noted below and use
3662 `shell-command' to convert LaTeX to MathML.
3663 %j: Executable file in fully expanded form as specified by
3664 `org-latex-to-mathml-jar-file'.
3665 %I: Input LaTeX file in fully expanded form
3666 %o: Output MathML file
3667 This command is used by `org-create-math-formula'.
3669 When using MathToWeb as the converter, set this to
3670 \"java -jar %j -unicode -force -df %o %I\"."
3671 :group 'org-latex
3672 :version "24.1"
3673 :type '(choice
3674 (const :tag "None" nil)
3675 (string :tag "\nShell command")))
3677 (defcustom org-latex-create-formula-image-program 'dvipng
3678 "Program to convert LaTeX fragments with.
3680 dvipng Process the LaTeX fragments to dvi file, then convert
3681 dvi files to png files using dvipng.
3682 This will also include processing of non-math environments.
3683 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3684 to convert pdf files to png files"
3685 :group 'org-latex
3686 :version "24.1"
3687 :type '(choice
3688 (const :tag "dvipng" dvipng)
3689 (const :tag "imagemagick" imagemagick)))
3691 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3692 "Path to store latex preview images.
3693 A relative path here creates many directories relative to the
3694 processed org files paths. An absolute path puts all preview
3695 images at the same place."
3696 :group 'org-latex
3697 :version "24.3"
3698 :type 'string)
3700 (defun org-format-latex-mathml-available-p ()
3701 "Return t if `org-latex-to-mathml-convert-command' is usable."
3702 (save-match-data
3703 (when (and (boundp 'org-latex-to-mathml-convert-command)
3704 org-latex-to-mathml-convert-command)
3705 (let ((executable (car (split-string
3706 org-latex-to-mathml-convert-command))))
3707 (when (executable-find executable)
3708 (if (string-match
3709 "%j" org-latex-to-mathml-convert-command)
3710 (file-readable-p org-latex-to-mathml-jar-file)
3711 t))))))
3713 (defcustom org-format-latex-header "\\documentclass{article}
3714 \\usepackage[usenames]{color}
3715 \\usepackage{amsmath}
3716 \\usepackage[mathscr]{eucal}
3717 \\pagestyle{empty} % do not remove
3718 \[PACKAGES]
3719 \[DEFAULT-PACKAGES]
3720 % The settings below are copied from fullpage.sty
3721 \\setlength{\\textwidth}{\\paperwidth}
3722 \\addtolength{\\textwidth}{-3cm}
3723 \\setlength{\\oddsidemargin}{1.5cm}
3724 \\addtolength{\\oddsidemargin}{-2.54cm}
3725 \\setlength{\\evensidemargin}{\\oddsidemargin}
3726 \\setlength{\\textheight}{\\paperheight}
3727 \\addtolength{\\textheight}{-\\headheight}
3728 \\addtolength{\\textheight}{-\\headsep}
3729 \\addtolength{\\textheight}{-\\footskip}
3730 \\addtolength{\\textheight}{-3cm}
3731 \\setlength{\\topmargin}{1.5cm}
3732 \\addtolength{\\topmargin}{-2.54cm}"
3733 "The document header used for processing LaTeX fragments.
3734 It is imperative that this header make sure that no page number
3735 appears on the page. The package defined in the variables
3736 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3737 will either replace the placeholder \"[PACKAGES]\" in this
3738 header, or they will be appended."
3739 :group 'org-latex
3740 :type 'string)
3742 (defun org-set-packages-alist (var val)
3743 "Set the packages alist and make sure it has 3 elements per entry."
3744 (set var (mapcar (lambda (x)
3745 (if (and (consp x) (= (length x) 2))
3746 (list (car x) (nth 1 x) t)
3748 val)))
3750 (defun org-get-packages-alist (var)
3751 "Get the packages alist and make sure it has 3 elements per entry."
3752 (mapcar (lambda (x)
3753 (if (and (consp x) (= (length x) 2))
3754 (list (car x) (nth 1 x) t)
3756 (default-value var)))
3758 (defcustom org-latex-default-packages-alist
3759 '(("AUTO" "inputenc" t)
3760 ("T1" "fontenc" t)
3761 ("" "fixltx2e" nil)
3762 ("" "graphicx" t)
3763 ("" "longtable" nil)
3764 ("" "float" nil)
3765 ("" "wrapfig" nil)
3766 ("" "soul" t)
3767 ("" "textcomp" t)
3768 ("" "marvosym" t)
3769 ("" "wasysym" t)
3770 ("" "latexsym" t)
3771 ("" "amssymb" t)
3772 ("" "hyperref" nil)
3773 "\\tolerance=1000")
3774 "Alist of default packages to be inserted in the header.
3776 Change this only if one of the packages here causes an
3777 incompatibility with another package you are using.
3779 The packages in this list are needed by one part or another of
3780 Org mode to function properly:
3782 - inputenc, fontenc: for basic font and character selection
3783 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3784 symbols used for interpreting the entities in `org-entities'.
3785 You can skip some of these packages if you don't use any of the
3786 symbols in it.
3787 - graphicx: for including images
3788 - float, wrapfig: for figure placement
3789 - longtable: for long tables
3790 - hyperref: for cross references
3792 Therefore you should not modify this variable unless you know
3793 what you are doing. The one reason to change it anyway is that
3794 you might be loading some other package that conflicts with one
3795 of the default packages. Each cell is of the format
3796 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3797 the package also needs to be included when compiling LaTeX
3798 snippets into images for inclusion into non-LaTeX output."
3799 :group 'org-latex
3800 :group 'org-export-latex
3801 :set 'org-set-packages-alist
3802 :get 'org-get-packages-alist
3803 :version "24.1"
3804 :type '(repeat
3805 (choice
3806 (list :tag "options/package pair"
3807 (string :tag "options")
3808 (string :tag "package")
3809 (boolean :tag "Snippet"))
3810 (string :tag "A line of LaTeX"))))
3812 (defcustom org-latex-packages-alist nil
3813 "Alist of packages to be inserted in every LaTeX header.
3815 These will be inserted after `org-latex-default-packages-alist'.
3816 Each cell is of the format:
3818 \(\"options\" \"package\" snippet-flag)
3820 SNIPPET-FLAG, when t, indicates that this package is also needed
3821 when turning LaTeX snippets into images for inclusion into
3822 non-LaTeX output.
3824 Make sure that you only list packages here which:
3826 - you want in every file
3827 - do not conflict with the setup in `org-format-latex-header'.
3828 - do not conflict with the default packages in
3829 `org-latex-default-packages-alist'."
3830 :group 'org-latex
3831 :group 'org-export-latex
3832 :set 'org-set-packages-alist
3833 :get 'org-get-packages-alist
3834 :type '(repeat
3835 (choice
3836 (list :tag "options/package pair"
3837 (string :tag "options")
3838 (string :tag "package")
3839 (boolean :tag "Snippet"))
3840 (string :tag "A line of LaTeX"))))
3842 (defgroup org-appearance nil
3843 "Settings for Org-mode appearance."
3844 :tag "Org Appearance"
3845 :group 'org)
3847 (defcustom org-level-color-stars-only nil
3848 "Non-nil means fontify only the stars in each headline.
3849 When nil, the entire headline is fontified.
3850 Changing it requires restart of `font-lock-mode' to become effective
3851 also in regions already fontified."
3852 :group 'org-appearance
3853 :type 'boolean)
3855 (defcustom org-hide-leading-stars nil
3856 "Non-nil means hide the first N-1 stars in a headline.
3857 This works by using the face `org-hide' for these stars. This
3858 face is white for a light background, and black for a dark
3859 background. You may have to customize the face `org-hide' to
3860 make this work.
3861 Changing it requires restart of `font-lock-mode' to become effective
3862 also in regions already fontified.
3863 You may also set this on a per-file basis by adding one of the following
3864 lines to the buffer:
3866 #+STARTUP: hidestars
3867 #+STARTUP: showstars"
3868 :group 'org-appearance
3869 :type 'boolean)
3871 (defcustom org-hidden-keywords nil
3872 "List of symbols corresponding to keywords to be hidden the org buffer.
3873 For example, a value '(title) for this list will make the document's title
3874 appear in the buffer without the initial #+TITLE: keyword."
3875 :group 'org-appearance
3876 :version "24.1"
3877 :type '(set (const :tag "#+AUTHOR" author)
3878 (const :tag "#+DATE" date)
3879 (const :tag "#+EMAIL" email)
3880 (const :tag "#+TITLE" title)))
3882 (defcustom org-custom-properties nil
3883 "List of properties (as strings) with a special meaning.
3884 The default use of these custom properties is to let the user
3885 hide them with `org-toggle-custom-properties-visibility'."
3886 :group 'org-properties
3887 :group 'org-appearance
3888 :version "24.3"
3889 :type '(repeat (string :tag "Property Name")))
3891 (defcustom org-fontify-done-headline nil
3892 "Non-nil means change the face of a headline if it is marked DONE.
3893 Normally, only the TODO/DONE keyword indicates the state of a headline.
3894 When this is non-nil, the headline after the keyword is set to the
3895 `org-headline-done' as an additional indication."
3896 :group 'org-appearance
3897 :type 'boolean)
3899 (defcustom org-fontify-emphasized-text t
3900 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3901 Changing this variable requires a restart of Emacs to take effect."
3902 :group 'org-appearance
3903 :type 'boolean)
3905 (defcustom org-fontify-whole-heading-line nil
3906 "Non-nil means fontify the whole line for headings.
3907 This is useful when setting a background color for the
3908 org-level-* faces."
3909 :group 'org-appearance
3910 :type 'boolean)
3912 (defcustom org-highlight-latex-and-related nil
3913 "Non-nil means highlight LaTeX related syntax in the buffer.
3914 When non nil, the value should be a list containing any of the
3915 following symbols:
3916 `latex' Highlight LaTeX snippets and environments.
3917 `script' Highlight subscript and superscript.
3918 `entities' Highlight entities."
3919 :group 'org-appearance
3920 :version "24.4"
3921 :package-version '(Org . "8.0")
3922 :type '(choice
3923 (const :tag "No highlighting" nil)
3924 (set :greedy t :tag "Highlight"
3925 (const :tag "LaTeX snippets and environments" latex)
3926 (const :tag "Subscript and superscript" script)
3927 (const :tag "Entities" entities))))
3929 (defcustom org-hide-emphasis-markers nil
3930 "Non-nil mean font-lock should hide the emphasis marker characters."
3931 :group 'org-appearance
3932 :type 'boolean)
3934 (defcustom org-pretty-entities nil
3935 "Non-nil means show entities as UTF8 characters.
3936 When nil, the \\name form remains in the buffer."
3937 :group 'org-appearance
3938 :version "24.1"
3939 :type 'boolean)
3941 (defcustom org-pretty-entities-include-sub-superscripts t
3942 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3943 :group 'org-appearance
3944 :version "24.1"
3945 :type 'boolean)
3947 (defvar org-emph-re nil
3948 "Regular expression for matching emphasis.
3949 After a match, the match groups contain these elements:
3950 0 The match of the full regular expression, including the characters
3951 before and after the proper match
3952 1 The character before the proper match, or empty at beginning of line
3953 2 The proper match, including the leading and trailing markers
3954 3 The leading marker like * or /, indicating the type of highlighting
3955 4 The text between the emphasis markers, not including the markers
3956 5 The character after the match, empty at the end of a line")
3957 (defvar org-verbatim-re nil
3958 "Regular expression for matching verbatim text.")
3959 (defvar org-emphasis-regexp-components) ; defined just below
3960 (defvar org-emphasis-alist) ; defined just below
3961 (defun org-set-emph-re (var val)
3962 "Set variable and compute the emphasis regular expression."
3963 (set var val)
3964 (when (and (boundp 'org-emphasis-alist)
3965 (boundp 'org-emphasis-regexp-components)
3966 org-emphasis-alist org-emphasis-regexp-components)
3967 (let* ((e org-emphasis-regexp-components)
3968 (pre (car e))
3969 (post (nth 1 e))
3970 (border (nth 2 e))
3971 (body (nth 3 e))
3972 (nl (nth 4 e))
3973 (body1 (concat body "*?"))
3974 (markers (mapconcat 'car org-emphasis-alist ""))
3975 (vmarkers (mapconcat
3976 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3977 org-emphasis-alist "")))
3978 ;; make sure special characters appear at the right position in the class
3979 (if (string-match "\\^" markers)
3980 (setq markers (concat (replace-match "" t t markers) "^")))
3981 (if (string-match "-" markers)
3982 (setq markers (concat (replace-match "" t t markers) "-")))
3983 (if (string-match "\\^" vmarkers)
3984 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3985 (if (string-match "-" vmarkers)
3986 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3987 (if (> nl 0)
3988 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3989 (int-to-string nl) "\\}")))
3990 ;; Make the regexp
3991 (setq org-emph-re
3992 (concat "\\([" pre "]\\|^\\)"
3993 "\\("
3994 "\\([" markers "]\\)"
3995 "\\("
3996 "[^" border "]\\|"
3997 "[^" border "]"
3998 body1
3999 "[^" border "]"
4000 "\\)"
4001 "\\3\\)"
4002 "\\([" post "]\\|$\\)"))
4003 (setq org-verbatim-re
4004 (concat "\\([" pre "]\\|^\\)"
4005 "\\("
4006 "\\([" vmarkers "]\\)"
4007 "\\("
4008 "[^" border "]\\|"
4009 "[^" border "]"
4010 body1
4011 "[^" border "]"
4012 "\\)"
4013 "\\3\\)"
4014 "\\([" post "]\\|$\\)")))))
4016 (defcustom org-emphasis-regexp-components
4017 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4018 "Components used to build the regular expression for emphasis.
4019 This is a list with five entries. Terminology: In an emphasis string
4020 like \" *strong word* \", we call the initial space PREMATCH, the final
4021 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4022 and \"trong wor\" is the body. The different components in this variable
4023 specify what is allowed/forbidden in each part:
4025 pre Chars allowed as prematch. Beginning of line will be allowed too.
4026 post Chars allowed as postmatch. End of line will be allowed too.
4027 border The chars *forbidden* as border characters.
4028 body-regexp A regexp like \".\" to match a body character. Don't use
4029 non-shy groups here, and don't allow newline here.
4030 newline The maximum number of newlines allowed in an emphasis exp.
4032 Use customize to modify this, or restart Emacs after changing it."
4033 :group 'org-appearance
4034 :set 'org-set-emph-re
4035 :type '(list
4036 (sexp :tag "Allowed chars in pre ")
4037 (sexp :tag "Allowed chars in post ")
4038 (sexp :tag "Forbidden chars in border ")
4039 (sexp :tag "Regexp for body ")
4040 (integer :tag "number of newlines allowed")
4041 (option (boolean :tag "Please ignore this button"))))
4043 (defcustom org-emphasis-alist
4044 `(("*" bold "<b>" "</b>")
4045 ("/" italic "<i>" "</i>")
4046 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4047 ("=" org-code "<code>" "</code>" verbatim)
4048 ("~" org-verbatim "<code>" "</code>" verbatim)
4049 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4050 "<del>" "</del>")
4052 "Special syntax for emphasized text.
4053 Text starting and ending with a special character will be emphasized, for
4054 example *bold*, _underlined_ and /italic/. This variable sets the marker
4055 characters, the face to be used by font-lock for highlighting in Org-mode
4056 Emacs buffers, and the HTML tags to be used for this.
4057 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4058 Use customize to modify this, or restart Emacs after changing it."
4059 :group 'org-appearance
4060 :set 'org-set-emph-re
4061 :type '(repeat
4062 (list
4063 (string :tag "Marker character")
4064 (choice
4065 (face :tag "Font-lock-face")
4066 (plist :tag "Face property list"))
4067 (string :tag "HTML start tag")
4068 (string :tag "HTML end tag")
4069 (option (const verbatim)))))
4071 (defvar org-protecting-blocks
4072 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4073 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4074 This is needed for font-lock setup.")
4076 ;;; Miscellaneous options
4078 (defgroup org-completion nil
4079 "Completion in Org-mode."
4080 :tag "Org Completion"
4081 :group 'org)
4083 (defcustom org-completion-use-ido nil
4084 "Non-nil means use ido completion wherever possible.
4085 Note that `ido-mode' must be active for this variable to be relevant.
4086 If you decide to turn this variable on, you might well want to turn off
4087 `org-outline-path-complete-in-steps'.
4088 See also `org-completion-use-iswitchb'."
4089 :group 'org-completion
4090 :type 'boolean)
4092 (defcustom org-completion-use-iswitchb nil
4093 "Non-nil means use iswitchb completion wherever possible.
4094 Note that `iswitchb-mode' must be active for this variable to be relevant.
4095 If you decide to turn this variable on, you might well want to turn off
4096 `org-outline-path-complete-in-steps'.
4097 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4098 :group 'org-completion
4099 :type 'boolean)
4101 (defcustom org-completion-fallback-command 'hippie-expand
4102 "The expansion command called by \\[pcomplete] in normal context.
4103 Normal means, no org-mode-specific context."
4104 :group 'org-completion
4105 :type 'function)
4107 ;;; Functions and variables from their packages
4108 ;; Declared here to avoid compiler warnings
4110 ;; XEmacs only
4111 (defvar outline-mode-menu-heading)
4112 (defvar outline-mode-menu-show)
4113 (defvar outline-mode-menu-hide)
4114 (defvar zmacs-regions) ; XEmacs regions
4116 ;; Emacs only
4117 (defvar mark-active)
4119 ;; Various packages
4120 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4121 (declare-function calendar-forward-day "cal-move" (arg))
4122 (declare-function calendar-goto-date "cal-move" (date))
4123 (declare-function calendar-goto-today "cal-move" ())
4124 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4125 (defvar calc-embedded-close-formula)
4126 (defvar calc-embedded-open-formula)
4127 (declare-function cdlatex-tab "ext:cdlatex" ())
4128 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4129 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4130 (defvar font-lock-unfontify-region-function)
4131 (declare-function iswitchb-read-buffer "iswitchb"
4132 (prompt &optional default require-match start matches-set))
4133 (defvar iswitchb-temp-buflist)
4134 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4135 (defvar org-agenda-tags-todo-honor-ignore-options)
4136 (declare-function org-agenda-skip "org-agenda" ())
4137 (declare-function
4138 org-agenda-format-item "org-agenda"
4139 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4140 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4141 (declare-function org-agenda-change-all-lines "org-agenda"
4142 (newhead hdmarker &optional fixface just-this))
4143 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4144 (declare-function org-agenda-maybe-redo "org-agenda" ())
4145 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4146 (beg end))
4147 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4148 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4149 "org-agenda" (&optional end))
4150 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4151 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4152 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4153 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4154 (declare-function org-indent-mode "org-indent" (&optional arg))
4155 (declare-function parse-time-string "parse-time" (string))
4156 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4157 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4158 (defvar remember-data-file)
4159 (defvar texmathp-why)
4160 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4161 (declare-function table--at-cell-p "table" (position &optional object at-column))
4163 (defvar org-latex-regexps)
4165 ;;; Autoload and prepare some org modules
4167 ;; Some table stuff that needs to be defined here, because it is used
4168 ;; by the functions setting up org-mode or checking for table context.
4170 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4171 "Detect an org-type or table-type table.")
4172 (defconst org-table-line-regexp "^[ \t]*|"
4173 "Detect an org-type table line.")
4174 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4175 "Detect an org-type table line.")
4176 (defconst org-table-hline-regexp "^[ \t]*|-"
4177 "Detect an org-type table hline.")
4178 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4179 "Detect a table-type table hline.")
4180 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4181 "Detect the first line outside a table when searching from within it.
4182 This works for both table types.")
4184 ;; Autoload the functions in org-table.el that are needed by functions here.
4186 (eval-and-compile
4187 (org-autoload "org-table"
4188 '(org-table-begin org-table-blank-field org-table-end)))
4190 ;;;###autoload
4191 (defun turn-on-orgtbl ()
4192 "Unconditionally turn on `orgtbl-mode'."
4193 (require 'org-table)
4194 (orgtbl-mode 1))
4196 (defun org-at-table-p (&optional table-type)
4197 "Return t if the cursor is inside an org-type table.
4198 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4199 (if org-enable-table-editor
4200 (save-excursion
4201 (beginning-of-line 1)
4202 (looking-at (if table-type org-table-any-line-regexp
4203 org-table-line-regexp)))
4204 nil))
4205 (defsubst org-table-p () (org-at-table-p))
4207 (defun org-at-table.el-p ()
4208 "Return t if and only if we are at a table.el table."
4209 (and (org-at-table-p 'any)
4210 (save-excursion
4211 (goto-char (org-table-begin 'any))
4212 (looking-at org-table1-hline-regexp))))
4214 (defun org-table-recognize-table.el ()
4215 "If there is a table.el table nearby, recognize it and move into it."
4216 (if org-table-tab-recognizes-table.el
4217 (if (org-at-table.el-p)
4218 (progn
4219 (beginning-of-line 1)
4220 (if (looking-at org-table-dataline-regexp)
4222 (if (looking-at org-table1-hline-regexp)
4223 (progn
4224 (beginning-of-line 2)
4225 (if (looking-at org-table-any-border-regexp)
4226 (beginning-of-line -1)))))
4227 (if (re-search-forward "|" (org-table-end t) t)
4228 (progn
4229 (require 'table)
4230 (if (table--at-cell-p (point))
4232 (message "recognizing table.el table...")
4233 (table-recognize-table)
4234 (message "recognizing table.el table...done")))
4235 (error "This should not happen"))
4237 nil)
4238 nil))
4240 (defun org-at-table-hline-p ()
4241 "Return t if the cursor is inside a hline in a table."
4242 (if org-enable-table-editor
4243 (save-excursion
4244 (beginning-of-line 1)
4245 (looking-at org-table-hline-regexp))
4246 nil))
4248 (defvar org-table-clean-did-remove-column nil)
4249 (defun org-table-map-tables (function &optional quietly)
4250 "Apply FUNCTION to the start of all tables in the buffer."
4251 (save-excursion
4252 (save-restriction
4253 (widen)
4254 (goto-char (point-min))
4255 (while (re-search-forward org-table-any-line-regexp nil t)
4256 (unless quietly
4257 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4258 (beginning-of-line 1)
4259 (when (and (looking-at org-table-line-regexp)
4260 ;; Exclude tables in src/example/verbatim/clocktable blocks
4261 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4262 (save-excursion (funcall function))
4263 (or (looking-at org-table-line-regexp)
4264 (forward-char 1)))
4265 (re-search-forward org-table-any-border-regexp nil 1))))
4266 (unless quietly (message "Mapping tables: done")))
4268 ;; Declare and autoload functions from ox.el and al.
4270 (declare-function org-export-get-environment "ox"
4271 (&optional backend subtreep ext-plist))
4272 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4274 ;; Declare and autoload functions from org-agenda.el
4276 (eval-and-compile
4277 (org-autoload "org-agenda"
4278 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4280 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4281 (declare-function org-clock-update-mode-line "org-clock" ())
4282 (declare-function org-resolve-clocks "org-clock"
4283 (&optional also-non-dangling-p prompt last-valid))
4284 (defvar org-clock-start-time)
4285 (defvar org-clock-marker (make-marker)
4286 "Marker recording the last clock-in.")
4287 (defvar org-clock-hd-marker (make-marker)
4288 "Marker recording the last clock-in, but the headline position.")
4289 (defvar org-clock-heading ""
4290 "The heading of the current clock entry.")
4291 (defun org-clock-is-active ()
4292 "Return non-nil if clock is currently running.
4293 The return value is actually the clock marker."
4294 (marker-buffer org-clock-marker))
4296 (eval-and-compile
4297 (org-autoload "org-clock" '(org-clock-remove-overlays
4298 org-clock-update-time-maybe
4299 org-clocktable-shift)))
4301 (defun org-check-running-clock ()
4302 "Check if the current buffer contains the running clock.
4303 If yes, offer to stop it and to save the buffer with the changes."
4304 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4305 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4306 (buffer-name))))
4307 (org-clock-out)
4308 (when (y-or-n-p "Save changed buffer?")
4309 (save-buffer))))
4311 (defun org-clocktable-try-shift (dir n)
4312 "Check if this line starts a clock table, if yes, shift the time block."
4313 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4314 (org-clocktable-shift dir n)))
4316 ;;;###autoload
4317 (defun org-clock-persistence-insinuate ()
4318 "Set up hooks for clock persistence."
4319 (require 'org-clock)
4320 (add-hook 'org-mode-hook 'org-clock-load)
4321 (add-hook 'kill-emacs-hook 'org-clock-save))
4323 ;; Define the variable already here, to make sure we have it.
4324 (defvar org-indent-mode nil
4325 "Non-nil if Org-Indent mode is enabled.
4326 Use the command `org-indent-mode' to change this variable.")
4328 ;; Autoload archiving code
4329 ;; The stuff that is needed for cycling and tags has to be defined here.
4331 (defgroup org-archive nil
4332 "Options concerning archiving in Org-mode."
4333 :tag "Org Archive"
4334 :group 'org-structure)
4336 (defcustom org-archive-location "%s_archive::"
4337 "The location where subtrees should be archived.
4339 The value of this variable is a string, consisting of two parts,
4340 separated by a double-colon. The first part is a filename and
4341 the second part is a headline.
4343 When the filename is omitted, archiving happens in the same file.
4344 %s in the filename will be replaced by the current file
4345 name (without the directory part). Archiving to a different file
4346 is useful to keep archived entries from contributing to the
4347 Org-mode Agenda.
4349 The archived entries will be filed as subtrees of the specified
4350 headline. When the headline is omitted, the subtrees are simply
4351 filed away at the end of the file, as top-level entries. Also in
4352 the heading you can use %s to represent the file name, this can be
4353 useful when using the same archive for a number of different files.
4355 Here are a few examples:
4356 \"%s_archive::\"
4357 If the current file is Projects.org, archive in file
4358 Projects.org_archive, as top-level trees. This is the default.
4360 \"::* Archived Tasks\"
4361 Archive in the current file, under the top-level headline
4362 \"* Archived Tasks\".
4364 \"~/org/archive.org::\"
4365 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4367 \"~/org/archive.org::* From %s\"
4368 Archive in file ~/org/archive.org (absolute path), under headlines
4369 \"From FILENAME\" where file name is the current file name.
4371 \"~/org/datetree.org::datetree/* Finished Tasks\"
4372 The \"datetree/\" string is special, signifying to archive
4373 items to the datetree. Items are placed in either the CLOSED
4374 date of the item, or the current date if there is no CLOSED date.
4375 The heading will be a subentry to the current date. There doesn't
4376 need to be a heading, but there always needs to be a slash after
4377 datetree. For example, to store archived items directly in the
4378 datetree, use \"~/org/datetree.org::datetree/\".
4380 \"basement::** Finished Tasks\"
4381 Archive in file ./basement (relative path), as level 3 trees
4382 below the level 2 heading \"** Finished Tasks\".
4384 You may set this option on a per-file basis by adding to the buffer a
4385 line like
4387 #+ARCHIVE: basement::** Finished Tasks
4389 You may also define it locally for a subtree by setting an ARCHIVE property
4390 in the entry. If such a property is found in an entry, or anywhere up
4391 the hierarchy, it will be used."
4392 :group 'org-archive
4393 :type 'string)
4395 (defcustom org-archive-tag "ARCHIVE"
4396 "The tag that marks a subtree as archived.
4397 An archived subtree does not open during visibility cycling, and does
4398 not contribute to the agenda listings.
4399 After changing this, font-lock must be restarted in the relevant buffers to
4400 get the proper fontification."
4401 :group 'org-archive
4402 :group 'org-keywords
4403 :type 'string)
4405 (defcustom org-agenda-skip-archived-trees t
4406 "Non-nil means the agenda will skip any items located in archived trees.
4407 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4408 variable is no longer recommended, you should leave it at the value t.
4409 Instead, use the key `v' to cycle the archives-mode in the agenda."
4410 :group 'org-archive
4411 :group 'org-agenda-skip
4412 :type 'boolean)
4414 (defcustom org-columns-skip-archived-trees t
4415 "Non-nil means ignore archived trees when creating column view."
4416 :group 'org-archive
4417 :group 'org-properties
4418 :type 'boolean)
4420 (defcustom org-cycle-open-archived-trees nil
4421 "Non-nil means `org-cycle' will open archived trees.
4422 An archived tree is a tree marked with the tag ARCHIVE.
4423 When nil, archived trees will stay folded. You can still open them with
4424 normal outline commands like `show-all', but not with the cycling commands."
4425 :group 'org-archive
4426 :group 'org-cycle
4427 :type 'boolean)
4429 (defcustom org-sparse-tree-open-archived-trees nil
4430 "Non-nil means sparse tree construction shows matches in archived trees.
4431 When nil, matches in these trees are highlighted, but the trees are kept in
4432 collapsed state."
4433 :group 'org-archive
4434 :group 'org-sparse-trees
4435 :type 'boolean)
4437 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4438 "The default date type when building a sparse tree.
4439 When this is nil, a date is a scheduled or a deadline timestamp.
4440 Otherwise, these types are allowed:
4442 all: all timestamps
4443 active: only active timestamps (<...>)
4444 inactive: only inactive timestamps (<...)
4445 scheduled: only scheduled timestamps
4446 deadline: only deadline timestamps"
4447 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4448 (const :tag "All timestamps" all)
4449 (const :tag "Only active timestamps" active)
4450 (const :tag "Only inactive timestamps" inactive)
4451 (const :tag "Only scheduled timestamps" scheduled)
4452 (const :tag "Only deadline timestamps" deadline))
4453 :version "24.3"
4454 :group 'org-sparse-trees)
4456 (defun org-cycle-hide-archived-subtrees (state)
4457 "Re-hide all archived subtrees after a visibility state change."
4458 (when (and (not org-cycle-open-archived-trees)
4459 (not (memq state '(overview folded))))
4460 (save-excursion
4461 (let* ((globalp (memq state '(contents all)))
4462 (beg (if globalp (point-min) (point)))
4463 (end (if globalp (point-max) (org-end-of-subtree t))))
4464 (org-hide-archived-subtrees beg end)
4465 (goto-char beg)
4466 (if (looking-at (concat ".*:" org-archive-tag ":"))
4467 (message "%s" (substitute-command-keys
4468 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4470 (defun org-force-cycle-archived ()
4471 "Cycle subtree even if it is archived."
4472 (interactive)
4473 (setq this-command 'org-cycle)
4474 (let ((org-cycle-open-archived-trees t))
4475 (call-interactively 'org-cycle)))
4477 (defun org-hide-archived-subtrees (beg end)
4478 "Re-hide all archived subtrees after a visibility state change."
4479 (save-excursion
4480 (let* ((re (concat ":" org-archive-tag ":")))
4481 (goto-char beg)
4482 (while (re-search-forward re end t)
4483 (when (org-at-heading-p)
4484 (org-flag-subtree t)
4485 (org-end-of-subtree t))))))
4487 (declare-function outline-end-of-heading "outline" ())
4488 (declare-function outline-flag-region "outline" (from to flag))
4489 (defun org-flag-subtree (flag)
4490 (save-excursion
4491 (org-back-to-heading t)
4492 (outline-end-of-heading)
4493 (outline-flag-region (point)
4494 (progn (org-end-of-subtree t) (point))
4495 flag)))
4497 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4499 (eval-and-compile
4500 (org-autoload "org-archive"
4501 '(org-add-archive-files)))
4503 ;; Autoload Column View Code
4505 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4506 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4507 (declare-function org-columns-compute "org-colview" (property))
4509 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4510 '(org-columns-number-to-string
4511 org-columns-get-format-and-top-level
4512 org-columns-compute
4513 org-columns-remove-overlays))
4515 ;; Autoload ID code
4517 (declare-function org-id-store-link "org-id")
4518 (declare-function org-id-locations-load "org-id")
4519 (declare-function org-id-locations-save "org-id")
4520 (defvar org-id-track-globally)
4521 (org-autoload "org-id"
4522 '(org-id-new
4523 org-id-copy
4524 org-id-get-with-outline-path-completion
4525 org-id-get-with-outline-drilling))
4527 ;;; Variables for pre-computed regular expressions, all buffer local
4529 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4530 "Matches first line of a hidden block.")
4531 (make-variable-buffer-local 'org-drawer-regexp)
4532 (defvar org-todo-regexp nil
4533 "Matches any of the TODO state keywords.")
4534 (make-variable-buffer-local 'org-todo-regexp)
4535 (defvar org-not-done-regexp nil
4536 "Matches any of the TODO state keywords except the last one.")
4537 (make-variable-buffer-local 'org-not-done-regexp)
4538 (defvar org-not-done-heading-regexp nil
4539 "Matches a TODO headline that is not done.")
4540 (make-variable-buffer-local 'org-not-done-regexp)
4541 (defvar org-todo-line-regexp nil
4542 "Matches a headline and puts TODO state into group 2 if present.")
4543 (make-variable-buffer-local 'org-todo-line-regexp)
4544 (defvar org-complex-heading-regexp nil
4545 "Matches a headline and puts everything into groups:
4546 group 1: the stars
4547 group 2: The todo keyword, maybe
4548 group 3: Priority cookie
4549 group 4: True headline
4550 group 5: Tags")
4551 (make-variable-buffer-local 'org-complex-heading-regexp)
4552 (defvar org-complex-heading-regexp-format nil
4553 "Printf format to make regexp to match an exact headline.
4554 This regexp will match the headline of any node which has the
4555 exact headline text that is put into the format, but may have any
4556 TODO state, priority and tags.")
4557 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4558 (defvar org-todo-line-tags-regexp nil
4559 "Matches a headline and puts TODO state into group 2 if present.
4560 Also put tags into group 4 if tags are present.")
4561 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4562 (defvar org-ds-keyword-length 12
4563 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4564 (make-variable-buffer-local 'org-ds-keyword-length)
4565 (defvar org-deadline-regexp nil
4566 "Matches the DEADLINE keyword.")
4567 (make-variable-buffer-local 'org-deadline-regexp)
4568 (defvar org-deadline-time-regexp nil
4569 "Matches the DEADLINE keyword together with a time stamp.")
4570 (make-variable-buffer-local 'org-deadline-time-regexp)
4571 (defvar org-deadline-time-hour-regexp nil
4572 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4573 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4574 (defvar org-deadline-line-regexp nil
4575 "Matches the DEADLINE keyword and the rest of the line.")
4576 (make-variable-buffer-local 'org-deadline-line-regexp)
4577 (defvar org-scheduled-regexp nil
4578 "Matches the SCHEDULED keyword.")
4579 (make-variable-buffer-local 'org-scheduled-regexp)
4580 (defvar org-scheduled-time-regexp nil
4581 "Matches the SCHEDULED keyword together with a time stamp.")
4582 (make-variable-buffer-local 'org-scheduled-time-regexp)
4583 (defvar org-scheduled-time-hour-regexp nil
4584 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4585 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4586 (defvar org-closed-time-regexp nil
4587 "Matches the CLOSED keyword together with a time stamp.")
4588 (make-variable-buffer-local 'org-closed-time-regexp)
4590 (defvar org-keyword-time-regexp nil
4591 "Matches any of the 4 keywords, together with the time stamp.")
4592 (make-variable-buffer-local 'org-keyword-time-regexp)
4593 (defvar org-keyword-time-not-clock-regexp nil
4594 "Matches any of the 3 keywords, together with the time stamp.")
4595 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4596 (defvar org-maybe-keyword-time-regexp nil
4597 "Matches a timestamp, possibly preceded by a keyword.")
4598 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4599 (defvar org-all-time-keywords nil
4600 "List of time keywords.")
4601 (make-variable-buffer-local 'org-all-time-keywords)
4603 (defconst org-plain-time-of-day-regexp
4604 (concat
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\(--?"
4608 "\\(\\<[012]?[0-9]"
4609 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4610 "\\)?")
4611 "Regular expression to match a plain time or time range.
4612 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4613 groups carry important information:
4614 0 the full match
4615 1 the first time, range or not
4616 8 the second time, if it is a range.")
4618 (defconst org-plain-time-extension-regexp
4619 (concat
4620 "\\(\\<[012]?[0-9]"
4621 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4622 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4623 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4624 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4625 groups carry important information:
4626 0 the full match
4627 7 hours of duration
4628 9 minutes of duration")
4630 (defconst org-stamp-time-of-day-regexp
4631 (concat
4632 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4633 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4634 "\\(--?"
4635 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4636 "Regular expression to match a timestamp time or time range.
4637 After a match, the following groups carry important information:
4638 0 the full match
4639 1 date plus weekday, for back referencing to make sure both times are on the same day
4640 2 the first time, range or not
4641 4 the second time, if it is a range.")
4643 (defconst org-startup-options
4644 '(("fold" org-startup-folded t)
4645 ("overview" org-startup-folded t)
4646 ("nofold" org-startup-folded nil)
4647 ("showall" org-startup-folded nil)
4648 ("showeverything" org-startup-folded showeverything)
4649 ("content" org-startup-folded content)
4650 ("indent" org-startup-indented t)
4651 ("noindent" org-startup-indented nil)
4652 ("hidestars" org-hide-leading-stars t)
4653 ("showstars" org-hide-leading-stars nil)
4654 ("odd" org-odd-levels-only t)
4655 ("oddeven" org-odd-levels-only nil)
4656 ("align" org-startup-align-all-tables t)
4657 ("noalign" org-startup-align-all-tables nil)
4658 ("inlineimages" org-startup-with-inline-images t)
4659 ("noinlineimages" org-startup-with-inline-images nil)
4660 ("latexpreview" org-startup-with-latex-preview t)
4661 ("nolatexpreview" org-startup-with-latex-preview nil)
4662 ("customtime" org-display-custom-times t)
4663 ("logdone" org-log-done time)
4664 ("lognotedone" org-log-done note)
4665 ("nologdone" org-log-done nil)
4666 ("lognoteclock-out" org-log-note-clock-out t)
4667 ("nolognoteclock-out" org-log-note-clock-out nil)
4668 ("logrepeat" org-log-repeat state)
4669 ("lognoterepeat" org-log-repeat note)
4670 ("logdrawer" org-log-into-drawer t)
4671 ("nologdrawer" org-log-into-drawer nil)
4672 ("logstatesreversed" org-log-states-order-reversed t)
4673 ("nologstatesreversed" org-log-states-order-reversed nil)
4674 ("nologrepeat" org-log-repeat nil)
4675 ("logreschedule" org-log-reschedule time)
4676 ("lognotereschedule" org-log-reschedule note)
4677 ("nologreschedule" org-log-reschedule nil)
4678 ("logredeadline" org-log-redeadline time)
4679 ("lognoteredeadline" org-log-redeadline note)
4680 ("nologredeadline" org-log-redeadline nil)
4681 ("logrefile" org-log-refile time)
4682 ("lognoterefile" org-log-refile note)
4683 ("nologrefile" org-log-refile nil)
4684 ("fninline" org-footnote-define-inline t)
4685 ("nofninline" org-footnote-define-inline nil)
4686 ("fnlocal" org-footnote-section nil)
4687 ("fnauto" org-footnote-auto-label t)
4688 ("fnprompt" org-footnote-auto-label nil)
4689 ("fnconfirm" org-footnote-auto-label confirm)
4690 ("fnplain" org-footnote-auto-label plain)
4691 ("fnadjust" org-footnote-auto-adjust t)
4692 ("nofnadjust" org-footnote-auto-adjust nil)
4693 ("constcgs" constants-unit-system cgs)
4694 ("constSI" constants-unit-system SI)
4695 ("noptag" org-tag-persistent-alist nil)
4696 ("hideblocks" org-hide-block-startup t)
4697 ("nohideblocks" org-hide-block-startup nil)
4698 ("beamer" org-startup-with-beamer-mode t)
4699 ("entitiespretty" org-pretty-entities t)
4700 ("entitiesplain" org-pretty-entities nil))
4701 "Variable associated with STARTUP options for org-mode.
4702 Each element is a list of three items: the startup options (as written
4703 in the #+STARTUP line), the corresponding variable, and the value to set
4704 this variable to if the option is found. An optional forth element PUSH
4705 means to push this value onto the list in the variable.")
4707 (defun org-update-property-plist (key val props)
4708 "Update PROPS with KEY and VAL."
4709 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4710 (key (if appending (substring key 0 (- (length key) 1)) key))
4711 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4712 (previous (cdr (assoc key props))))
4713 (if appending
4714 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4715 (cons (cons key val) remainder))))
4717 (defconst org-block-regexp
4718 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4719 "Regular expression for hiding blocks.")
4720 (defconst org-heading-keyword-regexp-format
4721 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4722 "Printf format for a regexp matching a headline with some keyword.
4723 This regexp will match the headline of any node which has the
4724 exact keyword that is put into the format. The keyword isn't in
4725 any group by default, but the stars and the body are.")
4726 (defconst org-heading-keyword-maybe-regexp-format
4727 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4728 "Printf format for a regexp matching a headline, possibly with some keyword.
4729 This regexp can match any headline with the specified keyword, or
4730 without a keyword. The keyword isn't in any group by default,
4731 but the stars and the body are.")
4733 (defun org-set-regexps-and-options ()
4734 "Precompute regular expressions for current buffer."
4735 (when (derived-mode-p 'org-mode)
4736 (org-set-local 'org-todo-kwd-alist nil)
4737 (org-set-local 'org-todo-key-alist nil)
4738 (org-set-local 'org-todo-key-trigger nil)
4739 (org-set-local 'org-todo-keywords-1 nil)
4740 (org-set-local 'org-done-keywords nil)
4741 (org-set-local 'org-todo-heads nil)
4742 (org-set-local 'org-todo-sets nil)
4743 (org-set-local 'org-todo-log-states nil)
4744 (org-set-local 'org-file-properties nil)
4745 (org-set-local 'org-file-tags nil)
4746 (let ((re (org-make-options-regexp
4747 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4748 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4749 "SETUPFILE" "OPTIONS")
4750 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4751 (splitre "[ \t]+")
4752 (scripts org-use-sub-superscripts)
4753 kwds kws0 kwsa key log value cat arch tags const links hw dws
4754 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4755 (start 0))
4756 (save-excursion
4757 (save-restriction
4758 (widen)
4759 (goto-char (point-min))
4760 (while (or (and ext-setup-or-nil
4761 (string-match re ext-setup-or-nil start)
4762 (setq start (match-end 0)))
4763 (and (setq ext-setup-or-nil nil start 0)
4764 (re-search-forward re nil t)))
4765 (setq key (upcase (match-string 1 ext-setup-or-nil))
4766 value (org-match-string-no-properties 2 ext-setup-or-nil))
4767 (if (stringp value) (setq value (org-trim value)))
4768 (cond
4769 ((equal key "CATEGORY")
4770 (setq cat value))
4771 ((member key '("SEQ_TODO" "TODO"))
4772 (push (cons 'sequence (org-split-string value splitre)) kwds))
4773 ((equal key "TYP_TODO")
4774 (push (cons 'type (org-split-string value splitre)) kwds))
4775 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4776 ;; general TODO-like setup
4777 (push (cons (intern (downcase (match-string 1 key)))
4778 (org-split-string value splitre)) kwds))
4779 ((equal key "TAGS")
4780 (setq tags (append tags (if tags '("\\n") nil)
4781 (org-split-string value splitre))))
4782 ((equal key "COLUMNS")
4783 (org-set-local 'org-columns-default-format value))
4784 ((equal key "LINK")
4785 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4786 (push (cons (match-string 1 value)
4787 (org-trim (match-string 2 value)))
4788 links)))
4789 ((equal key "PRIORITIES")
4790 (setq prio (org-split-string value " +")))
4791 ((equal key "PROPERTY")
4792 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4793 (setq props (org-update-property-plist (match-string 1 value)
4794 (match-string 2 value)
4795 props))))
4796 ((equal key "FILETAGS")
4797 (when (string-match "\\S-" value)
4798 (setq ftags
4799 (append
4800 ftags
4801 (apply 'append
4802 (mapcar (lambda (x) (org-split-string x ":"))
4803 (org-split-string value)))))))
4804 ((equal key "DRAWERS")
4805 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4806 ((equal key "CONSTANTS")
4807 (setq const (append const (org-split-string value splitre))))
4808 ((equal key "STARTUP")
4809 (let ((opts (org-split-string value splitre))
4810 l var val)
4811 (while (setq l (pop opts))
4812 (when (setq l (assoc l org-startup-options))
4813 (setq var (nth 1 l) val (nth 2 l))
4814 (if (not (nth 3 l))
4815 (set (make-local-variable var) val)
4816 (if (not (listp (symbol-value var)))
4817 (set (make-local-variable var) nil))
4818 (set (make-local-variable var) (symbol-value var))
4819 (add-to-list var val))))))
4820 ((equal key "ARCHIVE")
4821 (setq arch value)
4822 (remove-text-properties 0 (length arch)
4823 '(face t fontified t) arch))
4824 ((equal key "OPTIONS")
4825 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4826 (setq scripts (read (match-string 2 value)))))
4827 ((equal key "SETUPFILE")
4828 (setq setup-contents (org-file-contents
4829 (expand-file-name
4830 (org-remove-double-quotes value))
4831 'noerror))
4832 (if (not ext-setup-or-nil)
4833 (setq ext-setup-or-nil setup-contents start 0)
4834 (setq ext-setup-or-nil
4835 (concat (substring ext-setup-or-nil 0 start)
4836 "\n" setup-contents "\n"
4837 (substring ext-setup-or-nil start)))))))
4838 ;; search for property blocks
4839 (goto-char (point-min))
4840 (while (re-search-forward org-block-regexp nil t)
4841 (when (equal "PROPERTY" (upcase (match-string 1)))
4842 (setq value (replace-regexp-in-string
4843 "[\n\r]" " " (match-string 4)))
4844 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4845 (setq props (org-update-property-plist (match-string 1 value)
4846 (match-string 2 value)
4847 props)))))))
4848 (org-set-local 'org-use-sub-superscripts scripts)
4849 (when cat
4850 (org-set-local 'org-category (intern cat))
4851 (push (cons "CATEGORY" cat) props))
4852 (when prio
4853 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4854 (setq prio (mapcar 'string-to-char prio))
4855 (org-set-local 'org-highest-priority (nth 0 prio))
4856 (org-set-local 'org-lowest-priority (nth 1 prio))
4857 (org-set-local 'org-default-priority (nth 2 prio)))
4858 (and props (org-set-local 'org-file-properties (nreverse props)))
4859 (and ftags (org-set-local 'org-file-tags
4860 (mapcar 'org-add-prop-inherited ftags)))
4861 (and drawers (org-set-local 'org-drawers drawers))
4862 (and arch (org-set-local 'org-archive-location arch))
4863 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4864 ;; Process the TODO keywords
4865 (unless kwds
4866 ;; Use the global values as if they had been given locally.
4867 (setq kwds (default-value 'org-todo-keywords))
4868 (if (stringp (car kwds))
4869 (setq kwds (list (cons org-todo-interpretation
4870 (default-value 'org-todo-keywords)))))
4871 (setq kwds (reverse kwds)))
4872 (setq kwds (nreverse kwds))
4873 (let (inter kws kw)
4874 (while (setq kws (pop kwds))
4875 (let ((kws (or
4876 (run-hook-with-args-until-success
4877 'org-todo-setup-filter-hook kws)
4878 kws)))
4879 (setq inter (pop kws) sep (member "|" kws)
4880 kws0 (delete "|" (copy-sequence kws))
4881 kwsa nil
4882 kws1 (mapcar
4883 (lambda (x)
4884 ;; 1 2
4885 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4886 (progn
4887 (setq kw (match-string 1 x)
4888 key (and (match-end 2) (match-string 2 x))
4889 log (org-extract-log-state-settings x))
4890 (push (cons kw (and key (string-to-char key))) kwsa)
4891 (and log (push log org-todo-log-states))
4893 (error "Invalid TODO keyword %s" x)))
4894 kws0)
4895 kwsa (if kwsa (append '((:startgroup))
4896 (nreverse kwsa)
4897 '((:endgroup))))
4898 hw (car kws1)
4899 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4900 tail (list inter hw (car dws) (org-last dws))))
4901 (add-to-list 'org-todo-heads hw 'append)
4902 (push kws1 org-todo-sets)
4903 (setq org-done-keywords (append org-done-keywords dws nil))
4904 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4905 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4906 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4907 (setq org-todo-sets (nreverse org-todo-sets)
4908 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4909 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4910 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4911 ;; Process the constants
4912 (when const
4913 (let (e cst)
4914 (while (setq e (pop const))
4915 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4916 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4917 (setq org-table-formula-constants-local cst)))
4919 ;; Process the tags.
4920 (when tags
4921 (let (e tgs)
4922 (while (setq e (pop tags))
4923 (cond
4924 ((equal e "{") (push '(:startgroup) tgs))
4925 ((equal e "}") (push '(:endgroup) tgs))
4926 ((equal e "\\n") (push '(:newline) tgs))
4927 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4928 (push (cons (match-string 1 e)
4929 (string-to-char (match-string 2 e)))
4930 tgs))
4931 (t (push (list e) tgs))))
4932 (org-set-local 'org-tag-alist nil)
4933 (while (setq e (pop tgs))
4934 (or (and (stringp (car e))
4935 (assoc (car e) org-tag-alist))
4936 (push e org-tag-alist)))))
4938 ;; Compute the regular expressions and other local variables.
4939 ;; Using `org-outline-regexp-bol' would complicate them much,
4940 ;; because of the fixed white space at the end of that string.
4941 (if (not org-done-keywords)
4942 (setq org-done-keywords (and org-todo-keywords-1
4943 (list (org-last org-todo-keywords-1)))))
4944 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4945 (length org-scheduled-string)
4946 (length org-clock-string)
4947 (length org-closed-string)))
4948 org-drawer-regexp
4949 (concat "^[ \t]*:\\("
4950 (mapconcat 'regexp-quote org-drawers "\\|")
4951 "\\):[ \t]*$")
4952 org-not-done-keywords
4953 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4954 org-todo-regexp
4955 (concat "\\("
4956 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4957 "\\)")
4958 org-not-done-regexp
4959 (concat "\\("
4960 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4961 "\\)")
4962 org-not-done-heading-regexp
4963 (format org-heading-keyword-regexp-format org-not-done-regexp)
4964 org-todo-line-regexp
4965 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4966 org-complex-heading-regexp
4967 (concat "^\\(\\*+\\)"
4968 "\\(?: +" org-todo-regexp "\\)?"
4969 "\\(?: +\\(\\[#.\\]\\)\\)?"
4970 "\\(?: +\\(.*?\\)\\)??"
4971 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4972 "[ \t]*$")
4973 org-complex-heading-regexp-format
4974 (concat "^\\(\\*+\\)"
4975 "\\(?: +" org-todo-regexp "\\)?"
4976 "\\(?: +\\(\\[#.\\]\\)\\)?"
4977 "\\(?: +"
4978 ;; Stats cookies can be stuck to body.
4979 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4980 "\\(%s\\)"
4981 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4982 "\\)"
4983 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4984 "[ \t]*$")
4985 org-todo-line-tags-regexp
4986 (concat "^\\(\\*+\\)"
4987 "\\(?: +" org-todo-regexp "\\)?"
4988 "\\(?: +\\(.*?\\)\\)??"
4989 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4990 "[ \t]*$")
4991 org-deadline-regexp (concat "\\<" org-deadline-string)
4992 org-deadline-time-regexp
4993 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4994 org-deadline-time-hour-regexp
4995 (concat "\\<" org-deadline-string
4996 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
4997 org-deadline-line-regexp
4998 (concat "\\<\\(" org-deadline-string "\\).*")
4999 org-scheduled-regexp
5000 (concat "\\<" org-scheduled-string)
5001 org-scheduled-time-regexp
5002 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5003 org-scheduled-time-hour-regexp
5004 (concat "\\<" org-scheduled-string
5005 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5006 org-closed-time-regexp
5007 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5008 org-keyword-time-regexp
5009 (concat "\\<\\(" org-scheduled-string
5010 "\\|" org-deadline-string
5011 "\\|" org-closed-string
5012 "\\|" org-clock-string "\\)"
5013 " *[[<]\\([^]>]+\\)[]>]")
5014 org-keyword-time-not-clock-regexp
5015 (concat "\\<\\(" org-scheduled-string
5016 "\\|" org-deadline-string
5017 "\\|" org-closed-string
5018 "\\)"
5019 " *[[<]\\([^]>]+\\)[]>]")
5020 org-maybe-keyword-time-regexp
5021 (concat "\\(\\<\\(" org-scheduled-string
5022 "\\|" org-deadline-string
5023 "\\|" org-closed-string
5024 "\\|" org-clock-string "\\)\\)?"
5025 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5026 org-all-time-keywords
5027 (mapcar (lambda (w) (substring w 0 -1))
5028 (list org-scheduled-string org-deadline-string
5029 org-clock-string org-closed-string)))
5030 (org-compute-latex-and-related-regexp)
5031 (org-set-font-lock-defaults))))
5033 (defun org-file-contents (file &optional noerror)
5034 "Return the contents of FILE, as a string."
5035 (if (or (not file)
5036 (not (file-readable-p file)))
5037 (if noerror
5038 (progn
5039 (message "Cannot read file \"%s\"" file)
5040 (ding) (sit-for 2)
5042 (error "Cannot read file \"%s\"" file))
5043 (with-temp-buffer
5044 (insert-file-contents file)
5045 (buffer-string))))
5047 (defun org-extract-log-state-settings (x)
5048 "Extract the log state setting from a TODO keyword string.
5049 This will extract info from a string like \"WAIT(w@/!)\"."
5050 (let (kw key log1 log2)
5051 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5052 (setq kw (match-string 1 x)
5053 key (and (match-end 2) (match-string 2 x))
5054 log1 (and (match-end 3) (match-string 3 x))
5055 log2 (and (match-end 4) (match-string 4 x)))
5056 (and (or log1 log2)
5057 (list kw
5058 (and log1 (if (equal log1 "!") 'time 'note))
5059 (and log2 (if (equal log2 "!") 'time 'note)))))))
5061 (defun org-remove-keyword-keys (list)
5062 "Remove a pair of parenthesis at the end of each string in LIST."
5063 (mapcar (lambda (x)
5064 (if (string-match "(.*)$" x)
5065 (substring x 0 (match-beginning 0))
5067 list))
5069 (defun org-assign-fast-keys (alist)
5070 "Assign fast keys to a keyword-key alist.
5071 Respect keys that are already there."
5072 (let (new e (alt ?0))
5073 (while (setq e (pop alist))
5074 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5075 (cdr e)) ;; Key already assigned.
5076 (push e new)
5077 (let ((clist (string-to-list (downcase (car e))))
5078 (used (append new alist)))
5079 (when (= (car clist) ?@)
5080 (pop clist))
5081 (while (and clist (rassoc (car clist) used))
5082 (pop clist))
5083 (unless clist
5084 (while (rassoc alt used)
5085 (incf alt)))
5086 (push (cons (car e) (or (car clist) alt)) new))))
5087 (nreverse new)))
5089 ;;; Some variables used in various places
5091 (defvar org-window-configuration nil
5092 "Used in various places to store a window configuration.")
5093 (defvar org-selected-window nil
5094 "Used in various places to store a window configuration.")
5095 (defvar org-finish-function nil
5096 "Function to be called when `C-c C-c' is used.
5097 This is for getting out of special buffers like capture.")
5100 ;; FIXME: Occasionally check by commenting these, to make sure
5101 ;; no other functions uses these, forgetting to let-bind them.
5102 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5103 (defvar org-last-state)
5104 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5106 ;; Defined somewhere in this file, but used before definition.
5107 (defvar org-entities) ;; defined in org-entities.el
5108 (defvar org-struct-menu)
5109 (defvar org-org-menu)
5110 (defvar org-tbl-menu)
5112 ;;;; Define the Org-mode
5114 ;; We use a before-change function to check if a table might need
5115 ;; an update.
5116 (defvar org-table-may-need-update t
5117 "Indicates that a table might need an update.
5118 This variable is set by `org-before-change-function'.
5119 `org-table-align' sets it back to nil.")
5120 (defun org-before-change-function (beg end)
5121 "Every change indicates that a table might need an update."
5122 (setq org-table-may-need-update t))
5123 (defvar org-mode-map)
5124 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5125 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5126 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5127 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5128 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5129 (defvar org-table-buffer-is-an nil)
5131 (defvar bidi-paragraph-direction)
5132 (defvar buffer-face-mode-face)
5134 (require 'outline)
5135 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5136 (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"))
5137 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5139 ;; Other stuff we need.
5140 (require 'time-date)
5141 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5142 (require 'easymenu)
5143 (require 'overlay)
5145 ;; (require 'org-macs) moved higher up in the file before it is first used
5146 (require 'org-entities)
5147 ;; (require 'org-compat) moved higher up in the file before it is first used
5148 (require 'org-faces)
5149 (require 'org-list)
5150 (require 'org-pcomplete)
5151 (require 'org-src)
5152 (require 'org-footnote)
5153 (require 'org-macro)
5155 ;; babel
5156 (require 'ob)
5158 ;;;###autoload
5159 (define-derived-mode org-mode outline-mode "Org"
5160 "Outline-based notes management and organizer, alias
5161 \"Carsten's outline-mode for keeping track of everything.\"
5163 Org-mode develops organizational tasks around a NOTES file which
5164 contains information about projects as plain text. Org-mode is
5165 implemented on top of outline-mode, which is ideal to keep the content
5166 of large files well structured. It supports ToDo items, deadlines and
5167 time stamps, which magically appear in the diary listing of the Emacs
5168 calendar. Tables are easily created with a built-in table editor.
5169 Plain text URL-like links connect to websites, emails (VM), Usenet
5170 messages (Gnus), BBDB entries, and any files related to the project.
5171 For printing and sharing of notes, an Org-mode file (or a part of it)
5172 can be exported as a structured ASCII or HTML file.
5174 The following commands are available:
5176 \\{org-mode-map}"
5178 ;; Get rid of Outline menus, they are not needed
5179 ;; Need to do this here because define-derived-mode sets up
5180 ;; the keymap so late. Still, it is a waste to call this each time
5181 ;; we switch another buffer into org-mode.
5182 (if (featurep 'xemacs)
5183 (when (boundp 'outline-mode-menu-heading)
5184 ;; Assume this is Greg's port, it uses easymenu
5185 (easy-menu-remove outline-mode-menu-heading)
5186 (easy-menu-remove outline-mode-menu-show)
5187 (easy-menu-remove outline-mode-menu-hide))
5188 (define-key org-mode-map [menu-bar headings] 'undefined)
5189 (define-key org-mode-map [menu-bar hide] 'undefined)
5190 (define-key org-mode-map [menu-bar show] 'undefined))
5192 (org-load-modules-maybe)
5193 (easy-menu-add org-org-menu)
5194 (easy-menu-add org-tbl-menu)
5195 (org-install-agenda-files-menu)
5196 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5197 (add-to-invisibility-spec '(org-cwidth))
5198 (add-to-invisibility-spec '(org-hide-block . t))
5199 (when (featurep 'xemacs)
5200 (org-set-local 'line-move-ignore-invisible t))
5201 (org-set-local 'outline-regexp org-outline-regexp)
5202 (org-set-local 'outline-level 'org-outline-level)
5203 (setq bidi-paragraph-direction 'left-to-right)
5204 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5205 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5206 (when (and org-ellipsis
5207 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5208 (fboundp 'make-glyph-code))
5209 (unless org-display-table
5210 (setq org-display-table (make-display-table)))
5211 (set-display-table-slot
5212 org-display-table 4
5213 (vconcat (mapcar
5214 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5215 org-ellipsis)))
5216 (if (stringp org-ellipsis) org-ellipsis "..."))))
5217 (setq buffer-display-table org-display-table))
5218 (org-set-regexps-and-options)
5219 (when (and org-tag-faces (not org-tags-special-faces-re))
5220 ;; tag faces set outside customize.... force initialization.
5221 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5222 ;; Calc embedded
5223 (org-set-local 'calc-embedded-open-mode "# ")
5224 ;; Modify a few syntax entries
5225 (modify-syntax-entry ?@ "w")
5226 (modify-syntax-entry ?\" "\"")
5227 (if org-startup-truncated (setq truncate-lines t))
5228 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5229 (org-set-local 'font-lock-unfontify-region-function
5230 'org-unfontify-region)
5231 ;; Activate before-change-function
5232 (org-set-local 'org-table-may-need-update t)
5233 (org-add-hook 'before-change-functions 'org-before-change-function nil
5234 'local)
5235 ;; Check for running clock before killing a buffer
5236 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5237 ;; Initialize macros templates.
5238 (org-macro-initialize-templates)
5239 ;; Initialize radio targets.
5240 (org-update-radio-target-regexp)
5241 ;; Indentation.
5242 (org-set-local 'indent-line-function 'org-indent-line)
5243 (org-set-local 'indent-region-function 'org-indent-region)
5244 ;; Filling and auto-filling.
5245 (org-setup-filling)
5246 ;; Comments.
5247 (org-setup-comments-handling)
5248 ;; Beginning/end of defun
5249 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5250 (org-set-local 'end-of-defun-function 'org-forward-element)
5251 ;; Next error for sparse trees
5252 (org-set-local 'next-error-function 'org-occur-next-match)
5253 ;; Make sure dependence stuff works reliably, even for users who set it
5254 ;; too late :-(
5255 (if org-enforce-todo-dependencies
5256 (add-hook 'org-blocker-hook
5257 'org-block-todo-from-children-or-siblings-or-parent)
5258 (remove-hook 'org-blocker-hook
5259 'org-block-todo-from-children-or-siblings-or-parent))
5260 (if org-enforce-todo-checkbox-dependencies
5261 (add-hook 'org-blocker-hook
5262 'org-block-todo-from-checkboxes)
5263 (remove-hook 'org-blocker-hook
5264 'org-block-todo-from-checkboxes))
5266 ;; Align options lines
5267 (org-set-local
5268 'align-mode-rules-list
5269 '((org-in-buffer-settings
5270 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5271 (modes . '(org-mode)))))
5273 ;; Imenu
5274 (org-set-local 'imenu-create-index-function
5275 'org-imenu-get-tree)
5277 ;; Make isearch reveal context
5278 (if (or (featurep 'xemacs)
5279 (not (boundp 'outline-isearch-open-invisible-function)))
5280 ;; Emacs 21 and XEmacs make use of the hook
5281 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5282 ;; Emacs 22 deals with this through a special variable
5283 (org-set-local 'outline-isearch-open-invisible-function
5284 (lambda (&rest ignore) (org-show-context 'isearch)))
5285 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5287 ;; Setup the pcomplete hooks
5288 (set (make-local-variable 'pcomplete-command-completion-function)
5289 'org-pcomplete-initial)
5290 (set (make-local-variable 'pcomplete-command-name-function)
5291 'org-command-at-point)
5292 (set (make-local-variable 'pcomplete-default-completion-function)
5293 'ignore)
5294 (set (make-local-variable 'pcomplete-parse-arguments-function)
5295 'org-parse-arguments)
5296 (set (make-local-variable 'pcomplete-termination-string) "")
5297 (when (>= emacs-major-version 23)
5298 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5300 ;; If empty file that did not turn on org-mode automatically, make it to.
5301 (if (and org-insert-mode-line-in-empty-file
5302 (org-called-interactively-p 'any)
5303 (= (point-min) (point-max)))
5304 (insert "# -*- mode: org -*-\n\n"))
5305 (unless org-inhibit-startup
5306 (org-unmodified
5307 (and org-startup-with-beamer-mode (org-beamer-mode))
5308 (when org-startup-align-all-tables
5309 (org-table-map-tables 'org-table-align 'quietly))
5310 (when org-startup-with-inline-images
5311 (org-display-inline-images))
5312 (when org-startup-with-latex-preview
5313 (org-preview-latex-fragment))
5314 (unless org-inhibit-startup-visibility-stuff
5315 (org-set-startup-visibility))))
5316 ;; Try to set org-hide correctly
5317 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5319 ;; Update `customize-package-emacs-version-alist'
5320 (add-to-list 'customize-package-emacs-version-alist
5321 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5322 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5323 ("8.0" . "24.4")))
5325 (defvar org-mode-transpose-word-syntax-table
5326 (let ((st (make-syntax-table)))
5327 (mapc (lambda(c) (modify-syntax-entry
5328 (string-to-char (car c)) "w p" st))
5329 org-emphasis-alist)
5330 st))
5332 (when (fboundp 'abbrev-table-put)
5333 (abbrev-table-put org-mode-abbrev-table
5334 :parents (list text-mode-abbrev-table)))
5336 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5338 (defsubst org-fix-ellipsis-at-bol ()
5339 (save-excursion (goto-char (window-start)) (recenter 0)))
5341 (defun org-find-invisible-foreground ()
5342 (let ((candidates (remove
5343 "unspecified-bg"
5344 (nconc
5345 (list (face-background 'default)
5346 (face-background 'org-default))
5347 (mapcar
5348 (lambda (alist)
5349 (when (boundp alist)
5350 (cdr (assoc 'background-color (symbol-value alist)))))
5351 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5352 (list (face-foreground 'org-hide))))))
5353 (car (remove nil candidates))))
5355 (defun org-current-time (&optional rounding-minutes past)
5356 "Current time, possibly rounded to ROUNDING-MINUTES.
5357 When ROUNDING-MINUTES is not an integer, fall back on the car of
5358 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5359 the rounding returns a past time."
5360 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5361 (car org-time-stamp-rounding-minutes)))
5362 (time (decode-time)) res)
5363 (if (< r 1)
5364 (current-time)
5365 (setq res
5366 (apply 'encode-time
5367 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5368 (nthcdr 2 time))))
5369 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5370 (seconds-to-time (- (org-float-time res) (* r 60)))
5371 res))))
5373 (defun org-today ()
5374 "Return today date, considering `org-extend-today-until'."
5375 (time-to-days
5376 (time-subtract (current-time)
5377 (list 0 (* 3600 org-extend-today-until) 0))))
5379 ;;;; Font-Lock stuff, including the activators
5381 (defvar org-mouse-map (make-sparse-keymap))
5382 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5383 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5384 (when org-mouse-1-follows-link
5385 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5386 (when org-tab-follows-link
5387 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5388 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5390 (require 'font-lock)
5392 (defconst org-non-link-chars "]\t\n\r<>")
5393 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5394 "shell" "elisp" "doi" "message"))
5395 (defvar org-link-types-re nil
5396 "Matches a link that has a url-like prefix like \"http:\"")
5397 (defvar org-link-re-with-space nil
5398 "Matches a link with spaces, optional angular brackets around it.")
5399 (defvar org-link-re-with-space2 nil
5400 "Matches a link with spaces, optional angular brackets around it.")
5401 (defvar org-link-re-with-space3 nil
5402 "Matches a link with spaces, only for internal part in bracket links.")
5403 (defvar org-angle-link-re nil
5404 "Matches link with angular brackets, spaces are allowed.")
5405 (defvar org-plain-link-re nil
5406 "Matches plain link, without spaces.")
5407 (defvar org-bracket-link-regexp nil
5408 "Matches a link in double brackets.")
5409 (defvar org-bracket-link-analytic-regexp nil
5410 "Regular expression used to analyze links.
5411 Here is what the match groups contain after a match:
5412 1: http:
5413 2: http
5414 3: path
5415 4: [desc]
5416 5: desc")
5417 (defvar org-bracket-link-analytic-regexp++ nil
5418 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5419 (defvar org-any-link-re nil
5420 "Regular expression matching any link.")
5422 (defconst org-match-sexp-depth 3
5423 "Number of stacked braces for sub/superscript matching.")
5425 (defun org-create-multibrace-regexp (left right n)
5426 "Create a regular expression which will match a balanced sexp.
5427 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5428 as single character strings.
5429 The regexp returned will match the entire expression including the
5430 delimiters. It will also define a single group which contains the
5431 match except for the outermost delimiters. The maximum depth of
5432 stacked delimiters is N. Escaping delimiters is not possible."
5433 (let* ((nothing (concat "[^" left right "]*?"))
5434 (or "\\|")
5435 (re nothing)
5436 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5437 (while (> n 1)
5438 (setq n (1- n)
5439 re (concat re or next)
5440 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5441 (concat left "\\(" re "\\)" right)))
5443 (defvar org-match-substring-regexp
5444 (concat
5445 "\\(\\S-\\)\\([_^]\\)\\("
5446 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5447 "\\|"
5448 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5449 "\\|"
5450 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5451 "The regular expression matching a sub- or superscript.")
5453 (defvar org-match-substring-with-braces-regexp
5454 (concat
5455 "\\(\\S-\\)\\([_^]\\)\\("
5456 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5457 "\\)")
5458 "The regular expression matching a sub- or superscript, forcing braces.")
5460 (defun org-make-link-regexps ()
5461 "Update the link regular expressions.
5462 This should be called after the variable `org-link-types' has changed."
5463 (setq org-link-types-re
5464 (concat
5465 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5466 org-link-re-with-space
5467 (concat
5468 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5469 "\\([^" org-non-link-chars " ]"
5470 "[^" org-non-link-chars "]*"
5471 "[^" org-non-link-chars " ]\\)>?")
5472 org-link-re-with-space2
5473 (concat
5474 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5475 "\\([^" org-non-link-chars " ]"
5476 "[^\t\n\r]*"
5477 "[^" org-non-link-chars " ]\\)>?")
5478 org-link-re-with-space3
5479 (concat
5480 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5481 "\\([^" org-non-link-chars " ]"
5482 "[^\t\n\r]*\\)")
5483 org-angle-link-re
5484 (concat
5485 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5486 "\\([^" org-non-link-chars " ]"
5487 "[^" org-non-link-chars "]*"
5488 "\\)>")
5489 org-plain-link-re
5490 (concat
5491 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5492 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5493 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5494 org-bracket-link-regexp
5495 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5496 org-bracket-link-analytic-regexp
5497 (concat
5498 "\\[\\["
5499 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5500 "\\([^]]+\\)"
5501 "\\]"
5502 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5503 "\\]")
5504 org-bracket-link-analytic-regexp++
5505 (concat
5506 "\\[\\["
5507 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5508 "\\([^]]+\\)"
5509 "\\]"
5510 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5511 "\\]")
5512 org-any-link-re
5513 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5514 org-angle-link-re "\\)\\|\\("
5515 org-plain-link-re "\\)")))
5517 (org-make-link-regexps)
5519 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5520 "Regular expression for fast time stamp matching.")
5521 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5522 "Regular expression for fast time stamp matching.")
5523 (defconst org-ts-regexp0
5524 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5525 "Regular expression matching time strings for analysis.
5526 This one does not require the space after the date, so it can be used
5527 on a string that terminates immediately after the date.")
5528 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5529 "Regular expression matching time strings for analysis.")
5530 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5531 "Regular expression matching time stamps, with groups.")
5532 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5533 "Regular expression matching time stamps (also [..]), with groups.")
5534 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5535 "Regular expression matching a time stamp range.")
5536 (defconst org-tr-regexp-both
5537 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5538 "Regular expression matching a time stamp range.")
5539 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5540 org-ts-regexp "\\)?")
5541 "Regular expression matching a time stamp or time stamp range.")
5542 (defconst org-tsr-regexp-both
5543 (concat org-ts-regexp-both "\\(--?-?"
5544 org-ts-regexp-both "\\)?")
5545 "Regular expression matching a time stamp or time stamp range.
5546 The time stamps may be either active or inactive.")
5548 (defvar org-emph-face nil)
5550 (defun org-do-emphasis-faces (limit)
5551 "Run through the buffer and add overlays to emphasized strings."
5552 (let (rtn a)
5553 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5554 (if (not (= (char-after (match-beginning 3))
5555 (char-after (match-beginning 4))))
5556 (progn
5557 (setq rtn t)
5558 (setq a (assoc (match-string 3) org-emphasis-alist))
5559 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5560 'face
5561 (nth 1 a))
5562 (and (nth 4 a)
5563 (org-remove-flyspell-overlays-in
5564 (match-beginning 0) (match-end 0)))
5565 (add-text-properties (match-beginning 2) (match-end 2)
5566 '(font-lock-multiline t org-emphasis t))
5567 (when org-hide-emphasis-markers
5568 (add-text-properties (match-end 4) (match-beginning 5)
5569 '(invisible org-link))
5570 (add-text-properties (match-beginning 3) (match-end 3)
5571 '(invisible org-link)))))
5572 (backward-char 1))
5573 rtn))
5575 (defun org-emphasize (&optional char)
5576 "Insert or change an emphasis, i.e. a font like bold or italic.
5577 If there is an active region, change that region to a new emphasis.
5578 If there is no region, just insert the marker characters and position
5579 the cursor between them.
5580 CHAR should be either the marker character, or the first character of the
5581 HTML tag associated with that emphasis. If CHAR is a space, the means
5582 to remove the emphasis of the selected region.
5583 If char is not given (for example in an interactive call) it
5584 will be prompted for."
5585 (interactive)
5586 (let ((eal org-emphasis-alist) e det
5587 (erc org-emphasis-regexp-components)
5588 (prompt "")
5589 (string "") beg end move tag c s)
5590 (if (org-region-active-p)
5591 (setq beg (region-beginning) end (region-end)
5592 string (buffer-substring beg end))
5593 (setq move t))
5595 (while (setq e (pop eal))
5596 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5597 c (aref tag 0))
5598 (push (cons c (string-to-char (car e))) det)
5599 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5600 (substring tag 1)))))
5601 (setq det (nreverse det))
5602 (unless char
5603 (message "%s" (concat "Emphasis marker or tag:" prompt))
5604 (setq char (read-char-exclusive)))
5605 (setq char (or (cdr (assoc char det)) char))
5606 (if (equal char ?\ )
5607 (setq s "" move nil)
5608 (unless (assoc (char-to-string char) org-emphasis-alist)
5609 (error "No such emphasis marker: \"%c\"" char))
5610 (setq s (char-to-string char)))
5611 (while (and (> (length string) 1)
5612 (equal (substring string 0 1) (substring string -1))
5613 (assoc (substring string 0 1) org-emphasis-alist))
5614 (setq string (substring string 1 -1)))
5615 (setq string (concat s string s))
5616 (if beg (delete-region beg end))
5617 (unless (or (bolp)
5618 (string-match (concat "[" (nth 0 erc) "\n]")
5619 (char-to-string (char-before (point)))))
5620 (insert " "))
5621 (unless (or (eobp)
5622 (string-match (concat "[" (nth 1 erc) "\n]")
5623 (char-to-string (char-after (point)))))
5624 (insert " ") (backward-char 1))
5625 (insert string)
5626 (and move (backward-char 1))))
5628 (defconst org-nonsticky-props
5629 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5631 (defsubst org-rear-nonsticky-at (pos)
5632 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5634 (defun org-activate-plain-links (limit)
5635 "Run through the buffer and add overlays to links."
5636 (let (f hl)
5637 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5638 (not (org-in-src-block-p)))
5639 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5640 (setq f (get-text-property (match-beginning 0) 'face))
5641 (setq hl (org-match-string-no-properties 0))
5642 (if (or (eq f 'org-tag)
5643 (and (listp f) (memq 'org-tag f)))
5645 (add-text-properties (match-beginning 0) (match-end 0)
5646 (list 'mouse-face 'highlight
5647 'face 'org-link
5648 'htmlize-link `(:uri ,hl)
5649 'keymap org-mouse-map))
5650 (org-rear-nonsticky-at (match-end 0)))
5651 t)))
5653 (defun org-activate-code (limit)
5654 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5655 (progn
5656 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5657 (remove-text-properties (match-beginning 0) (match-end 0)
5658 '(display t invisible t intangible t))
5659 t)))
5661 (defcustom org-src-fontify-natively nil
5662 "When non-nil, fontify code in code blocks."
5663 :type 'boolean
5664 :version "24.1"
5665 :group 'org-appearance
5666 :group 'org-babel)
5668 (defcustom org-allow-promoting-top-level-subtree nil
5669 "When non-nil, allow promoting a top level subtree.
5670 The leading star of the top level headline will be replaced
5671 by a #."
5672 :type 'boolean
5673 :version "24.1"
5674 :group 'org-appearance)
5676 (defun org-fontify-meta-lines-and-blocks (limit)
5677 (condition-case nil
5678 (org-fontify-meta-lines-and-blocks-1 limit)
5679 (error (message "org-mode fontification error"))))
5681 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5682 "Fontify #+ lines and blocks, in the correct ways."
5683 (let ((case-fold-search t))
5684 (if (re-search-forward
5685 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5686 limit t)
5687 (let ((beg (match-beginning 0))
5688 (block-start (match-end 0))
5689 (block-end nil)
5690 (lang (match-string 7))
5691 (beg1 (line-beginning-position 2))
5692 (dc1 (downcase (match-string 2)))
5693 (dc3 (downcase (match-string 3)))
5694 end end1 quoting block-type ovl)
5695 (cond
5696 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5697 ;; a single line of backend-specific content
5698 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5699 (remove-text-properties (match-beginning 0) (match-end 0)
5700 '(display t invisible t intangible t))
5701 (add-text-properties (match-beginning 1) (match-end 3)
5702 '(font-lock-fontified t face org-meta-line))
5703 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5704 '(font-lock-fontified t face org-block))
5705 ; for backend-specific code
5707 ((and (match-end 4) (equal dc3 "+begin"))
5708 ;; Truly a block
5709 (setq block-type (downcase (match-string 5))
5710 quoting (member block-type org-protecting-blocks))
5711 (when (re-search-forward
5712 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5713 nil t) ;; on purpose, we look further than LIMIT
5714 (setq end (min (point-max) (match-end 0))
5715 end1 (min (point-max) (1- (match-beginning 0))))
5716 (setq block-end (match-beginning 0))
5717 (when quoting
5718 (remove-text-properties beg end
5719 '(display t invisible t intangible t)))
5720 (add-text-properties
5721 beg end
5722 '(font-lock-fontified t font-lock-multiline t))
5723 (add-text-properties beg beg1 '(face org-meta-line))
5724 (add-text-properties end1 (min (point-max) (1+ end))
5725 '(face org-meta-line)) ; for end_src
5726 (cond
5727 ((and lang (not (string= lang "")) org-src-fontify-natively)
5728 (org-src-font-lock-fontify-block lang block-start block-end)
5729 ;; remove old background overlays
5730 (mapc (lambda (ov)
5731 (if (eq (overlay-get ov 'face) 'org-block-background)
5732 (delete-overlay ov)))
5733 (overlays-at (/ (+ beg1 block-end) 2)))
5734 ;; add a background overlay
5735 (setq ovl (make-overlay beg1 block-end))
5736 (overlay-put ovl 'face 'org-block-background)
5737 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5738 (quoting
5739 (add-text-properties beg1 (min (point-max) (1+ end1))
5740 '(face org-block))) ; end of source block
5741 ((not org-fontify-quote-and-verse-blocks))
5742 ((string= block-type "quote")
5743 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5744 ((string= block-type "verse")
5745 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5746 (add-text-properties beg beg1 '(face org-block-begin-line))
5747 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5748 '(face org-block-end-line))
5750 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5751 (add-text-properties
5752 beg (match-end 3)
5753 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5754 '(font-lock-fontified t invisible t)
5755 '(font-lock-fontified t face org-document-info-keyword)))
5756 (add-text-properties
5757 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5758 (if (string-equal dc1 "+title:")
5759 '(font-lock-fontified t face org-document-title)
5760 '(font-lock-fontified t face org-document-info))))
5761 ((or (equal dc1 "+results")
5762 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5763 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5764 "+call:" "+header:" "+headers:" "+name:"))
5765 (and (match-end 4) (equal dc3 "+attr")))
5766 (add-text-properties
5767 beg (match-end 0)
5768 '(font-lock-fontified t face org-meta-line))
5770 ((member dc3 '(" " ""))
5771 (add-text-properties
5772 beg (match-end 0)
5773 '(font-lock-fontified t face font-lock-comment-face)))
5774 ((not (member (char-after beg) '(?\ ?\t)))
5775 ;; just any other in-buffer setting, but not indented
5776 (add-text-properties
5777 beg (match-end 0)
5778 '(font-lock-fontified t face org-meta-line))
5780 (t nil))))))
5782 (defun org-activate-angle-links (limit)
5783 "Run through the buffer and add overlays to links."
5784 (if (and (re-search-forward org-angle-link-re limit t)
5785 (not (org-in-src-block-p)))
5786 (progn
5787 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5788 (add-text-properties (match-beginning 0) (match-end 0)
5789 (list 'mouse-face 'highlight
5790 'keymap org-mouse-map))
5791 (org-rear-nonsticky-at (match-end 0))
5792 t)))
5794 (defun org-activate-footnote-links (limit)
5795 "Run through the buffer and add overlays to footnotes."
5796 (let ((fn (org-footnote-next-reference-or-definition limit)))
5797 (when fn
5798 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5799 (org-remove-flyspell-overlays-in beg end)
5800 (add-text-properties beg end
5801 (list 'mouse-face 'highlight
5802 'keymap org-mouse-map
5803 'help-echo
5804 (if (= (point-at-bol) beg)
5805 "Footnote definition"
5806 "Footnote reference")
5807 'font-lock-fontified t
5808 'font-lock-multiline t
5809 'face 'org-footnote))))))
5811 (defun org-activate-bracket-links (limit)
5812 "Run through the buffer and add overlays to bracketed links."
5813 (if (and (re-search-forward org-bracket-link-regexp limit t)
5814 (not (org-in-src-block-p)))
5815 (let* ((hl (org-match-string-no-properties 1))
5816 (help (concat "LINK: " hl))
5817 ;; FIXME: Above we should remove the escapes. But that
5818 ;; requires another match, protecting match data, a lot
5819 ;; of overhead for font-lock.
5820 (ip (org-maybe-intangible
5821 (list 'invisible 'org-link
5822 'keymap org-mouse-map 'mouse-face 'highlight
5823 'font-lock-multiline t 'help-echo help
5824 'htmlize-link `(:uri ,hl))))
5825 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5826 'font-lock-multiline t 'help-echo help
5827 'htmlize-link `(:uri ,hl))))
5828 ;; We need to remove the invisible property here. Table narrowing
5829 ;; may have made some of this invisible.
5830 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5831 (remove-text-properties (match-beginning 0) (match-end 0)
5832 '(invisible nil))
5833 (if (match-end 3)
5834 (progn
5835 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5836 (org-rear-nonsticky-at (match-beginning 3))
5837 (add-text-properties (match-beginning 3) (match-end 3) vp)
5838 (org-rear-nonsticky-at (match-end 3))
5839 (add-text-properties (match-end 3) (match-end 0) ip)
5840 (org-rear-nonsticky-at (match-end 0)))
5841 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5842 (org-rear-nonsticky-at (match-beginning 1))
5843 (add-text-properties (match-beginning 1) (match-end 1) vp)
5844 (org-rear-nonsticky-at (match-end 1))
5845 (add-text-properties (match-end 1) (match-end 0) ip)
5846 (org-rear-nonsticky-at (match-end 0)))
5847 t)))
5849 (defun org-activate-dates (limit)
5850 "Run through the buffer and add overlays to dates."
5851 (if (and (re-search-forward org-tsr-regexp-both limit t)
5852 (not (equal (char-before (match-beginning 0)) 91)))
5853 (progn
5854 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5855 (add-text-properties (match-beginning 0) (match-end 0)
5856 (list 'mouse-face 'highlight
5857 'keymap org-mouse-map))
5858 (org-rear-nonsticky-at (match-end 0))
5859 (when org-display-custom-times
5860 (if (match-end 3)
5861 (org-display-custom-time (match-beginning 3) (match-end 3)))
5862 (org-display-custom-time (match-beginning 1) (match-end 1)))
5863 t)))
5865 (defvar org-target-link-regexp nil
5866 "Regular expression matching radio targets in plain text.")
5867 (make-variable-buffer-local 'org-target-link-regexp)
5868 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5869 "Regular expression matching a link target.")
5870 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5871 "Regular expression matching a radio target.")
5872 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5873 "Regular expression matching any target.")
5875 (defun org-activate-target-links (limit)
5876 "Run through the buffer and add overlays to target matches."
5877 (when org-target-link-regexp
5878 (let ((case-fold-search t))
5879 (if (re-search-forward org-target-link-regexp limit t)
5880 (progn
5881 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5882 (add-text-properties (match-beginning 0) (match-end 0)
5883 (list 'mouse-face 'highlight
5884 'keymap org-mouse-map
5885 'help-echo "Radio target link"
5886 'org-linked-text t))
5887 (org-rear-nonsticky-at (match-end 0))
5888 t)))))
5890 (defun org-update-radio-target-regexp ()
5891 "Find all radio targets in this file and update the regular expression."
5892 (interactive)
5893 (when (memq 'radio org-activate-links)
5894 (setq org-target-link-regexp
5895 (org-make-target-link-regexp (org-all-targets 'radio)))
5896 (org-restart-font-lock)))
5898 (defun org-hide-wide-columns (limit)
5899 (let (s e)
5900 (setq s (text-property-any (point) (or limit (point-max))
5901 'org-cwidth t))
5902 (when s
5903 (setq e (next-single-property-change s 'org-cwidth))
5904 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5905 (goto-char e)
5906 t)))
5908 (defvar org-latex-and-related-regexp nil
5909 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5910 (defvar org-match-substring-regexp)
5911 (defvar org-match-substring-with-braces-regexp)
5913 (defun org-compute-latex-and-related-regexp ()
5914 "Compute regular expression for LaTeX, entities and sub/superscript.
5915 Result depends on variable `org-highlight-latex-and-related'."
5916 (org-set-local
5917 'org-latex-and-related-regexp
5918 (let* ((re-sub
5919 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5920 ((eq org-use-sub-superscripts '{})
5921 (list org-match-substring-with-braces-regexp))
5922 (org-use-sub-superscripts (list org-match-substring-regexp))))
5923 (re-latex
5924 (when (memq 'latex org-highlight-latex-and-related)
5925 (let ((matchers (plist-get org-format-latex-options :matchers)))
5926 (delq nil
5927 (mapcar (lambda (x)
5928 (and (member (car x) matchers) (nth 1 x)))
5929 org-latex-regexps)))))
5930 (re-entities
5931 (when (memq 'entities org-highlight-latex-and-related)
5932 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5933 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5935 (defun org-do-latex-and-related (limit)
5936 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5937 LIMIT bounds the search for syntax to highlight. Stop at first
5938 highlighted object, if any. Return t if some highlighting was
5939 done, nil otherwise."
5940 (when (org-string-nw-p org-latex-and-related-regexp)
5941 (catch 'found
5942 (while (re-search-forward org-latex-and-related-regexp limit t)
5943 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5944 'face))
5945 '(org-code org-verbatim underline))
5946 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5947 '(?_ ?^))
5949 0)))
5950 (font-lock-prepend-text-property
5951 (+ offset (match-beginning 0)) (match-end 0)
5952 'face 'org-latex-and-related)
5953 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5954 '(font-lock-multiline t)))
5955 (throw 'found t)))
5956 nil)))
5958 (defun org-restart-font-lock ()
5959 "Restart `font-lock-mode', to force refontification."
5960 (when (and (boundp 'font-lock-mode) font-lock-mode)
5961 (font-lock-mode -1)
5962 (font-lock-mode 1)))
5964 (defun org-all-targets (&optional radio)
5965 "Return a list of all targets in this file.
5966 When optional argument RADIO is non-nil, only find radio
5967 targets."
5968 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5969 (save-excursion
5970 (goto-char (point-min))
5971 (while (re-search-forward re nil t)
5972 ;; Make sure point is really within the object.
5973 (backward-char)
5974 (let ((obj (org-element-context)))
5975 (when (memq (org-element-type obj) '(radio-target target))
5976 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5977 rtn)))
5979 (defun org-make-target-link-regexp (targets)
5980 "Make regular expression matching all strings in TARGETS.
5981 The regular expression finds the targets also if there is a line break
5982 between words."
5983 (and targets
5984 (concat
5985 "\\<\\("
5986 (mapconcat
5987 (lambda (x)
5988 (setq x (regexp-quote x))
5989 (while (string-match " +" x)
5990 (setq x (replace-match "\\s-+" t t x)))
5992 targets
5993 "\\|")
5994 "\\)\\>")))
5996 (defun org-activate-tags (limit)
5997 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5998 (progn
5999 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6000 (add-text-properties (match-beginning 1) (match-end 1)
6001 (list 'mouse-face 'highlight
6002 'keymap org-mouse-map))
6003 (org-rear-nonsticky-at (match-end 1))
6004 t)))
6006 (defun org-outline-level ()
6007 "Compute the outline level of the heading at point.
6008 If this is called at a normal headline, the level is the number of stars.
6009 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6010 (save-excursion
6011 (if (not (condition-case nil
6012 (org-back-to-heading t)
6013 (error nil)))
6015 (looking-at org-outline-regexp)
6016 (1- (- (match-end 0) (match-beginning 0))))))
6018 (defvar org-font-lock-keywords nil)
6020 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6021 "Regular expression matching a property line.")
6023 (defvar org-font-lock-hook nil
6024 "Functions to be called for special font lock stuff.")
6026 (defvar org-font-lock-set-keywords-hook nil
6027 "Functions that can manipulate `org-font-lock-extra-keywords'.
6028 This is called after `org-font-lock-extra-keywords' is defined, but before
6029 it is installed to be used by font lock. This can be useful if something
6030 needs to be inserted at a specific position in the font-lock sequence.")
6032 (defun org-font-lock-hook (limit)
6033 "Run `org-font-lock-hook' within LIMIT."
6034 (run-hook-with-args 'org-font-lock-hook limit))
6036 (defun org-set-font-lock-defaults ()
6037 "Set font lock defaults for the current buffer."
6038 (let* ((em org-fontify-emphasized-text)
6039 (lk org-activate-links)
6040 (org-font-lock-extra-keywords
6041 (list
6042 ;; Call the hook
6043 '(org-font-lock-hook)
6044 ;; Headlines
6045 `(,(if org-fontify-whole-heading-line
6046 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6047 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6048 (1 (org-get-level-face 1))
6049 (2 (org-get-level-face 2))
6050 (3 (org-get-level-face 3)))
6051 ;; Table lines
6052 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6053 (1 'org-table t))
6054 ;; Table internals
6055 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6056 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6057 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6058 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6059 ;; Drawers
6060 (list org-drawer-regexp '(0 'org-special-keyword t))
6061 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6062 ;; Properties
6063 (list org-property-re
6064 '(1 'org-special-keyword t)
6065 '(3 'org-property-value t))
6066 ;; Links
6067 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6068 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6069 (if (memq 'plain lk) '(org-activate-plain-links))
6070 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6071 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6072 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6073 (if (memq 'footnote lk) '(org-activate-footnote-links))
6074 ;; Targets.
6075 (list org-any-target-regexp '(0 'org-target t))
6076 ;; Diary sexps.
6077 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6078 ;; Macro
6079 '("{{{.+}}}" (0 'org-macro t))
6080 '(org-hide-wide-columns (0 nil append))
6081 ;; TODO keyword
6082 (list (format org-heading-keyword-regexp-format
6083 org-todo-regexp)
6084 '(2 (org-get-todo-face 2) t))
6085 ;; DONE
6086 (if org-fontify-done-headline
6087 (list (format org-heading-keyword-regexp-format
6088 (concat
6089 "\\(?:"
6090 (mapconcat 'regexp-quote org-done-keywords "\\|")
6091 "\\)"))
6092 '(2 'org-headline-done t))
6093 nil)
6094 ;; Priorities
6095 '(org-font-lock-add-priority-faces)
6096 ;; Tags
6097 '(org-font-lock-add-tag-faces)
6098 ;; Special keywords
6099 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6100 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6101 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6102 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6103 ;; Emphasis
6104 (if em
6105 (if (featurep 'xemacs)
6106 '(org-do-emphasis-faces (0 nil append))
6107 '(org-do-emphasis-faces)))
6108 ;; Checkboxes
6109 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6110 1 'org-checkbox prepend)
6111 (if (cdr (assq 'checkbox org-list-automatic-rules))
6112 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6113 (0 (org-get-checkbox-statistics-face) t)))
6114 ;; Description list items
6115 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6116 1 'org-list-dt prepend)
6117 ;; ARCHIVEd headings
6118 (list (concat
6119 org-outline-regexp-bol
6120 "\\(.*:" org-archive-tag ":.*\\)")
6121 '(1 'org-archived prepend))
6122 ;; Specials
6123 '(org-do-latex-and-related)
6124 '(org-fontify-entities)
6125 '(org-raise-scripts)
6126 ;; Code
6127 '(org-activate-code (1 'org-code t))
6128 ;; COMMENT
6129 (list (format org-heading-keyword-regexp-format
6130 (concat "\\("
6131 org-comment-string "\\|" org-quote-string
6132 "\\)"))
6133 '(2 'org-special-keyword t))
6134 ;; Blocks and meta lines
6135 '(org-fontify-meta-lines-and-blocks)
6137 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6138 (run-hooks 'org-font-lock-set-keywords-hook)
6139 ;; Now set the full font-lock-keywords
6140 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6141 (org-set-local 'font-lock-defaults
6142 '(org-font-lock-keywords t nil nil backward-paragraph))
6143 (kill-local-variable 'font-lock-keywords) nil))
6145 (defun org-toggle-pretty-entities ()
6146 "Toggle the composition display of entities as UTF8 characters."
6147 (interactive)
6148 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6149 (org-restart-font-lock)
6150 (if org-pretty-entities
6151 (message "Entities are displayed as UTF8 characters")
6152 (save-restriction
6153 (widen)
6154 (org-decompose-region (point-min) (point-max))
6155 (message "Entities are displayed plain"))))
6157 (defvar org-custom-properties-overlays nil
6158 "List of overlays used for custom properties.")
6159 (make-variable-buffer-local 'org-custom-properties-overlays)
6161 (defun org-toggle-custom-properties-visibility ()
6162 "Display or hide properties in `org-custom-properties'."
6163 (interactive)
6164 (if org-custom-properties-overlays
6165 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6166 (setq org-custom-properties-overlays nil))
6167 (unless (not org-custom-properties)
6168 (save-excursion
6169 (save-restriction
6170 (widen)
6171 (goto-char (point-min))
6172 (while (re-search-forward org-property-re nil t)
6173 (mapc (lambda(p)
6174 (when (equal p (substring (match-string 1) 1 -1))
6175 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6176 (overlay-put o 'invisible t)
6177 (overlay-put o 'org-custom-property t)
6178 (push o org-custom-properties-overlays))))
6179 org-custom-properties)))))))
6181 (defun org-fontify-entities (limit)
6182 "Find an entity to fontify."
6183 (let (ee)
6184 (when org-pretty-entities
6185 (catch 'match
6186 (while (re-search-forward
6187 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6188 limit t)
6189 (if (and (not (org-in-indented-comment-line))
6190 (setq ee (org-entity-get (match-string 1)))
6191 (= (length (nth 6 ee)) 1))
6192 (let*
6193 ((end (if (equal (match-string 2) "{}")
6194 (match-end 2)
6195 (match-end 1))))
6196 (add-text-properties
6197 (match-beginning 0) end
6198 (list 'font-lock-fontified t))
6199 (compose-region (match-beginning 0) end
6200 (nth 6 ee) nil)
6201 (backward-char 1)
6202 (throw 'match t))))
6203 nil))))
6205 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6206 "Fontify string S like in Org-mode."
6207 (with-temp-buffer
6208 (insert s)
6209 (let ((org-odd-levels-only odd-levels))
6210 (org-mode)
6211 (font-lock-fontify-buffer)
6212 (buffer-string))))
6214 (defvar org-m nil)
6215 (defvar org-l nil)
6216 (defvar org-f nil)
6217 (defun org-get-level-face (n)
6218 "Get the right face for match N in font-lock matching of headlines."
6219 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6220 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6221 (if org-cycle-level-faces
6222 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6223 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6224 (cond
6225 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6226 ((eq n 2) org-f)
6227 (t (if org-level-color-stars-only nil org-f))))
6230 (defun org-get-todo-face (kwd)
6231 "Get the right face for a TODO keyword KWD.
6232 If KWD is a number, get the corresponding match group."
6233 (if (numberp kwd) (setq kwd (match-string kwd)))
6234 (or (org-face-from-face-or-color
6235 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6236 (and (member kwd org-done-keywords) 'org-done)
6237 'org-todo))
6239 (defun org-face-from-face-or-color (context inherit face-or-color)
6240 "Create a face list that inherits INHERIT, but sets the foreground color.
6241 When FACE-OR-COLOR is not a string, just return it."
6242 (if (stringp face-or-color)
6243 (list :inherit inherit
6244 (cdr (assoc context org-faces-easy-properties))
6245 face-or-color)
6246 face-or-color))
6248 (defun org-font-lock-add-tag-faces (limit)
6249 "Add the special tag faces."
6250 (when (and org-tag-faces org-tags-special-faces-re)
6251 (while (re-search-forward org-tags-special-faces-re limit t)
6252 (add-text-properties (match-beginning 1) (match-end 1)
6253 (list 'face (org-get-tag-face 1)
6254 'font-lock-fontified t))
6255 (backward-char 1))))
6257 (defun org-font-lock-add-priority-faces (limit)
6258 "Add the special priority faces."
6259 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6260 (when (save-match-data (org-at-heading-p))
6261 (add-text-properties
6262 (match-beginning 0) (match-end 0)
6263 (list 'face (or (org-face-from-face-or-color
6264 'priority 'org-priority
6265 (cdr (assoc (char-after (match-beginning 1))
6266 org-priority-faces)))
6267 'org-priority)
6268 'font-lock-fontified t)))))
6270 (defun org-get-tag-face (kwd)
6271 "Get the right face for a TODO keyword KWD.
6272 If KWD is a number, get the corresponding match group."
6273 (if (numberp kwd) (setq kwd (match-string kwd)))
6274 (or (org-face-from-face-or-color
6275 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6276 'org-tag))
6278 (defun org-unfontify-region (beg end &optional maybe_loudly)
6279 "Remove fontification and activation overlays from links."
6280 (font-lock-default-unfontify-region beg end)
6281 (let* ((buffer-undo-list t)
6282 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6283 (inhibit-modification-hooks t)
6284 deactivate-mark buffer-file-name buffer-file-truename)
6285 (org-decompose-region beg end)
6286 (remove-text-properties beg end
6287 '(mouse-face t keymap t org-linked-text t
6288 invisible t intangible t
6289 org-no-flyspell t org-emphasis t))
6290 (org-remove-font-lock-display-properties beg end)))
6292 (defconst org-script-display '(((raise -0.3) (height 0.7))
6293 ((raise 0.3) (height 0.7))
6294 ((raise -0.5))
6295 ((raise 0.5)))
6296 "Display properties for showing superscripts and subscripts.")
6298 (defun org-remove-font-lock-display-properties (beg end)
6299 "Remove specific display properties that have been added by font lock.
6300 The will remove the raise properties that are used to show superscripts
6301 and subscripts."
6302 (let (next prop)
6303 (while (< beg end)
6304 (setq next (next-single-property-change beg 'display nil end)
6305 prop (get-text-property beg 'display))
6306 (if (member prop org-script-display)
6307 (put-text-property beg next 'display nil))
6308 (setq beg next))))
6310 (defun org-raise-scripts (limit)
6311 "Add raise properties to sub/superscripts."
6312 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6313 (if (re-search-forward
6314 (if (eq org-use-sub-superscripts t)
6315 org-match-substring-regexp
6316 org-match-substring-with-braces-regexp)
6317 limit t)
6318 (let* ((pos (point)) table-p comment-p
6319 (mpos (match-beginning 3))
6320 (emph-p (get-text-property mpos 'org-emphasis))
6321 (link-p (get-text-property mpos 'mouse-face))
6322 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6323 (goto-char (point-at-bol))
6324 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6325 comment-p (org-looking-at-p "[ \t]*#"))
6326 (goto-char pos)
6327 ;; FIXME: Should we go back one character here, for a_b^c
6328 ;; (goto-char (1- pos)) ;????????????????????
6329 (if (or comment-p emph-p link-p keyw-p)
6331 (put-text-property (match-beginning 3) (match-end 0)
6332 'display
6333 (if (equal (char-after (match-beginning 2)) ?^)
6334 (nth (if table-p 3 1) org-script-display)
6335 (nth (if table-p 2 0) org-script-display)))
6336 (add-text-properties (match-beginning 2) (match-end 2)
6337 (list 'invisible t
6338 'org-dwidth t 'org-dwidth-n 1))
6339 (if (and (eq (char-after (match-beginning 3)) ?{)
6340 (eq (char-before (match-end 3)) ?}))
6341 (progn
6342 (add-text-properties
6343 (match-beginning 3) (1+ (match-beginning 3))
6344 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6345 (add-text-properties
6346 (1- (match-end 3)) (match-end 3)
6347 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6348 t)))))
6350 ;;;; Visibility cycling, including org-goto and indirect buffer
6352 ;;; Cycling
6354 (defvar org-cycle-global-status nil)
6355 (make-variable-buffer-local 'org-cycle-global-status)
6356 (put 'org-cycle-global-status 'org-state t)
6357 (defvar org-cycle-subtree-status nil)
6358 (make-variable-buffer-local 'org-cycle-subtree-status)
6359 (put 'org-cycle-subtree-status 'org-state t)
6361 (defvar org-inlinetask-min-level)
6363 ;;;###autoload
6364 (defun org-cycle (&optional arg)
6365 "TAB-action and visibility cycling for Org-mode.
6367 This is the command invoked in Org-mode by the TAB key. Its main purpose
6368 is outline visibility cycling, but it also invokes other actions
6369 in special contexts.
6371 - When this function is called with a prefix argument, rotate the entire
6372 buffer through 3 states (global cycling)
6373 1. OVERVIEW: Show only top-level headlines.
6374 2. CONTENTS: Show all headlines of all levels, but no body text.
6375 3. SHOW ALL: Show everything.
6376 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6377 determined by the variable `org-startup-folded', and by any VISIBILITY
6378 properties in the buffer.
6379 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6380 including any drawers.
6382 - When inside a table, re-align the table and move to the next field.
6384 - When point is at the beginning of a headline, rotate the subtree started
6385 by this line through 3 different states (local cycling)
6386 1. FOLDED: Only the main headline is shown.
6387 2. CHILDREN: The main headline and the direct children are shown.
6388 From this state, you can move to one of the children
6389 and zoom in further.
6390 3. SUBTREE: Show the entire subtree, including body text.
6391 If there is no subtree, switch directly from CHILDREN to FOLDED.
6393 - When point is at the beginning of an empty headline and the variable
6394 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6395 of the headline by demoting and promoting it to likely levels. This
6396 speeds up creation document structure by pressing TAB once or several
6397 times right after creating a new headline.
6399 - When there is a numeric prefix, go up to a heading with level ARG, do
6400 a `show-subtree' and return to the previous cursor position. If ARG
6401 is negative, go up that many levels.
6403 - When point is not at the beginning of a headline, execute the global
6404 binding for TAB, which is re-indenting the line. See the option
6405 `org-cycle-emulate-tab' for details.
6407 - Special case: if point is at the beginning of the buffer and there is
6408 no headline in line 1, this function will act as if called with prefix arg
6409 (C-u TAB, same as S-TAB) also when called without prefix arg.
6410 But only if also the variable `org-cycle-global-at-bob' is t."
6411 (interactive "P")
6412 (org-load-modules-maybe)
6413 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6414 (and org-cycle-level-after-item/entry-creation
6415 (or (org-cycle-level)
6416 (org-cycle-item-indentation))))
6417 (let* (message-log-max ; Don't populate the *Messages* buffer
6418 (limit-level
6419 (or org-cycle-max-level
6420 (and (boundp 'org-inlinetask-min-level)
6421 org-inlinetask-min-level
6422 (1- org-inlinetask-min-level))))
6423 (nstars (and limit-level
6424 (if org-odd-levels-only
6425 (and limit-level (1- (* limit-level 2)))
6426 limit-level)))
6427 (org-outline-regexp
6428 (if (not (derived-mode-p 'org-mode))
6429 outline-regexp
6430 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6431 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6432 (not (looking-at org-outline-regexp))))
6433 (org-cycle-hook
6434 (if bob-special
6435 (delq 'org-optimize-window-after-visibility-change
6436 (copy-sequence org-cycle-hook))
6437 org-cycle-hook))
6438 (pos (point)))
6440 (if (or bob-special (equal arg '(4)))
6441 ;; special case: use global cycling
6442 (setq arg t))
6444 (cond
6446 ((equal arg '(16))
6447 (setq last-command 'dummy)
6448 (org-set-startup-visibility)
6449 (message "Startup visibility, plus VISIBILITY properties"))
6451 ((equal arg '(64))
6452 (show-all)
6453 (message "Entire buffer visible, including drawers"))
6455 ;; Table: enter it or move to the next field.
6456 ((org-at-table-p 'any)
6457 (if (org-at-table.el-p)
6458 (message "Use C-c ' to edit table.el tables")
6459 (if arg (org-table-edit-field t)
6460 (org-table-justify-field-maybe)
6461 (call-interactively 'org-table-next-field))))
6463 ((run-hook-with-args-until-success
6464 'org-tab-after-check-for-table-hook))
6466 ;; Global cycling: delegate to `org-cycle-internal-global'.
6467 ((eq arg t) (org-cycle-internal-global))
6469 ;; Drawers: delegate to `org-flag-drawer'.
6470 ((and org-drawers org-drawer-regexp
6471 (save-excursion
6472 (beginning-of-line 1)
6473 (looking-at org-drawer-regexp)))
6474 (org-flag-drawer ; toggle block visibility
6475 (not (get-char-property (match-end 0) 'invisible))))
6477 ;; Show-subtree, ARG levels up from here.
6478 ((integerp arg)
6479 (save-excursion
6480 (org-back-to-heading)
6481 (outline-up-heading (if (< arg 0) (- arg)
6482 (- (funcall outline-level) arg)))
6483 (org-show-subtree)))
6485 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6486 ((and (featurep 'org-inlinetask)
6487 (org-inlinetask-at-task-p)
6488 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6489 (org-inlinetask-toggle-visibility))
6491 ((org-try-cdlatex-tab))
6493 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6494 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6495 (save-excursion (beginning-of-line 1)
6496 (looking-at org-outline-regexp)))
6497 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6498 (org-cycle-internal-local))
6500 ;; From there: TAB emulation and template completion.
6501 (buffer-read-only (org-back-to-heading))
6503 ((run-hook-with-args-until-success
6504 'org-tab-after-check-for-cycling-hook))
6506 ((org-try-structure-completion))
6508 ((run-hook-with-args-until-success
6509 'org-tab-before-tab-emulation-hook))
6511 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6512 (or (not (bolp))
6513 (not (looking-at org-outline-regexp))))
6514 (call-interactively (global-key-binding "\t")))
6516 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6517 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6518 (or (and (eq org-cycle-emulate-tab 'white)
6519 (= (match-end 0) (point-at-eol)))
6520 (and (eq org-cycle-emulate-tab 'whitestart)
6521 (>= (match-end 0) pos))))
6523 (eq org-cycle-emulate-tab t))
6524 (call-interactively (global-key-binding "\t")))
6526 (t (save-excursion
6527 (org-back-to-heading)
6528 (org-cycle)))))))
6530 (defun org-cycle-internal-global ()
6531 "Do the global cycling action."
6532 ;; Hack to avoid display of messages for .org attachments in Gnus
6533 (let (message-log-max ; Don't populate the *Messages* buffer
6534 (ga (string-match "\\*fontification" (buffer-name))))
6535 (cond
6536 ((and (eq last-command this-command)
6537 (eq org-cycle-global-status 'overview))
6538 ;; We just created the overview - now do table of contents
6539 ;; This can be slow in very large buffers, so indicate action
6540 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6541 (unless ga (message "CONTENTS..."))
6542 (org-content)
6543 (unless ga (message "CONTENTS...done"))
6544 (setq org-cycle-global-status 'contents)
6545 (run-hook-with-args 'org-cycle-hook 'contents))
6547 ((and (eq last-command this-command)
6548 (eq org-cycle-global-status 'contents))
6549 ;; We just showed the table of contents - now show everything
6550 (run-hook-with-args 'org-pre-cycle-hook 'all)
6551 (show-all)
6552 (unless ga (message "SHOW ALL"))
6553 (setq org-cycle-global-status 'all)
6554 (run-hook-with-args 'org-cycle-hook 'all))
6557 ;; Default action: go to overview
6558 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6559 (org-overview)
6560 (unless ga (message "OVERVIEW"))
6561 (setq org-cycle-global-status 'overview)
6562 (run-hook-with-args 'org-cycle-hook 'overview)))))
6564 (defun org-cycle-internal-local ()
6565 "Do the local cycling action."
6566 (let (message-log-max ; Don't populate the *Messages* buffer
6567 (goal-column 0) eoh eol eos has-children children-skipped struct)
6568 ;; First, determine end of headline (EOH), end of subtree or item
6569 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6570 (save-excursion
6571 (if (org-at-item-p)
6572 (progn
6573 (beginning-of-line)
6574 (setq struct (org-list-struct))
6575 (setq eoh (point-at-eol))
6576 (setq eos (org-list-get-item-end-before-blank (point) struct))
6577 (setq has-children (org-list-has-child-p (point) struct)))
6578 (org-back-to-heading)
6579 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6580 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6581 (setq has-children
6582 (or (save-excursion
6583 (let ((level (funcall outline-level)))
6584 (outline-next-heading)
6585 (and (org-at-heading-p t)
6586 (> (funcall outline-level) level))))
6587 (save-excursion
6588 (org-list-search-forward (org-item-beginning-re) eos t)))))
6589 ;; Determine end invisible part of buffer (EOL)
6590 (beginning-of-line 2)
6591 ;; XEmacs doesn't have `next-single-char-property-change'
6592 (if (featurep 'xemacs)
6593 (while (and (not (eobp)) ;; this is like `next-line'
6594 (get-char-property (1- (point)) 'invisible))
6595 (beginning-of-line 2))
6596 (while (and (not (eobp)) ;; this is like `next-line'
6597 (get-char-property (1- (point)) 'invisible))
6598 (goto-char (next-single-char-property-change (point) 'invisible))
6599 (and (eolp) (beginning-of-line 2))))
6600 (setq eol (point)))
6601 ;; Find out what to do next and set `this-command'
6602 (cond
6603 ((= eos eoh)
6604 ;; Nothing is hidden behind this heading
6605 (unless (org-before-first-heading-p)
6606 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6607 (message "EMPTY ENTRY")
6608 (setq org-cycle-subtree-status nil)
6609 (save-excursion
6610 (goto-char eos)
6611 (outline-next-heading)
6612 (if (outline-invisible-p) (org-flag-heading nil))))
6613 ((and (or (>= eol eos)
6614 (not (string-match "\\S-" (buffer-substring eol eos))))
6615 (or has-children
6616 (not (setq children-skipped
6617 org-cycle-skip-children-state-if-no-children))))
6618 ;; Entire subtree is hidden in one line: children view
6619 (unless (org-before-first-heading-p)
6620 (run-hook-with-args 'org-pre-cycle-hook 'children))
6621 (if (org-at-item-p)
6622 (org-list-set-item-visibility (point-at-bol) struct 'children)
6623 (org-show-entry)
6624 (org-with-limited-levels (show-children))
6625 ;; FIXME: This slows down the func way too much.
6626 ;; How keep drawers hidden in subtree anyway?
6627 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6628 ;; (org-cycle-hide-drawers 'subtree))
6630 ;; Fold every list in subtree to top-level items.
6631 (when (eq org-cycle-include-plain-lists 'integrate)
6632 (save-excursion
6633 (org-back-to-heading)
6634 (while (org-list-search-forward (org-item-beginning-re) eos t)
6635 (beginning-of-line 1)
6636 (let* ((struct (org-list-struct))
6637 (prevs (org-list-prevs-alist struct))
6638 (end (org-list-get-bottom-point struct)))
6639 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6640 (org-list-get-all-items (point) struct prevs))
6641 (goto-char end))))))
6642 (message "CHILDREN")
6643 (save-excursion
6644 (goto-char eos)
6645 (outline-next-heading)
6646 (if (outline-invisible-p) (org-flag-heading nil)))
6647 (setq org-cycle-subtree-status 'children)
6648 (unless (org-before-first-heading-p)
6649 (run-hook-with-args 'org-cycle-hook 'children)))
6650 ((or children-skipped
6651 (and (eq last-command this-command)
6652 (eq org-cycle-subtree-status 'children)))
6653 ;; We just showed the children, or no children are there,
6654 ;; now show everything.
6655 (unless (org-before-first-heading-p)
6656 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6657 (outline-flag-region eoh eos nil)
6658 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6659 (setq org-cycle-subtree-status 'subtree)
6660 (unless (org-before-first-heading-p)
6661 (run-hook-with-args 'org-cycle-hook 'subtree)))
6663 ;; Default action: hide the subtree.
6664 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6665 (outline-flag-region eoh eos t)
6666 (message "FOLDED")
6667 (setq org-cycle-subtree-status 'folded)
6668 (unless (org-before-first-heading-p)
6669 (run-hook-with-args 'org-cycle-hook 'folded))))))
6671 ;;;###autoload
6672 (defun org-global-cycle (&optional arg)
6673 "Cycle the global visibility. For details see `org-cycle'.
6674 With \\[universal-argument] prefix arg, switch to startup visibility.
6675 With a numeric prefix, show all headlines up to that level."
6676 (interactive "P")
6677 (let ((org-cycle-include-plain-lists
6678 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6679 (cond
6680 ((integerp arg)
6681 (show-all)
6682 (hide-sublevels arg)
6683 (setq org-cycle-global-status 'contents))
6684 ((equal arg '(4))
6685 (org-set-startup-visibility)
6686 (message "Startup visibility, plus VISIBILITY properties."))
6688 (org-cycle '(4))))))
6690 (defun org-set-startup-visibility ()
6691 "Set the visibility required by startup options and properties."
6692 (cond
6693 ((eq org-startup-folded t)
6694 (org-cycle '(4)))
6695 ((eq org-startup-folded 'content)
6696 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6697 (org-cycle '(4)) (org-cycle '(4)))))
6698 (unless (eq org-startup-folded 'showeverything)
6699 (if org-hide-block-startup (org-hide-block-all))
6700 (org-set-visibility-according-to-property 'no-cleanup)
6701 (org-cycle-hide-archived-subtrees 'all)
6702 (org-cycle-hide-drawers 'all)
6703 (org-cycle-show-empty-lines t)))
6705 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6706 "Switch subtree visibilities according to :VISIBILITY: property."
6707 (interactive)
6708 (let (org-show-entry-below state)
6709 (save-excursion
6710 (goto-char (point-min))
6711 (while (re-search-forward
6712 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6713 nil t)
6714 (setq state (match-string 1))
6715 (save-excursion
6716 (org-back-to-heading t)
6717 (hide-subtree)
6718 (org-reveal)
6719 (cond
6720 ((equal state '("fold" "folded"))
6721 (hide-subtree))
6722 ((equal state "children")
6723 (org-show-hidden-entry)
6724 (show-children))
6725 ((equal state "content")
6726 (save-excursion
6727 (save-restriction
6728 (org-narrow-to-subtree)
6729 (org-content))))
6730 ((member state '("all" "showall"))
6731 (show-subtree)))))
6732 (unless no-cleanup
6733 (org-cycle-hide-archived-subtrees 'all)
6734 (org-cycle-hide-drawers 'all)
6735 (org-cycle-show-empty-lines 'all)))))
6737 ;; This function uses outline-regexp instead of the more fundamental
6738 ;; org-outline-regexp so that org-cycle-global works outside of Org
6739 ;; buffers, where outline-regexp is needed.
6740 (defun org-overview ()
6741 "Switch to overview mode, showing only top-level headlines.
6742 Really, this shows all headlines with level equal or greater than the level
6743 of the first headline in the buffer. This is important, because if the
6744 first headline is not level one, then (hide-sublevels 1) gives confusing
6745 results."
6746 (interactive)
6747 (let ((l (org-current-line))
6748 (level (save-excursion
6749 (goto-char (point-min))
6750 (if (re-search-forward (concat "^" outline-regexp) nil t)
6751 (progn
6752 (goto-char (match-beginning 0))
6753 (funcall outline-level))))))
6754 (and level (hide-sublevels level))
6755 (recenter '(4))
6756 (org-goto-line l)))
6758 (defun org-content (&optional arg)
6759 "Show all headlines in the buffer, like a table of contents.
6760 With numerical argument N, show content up to level N."
6761 (interactive "P")
6762 (save-excursion
6763 ;; Visit all headings and show their offspring
6764 (and (integerp arg) (org-overview))
6765 (goto-char (point-max))
6766 (catch 'exit
6767 (while (and (progn (condition-case nil
6768 (outline-previous-visible-heading 1)
6769 (error (goto-char (point-min))))
6771 (looking-at org-outline-regexp))
6772 (if (integerp arg)
6773 (show-children (1- arg))
6774 (show-branches))
6775 (if (bobp) (throw 'exit nil))))))
6778 (defun org-optimize-window-after-visibility-change (state)
6779 "Adjust the window after a change in outline visibility.
6780 This function is the default value of the hook `org-cycle-hook'."
6781 (when (get-buffer-window (current-buffer))
6782 (cond
6783 ((eq state 'content) nil)
6784 ((eq state 'all) nil)
6785 ((eq state 'folded) nil)
6786 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6787 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6789 (defun org-remove-empty-overlays-at (pos)
6790 "Remove outline overlays that do not contain non-white stuff."
6791 (mapc
6792 (lambda (o)
6793 (and (eq 'outline (overlay-get o 'invisible))
6794 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6795 (overlay-end o))))
6796 (delete-overlay o)))
6797 (overlays-at pos)))
6799 (defun org-clean-visibility-after-subtree-move ()
6800 "Fix visibility issues after moving a subtree."
6801 ;; First, find a reasonable region to look at:
6802 ;; Start two siblings above, end three below
6803 (let* ((beg (save-excursion
6804 (and (org-get-last-sibling)
6805 (org-get-last-sibling))
6806 (point)))
6807 (end (save-excursion
6808 (and (org-get-next-sibling)
6809 (org-get-next-sibling)
6810 (org-get-next-sibling))
6811 (if (org-at-heading-p)
6812 (point-at-eol)
6813 (point))))
6814 (level (looking-at "\\*+"))
6815 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6816 (save-excursion
6817 (save-restriction
6818 (narrow-to-region beg end)
6819 (when re
6820 ;; Properly fold already folded siblings
6821 (goto-char (point-min))
6822 (while (re-search-forward re nil t)
6823 (if (and (not (outline-invisible-p))
6824 (save-excursion
6825 (goto-char (point-at-eol)) (outline-invisible-p)))
6826 (hide-entry))))
6827 (org-cycle-show-empty-lines 'overview)
6828 (org-cycle-hide-drawers 'overview)))))
6830 (defun org-cycle-show-empty-lines (state)
6831 "Show empty lines above all visible headlines.
6832 The region to be covered depends on STATE when called through
6833 `org-cycle-hook'. Lisp program can use t for STATE to get the
6834 entire buffer covered. Note that an empty line is only shown if there
6835 are at least `org-cycle-separator-lines' empty lines before the headline."
6836 (when (not (= org-cycle-separator-lines 0))
6837 (save-excursion
6838 (let* ((n (abs org-cycle-separator-lines))
6839 (re (cond
6840 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6841 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6842 (t (let ((ns (number-to-string (- n 2))))
6843 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6844 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6845 beg end b e)
6846 (cond
6847 ((memq state '(overview contents t))
6848 (setq beg (point-min) end (point-max)))
6849 ((memq state '(children folded))
6850 (setq beg (point) end (progn (org-end-of-subtree t t)
6851 (beginning-of-line 2)
6852 (point)))))
6853 (when beg
6854 (goto-char beg)
6855 (while (re-search-forward re end t)
6856 (unless (get-char-property (match-end 1) 'invisible)
6857 (setq e (match-end 1))
6858 (if (< org-cycle-separator-lines 0)
6859 (setq b (save-excursion
6860 (goto-char (match-beginning 0))
6861 (org-back-over-empty-lines)
6862 (if (save-excursion
6863 (goto-char (max (point-min) (1- (point))))
6864 (org-at-heading-p))
6865 (1- (point))
6866 (point))))
6867 (setq b (match-beginning 1)))
6868 (outline-flag-region b e nil)))))))
6869 ;; Never hide empty lines at the end of the file.
6870 (save-excursion
6871 (goto-char (point-max))
6872 (outline-previous-heading)
6873 (outline-end-of-heading)
6874 (if (and (looking-at "[ \t\n]+")
6875 (= (match-end 0) (point-max)))
6876 (outline-flag-region (point) (match-end 0) nil))))
6878 (defun org-show-empty-lines-in-parent ()
6879 "Move to the parent and re-show empty lines before visible headlines."
6880 (save-excursion
6881 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6882 (org-cycle-show-empty-lines context))))
6884 (defun org-files-list ()
6885 "Return `org-agenda-files' list, plus all open org-mode files.
6886 This is useful for operations that need to scan all of a user's
6887 open and agenda-wise Org files."
6888 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6889 (dolist (buf (buffer-list))
6890 (with-current-buffer buf
6891 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6892 (let ((file (expand-file-name (buffer-file-name))))
6893 (unless (member file files)
6894 (push file files))))))
6895 files))
6897 (defsubst org-entry-beginning-position ()
6898 "Return the beginning position of the current entry."
6899 (save-excursion (outline-back-to-heading t) (point)))
6901 (defsubst org-entry-end-position ()
6902 "Return the end position of the current entry."
6903 (save-excursion (outline-next-heading) (point)))
6905 (defun org-cycle-hide-drawers (state)
6906 "Re-hide all drawers after a visibility state change."
6907 (when (and (derived-mode-p 'org-mode)
6908 (not (memq state '(overview folded contents))))
6909 (save-excursion
6910 (let* ((globalp (memq state '(contents all)))
6911 (beg (if globalp (point-min) (point)))
6912 (end (if globalp (point-max)
6913 (if (eq state 'children)
6914 (save-excursion (outline-next-heading) (point))
6915 (org-end-of-subtree t)))))
6916 (goto-char beg)
6917 (while (re-search-forward org-drawer-regexp end t)
6918 (org-flag-drawer t))))))
6920 (defun org-cycle-hide-inline-tasks (state)
6921 "Re-hide inline task when switching to 'contents visibility state."
6922 (when (and (eq state 'contents)
6923 (boundp 'org-inlinetask-min-level)
6924 org-inlinetask-min-level)
6925 (hide-sublevels (1- org-inlinetask-min-level))))
6927 (defun org-flag-drawer (flag)
6928 "When FLAG is non-nil, hide the drawer we are within.
6929 Otherwise make it visible."
6930 (save-excursion
6931 (beginning-of-line 1)
6932 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6933 (let ((b (match-end 0)))
6934 (if (re-search-forward
6935 "^[ \t]*:END:"
6936 (save-excursion (outline-next-heading) (point)) t)
6937 (outline-flag-region b (point-at-eol) flag)
6938 (error ":END: line missing at position %s" b))))))
6940 (defun org-subtree-end-visible-p ()
6941 "Is the end of the current subtree visible?"
6942 (pos-visible-in-window-p
6943 (save-excursion (org-end-of-subtree t) (point))))
6945 (defun org-first-headline-recenter (&optional N)
6946 "Move cursor to the first headline and recenter the headline.
6947 Optional argument N means put the headline into the Nth line of the window."
6948 (goto-char (point-min))
6949 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6950 (beginning-of-line)
6951 (recenter (prefix-numeric-value N))))
6953 ;;; Saving and restoring visibility
6955 (defun org-outline-overlay-data (&optional use-markers)
6956 "Return a list of the locations of all outline overlays.
6957 These are overlays with the `invisible' property value `outline'.
6958 The return value is a list of cons cells, with start and stop
6959 positions for each overlay.
6960 If USE-MARKERS is set, return the positions as markers."
6961 (let (beg end)
6962 (save-excursion
6963 (save-restriction
6964 (widen)
6965 (delq nil
6966 (mapcar (lambda (o)
6967 (when (eq (overlay-get o 'invisible) 'outline)
6968 (setq beg (overlay-start o)
6969 end (overlay-end o))
6970 (and beg end (> end beg)
6971 (if use-markers
6972 (cons (move-marker (make-marker) beg)
6973 (move-marker (make-marker) end))
6974 (cons beg end)))))
6975 (overlays-in (point-min) (point-max))))))))
6977 (defun org-set-outline-overlay-data (data)
6978 "Create visibility overlays for all positions in DATA.
6979 DATA should have been made by `org-outline-overlay-data'."
6980 (let (o)
6981 (save-excursion
6982 (save-restriction
6983 (widen)
6984 (show-all)
6985 (mapc (lambda (c)
6986 (outline-flag-region (car c) (cdr c) t))
6987 data)))))
6989 ;;; Folding of blocks
6991 (defvar org-hide-block-overlays nil
6992 "Overlays hiding blocks.")
6993 (make-variable-buffer-local 'org-hide-block-overlays)
6995 (defun org-block-map (function &optional start end)
6996 "Call FUNCTION at the head of all source blocks in the current buffer.
6997 Optional arguments START and END can be used to limit the range."
6998 (let ((start (or start (point-min)))
6999 (end (or end (point-max))))
7000 (save-excursion
7001 (goto-char start)
7002 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7003 (save-excursion
7004 (save-match-data
7005 (goto-char (match-beginning 0))
7006 (funcall function)))))))
7008 (defun org-hide-block-toggle-all ()
7009 "Toggle the visibility of all blocks in the current buffer."
7010 (org-block-map #'org-hide-block-toggle))
7012 (defun org-hide-block-all ()
7013 "Fold all blocks in the current buffer."
7014 (interactive)
7015 (org-show-block-all)
7016 (org-block-map #'org-hide-block-toggle-maybe))
7018 (defun org-show-block-all ()
7019 "Unfold all blocks in the current buffer."
7020 (interactive)
7021 (mapc 'delete-overlay org-hide-block-overlays)
7022 (setq org-hide-block-overlays nil))
7024 (defun org-hide-block-toggle-maybe ()
7025 "Toggle visibility of block at point."
7026 (interactive)
7027 (let ((case-fold-search t))
7028 (if (save-excursion
7029 (beginning-of-line 1)
7030 (looking-at org-block-regexp))
7031 (progn (org-hide-block-toggle)
7032 t) ;; to signal that we took action
7033 nil))) ;; to signal that we did not
7035 (defun org-hide-block-toggle (&optional force)
7036 "Toggle the visibility of the current block."
7037 (interactive)
7038 (save-excursion
7039 (beginning-of-line)
7040 (if (re-search-forward org-block-regexp nil t)
7041 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7042 (end (match-end 0)) ;; end of entire body
7044 (if (memq t (mapcar (lambda (overlay)
7045 (eq (overlay-get overlay 'invisible)
7046 'org-hide-block))
7047 (overlays-at start)))
7048 (if (or (not force) (eq force 'off))
7049 (mapc (lambda (ov)
7050 (when (member ov org-hide-block-overlays)
7051 (setq org-hide-block-overlays
7052 (delq ov org-hide-block-overlays)))
7053 (when (eq (overlay-get ov 'invisible)
7054 'org-hide-block)
7055 (delete-overlay ov)))
7056 (overlays-at start)))
7057 (setq ov (make-overlay start end))
7058 (overlay-put ov 'invisible 'org-hide-block)
7059 ;; make the block accessible to isearch
7060 (overlay-put
7061 ov 'isearch-open-invisible
7062 (lambda (ov)
7063 (when (member ov org-hide-block-overlays)
7064 (setq org-hide-block-overlays
7065 (delq ov org-hide-block-overlays)))
7066 (when (eq (overlay-get ov 'invisible)
7067 'org-hide-block)
7068 (delete-overlay ov))))
7069 (push ov org-hide-block-overlays)))
7070 (error "Not looking at a source block"))))
7072 ;; org-tab-after-check-for-cycling-hook
7073 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7074 ;; Remove overlays when changing major mode
7075 (add-hook 'org-mode-hook
7076 (lambda () (org-add-hook 'change-major-mode-hook
7077 'org-show-block-all 'append 'local)))
7079 ;;; Org-goto
7081 (defvar org-goto-window-configuration nil)
7082 (defvar org-goto-marker nil)
7083 (defvar org-goto-map)
7084 (defun org-goto-map ()
7085 "Set the keymap `org-goto'."
7086 (setq org-goto-map
7087 (let ((map (make-sparse-keymap)))
7088 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7089 mouse-drag-region universal-argument org-occur))
7090 cmd)
7091 (while (setq cmd (pop cmds))
7092 (substitute-key-definition cmd cmd map global-map)))
7093 (suppress-keymap map)
7094 (org-defkey map "\C-m" 'org-goto-ret)
7095 (org-defkey map [(return)] 'org-goto-ret)
7096 (org-defkey map [(left)] 'org-goto-left)
7097 (org-defkey map [(right)] 'org-goto-right)
7098 (org-defkey map [(control ?g)] 'org-goto-quit)
7099 (org-defkey map "\C-i" 'org-cycle)
7100 (org-defkey map [(tab)] 'org-cycle)
7101 (org-defkey map [(down)] 'outline-next-visible-heading)
7102 (org-defkey map [(up)] 'outline-previous-visible-heading)
7103 (if org-goto-auto-isearch
7104 (if (fboundp 'define-key-after)
7105 (define-key-after map [t] 'org-goto-local-auto-isearch)
7106 nil)
7107 (org-defkey map "q" 'org-goto-quit)
7108 (org-defkey map "n" 'outline-next-visible-heading)
7109 (org-defkey map "p" 'outline-previous-visible-heading)
7110 (org-defkey map "f" 'outline-forward-same-level)
7111 (org-defkey map "b" 'outline-backward-same-level)
7112 (org-defkey map "u" 'outline-up-heading))
7113 (org-defkey map "/" 'org-occur)
7114 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7115 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7116 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7117 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7118 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7119 map)))
7121 (defconst org-goto-help
7122 "Browse buffer copy, to find location or copy text.%s
7123 RET=jump to location C-g=quit and return to previous location
7124 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7126 (defvar org-goto-start-pos) ; dynamically scoped parameter
7128 ;; FIXME: Docstring does not mention both interfaces
7129 (defun org-goto (&optional alternative-interface)
7130 "Look up a different location in the current file, keeping current visibility.
7132 When you want look-up or go to a different location in a
7133 document, the fastest way is often to fold the entire buffer and
7134 then dive into the tree. This method has the disadvantage, that
7135 the previous location will be folded, which may not be what you
7136 want.
7138 This command works around this by showing a copy of the current
7139 buffer in an indirect buffer, in overview mode. You can dive
7140 into the tree in that copy, use org-occur and incremental search
7141 to find a location. When pressing RET or `Q', the command
7142 returns to the original buffer in which the visibility is still
7143 unchanged. After RET it will also jump to the location selected
7144 in the indirect buffer and expose the headline hierarchy above.
7146 With a prefix argument, use the alternative interface: e.g. if
7147 `org-goto-interface' is 'outline use 'outline-path-completion."
7148 (interactive "P")
7149 (org-goto-map)
7150 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7151 (org-refile-use-outline-path t)
7152 (org-refile-target-verify-function nil)
7153 (interface
7154 (if (not alternative-interface)
7155 org-goto-interface
7156 (if (eq org-goto-interface 'outline)
7157 'outline-path-completion
7158 'outline)))
7159 (org-goto-start-pos (point))
7160 (selected-point
7161 (if (eq interface 'outline)
7162 (car (org-get-location (current-buffer) org-goto-help))
7163 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7164 (org-refile-check-position pa)
7165 (nth 3 pa)))))
7166 (if selected-point
7167 (progn
7168 (org-mark-ring-push org-goto-start-pos)
7169 (goto-char selected-point)
7170 (if (or (outline-invisible-p) (org-invisible-p2))
7171 (org-show-context 'org-goto)))
7172 (message "Quit"))))
7174 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7175 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7176 (defvar org-goto-local-auto-isearch-map) ; defined below
7178 (defun org-get-location (buf help)
7179 "Let the user select a location in the Org-mode buffer BUF.
7180 This function uses a recursive edit. It returns the selected position
7181 or nil."
7182 (org-no-popups
7183 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7184 (isearch-hide-immediately nil)
7185 (isearch-search-fun-function
7186 (lambda () 'org-goto-local-search-headings))
7187 (org-goto-selected-point org-goto-exit-command))
7188 (save-excursion
7189 (save-window-excursion
7190 (delete-other-windows)
7191 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7192 (org-pop-to-buffer-same-window
7193 (condition-case nil
7194 (make-indirect-buffer (current-buffer) "*org-goto*")
7195 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7196 (with-output-to-temp-buffer "*Org Help*"
7197 (princ (format help (if org-goto-auto-isearch
7198 " Just type for auto-isearch."
7199 " n/p/f/b/u to navigate, q to quit."))))
7200 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7201 (setq buffer-read-only nil)
7202 (let ((org-startup-truncated t)
7203 (org-startup-folded nil)
7204 (org-startup-align-all-tables nil))
7205 (org-mode)
7206 (org-overview))
7207 (setq buffer-read-only t)
7208 (if (and (boundp 'org-goto-start-pos)
7209 (integer-or-marker-p org-goto-start-pos))
7210 (let ((org-show-hierarchy-above t)
7211 (org-show-siblings t)
7212 (org-show-following-heading t))
7213 (goto-char org-goto-start-pos)
7214 (and (outline-invisible-p) (org-show-context)))
7215 (goto-char (point-min)))
7216 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7217 (message "Select location and press RET")
7218 (use-local-map org-goto-map)
7219 (recursive-edit)))
7220 (kill-buffer "*org-goto*")
7221 (cons org-goto-selected-point org-goto-exit-command))))
7223 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7224 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7225 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7226 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7228 (defun org-goto-local-search-headings (string bound noerror)
7229 "Search and make sure that any matches are in headlines."
7230 (catch 'return
7231 (while (if isearch-forward
7232 (search-forward string bound noerror)
7233 (search-backward string bound noerror))
7234 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7235 (and (member :headline context)
7236 (not (member :tags context))))
7237 (throw 'return (point))))))
7239 (defun org-goto-local-auto-isearch ()
7240 "Start isearch."
7241 (interactive)
7242 (goto-char (point-min))
7243 (let ((keys (this-command-keys)))
7244 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7245 (isearch-mode t)
7246 (isearch-process-search-char (string-to-char keys)))))
7248 (defun org-goto-ret (&optional arg)
7249 "Finish `org-goto' by going to the new location."
7250 (interactive "P")
7251 (setq org-goto-selected-point (point)
7252 org-goto-exit-command 'return)
7253 (throw 'exit nil))
7255 (defun org-goto-left ()
7256 "Finish `org-goto' by going to the new location."
7257 (interactive)
7258 (if (org-at-heading-p)
7259 (progn
7260 (beginning-of-line 1)
7261 (setq org-goto-selected-point (point)
7262 org-goto-exit-command 'left)
7263 (throw 'exit nil))
7264 (error "Not on a heading")))
7266 (defun org-goto-right ()
7267 "Finish `org-goto' by going to the new location."
7268 (interactive)
7269 (if (org-at-heading-p)
7270 (progn
7271 (setq org-goto-selected-point (point)
7272 org-goto-exit-command 'right)
7273 (throw 'exit nil))
7274 (error "Not on a heading")))
7276 (defun org-goto-quit ()
7277 "Finish `org-goto' without cursor motion."
7278 (interactive)
7279 (setq org-goto-selected-point nil)
7280 (setq org-goto-exit-command 'quit)
7281 (throw 'exit nil))
7283 ;;; Indirect buffer display of subtrees
7285 (defvar org-indirect-dedicated-frame nil
7286 "This is the frame being used for indirect tree display.")
7287 (defvar org-last-indirect-buffer nil)
7289 (defun org-tree-to-indirect-buffer (&optional arg)
7290 "Create indirect buffer and narrow it to current subtree.
7291 With a numerical prefix ARG, go up to this level and then take that tree.
7292 If ARG is negative, go up that many levels.
7294 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7295 indirect buffer previously made with this command, to avoid proliferation of
7296 indirect buffers. However, when you call the command with a \
7297 \\[universal-argument] prefix, or
7298 when `org-indirect-buffer-display' is `new-frame', the last buffer
7299 is kept so that you can work with several indirect buffers at the same time.
7300 If `org-indirect-buffer-display' is `dedicated-frame', the \
7301 \\[universal-argument] prefix also
7302 requests that a new frame be made for the new buffer, so that the dedicated
7303 frame is not changed."
7304 (interactive "P")
7305 (let ((cbuf (current-buffer))
7306 (cwin (selected-window))
7307 (pos (point))
7308 beg end level heading ibuf)
7309 (save-excursion
7310 (org-back-to-heading t)
7311 (when (numberp arg)
7312 (setq level (org-outline-level))
7313 (if (< arg 0) (setq arg (+ level arg)))
7314 (while (> (setq level (org-outline-level)) arg)
7315 (org-up-heading-safe)))
7316 (setq beg (point)
7317 heading (org-get-heading))
7318 (org-end-of-subtree t t)
7319 (if (org-at-heading-p) (backward-char 1))
7320 (setq end (point)))
7321 (if (and (buffer-live-p org-last-indirect-buffer)
7322 (not (eq org-indirect-buffer-display 'new-frame))
7323 (not arg))
7324 (kill-buffer org-last-indirect-buffer))
7325 (setq ibuf (org-get-indirect-buffer cbuf)
7326 org-last-indirect-buffer ibuf)
7327 (cond
7328 ((or (eq org-indirect-buffer-display 'new-frame)
7329 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7330 (select-frame (make-frame))
7331 (delete-other-windows)
7332 (org-pop-to-buffer-same-window ibuf)
7333 (org-set-frame-title heading))
7334 ((eq org-indirect-buffer-display 'dedicated-frame)
7335 (raise-frame
7336 (select-frame (or (and org-indirect-dedicated-frame
7337 (frame-live-p org-indirect-dedicated-frame)
7338 org-indirect-dedicated-frame)
7339 (setq org-indirect-dedicated-frame (make-frame)))))
7340 (delete-other-windows)
7341 (org-pop-to-buffer-same-window ibuf)
7342 (org-set-frame-title (concat "Indirect: " heading)))
7343 ((eq org-indirect-buffer-display 'current-window)
7344 (org-pop-to-buffer-same-window ibuf))
7345 ((eq org-indirect-buffer-display 'other-window)
7346 (pop-to-buffer ibuf))
7347 (t (error "Invalid value")))
7348 (if (featurep 'xemacs)
7349 (save-excursion (org-mode) (turn-on-font-lock)))
7350 (narrow-to-region beg end)
7351 (show-all)
7352 (goto-char pos)
7353 (run-hook-with-args 'org-cycle-hook 'all)
7354 (and (window-live-p cwin) (select-window cwin))))
7356 (defun org-get-indirect-buffer (&optional buffer)
7357 (setq buffer (or buffer (current-buffer)))
7358 (let ((n 1) (base (buffer-name buffer)) bname)
7359 (while (buffer-live-p
7360 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7361 (setq n (1+ n)))
7362 (condition-case nil
7363 (make-indirect-buffer buffer bname 'clone)
7364 (error (make-indirect-buffer buffer bname)))))
7366 (defun org-set-frame-title (title)
7367 "Set the title of the current frame to the string TITLE."
7368 ;; FIXME: how to name a single frame in XEmacs???
7369 (unless (featurep 'xemacs)
7370 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7372 ;;;; Structure editing
7374 ;;; Inserting headlines
7376 (defun org-previous-line-empty-p (&optional next)
7377 "Is the previous line a blank line?
7378 When NEXT is non-nil, check the next line instead."
7379 (save-excursion
7380 (and (not (bobp))
7381 (or (beginning-of-line (if next 2 0)) t)
7382 (save-match-data
7383 (looking-at "[ \t]*$")))))
7385 (defun org-insert-heading (&optional arg invisible-ok)
7386 "Insert a new heading or item with same depth at point.
7387 If point is in a plain list and ARG is nil, create a new list item.
7388 With one universal prefix argument, insert a heading even in lists.
7389 With two universal prefix arguments, insert the heading at the end
7390 of the parent subtree.
7392 If point is at the beginning of a headline, insert a sibling before
7393 the current headline. If point is not at the beginning, split the line
7394 and create a new headline with the text in the current line after point
7395 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7397 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7398 This is important for non-interactive uses of the command."
7399 (interactive "P")
7400 (cond
7401 ((or (= (buffer-size) 0)
7402 (and (not (save-excursion
7403 (and (ignore-errors (org-back-to-heading invisible-ok))
7404 (org-at-heading-p))))
7405 (or arg (not (org-in-item-p)))))
7406 (insert
7407 (if (org-previous-line-empty-p) "" "\n")
7408 (if (org-in-src-block-p) ",* " "* "))
7409 (run-hooks 'org-insert-heading-hook))
7410 ((or arg (not (org-insert-item
7411 (save-excursion
7412 (beginning-of-line)
7413 (looking-at org-list-full-item-re)
7414 (match-string 3)))))
7415 (let (begn endn)
7416 (when (org-buffer-narrowed-p)
7417 (setq begn (point-min) endn (point-max))
7418 (widen))
7419 (let* ((empty-line-p nil)
7420 (eops (equal arg '(16))) ; insert at end of parent subtree
7421 (org-insert-heading-respect-content
7422 (or (not (null arg)) org-insert-heading-respect-content))
7423 (level nil)
7424 (on-heading (org-at-heading-p))
7425 (head (save-excursion
7426 (condition-case nil
7427 (progn
7428 (org-back-to-heading invisible-ok)
7429 (when (and (not on-heading)
7430 (featurep 'org-inlinetask)
7431 (integerp org-inlinetask-min-level)
7432 (>= (length (match-string 0))
7433 org-inlinetask-min-level))
7434 ;; Find a heading level before the inline task
7435 (while (and (setq level (org-up-heading-safe))
7436 (>= level org-inlinetask-min-level)))
7437 (if (org-at-heading-p)
7438 (org-back-to-heading invisible-ok)
7439 (error "This should not happen")))
7440 (unless (and (save-excursion
7441 (save-match-data
7442 (org-backward-heading-same-level 1 invisible-ok))
7443 (= (point) (match-beginning 0)))
7444 (not (org-previous-line-empty-p t)))
7445 (setq empty-line-p (org-previous-line-empty-p)))
7446 (match-string 0))
7447 (error "* "))))
7448 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7449 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7450 pos hide-previous previous-pos)
7451 (if ;; At the beginning of a heading, open a new line for insertiong
7452 (and (bolp) (org-at-heading-p)
7453 (not eops)
7454 (or (bobp)
7455 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7456 (open-line (if blank 2 1))
7457 (save-excursion
7458 (setq previous-pos (point-at-bol))
7459 (end-of-line)
7460 (setq hide-previous (outline-invisible-p)))
7461 (and org-insert-heading-respect-content
7462 (save-excursion
7463 (while (outline-invisible-p)
7464 (org-show-subtree)
7465 (org-up-heading-safe))))
7466 (let ((split
7467 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7468 (save-excursion
7469 (let ((p (point)))
7470 (goto-char (point-at-bol))
7471 (and (looking-at org-complex-heading-regexp)
7472 (match-beginning 4)
7473 (> p (match-beginning 4)))))))
7474 tags pos)
7475 (cond
7476 ;; Insert a new line, possibly at end of parent subtree
7477 (org-insert-heading-respect-content
7478 (if (not eops)
7479 (progn
7480 (org-end-of-subtree nil t)
7481 (and (looking-at "^\\*") (backward-char 1))
7482 (while (and (not (bobp))
7483 ;; Don't delete spaces in empty headlines
7484 (not (looking-back org-outline-regexp))
7485 (member (char-before) '(?\ ?\t ?\n)))
7486 (backward-delete-char 1)))
7487 (let ((p (point)))
7488 (org-up-heading-safe)
7489 (if (= p (point))
7490 (goto-char (point-max))
7491 (org-end-of-subtree nil t))))
7492 (when (featurep 'org-inlinetask)
7493 (while (and (not (eobp))
7494 (looking-at "\\(\\*+\\)[ \t]+")
7495 (>= (length (match-string 1))
7496 org-inlinetask-min-level))
7497 (org-end-of-subtree nil t)))
7498 (or (bolp) (newline))
7499 (or (org-previous-line-empty-p)
7500 (and blank (newline)))
7501 (if (or empty-line-p eops) (open-line 1)))
7502 ;; Insert a headling containing text after point
7503 ((org-at-heading-p)
7504 (when hide-previous
7505 (show-children)
7506 (org-show-entry))
7507 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7508 (setq tags (and (match-end 2) (match-string 2)))
7509 (and (match-end 1)
7510 (delete-region (match-beginning 1) (match-end 1)))
7511 (setq pos (point-at-bol))
7512 (or split (end-of-line 1))
7513 (delete-horizontal-space)
7514 (if (string-match "\\`\\*+\\'"
7515 (buffer-substring (point-at-bol) (point)))
7516 (insert " "))
7517 (newline (if blank 2 1))
7518 (when tags
7519 (save-excursion
7520 (goto-char pos)
7521 (end-of-line 1)
7522 (insert " " tags)
7523 (org-set-tags nil 'align))))
7525 (or split (end-of-line 1))
7526 (newline (if blank 2 1))))))
7527 (insert head) (just-one-space)
7528 (setq pos (point))
7529 (end-of-line 1)
7530 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7531 (when (and org-insert-heading-respect-content hide-previous)
7532 (save-excursion
7533 (goto-char previous-pos)
7534 (hide-subtree)))
7535 (when (and begn endn)
7536 (narrow-to-region (min (point) begn) (max (point) endn)))
7537 (run-hooks 'org-insert-heading-hook))))))
7539 (defun org-get-heading (&optional no-tags no-todo)
7540 "Return the heading of the current entry, without the stars.
7541 When NO-TAGS is non-nil, don't include tags.
7542 When NO-TODO is non-nil, don't include TODO keywords."
7543 (save-excursion
7544 (org-back-to-heading t)
7545 (cond
7546 ((and no-tags no-todo)
7547 (looking-at org-complex-heading-regexp)
7548 (match-string 4))
7549 (no-tags
7550 (looking-at (concat org-outline-regexp
7551 "\\(.*?\\)"
7552 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7553 (match-string 1))
7554 (no-todo
7555 (looking-at org-todo-line-regexp)
7556 (match-string 3))
7557 (t (looking-at org-heading-regexp)
7558 (match-string 2)))))
7560 (defvar orgstruct-mode) ; defined below
7562 (defun org-heading-components ()
7563 "Return the components of the current heading.
7564 This is a list with the following elements:
7565 - the level as an integer
7566 - the reduced level, different if `org-odd-levels-only' is set.
7567 - the TODO keyword, or nil
7568 - the priority character, like ?A, or nil if no priority is given
7569 - the headline text itself, or the tags string if no headline text
7570 - the tags string, or nil."
7571 (save-excursion
7572 (org-back-to-heading t)
7573 (if (let (case-fold-search)
7574 (looking-at
7575 (if orgstruct-mode
7576 org-heading-regexp
7577 org-complex-heading-regexp)))
7578 (if orgstruct-mode
7579 (list (length (match-string 1))
7580 (org-reduced-level (length (match-string 1)))
7583 (match-string 2)
7584 nil)
7585 (list (length (match-string 1))
7586 (org-reduced-level (length (match-string 1)))
7587 (org-match-string-no-properties 2)
7588 (and (match-end 3) (aref (match-string 3) 2))
7589 (org-match-string-no-properties 4)
7590 (org-match-string-no-properties 5))))))
7592 (defun org-get-entry ()
7593 "Get the entry text, after heading, entire subtree."
7594 (save-excursion
7595 (org-back-to-heading t)
7596 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7598 (defun org-insert-heading-after-current ()
7599 "Insert a new heading with same level as current, after current subtree."
7600 (interactive)
7601 (org-back-to-heading)
7602 (org-insert-heading)
7603 (org-move-subtree-down)
7604 (end-of-line 1))
7606 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7607 "Insert heading with `org-insert-heading-respect-content' set to t."
7608 (interactive "P")
7609 (let ((org-insert-heading-respect-content t))
7610 (org-insert-heading arg invisible-ok)))
7612 (defun org-insert-todo-heading-respect-content (&optional force-state)
7613 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7614 (interactive "P")
7615 (let ((org-insert-heading-respect-content t))
7616 (org-insert-todo-heading force-state t)))
7618 (defun org-insert-todo-heading (arg &optional force-heading)
7619 "Insert a new heading with the same level and TODO state as current heading.
7620 If the heading has no TODO state, or if the state is DONE, use the first
7621 state (TODO by default). Also one prefix arg, force first state. With two
7622 prefix args, force inserting at the end of the parent subtree."
7623 (interactive "P")
7624 (when (or force-heading (not (org-insert-item 'checkbox)))
7625 (org-insert-heading (or (and (equal arg '(16)) '(16))
7626 force-heading))
7627 (save-excursion
7628 (org-back-to-heading)
7629 (outline-previous-heading)
7630 (looking-at org-todo-line-regexp))
7631 (let*
7632 ((new-mark-x
7633 (if (or arg
7634 (not (match-beginning 2))
7635 (member (match-string 2) org-done-keywords))
7636 (car org-todo-keywords-1)
7637 (match-string 2)))
7638 (new-mark
7640 (run-hook-with-args-until-success
7641 'org-todo-get-default-hook new-mark-x nil)
7642 new-mark-x)))
7643 (beginning-of-line 1)
7644 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7645 (if org-treat-insert-todo-heading-as-state-change
7646 (org-todo new-mark)
7647 (insert new-mark " "))))
7648 (when org-provide-todo-statistics
7649 (org-update-parent-todo-statistics))))
7651 (defun org-insert-subheading (arg)
7652 "Insert a new subheading and demote it.
7653 Works for outline headings and for plain lists alike."
7654 (interactive "P")
7655 (org-insert-heading arg)
7656 (cond
7657 ((org-at-heading-p) (org-do-demote))
7658 ((org-at-item-p) (org-indent-item))))
7660 (defun org-insert-todo-subheading (arg)
7661 "Insert a new subheading with TODO keyword or checkbox and demote it.
7662 Works for outline headings and for plain lists alike."
7663 (interactive "P")
7664 (org-insert-todo-heading arg)
7665 (cond
7666 ((org-at-heading-p) (org-do-demote))
7667 ((org-at-item-p) (org-indent-item))))
7669 ;;; Promotion and Demotion
7671 (defvar org-after-demote-entry-hook nil
7672 "Hook run after an entry has been demoted.
7673 The cursor will be at the beginning of the entry.
7674 When a subtree is being demoted, the hook will be called for each node.")
7676 (defvar org-after-promote-entry-hook nil
7677 "Hook run after an entry has been promoted.
7678 The cursor will be at the beginning of the entry.
7679 When a subtree is being promoted, the hook will be called for each node.")
7681 (defun org-promote-subtree ()
7682 "Promote the entire subtree.
7683 See also `org-promote'."
7684 (interactive)
7685 (save-excursion
7686 (org-with-limited-levels (org-map-tree 'org-promote)))
7687 (org-fix-position-after-promote))
7689 (defun org-demote-subtree ()
7690 "Demote the entire subtree. See `org-demote'.
7691 See also `org-promote'."
7692 (interactive)
7693 (save-excursion
7694 (org-with-limited-levels (org-map-tree 'org-demote)))
7695 (org-fix-position-after-promote))
7698 (defun org-do-promote ()
7699 "Promote the current heading higher up the tree.
7700 If the region is active in `transient-mark-mode', promote all headings
7701 in the region."
7702 (interactive)
7703 (save-excursion
7704 (if (org-region-active-p)
7705 (org-map-region 'org-promote (region-beginning) (region-end))
7706 (org-promote)))
7707 (org-fix-position-after-promote))
7709 (defun org-do-demote ()
7710 "Demote the current heading lower down the tree.
7711 If the region is active in `transient-mark-mode', demote all headings
7712 in the region."
7713 (interactive)
7714 (save-excursion
7715 (if (org-region-active-p)
7716 (org-map-region 'org-demote (region-beginning) (region-end))
7717 (org-demote)))
7718 (org-fix-position-after-promote))
7720 (defun org-fix-position-after-promote ()
7721 "Make sure that after pro/demotion cursor position is right."
7722 (let ((pos (point)))
7723 (when (save-excursion
7724 (beginning-of-line 1)
7725 (looking-at org-todo-line-regexp)
7726 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7727 (cond ((eobp) (insert " "))
7728 ((eolp) (insert " "))
7729 ((equal (char-after) ?\ ) (forward-char 1))))))
7731 (defun org-current-level ()
7732 "Return the level of the current entry, or nil if before the first headline.
7733 The level is the number of stars at the beginning of the headline."
7734 (save-excursion
7735 (org-with-limited-levels
7736 (if (ignore-errors (org-back-to-heading t))
7737 (funcall outline-level)))))
7739 (defun org-get-previous-line-level ()
7740 "Return the outline depth of the last headline before the current line.
7741 Returns 0 for the first headline in the buffer, and nil if before the
7742 first headline."
7743 (let ((current-level (org-current-level))
7744 (prev-level (when (> (line-number-at-pos) 1)
7745 (save-excursion
7746 (beginning-of-line 0)
7747 (org-current-level)))))
7748 (cond ((null current-level) nil) ; Before first headline
7749 ((null prev-level) 0) ; At first headline
7750 (prev-level))))
7752 (defun org-reduced-level (l)
7753 "Compute the effective level of a heading.
7754 This takes into account the setting of `org-odd-levels-only'."
7755 (cond
7756 ((zerop l) 0)
7757 (org-odd-levels-only (1+ (floor (/ l 2))))
7758 (t l)))
7760 (defun org-level-increment ()
7761 "Return the number of stars that will be added or removed at a
7762 time to headlines when structure editing, based on the value of
7763 `org-odd-levels-only'."
7764 (if org-odd-levels-only 2 1))
7766 (defun org-get-valid-level (level &optional change)
7767 "Rectify a level change under the influence of `org-odd-levels-only'
7768 LEVEL is a current level, CHANGE is by how much the level should be
7769 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7770 even level numbers will become the next higher odd number."
7771 (if org-odd-levels-only
7772 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7773 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7774 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7775 (max 1 (+ level (or change 0)))))
7777 (if (boundp 'define-obsolete-function-alias)
7778 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7779 (define-obsolete-function-alias 'org-get-legal-level
7780 'org-get-valid-level)
7781 (define-obsolete-function-alias 'org-get-legal-level
7782 'org-get-valid-level "23.1")))
7784 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7785 ;; ̀org-with-limited-levels'
7786 (defun org-promote ()
7787 "Promote the current heading higher up the tree.
7788 If the region is active in `transient-mark-mode', promote all headings
7789 in the region."
7790 (org-back-to-heading t)
7791 (let* ((level (save-match-data (funcall outline-level)))
7792 (after-change-functions (remove 'flyspell-after-change-function
7793 after-change-functions))
7794 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7795 (diff (abs (- level (length up-head) -1))))
7796 (cond ((and (= level 1) org-called-with-limited-levels
7797 org-allow-promoting-top-level-subtree)
7798 (replace-match "# " nil t))
7799 ((= level 1)
7800 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7801 (t (replace-match up-head nil t)))
7802 ;; Fixup tag positioning
7803 (unless (= level 1)
7804 (and org-auto-align-tags (org-set-tags nil t))
7805 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7806 (run-hooks 'org-after-promote-entry-hook)))
7808 (defun org-demote ()
7809 "Demote the current heading lower down the tree.
7810 If the region is active in `transient-mark-mode', demote all headings
7811 in the region."
7812 (org-back-to-heading t)
7813 (let* ((level (save-match-data (funcall outline-level)))
7814 (after-change-functions (remove 'flyspell-after-change-function
7815 after-change-functions))
7816 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7817 (diff (abs (- level (length down-head) -1))))
7818 (replace-match down-head nil t)
7819 ;; Fixup tag positioning
7820 (and org-auto-align-tags (org-set-tags nil t))
7821 (if org-adapt-indentation (org-fixup-indentation diff))
7822 (run-hooks 'org-after-demote-entry-hook)))
7824 (defun org-cycle-level ()
7825 "Cycle the level of an empty headline through possible states.
7826 This goes first to child, then to parent, level, then up the hierarchy.
7827 After top level, it switches back to sibling level."
7828 (interactive)
7829 (let ((org-adapt-indentation nil))
7830 (when (org-point-at-end-of-empty-headline)
7831 (setq this-command 'org-cycle-level) ; Only needed for caching
7832 (let ((cur-level (org-current-level))
7833 (prev-level (org-get-previous-line-level)))
7834 (cond
7835 ;; If first headline in file, promote to top-level.
7836 ((= prev-level 0)
7837 (loop repeat (/ (- cur-level 1) (org-level-increment))
7838 do (org-do-promote)))
7839 ;; If same level as prev, demote one.
7840 ((= prev-level cur-level)
7841 (org-do-demote))
7842 ;; If parent is top-level, promote to top level if not already.
7843 ((= prev-level 1)
7844 (loop repeat (/ (- cur-level 1) (org-level-increment))
7845 do (org-do-promote)))
7846 ;; If top-level, return to prev-level.
7847 ((= cur-level 1)
7848 (loop repeat (/ (- prev-level 1) (org-level-increment))
7849 do (org-do-demote)))
7850 ;; If less than prev-level, promote one.
7851 ((< cur-level prev-level)
7852 (org-do-promote))
7853 ;; If deeper than prev-level, promote until higher than
7854 ;; prev-level.
7855 ((> cur-level prev-level)
7856 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7857 do (org-do-promote))))
7858 t))))
7860 (defun org-map-tree (fun)
7861 "Call FUN for every heading underneath the current one."
7862 (org-back-to-heading)
7863 (let ((level (funcall outline-level)))
7864 (save-excursion
7865 (funcall fun)
7866 (while (and (progn
7867 (outline-next-heading)
7868 (> (funcall outline-level) level))
7869 (not (eobp)))
7870 (funcall fun)))))
7872 (defun org-map-region (fun beg end)
7873 "Call FUN for every heading between BEG and END."
7874 (let ((org-ignore-region t))
7875 (save-excursion
7876 (setq end (copy-marker end))
7877 (goto-char beg)
7878 (if (and (re-search-forward org-outline-regexp-bol nil t)
7879 (< (point) end))
7880 (funcall fun))
7881 (while (and (progn
7882 (outline-next-heading)
7883 (< (point) end))
7884 (not (eobp)))
7885 (funcall fun)))))
7887 (defvar org-property-end-re) ; silence byte-compiler
7888 (defun org-fixup-indentation (diff)
7889 "Change the indentation in the current entry by DIFF.
7890 However, if any line in the current entry has no indentation, or if it
7891 would end up with no indentation after the change, nothing at all is done."
7892 (save-excursion
7893 (let ((end (save-excursion (outline-next-heading)
7894 (point-marker)))
7895 (prohibit (if (> diff 0)
7896 "^\\S-"
7897 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7898 col)
7899 (unless (save-excursion (end-of-line 1)
7900 (re-search-forward prohibit end t))
7901 (while (and (< (point) end)
7902 (re-search-forward "^[ \t]+" end t))
7903 (goto-char (match-end 0))
7904 (setq col (current-column))
7905 (if (< diff 0) (replace-match ""))
7906 (org-indent-to-column (+ diff col))))
7907 (move-marker end nil))))
7909 (defun org-convert-to-odd-levels ()
7910 "Convert an org-mode file with all levels allowed to one with odd levels.
7911 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7912 level 5 etc."
7913 (interactive)
7914 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7915 (let ((outline-level 'org-outline-level)
7916 (org-odd-levels-only nil) n)
7917 (save-excursion
7918 (goto-char (point-min))
7919 (while (re-search-forward "^\\*\\*+ " nil t)
7920 (setq n (- (length (match-string 0)) 2))
7921 (while (>= (setq n (1- n)) 0)
7922 (org-demote))
7923 (end-of-line 1))))))
7925 (defun org-convert-to-oddeven-levels ()
7926 "Convert an org-mode file with only odd levels to one with odd/even levels.
7927 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7928 file contains a section with an even level, conversion would
7929 destroy the structure of the file. An error is signaled in this
7930 case."
7931 (interactive)
7932 (goto-char (point-min))
7933 ;; First check if there are no even levels
7934 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7935 (org-show-context t)
7936 (error "Not all levels are odd in this file. Conversion not possible"))
7937 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7938 (let ((outline-regexp org-outline-regexp)
7939 (outline-level 'org-outline-level)
7940 (org-odd-levels-only nil) n)
7941 (save-excursion
7942 (goto-char (point-min))
7943 (while (re-search-forward "^\\*\\*+ " nil t)
7944 (setq n (/ (1- (length (match-string 0))) 2))
7945 (while (>= (setq n (1- n)) 0)
7946 (org-promote))
7947 (end-of-line 1))))))
7949 (defun org-tr-level (n)
7950 "Make N odd if required."
7951 (if org-odd-levels-only (1+ (/ n 2)) n))
7953 ;;; Vertical tree motion, cutting and pasting of subtrees
7955 (defun org-move-subtree-up (&optional arg)
7956 "Move the current subtree up past ARG headlines of the same level."
7957 (interactive "p")
7958 (org-move-subtree-down (- (prefix-numeric-value arg))))
7960 (defun org-move-subtree-down (&optional arg)
7961 "Move the current subtree down past ARG headlines of the same level."
7962 (interactive "p")
7963 (setq arg (prefix-numeric-value arg))
7964 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7965 'org-get-last-sibling))
7966 (ins-point (make-marker))
7967 (cnt (abs arg))
7968 (col (current-column))
7969 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7970 ;; Select the tree
7971 (org-back-to-heading)
7972 (setq beg0 (point))
7973 (save-excursion
7974 (setq ne-beg (org-back-over-empty-lines))
7975 (setq beg (point)))
7976 (save-match-data
7977 (save-excursion (outline-end-of-heading)
7978 (setq folded (outline-invisible-p)))
7979 (outline-end-of-subtree))
7980 (outline-next-heading)
7981 (setq ne-end (org-back-over-empty-lines))
7982 (setq end (point))
7983 (goto-char beg0)
7984 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7985 ;; include less whitespace
7986 (save-excursion
7987 (goto-char beg)
7988 (forward-line (- ne-beg ne-end))
7989 (setq beg (point))))
7990 ;; Find insertion point, with error handling
7991 (while (> cnt 0)
7992 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7993 (progn (goto-char beg0)
7994 (user-error "Cannot move past superior level or buffer limit")))
7995 (setq cnt (1- cnt)))
7996 (if (> arg 0)
7997 ;; Moving forward - still need to move over subtree
7998 (progn (org-end-of-subtree t t)
7999 (save-excursion
8000 (org-back-over-empty-lines)
8001 (or (bolp) (newline)))))
8002 (setq ne-ins (org-back-over-empty-lines))
8003 (move-marker ins-point (point))
8004 (setq txt (buffer-substring beg end))
8005 (org-save-markers-in-region beg end)
8006 (delete-region beg end)
8007 (org-remove-empty-overlays-at beg)
8008 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8009 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8010 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8011 (let ((bbb (point)))
8012 (insert-before-markers txt)
8013 (org-reinstall-markers-in-region bbb)
8014 (move-marker ins-point bbb))
8015 (or (bolp) (insert "\n"))
8016 (setq ins-end (point))
8017 (goto-char ins-point)
8018 (org-skip-whitespace)
8019 (when (and (< arg 0)
8020 (org-first-sibling-p)
8021 (> ne-ins ne-beg))
8022 ;; Move whitespace back to beginning
8023 (save-excursion
8024 (goto-char ins-end)
8025 (let ((kill-whole-line t))
8026 (kill-line (- ne-ins ne-beg)) (point)))
8027 (insert (make-string (- ne-ins ne-beg) ?\n)))
8028 (move-marker ins-point nil)
8029 (if folded
8030 (hide-subtree)
8031 (org-show-entry)
8032 (show-children)
8033 (org-cycle-hide-drawers 'children))
8034 (org-clean-visibility-after-subtree-move)
8035 ;; move back to the initial column we were at
8036 (move-to-column col)))
8038 (defvar org-subtree-clip ""
8039 "Clipboard for cut and paste of subtrees.
8040 This is actually only a copy of the kill, because we use the normal kill
8041 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8043 (defvar org-subtree-clip-folded nil
8044 "Was the last copied subtree folded?
8045 This is used to fold the tree back after pasting.")
8047 (defun org-cut-subtree (&optional n)
8048 "Cut the current subtree into the clipboard.
8049 With prefix arg N, cut this many sequential subtrees.
8050 This is a short-hand for marking the subtree and then cutting it."
8051 (interactive "p")
8052 (org-copy-subtree n 'cut))
8054 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8055 "Cut the current subtree into the clipboard.
8056 With prefix arg N, cut this many sequential subtrees.
8057 This is a short-hand for marking the subtree and then copying it.
8058 If CUT is non-nil, actually cut the subtree.
8059 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8060 of some markers in the region, even if CUT is non-nil. This is
8061 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8062 (interactive "p")
8063 (let (beg end folded (beg0 (point)))
8064 (if (org-called-interactively-p 'any)
8065 (org-back-to-heading nil) ; take what looks like a subtree
8066 (org-back-to-heading t)) ; take what is really there
8067 (setq beg (point))
8068 (skip-chars-forward " \t\r\n")
8069 (save-match-data
8070 (if nosubtrees
8071 (outline-next-heading)
8072 (save-excursion (outline-end-of-heading)
8073 (setq folded (outline-invisible-p)))
8074 (condition-case nil
8075 (org-forward-heading-same-level (1- n) t)
8076 (error nil))
8077 (org-end-of-subtree t t)))
8078 (setq end (point))
8079 (goto-char beg0)
8080 (when (> end beg)
8081 (setq org-subtree-clip-folded folded)
8082 (when (or cut force-store-markers)
8083 (org-save-markers-in-region beg end))
8084 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8085 (setq org-subtree-clip (current-kill 0))
8086 (message "%s: Subtree(s) with %d characters"
8087 (if cut "Cut" "Copied")
8088 (length org-subtree-clip)))))
8090 (defun org-paste-subtree (&optional level tree for-yank)
8091 "Paste the clipboard as a subtree, with modification of headline level.
8092 The entire subtree is promoted or demoted in order to match a new headline
8093 level.
8095 If the cursor is at the beginning of a headline, the same level as
8096 that headline is used to paste the tree.
8098 If not, the new level is derived from the *visible* headings
8099 before and after the insertion point, and taken to be the inferior headline
8100 level of the two. So if the previous visible heading is level 3 and the
8101 next is level 4 (or vice versa), level 4 will be used for insertion.
8102 This makes sure that the subtree remains an independent subtree and does
8103 not swallow low level entries.
8105 You can also force a different level, either by using a numeric prefix
8106 argument, or by inserting the heading marker by hand. For example, if the
8107 cursor is after \"*****\", then the tree will be shifted to level 5.
8109 If optional TREE is given, use this text instead of the kill ring.
8111 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8112 move back over whitespace before inserting, and move point to the end of
8113 the inserted text when done."
8114 (interactive "P")
8115 (setq tree (or tree (and kill-ring (current-kill 0))))
8116 (unless (org-kill-is-subtree-p tree)
8117 (error "%s"
8118 (substitute-command-keys
8119 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8120 (org-with-limited-levels
8121 (let* ((visp (not (outline-invisible-p)))
8122 (txt tree)
8123 (^re_ "\\(\\*+\\)[ \t]*")
8124 (old-level (if (string-match org-outline-regexp-bol txt)
8125 (- (match-end 0) (match-beginning 0) 1)
8126 -1))
8127 (force-level (cond (level (prefix-numeric-value level))
8128 ((and (looking-at "[ \t]*$")
8129 (string-match
8130 "^\\*+$" (buffer-substring
8131 (point-at-bol) (point))))
8132 (- (match-end 1) (match-beginning 1)))
8133 ((and (bolp)
8134 (looking-at org-outline-regexp))
8135 (- (match-end 0) (point) 1))))
8136 (previous-level (save-excursion
8137 (condition-case nil
8138 (progn
8139 (outline-previous-visible-heading 1)
8140 (if (looking-at ^re_)
8141 (- (match-end 0) (match-beginning 0) 1)
8143 (error 1))))
8144 (next-level (save-excursion
8145 (condition-case nil
8146 (progn
8147 (or (looking-at org-outline-regexp)
8148 (outline-next-visible-heading 1))
8149 (if (looking-at ^re_)
8150 (- (match-end 0) (match-beginning 0) 1)
8152 (error 1))))
8153 (new-level (or force-level (max previous-level next-level)))
8154 (shift (if (or (= old-level -1)
8155 (= new-level -1)
8156 (= old-level new-level))
8158 (- new-level old-level)))
8159 (delta (if (> shift 0) -1 1))
8160 (func (if (> shift 0) 'org-demote 'org-promote))
8161 (org-odd-levels-only nil)
8162 beg end newend)
8163 ;; Remove the forced level indicator
8164 (if force-level
8165 (delete-region (point-at-bol) (point)))
8166 ;; Paste
8167 (beginning-of-line (if (bolp) 1 2))
8168 (setq beg (point))
8169 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8170 (insert-before-markers txt)
8171 (unless (string-match "\n\\'" txt) (insert "\n"))
8172 (setq newend (point))
8173 (org-reinstall-markers-in-region beg)
8174 (setq end (point))
8175 (goto-char beg)
8176 (skip-chars-forward " \t\n\r")
8177 (setq beg (point))
8178 (if (and (outline-invisible-p) visp)
8179 (save-excursion (outline-show-heading)))
8180 ;; Shift if necessary
8181 (unless (= shift 0)
8182 (save-restriction
8183 (narrow-to-region beg end)
8184 (while (not (= shift 0))
8185 (org-map-region func (point-min) (point-max))
8186 (setq shift (+ delta shift)))
8187 (goto-char (point-min))
8188 (setq newend (point-max))))
8189 (when (or (org-called-interactively-p 'interactive) for-yank)
8190 (message "Clipboard pasted as level %d subtree" new-level))
8191 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8192 kill-ring
8193 (eq org-subtree-clip (current-kill 0))
8194 org-subtree-clip-folded)
8195 ;; The tree was folded before it was killed/copied
8196 (hide-subtree))
8197 (and for-yank (goto-char newend)))))
8199 (defun org-kill-is-subtree-p (&optional txt)
8200 "Check if the current kill is an outline subtree, or a set of trees.
8201 Returns nil if kill does not start with a headline, or if the first
8202 headline level is not the largest headline level in the tree.
8203 So this will actually accept several entries of equal levels as well,
8204 which is OK for `org-paste-subtree'.
8205 If optional TXT is given, check this string instead of the current kill."
8206 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8207 (re (org-get-limited-outline-regexp))
8208 (^re (concat "^" re))
8209 (start-level (and kill
8210 (string-match
8211 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8212 kill)
8213 (- (match-end 2) (match-beginning 2) 1)))
8214 (start (1+ (or (match-beginning 2) -1))))
8215 (if (not start-level)
8216 (progn
8217 nil) ;; does not even start with a heading
8218 (catch 'exit
8219 (while (setq start (string-match ^re kill (1+ start)))
8220 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8221 (throw 'exit nil)))
8222 t))))
8224 (defvar org-markers-to-move nil
8225 "Markers that should be moved with a cut-and-paste operation.
8226 Those markers are stored together with their positions relative to
8227 the start of the region.")
8229 (defun org-save-markers-in-region (beg end)
8230 "Check markers in region.
8231 If these markers are between BEG and END, record their position relative
8232 to BEG, so that after moving the block of text, we can put the markers back
8233 into place.
8234 This function gets called just before an entry or tree gets cut from the
8235 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8236 called immediately, to move the markers with the entries."
8237 (setq org-markers-to-move nil)
8238 (when (featurep 'org-clock)
8239 (org-clock-save-markers-for-cut-and-paste beg end))
8240 (when (featurep 'org-agenda)
8241 (org-agenda-save-markers-for-cut-and-paste beg end)))
8243 (defun org-check-and-save-marker (marker beg end)
8244 "Check if MARKER is between BEG and END.
8245 If yes, remember the marker and the distance to BEG."
8246 (when (and (marker-buffer marker)
8247 (equal (marker-buffer marker) (current-buffer)))
8248 (if (and (>= marker beg) (< marker end))
8249 (push (cons marker (- marker beg)) org-markers-to-move))))
8251 (defun org-reinstall-markers-in-region (beg)
8252 "Move all remembered markers to their position relative to BEG."
8253 (mapc (lambda (x)
8254 (move-marker (car x) (+ beg (cdr x))))
8255 org-markers-to-move)
8256 (setq org-markers-to-move nil))
8258 (defun org-narrow-to-subtree ()
8259 "Narrow buffer to the current subtree."
8260 (interactive)
8261 (save-excursion
8262 (save-match-data
8263 (org-with-limited-levels
8264 (narrow-to-region
8265 (progn (org-back-to-heading t) (point))
8266 (progn (org-end-of-subtree t t)
8267 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8268 (point)))))))
8270 (defun org-narrow-to-block ()
8271 "Narrow buffer to the current block."
8272 (interactive)
8273 (let* ((case-fold-search t)
8274 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8275 "^[ \t]*#\\+end_.*")))
8276 (if blockp
8277 (narrow-to-region (car blockp) (cdr blockp))
8278 (error "Not in a block"))))
8280 (eval-when-compile
8281 (defvar org-property-drawer-re))
8283 (defvar org-property-start-re) ;; defined below
8284 (defun org-clone-subtree-with-time-shift (n &optional shift)
8285 "Clone the task (subtree) at point N times.
8286 The clones will be inserted as siblings.
8288 In interactive use, the user will be prompted for the number of
8289 clones to be produced. When called with a universal prefix argument
8290 and if the entry has a timestamp, the user will also be prompted for
8291 a time shift, which may be a repeater as used in time stamps, for
8292 example `+3d'.
8294 When a valid repeater is given and the entry contains any time
8295 stamps, the clones will become a sequence in time, with time
8296 stamps in the subtree shifted for each clone produced. If SHIFT
8297 is nil or the empty string, time stamps will be left alone. The
8298 ID property of the original subtree is removed.
8300 If the original subtree did contain time stamps with a repeater,
8301 the following will happen:
8302 - the repeater will be removed in each clone
8303 - an additional clone will be produced, with the current, unshifted
8304 date(s) in the entry.
8305 - the original entry will be placed *after* all the clones, with
8306 repeater intact.
8307 - the start days in the repeater in the original entry will be shifted
8308 to past the last clone.
8309 In this way you can spell out a number of instances of a repeating task,
8310 and still retain the repeater to cover future instances of the task."
8311 (interactive "nNumber of clones to produce: ")
8312 (let ((shift
8313 (or shift
8314 (if (and (equal current-prefix-arg '(4))
8315 (save-excursion
8316 (re-search-forward org-ts-regexp-both
8317 (save-excursion
8318 (org-end-of-subtree t)
8319 (point)) t)))
8320 (read-from-minibuffer
8321 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8322 ""))) ;; No time shift
8323 (n-no-remove -1)
8324 (drawer-re org-drawer-regexp)
8325 beg end template task idprop
8326 shift-n shift-what doshift nmin nmax)
8327 (if (not (and (integerp n) (> n 0)))
8328 (error "Invalid number of replications %s" n))
8329 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8330 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8331 shift)))
8332 (error "Invalid shift specification %s" shift))
8333 (when doshift
8334 (setq shift-n (string-to-number (match-string 1 shift))
8335 shift-what (cdr (assoc (match-string 2 shift)
8336 '(("d" . day) ("w" . week)
8337 ("m" . month) ("y" . year))))))
8338 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8339 (setq nmin 1 nmax n)
8340 (org-back-to-heading t)
8341 (setq beg (point))
8342 (setq idprop (org-entry-get nil "ID"))
8343 (org-end-of-subtree t t)
8344 (or (bolp) (insert "\n"))
8345 (setq end (point))
8346 (setq template (buffer-substring beg end))
8347 (when (and doshift
8348 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8349 (delete-region beg end)
8350 (setq end beg)
8351 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8352 (goto-char end)
8353 (loop for n from nmin to nmax do
8354 ;; prepare clone
8355 (with-temp-buffer
8356 (insert template)
8357 (org-mode)
8358 (goto-char (point-min))
8359 (org-show-subtree)
8360 (and idprop (if org-clone-delete-id
8361 (org-entry-delete nil "ID")
8362 (org-id-get-create t)))
8363 (unless (= n 0)
8364 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8365 (kill-whole-line))
8366 (goto-char (point-min))
8367 (while (re-search-forward drawer-re nil t)
8368 (mapc (lambda (d)
8369 (org-remove-empty-drawer-at d (point))) org-drawers)))
8370 (goto-char (point-min))
8371 (when doshift
8372 (while (re-search-forward org-ts-regexp-both nil t)
8373 (org-timestamp-change (* n shift-n) shift-what))
8374 (unless (= n n-no-remove)
8375 (goto-char (point-min))
8376 (while (re-search-forward org-ts-regexp nil t)
8377 (save-excursion
8378 (goto-char (match-beginning 0))
8379 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8380 (delete-region (match-beginning 1) (match-end 1)))))))
8381 (setq task (buffer-string)))
8382 (insert task))
8383 (goto-char beg)))
8385 ;;; Outline Sorting
8387 (defun org-sort (with-case)
8388 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8389 Optional argument WITH-CASE means sort case-sensitively."
8390 (interactive "P")
8391 (cond
8392 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8393 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8395 (org-call-with-arg 'org-sort-entries with-case))))
8397 (defun org-sort-remove-invisible (s)
8398 "Remove invisible links from string S."
8399 (remove-text-properties 0 (length s) org-rm-props s)
8400 (while (string-match org-bracket-link-regexp s)
8401 (setq s (replace-match (if (match-end 2)
8402 (match-string 3 s)
8403 (match-string 1 s)) t t s)))
8404 (let ((st (format " %s " s)))
8405 (while (string-match org-emph-re st)
8406 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8407 (setq s (substring st 1 -1)))
8410 (defvar org-priority-regexp) ; defined later in the file
8412 (defvar org-after-sorting-entries-or-items-hook nil
8413 "Hook that is run after a bunch of entries or items have been sorted.
8414 When children are sorted, the cursor is in the parent line when this
8415 hook gets called. When a region or a plain list is sorted, the cursor
8416 will be in the first entry of the sorted region/list.")
8418 (defun org-sort-entries
8419 (&optional with-case sorting-type getkey-func compare-func property)
8420 "Sort entries on a certain level of an outline tree.
8421 If there is an active region, the entries in the region are sorted.
8422 Else, if the cursor is before the first entry, sort the top-level items.
8423 Else, the children of the entry at point are sorted.
8425 Sorting can be alphabetically, numerically, by date/time as given by
8426 a time stamp, by a property, by priority order, or by a custom function.
8428 The command prompts for the sorting type unless it has been given to the
8429 function through the SORTING-TYPE argument, which needs to be a character,
8430 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8431 precise meaning of each character:
8433 n Numerically, by converting the beginning of the entry/item to a number.
8434 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8435 o By order of TODO keywords.
8436 t By date/time, either the first active time stamp in the entry, or, if
8437 none exist, by the first inactive one.
8438 s By the scheduled date/time.
8439 d By deadline date/time.
8440 c By creation time, which is assumed to be the first inactive time stamp
8441 at the beginning of a line.
8442 p By priority according to the cookie.
8443 r By the value of a property.
8445 Capital letters will reverse the sort order.
8447 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8448 called with point at the beginning of the record. It must return either
8449 a string or a number that should serve as the sorting key for that record.
8451 Comparing entries ignores case by default. However, with an optional argument
8452 WITH-CASE, the sorting considers case as well.
8454 Sorting is done against the visible part of the headlines, it ignores hidden
8455 links."
8456 (interactive "P")
8457 (let ((case-func (if with-case 'identity 'downcase))
8458 (cmstr
8459 ;; The clock marker is lost when using `sort-subr', let's
8460 ;; store the clocking string.
8461 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8462 (save-excursion
8463 (goto-char org-clock-marker)
8464 (looking-back "^.*") (match-string-no-properties 0))))
8465 start beg end stars re re2
8466 txt what tmp)
8467 ;; Find beginning and end of region to sort
8468 (cond
8469 ((org-region-active-p)
8470 ;; we will sort the region
8471 (setq end (region-end)
8472 what "region")
8473 (goto-char (region-beginning))
8474 (if (not (org-at-heading-p)) (outline-next-heading))
8475 (setq start (point)))
8476 ((or (org-at-heading-p)
8477 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8478 ;; we will sort the children of the current headline
8479 (org-back-to-heading)
8480 (setq start (point)
8481 end (progn (org-end-of-subtree t t)
8482 (or (bolp) (insert "\n"))
8483 (org-back-over-empty-lines)
8484 (point))
8485 what "children")
8486 (goto-char start)
8487 (show-subtree)
8488 (outline-next-heading))
8490 ;; we will sort the top-level entries in this file
8491 (goto-char (point-min))
8492 (or (org-at-heading-p) (outline-next-heading))
8493 (setq start (point))
8494 (goto-char (point-max))
8495 (beginning-of-line 1)
8496 (when (looking-at ".*?\\S-")
8497 ;; File ends in a non-white line
8498 (end-of-line 1)
8499 (insert "\n"))
8500 (setq end (point-max))
8501 (setq what "top-level")
8502 (goto-char start)
8503 (show-all)))
8505 (setq beg (point))
8506 (if (>= beg end) (error "Nothing to sort"))
8508 (looking-at "\\(\\*+\\)")
8509 (setq stars (match-string 1)
8510 re (concat "^" (regexp-quote stars) " +")
8511 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8512 txt (buffer-substring beg end))
8513 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8514 (if (and (not (equal stars "*")) (string-match re2 txt))
8515 (error "Region to sort contains a level above the first entry"))
8517 (unless sorting-type
8518 (message
8519 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8520 [t]ime [s]cheduled [d]eadline [c]reated
8521 A/N/P/R/O/F/T/S/D/C means reversed:"
8522 what)
8523 (setq sorting-type (read-char-exclusive))
8525 (unless getkey-func
8526 (and (= (downcase sorting-type) ?f)
8527 (setq getkey-func
8528 (org-icompleting-read "Sort using function: "
8529 obarray 'fboundp t nil nil))
8530 (setq getkey-func (intern getkey-func))))
8532 (and (= (downcase sorting-type) ?r)
8533 (not property)
8534 (setq property
8535 (org-icompleting-read "Property: "
8536 (mapcar 'list (org-buffer-property-keys t))
8537 nil t))))
8539 (message "Sorting entries...")
8541 (save-restriction
8542 (narrow-to-region start end)
8543 (let ((dcst (downcase sorting-type))
8544 (case-fold-search nil)
8545 (now (current-time)))
8546 (sort-subr
8547 (/= dcst sorting-type)
8548 ;; This function moves to the beginning character of the "record" to
8549 ;; be sorted.
8550 (lambda nil
8551 (if (re-search-forward re nil t)
8552 (goto-char (match-beginning 0))
8553 (goto-char (point-max))))
8554 ;; This function moves to the last character of the "record" being
8555 ;; sorted.
8556 (lambda nil
8557 (save-match-data
8558 (condition-case nil
8559 (outline-forward-same-level 1)
8560 (error
8561 (goto-char (point-max))))))
8562 ;; This function returns the value that gets sorted against.
8563 (lambda nil
8564 (cond
8565 ((= dcst ?n)
8566 (if (looking-at org-complex-heading-regexp)
8567 (string-to-number (org-sort-remove-invisible (match-string 4)))
8568 nil))
8569 ((= dcst ?a)
8570 (if (looking-at org-complex-heading-regexp)
8571 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8572 nil))
8573 ((= dcst ?t)
8574 (let ((end (save-excursion (outline-next-heading) (point))))
8575 (if (or (re-search-forward org-ts-regexp end t)
8576 (re-search-forward org-ts-regexp-both end t))
8577 (org-time-string-to-seconds (match-string 0))
8578 (org-float-time now))))
8579 ((= dcst ?c)
8580 (let ((end (save-excursion (outline-next-heading) (point))))
8581 (if (re-search-forward
8582 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8583 end t)
8584 (org-time-string-to-seconds (match-string 0))
8585 (org-float-time now))))
8586 ((= dcst ?s)
8587 (let ((end (save-excursion (outline-next-heading) (point))))
8588 (if (re-search-forward org-scheduled-time-regexp end t)
8589 (org-time-string-to-seconds (match-string 1))
8590 (org-float-time now))))
8591 ((= dcst ?d)
8592 (let ((end (save-excursion (outline-next-heading) (point))))
8593 (if (re-search-forward org-deadline-time-regexp end t)
8594 (org-time-string-to-seconds (match-string 1))
8595 (org-float-time now))))
8596 ((= dcst ?p)
8597 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8598 (string-to-char (match-string 2))
8599 org-default-priority))
8600 ((= dcst ?r)
8601 (or (org-entry-get nil property) ""))
8602 ((= dcst ?o)
8603 (if (looking-at org-complex-heading-regexp)
8604 (- 9999 (length (member (match-string 2)
8605 org-todo-keywords-1)))))
8606 ((= dcst ?f)
8607 (if getkey-func
8608 (progn
8609 (setq tmp (funcall getkey-func))
8610 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8611 tmp)
8612 (error "Invalid key function `%s'" getkey-func)))
8613 (t (error "Invalid sorting type `%c'" sorting-type))))
8615 (cond
8616 ((= dcst ?a) 'string<)
8617 ((= dcst ?f) compare-func)
8618 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8619 (run-hooks 'org-after-sorting-entries-or-items-hook)
8620 ;; Reset the clock marker if needed
8621 (when cmstr
8622 (save-excursion
8623 (goto-char start)
8624 (search-forward cmstr nil t)
8625 (move-marker org-clock-marker (point))))
8626 (message "Sorting entries...done")))
8628 (defun org-do-sort (table what &optional with-case sorting-type)
8629 "Sort TABLE of WHAT according to SORTING-TYPE.
8630 The user will be prompted for the SORTING-TYPE if the call to this
8631 function does not specify it. WHAT is only for the prompt, to indicate
8632 what is being sorted. The sorting key will be extracted from
8633 the car of the elements of the table.
8634 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8635 (unless sorting-type
8636 (message
8637 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8638 what)
8639 (setq sorting-type (read-char-exclusive)))
8640 (let ((dcst (downcase sorting-type))
8641 extractfun comparefun)
8642 ;; Define the appropriate functions
8643 (cond
8644 ((= dcst ?n)
8645 (setq extractfun 'string-to-number
8646 comparefun (if (= dcst sorting-type) '< '>)))
8647 ((= dcst ?a)
8648 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8649 (lambda(x) (downcase (org-sort-remove-invisible x))))
8650 comparefun (if (= dcst sorting-type)
8651 'string<
8652 (lambda (a b) (and (not (string< a b))
8653 (not (string= a b)))))))
8654 ((= dcst ?t)
8655 (setq extractfun
8656 (lambda (x)
8657 (if (or (string-match org-ts-regexp x)
8658 (string-match org-ts-regexp-both x))
8659 (org-float-time
8660 (org-time-string-to-time (match-string 0 x)))
8662 comparefun (if (= dcst sorting-type) '< '>)))
8663 (t (error "Invalid sorting type `%c'" sorting-type)))
8665 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8666 table)
8667 (lambda (a b) (funcall comparefun (car a) (car b))))))
8670 ;;; The orgstruct minor mode
8672 ;; Define a minor mode which can be used in other modes in order to
8673 ;; integrate the org-mode structure editing commands.
8675 ;; This is really a hack, because the org-mode structure commands use
8676 ;; keys which normally belong to the major mode. Here is how it
8677 ;; works: The minor mode defines all the keys necessary to operate the
8678 ;; structure commands, but wraps the commands into a function which
8679 ;; tests if the cursor is currently at a headline or a plain list
8680 ;; item. If that is the case, the structure command is used,
8681 ;; temporarily setting many Org-mode variables like regular
8682 ;; expressions for filling etc. However, when any of those keys is
8683 ;; used at a different location, function uses `key-binding' to look
8684 ;; up if the key has an associated command in another currently active
8685 ;; keymap (minor modes, major mode, global), and executes that
8686 ;; command. There might be problems if any of the keys is otherwise
8687 ;; used as a prefix key.
8689 (defcustom orgstruct-heading-prefix-regexp nil
8690 "Regexp that matches the custom prefix of Org headlines in
8691 orgstruct(++)-mode."
8692 :group 'org
8693 :version "24.4"
8694 :package-version '(Org . "8.0")
8695 :type 'string)
8696 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8698 (defcustom orgstruct-setup-hook nil
8699 "Hook run after orgstruct-mode-map is filled."
8700 :group 'org
8701 :version "24.4"
8702 :package-version '(Org . "8.0")
8703 :type 'hook)
8705 (defvar orgstruct-initialized nil)
8707 (defvar org-local-vars nil
8708 "List of local variables, for use by `orgstruct-mode'.")
8710 ;;;###autoload
8711 (define-minor-mode orgstruct-mode
8712 "Toggle the minor mode `orgstruct-mode'.
8713 This mode is for using Org-mode structure commands in other
8714 modes. The following keys behave as if Org-mode were active, if
8715 the cursor is on a headline, or on a plain list item (both as
8716 defined by Org-mode)."
8717 nil " OrgStruct" (make-sparse-keymap)
8718 (funcall (if orgstruct-mode
8719 'add-to-invisibility-spec
8720 'remove-from-invisibility-spec)
8721 '(outline . t))
8722 (when orgstruct-mode
8723 (org-load-modules-maybe)
8724 (unless orgstruct-initialized
8725 (orgstruct-setup)
8726 (setq orgstruct-initialized t))))
8728 ;;;###autoload
8729 (defun turn-on-orgstruct ()
8730 "Unconditionally turn on `orgstruct-mode'."
8731 (orgstruct-mode 1))
8733 (defvar org-fb-vars nil)
8734 (make-variable-buffer-local 'org-fb-vars)
8735 (defun orgstruct++-mode (&optional arg)
8736 "Toggle `orgstruct-mode', the enhanced version of it.
8737 In addition to setting orgstruct-mode, this also exports all
8738 indentation and autofilling variables from org-mode into the
8739 buffer. It will also recognize item context in multiline items."
8740 (interactive "P")
8741 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8742 (if (< arg 1)
8743 (progn (orgstruct-mode -1)
8744 (mapc (lambda(v)
8745 (org-set-local (car v)
8746 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8747 org-fb-vars))
8748 (orgstruct-mode 1)
8749 (setq org-fb-vars nil)
8750 (let (var val)
8751 (mapc
8752 (lambda (x)
8753 (when (string-match
8754 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8755 (symbol-name (car x)))
8756 (setq var (car x) val (nth 1 x))
8757 (push (list var `(quote ,(eval var))) org-fb-vars)
8758 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8759 org-local-vars)
8760 (org-set-local 'orgstruct-is-++ t))))
8762 (defvar orgstruct-is-++ nil
8763 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8764 (make-variable-buffer-local 'orgstruct-is-++)
8766 ;;;###autoload
8767 (defun turn-on-orgstruct++ ()
8768 "Unconditionally turn on `orgstruct++-mode'."
8769 (orgstruct++-mode 1))
8771 (defun orgstruct-error ()
8772 "Error when there is no default binding for a structure key."
8773 (interactive)
8774 (funcall (if (fboundp 'user-error)
8775 'user-error
8776 'error)
8777 "This key has no function outside structure elements"))
8779 (defun orgstruct-setup ()
8780 "Setup orgstruct keymap."
8781 (dolist (cell '((org-demote . t)
8782 (org-metaleft . t)
8783 (org-metaright . t)
8784 (org-promote . t)
8785 (org-shiftmetaleft . t)
8786 (org-shiftmetaright . t)
8787 org-backward-element
8788 org-backward-heading-same-level
8789 org-ctrl-c-ret
8790 org-ctrl-c-minus
8791 org-ctrl-c-star
8792 org-cycle
8793 org-forward-heading-same-level
8794 org-insert-heading
8795 org-insert-heading-respect-content
8796 org-kill-note-or-show-branches
8797 org-mark-subtree
8798 org-meta-return
8799 org-metadown
8800 org-metaup
8801 org-narrow-to-subtree
8802 org-promote-subtree
8803 org-reveal
8804 org-shiftdown
8805 org-shiftleft
8806 org-shiftmetadown
8807 org-shiftmetaup
8808 org-shiftright
8809 org-shifttab
8810 org-shifttab
8811 org-shiftup
8812 org-show-subtree
8813 org-sort
8814 org-up-element
8815 outline-demote
8816 outline-next-visible-heading
8817 outline-previous-visible-heading
8818 outline-promote
8819 outline-up-heading
8820 show-children))
8821 (let ((f (or (car-safe cell) cell))
8822 (disable-when-heading-prefix (cdr-safe cell)))
8823 (when (fboundp f)
8824 (dolist (binding (nconc (where-is-internal f org-mode-map)
8825 (where-is-internal f outline-mode-map)))
8826 ;; TODO use local-function-key-map
8827 (dolist (rep '(("<tab>" . "TAB")
8828 ("<return>" . "RET")
8829 ("<escape>" . "ESC")
8830 ("<delete>" . "DEL")))
8831 (setq binding (read-kbd-macro
8832 (let ((case-fold-search))
8833 (replace-regexp-in-string
8834 (regexp-quote (cdr rep))
8835 (car rep)
8836 (key-description binding))))))
8837 (let ((key (lookup-key orgstruct-mode-map binding)))
8838 (when (or (not key) (numberp key))
8839 (condition-case nil
8840 (org-defkey orgstruct-mode-map
8841 binding
8842 (orgstruct-make-binding f binding disable-when-heading-prefix))
8843 (error nil))))))))
8844 (run-hooks 'orgstruct-setup-hook))
8846 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8847 "Create a function for binding in the structure minor mode.
8848 FUN is the command to call inside a table. KEY is the key that
8849 should be checked in for a command to execute outside of tables.
8850 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8851 if `orgstruct-heading-prefix-regexp' is non-nil."
8852 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8853 (let ((nname name)
8854 (i 0))
8855 (while (fboundp (intern nname))
8856 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8857 (setq name (intern nname)))
8858 (eval
8859 (let ((bindings '((org-heading-regexp
8860 (concat "^"
8861 orgstruct-heading-prefix-regexp
8862 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8863 (org-outline-regexp
8864 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8865 (org-outline-regexp-bol
8866 (concat "^" org-outline-regexp))
8867 (outline-regexp org-outline-regexp)
8868 (outline-heading-end-regexp "\n")
8869 (outline-level 'org-outline-level)
8870 (outline-heading-alist))))
8871 `(defun ,name (arg)
8872 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8873 "Outside of structure, run the binding of `"
8874 (key-description key) "'."
8875 (when disable-when-heading-prefix
8876 (concat
8877 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8878 "back to the default binding due to limitations of Org's implementation of\n"
8879 "`" (symbol-name fun) "'.")))
8880 (interactive "p")
8881 (let* ((disable
8882 ,(when disable-when-heading-prefix
8883 '(and orgstruct-heading-prefix-regexp
8884 (not (string= orgstruct-heading-prefix-regexp "")))))
8885 (fallback
8886 (or disable
8887 (not
8888 (let* ,bindings
8889 (org-context-p 'headline 'item
8890 ,(when (memq fun '(org-insert-heading))
8891 '(when orgstruct-is-++
8892 'item-body))))))))
8893 (if fallback
8894 (let* ((orgstruct-mode)
8895 (binding
8896 (loop with key = ,key
8897 for rep in '(nil
8898 ("<tab>" . "TAB")
8899 ("<return>" . "RET")
8900 ("<escape>" . "ESC")
8901 ("<delete>" . "DEL"))
8903 (when rep
8904 (setq key (read-kbd-macro
8905 (let ((case-fold-search))
8906 (replace-regexp-in-string
8907 (regexp-quote (car rep))
8908 (cdr rep)
8909 (key-description key))))))
8910 thereis (key-binding key))))
8911 (if (keymapp binding)
8912 (set-temporary-overlay-map binding)
8913 (let ((func (or binding
8914 (unless disable
8915 'orgstruct-error))))
8916 (when func
8917 (call-interactively func)))))
8918 (org-run-like-in-org-mode
8919 (lambda ()
8920 (interactive)
8921 (let* ,bindings
8922 (call-interactively ',fun)))))))))
8923 name))
8925 (defun org-contextualize-keys (alist contexts)
8926 "Return valid elements in ALIST depending on CONTEXTS.
8928 `org-agenda-custom-commands' or `org-capture-templates' are the
8929 values used for ALIST, and `org-agenda-custom-commands-contexts'
8930 or `org-capture-templates-contexts' are the associated contexts
8931 definitions."
8932 (let ((contexts
8933 ;; normalize contexts
8934 (mapcar
8935 (lambda(c) (cond ((listp (cadr c))
8936 (list (car c) (car c) (cadr c)))
8937 ((string= "" (cadr c))
8938 (list (car c) (car c) (caddr c)))
8939 (t c))) contexts))
8940 (a alist) c r s)
8941 ;; loop over all commands or templates
8942 (while (setq c (pop a))
8943 (let (vrules repl)
8944 (cond
8945 ((not (assoc (car c) contexts))
8946 (push c r))
8947 ((and (assoc (car c) contexts)
8948 (setq vrules (org-contextualize-validate-key
8949 (car c) contexts)))
8950 (mapc (lambda (vr)
8951 (when (not (equal (car vr) (cadr vr)))
8952 (setq repl vr))) vrules)
8953 (if (not repl) (push c r)
8954 (push (cadr repl) s)
8955 (push
8956 (cons (car c)
8957 (cdr (or (assoc (cadr repl) alist)
8958 (error "Undefined key `%s' as contextual replacement for `%s'"
8959 (cadr repl) (car c)))))
8960 r))))))
8961 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8962 (delq
8964 (delete-dups
8965 (mapcar (lambda (x)
8966 (let ((tpl (car x)))
8967 (when (not (delq
8969 (mapcar (lambda(y)
8970 (equal y tpl)) s))) x)))
8971 (reverse r))))))
8973 (defun org-contextualize-validate-key (key contexts)
8974 "Check CONTEXTS for agenda or capture KEY."
8975 (let (r rr res)
8976 (while (setq r (pop contexts))
8977 (mapc
8978 (lambda (rr)
8979 (when
8980 (and (equal key (car r))
8981 (if (functionp rr) (funcall rr)
8982 (or (and (eq (car rr) 'in-file)
8983 (buffer-file-name)
8984 (string-match (cdr rr) (buffer-file-name)))
8985 (and (eq (car rr) 'in-mode)
8986 (string-match (cdr rr) (symbol-name major-mode)))
8987 (and (eq (car rr) 'in-buffer)
8988 (string-match (cdr rr) (buffer-name)))
8989 (when (and (eq (car rr) 'not-in-file)
8990 (buffer-file-name))
8991 (not (string-match (cdr rr) (buffer-file-name))))
8992 (when (eq (car rr) 'not-in-mode)
8993 (not (string-match (cdr rr) (symbol-name major-mode))))
8994 (when (eq (car rr) 'not-in-buffer)
8995 (not (string-match (cdr rr) (buffer-name)))))))
8996 (push r res)))
8997 (car (last r))))
8998 (delete-dups (delq nil res))))
9000 (defun org-context-p (&rest contexts)
9001 "Check if local context is any of CONTEXTS.
9002 Possible values in the list of contexts are `table', `headline', and `item'."
9003 (let ((pos (point)))
9004 (goto-char (point-at-bol))
9005 (prog1 (or (and (memq 'table contexts)
9006 (looking-at "[ \t]*|"))
9007 (and (memq 'headline contexts)
9008 (looking-at org-outline-regexp))
9009 (and (memq 'item contexts)
9010 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9011 (and (memq 'item-body contexts)
9012 (org-in-item-p)))
9013 (goto-char pos))))
9015 (defun org-get-local-variables ()
9016 "Return a list of all local variables in an Org mode buffer."
9017 (let (varlist)
9018 (with-current-buffer (get-buffer-create "*Org tmp*")
9019 (erase-buffer)
9020 (org-mode)
9021 (setq varlist (buffer-local-variables)))
9022 (kill-buffer "*Org tmp*")
9023 (delq nil
9024 (mapcar
9025 (lambda (x)
9026 (setq x
9027 (if (symbolp x)
9028 (list x)
9029 (list (car x) (cdr x))))
9030 (if (and (not (get (car x) 'org-state))
9031 (string-match
9032 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9033 (symbol-name (car x))))
9034 x nil))
9035 varlist))))
9037 (defun org-clone-local-variables (from-buffer &optional regexp)
9038 "Clone local variables from FROM-BUFFER.
9039 Optional argument REGEXP selects variables to clone."
9040 (mapc
9041 (lambda (pair)
9042 (and (symbolp (car pair))
9043 (or (null regexp)
9044 (string-match regexp (symbol-name (car pair))))
9045 (set (make-local-variable (car pair))
9046 (cdr pair))))
9047 (buffer-local-variables from-buffer)))
9049 ;;;###autoload
9050 (defun org-run-like-in-org-mode (cmd)
9051 "Run a command, pretending that the current buffer is in Org-mode.
9052 This will temporarily bind local variables that are typically bound in
9053 Org-mode to the values they have in Org-mode, and then interactively
9054 call CMD."
9055 (org-load-modules-maybe)
9056 (unless org-local-vars
9057 (setq org-local-vars (org-get-local-variables)))
9058 (let (binds)
9059 (dolist (var org-local-vars)
9060 (when (or (not (boundp (car var)))
9061 (eq (symbol-value (car var))
9062 (default-value (car var))))
9063 (push (list (car var) `(quote ,(cadr var))) binds)))
9064 (eval `(let ,binds
9065 (call-interactively (quote ,cmd))))))
9067 ;;;; Archiving
9069 (defun org-get-category (&optional pos force-refresh)
9070 "Get the category applying to position POS."
9071 (save-match-data
9072 (if force-refresh (org-refresh-category-properties))
9073 (let ((pos (or pos (point))))
9074 (or (get-text-property pos 'org-category)
9075 (progn (org-refresh-category-properties)
9076 (get-text-property pos 'org-category))))))
9078 (defun org-refresh-category-properties ()
9079 "Refresh category text properties in the buffer."
9080 (let ((case-fold-search t)
9081 (inhibit-read-only t)
9082 (def-cat (cond
9083 ((null org-category)
9084 (if buffer-file-name
9085 (file-name-sans-extension
9086 (file-name-nondirectory buffer-file-name))
9087 "???"))
9088 ((symbolp org-category) (symbol-name org-category))
9089 (t org-category)))
9090 beg end cat pos optionp)
9091 (org-with-silent-modifications
9092 (save-excursion
9093 (save-restriction
9094 (widen)
9095 (goto-char (point-min))
9096 (put-text-property (point) (point-max) 'org-category def-cat)
9097 (while (re-search-forward
9098 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9099 (setq pos (match-end 0)
9100 optionp (equal (char-after (match-beginning 0)) ?#)
9101 cat (org-trim (match-string 2)))
9102 (if optionp
9103 (setq beg (point-at-bol) end (point-max))
9104 (org-back-to-heading t)
9105 (setq beg (point) end (org-end-of-subtree t t)))
9106 (put-text-property beg end 'org-category cat)
9107 (put-text-property beg end 'org-category-position beg)
9108 (goto-char pos)))))))
9110 (defun org-refresh-properties (dprop tprop)
9111 "Refresh buffer text properties.
9112 DPROP is the drawer property and TPROP is the corresponding text
9113 property to set."
9114 (let ((case-fold-search t)
9115 (inhibit-read-only t) p)
9116 (org-with-silent-modifications
9117 (save-excursion
9118 (save-restriction
9119 (widen)
9120 (goto-char (point-min))
9121 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9122 (setq p (org-match-string-no-properties 1))
9123 (save-excursion
9124 (org-back-to-heading t)
9125 (put-text-property
9126 (point-at-bol) (point-at-eol) tprop p))))))))
9129 ;;;; Link Stuff
9131 ;;; Link abbreviations
9133 (defun org-link-expand-abbrev (link)
9134 "Apply replacements as defined in `org-link-abbrev-alist'."
9135 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9136 (let* ((key (match-string 1 link))
9137 (as (or (assoc key org-link-abbrev-alist-local)
9138 (assoc key org-link-abbrev-alist)))
9139 (tag (and (match-end 2) (match-string 3 link)))
9140 rpl)
9141 (if (not as)
9142 link
9143 (setq rpl (cdr as))
9144 (cond
9145 ((symbolp rpl) (funcall rpl tag))
9146 ((string-match "%(\\([^)]+\\))" rpl)
9147 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9148 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9149 ((string-match "%h" rpl)
9150 (replace-match (url-hexify-string (or tag "")) t t rpl))
9151 (t (concat rpl tag)))))
9152 link))
9154 ;;; Storing and inserting links
9156 (defvar org-insert-link-history nil
9157 "Minibuffer history for links inserted with `org-insert-link'.")
9159 (defvar org-stored-links nil
9160 "Contains the links stored with `org-store-link'.")
9162 (defvar org-store-link-plist nil
9163 "Plist with info about the most recently link created with `org-store-link'.")
9165 (defvar org-link-protocols nil
9166 "Link protocols added to Org-mode using `org-add-link-type'.")
9168 (defvar org-store-link-functions nil
9169 "List of functions that are called to create and store a link.
9170 Each function will be called in turn until one returns a non-nil
9171 value. Each function should check if it is responsible for creating
9172 this link (for example by looking at the major mode).
9173 If not, it must exit and return nil.
9174 If yes, it should return a non-nil value after a calling
9175 `org-store-link-props' with a list of properties and values.
9176 Special properties are:
9178 :type The link prefix, like \"http\". This must be given.
9179 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9180 This is obligatory as well.
9181 :description Optional default description for the second pair
9182 of brackets in an Org-mode link. The user can still change
9183 this when inserting this link into an Org-mode buffer.
9185 In addition to these, any additional properties can be specified
9186 and then used in capture templates.")
9188 (defun org-add-link-type (type &optional follow export)
9189 "Add TYPE to the list of `org-link-types'.
9190 Re-compute all regular expressions depending on `org-link-types'
9192 FOLLOW and EXPORT are two functions.
9194 FOLLOW should take the link path as the single argument and do whatever
9195 is necessary to follow the link, for example find a file or display
9196 a mail message.
9198 EXPORT should format the link path for export to one of the export formats.
9199 It should be a function accepting three arguments:
9201 path the path of the link, the text after the prefix (like \"http:\")
9202 desc the description of the link, if any, or a description added by
9203 org-export-normalize-links if there is none
9204 format the export format, a symbol like `html' or `latex' or `ascii'..
9206 The function may use the FORMAT information to return different values
9207 depending on the format. The return value will be put literally into
9208 the exported file. If the return value is nil, this means Org should
9209 do what it normally does with links which do not have EXPORT defined.
9211 Org-mode has a built-in default for exporting links. If you are happy with
9212 this default, there is no need to define an export function for the link
9213 type. For a simple example of an export function, see `org-bbdb.el'."
9214 (add-to-list 'org-link-types type t)
9215 (org-make-link-regexps)
9216 (if (assoc type org-link-protocols)
9217 (setcdr (assoc type org-link-protocols) (list follow export))
9218 (push (list type follow export) org-link-protocols)))
9220 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9221 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9223 ;;;###autoload
9224 (defun org-store-link (arg)
9225 "\\<org-mode-map>Store an org-link to the current location.
9226 This link is added to `org-stored-links' and can later be inserted
9227 into an org-buffer with \\[org-insert-link].
9229 For some link types, a prefix arg is interpreted.
9230 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9231 For file links, arg negates `org-context-in-file-links'.
9233 A double prefix arg force skipping storing functions that are not
9234 part of Org's core."
9235 (interactive "P")
9236 (org-load-modules-maybe)
9237 (setq org-store-link-plist nil) ; reset
9238 (org-with-limited-levels
9239 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9240 (cond
9241 ((and (not (equal arg '(16)))
9242 (setq sfuns
9243 (delq
9244 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9245 org-store-link-functions))
9246 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9247 (or (and (cdr sfuns)
9248 (funcall (intern
9249 (completing-read "Which function for creating the link? "
9250 sfunsn t (car sfunsn)))))
9251 (funcall (caar sfuns)))
9252 (setq link (plist-get org-store-link-plist :link)
9253 desc (or (plist-get org-store-link-plist :description) link))))
9254 ((org-src-edit-buffer-p)
9255 (let (label gc)
9256 (while (or (not label)
9257 (save-excursion
9258 (save-restriction
9259 (widen)
9260 (goto-char (point-min))
9261 (re-search-forward
9262 (regexp-quote (format org-coderef-label-format label))
9263 nil t))))
9264 (when label (message "Label exists already") (sit-for 2))
9265 (setq label (read-string "Code line label: " label)))
9266 (end-of-line 1)
9267 (setq link (format org-coderef-label-format label))
9268 (setq gc (- 79 (length link)))
9269 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9270 (insert link)
9271 (setq link (concat "(" label ")") desc nil)))
9273 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9274 ;; We are in the agenda, link to referenced location
9275 (let ((m (or (get-text-property (point) 'org-hd-marker)
9276 (get-text-property (point) 'org-marker))))
9277 (when m
9278 (org-with-point-at m
9279 (setq agenda-link
9280 (if (org-called-interactively-p 'any)
9281 (call-interactively 'org-store-link)
9282 (org-store-link nil)))))))
9284 ((eq major-mode 'calendar-mode)
9285 (let ((cd (calendar-cursor-to-date)))
9286 (setq link
9287 (format-time-string
9288 (car org-time-stamp-formats)
9289 (apply 'encode-time
9290 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9291 nil nil nil))))
9292 (org-store-link-props :type "calendar" :date cd)))
9294 ((eq major-mode 'help-mode)
9295 (setq link (concat "help:" (save-excursion
9296 (goto-char (point-min))
9297 (looking-at "^[^ ]+")
9298 (match-string 0))))
9299 (org-store-link-props :type "help"))
9301 ((eq major-mode 'w3-mode)
9302 (setq cpltxt (if (and (buffer-name)
9303 (not (string-match "Untitled" (buffer-name))))
9304 (buffer-name)
9305 (url-view-url t))
9306 link (url-view-url t))
9307 (org-store-link-props :type "w3" :url (url-view-url t)))
9309 ((setq search (run-hook-with-args-until-success
9310 'org-create-file-search-functions))
9311 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9312 "::" search))
9313 (setq cpltxt (or description link)))
9315 ((eq major-mode 'image-mode)
9316 (setq cpltxt (concat "file:"
9317 (abbreviate-file-name buffer-file-name))
9318 link cpltxt)
9319 (org-store-link-props :type "image" :file buffer-file-name))
9321 ((eq major-mode 'dired-mode)
9322 ;; link to the file in the current line
9323 (let ((file (dired-get-filename nil t)))
9324 (setq file (if file
9325 (abbreviate-file-name
9326 (expand-file-name (dired-get-filename nil t)))
9327 ;; otherwise, no file so use current directory.
9328 default-directory))
9329 (setq cpltxt (concat "file:" file)
9330 link cpltxt)))
9332 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9333 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9334 (cond
9335 ((org-in-regexp "<<\\(.*?\\)>>")
9336 (setq cpltxt
9337 (concat "file:"
9338 (abbreviate-file-name
9339 (buffer-file-name (buffer-base-buffer)))
9340 "::" (match-string 1))
9341 link cpltxt))
9342 ((and (featurep 'org-id)
9343 (or (eq org-id-link-to-org-use-id t)
9344 (and (org-called-interactively-p 'any)
9345 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9346 (and (eq org-id-link-to-org-use-id
9347 'create-if-interactive-and-no-custom-id)
9348 (not custom-id))))
9349 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9350 ;; We can make a link using the ID.
9351 (setq link (condition-case nil
9352 (prog1 (org-id-store-link)
9353 (setq desc (plist-get org-store-link-plist :description)))
9354 (error
9355 ;; probably before first headline, link to file only
9356 (concat "file:"
9357 (abbreviate-file-name
9358 (buffer-file-name (buffer-base-buffer))))))))
9360 ;; Just link to current headline
9361 (setq cpltxt (concat "file:"
9362 (abbreviate-file-name
9363 (buffer-file-name (buffer-base-buffer)))))
9364 ;; Add a context search string
9365 (when (org-xor org-context-in-file-links arg)
9366 (let* ((ee (org-element-at-point))
9367 (et (org-element-type ee))
9368 (ev (plist-get (cadr ee) :value)))
9369 (setq txt (cond
9370 ((org-at-heading-p) nil)
9371 ((eq et 'keyword) ev)
9372 ((org-region-active-p)
9373 (buffer-substring (region-beginning) (region-end)))))
9374 (when (or (null txt) (string-match "\\S-" txt))
9375 (setq cpltxt
9376 (concat cpltxt "::"
9377 (condition-case nil
9378 (org-make-org-heading-search-string txt)
9379 (error "")))
9380 desc (or (and (eq et 'keyword) ev)
9381 (nth 4 (ignore-errors (org-heading-components)))
9382 "NONE")))))
9383 (if (string-match "::\\'" cpltxt)
9384 (setq cpltxt (substring cpltxt 0 -2)))
9385 (setq link cpltxt))))
9387 ((buffer-file-name (buffer-base-buffer))
9388 ;; Just link to this file here.
9389 (setq cpltxt (concat "file:"
9390 (abbreviate-file-name
9391 (buffer-file-name (buffer-base-buffer)))))
9392 ;; Add a context string
9393 (when (org-xor org-context-in-file-links arg)
9394 (setq txt (if (org-region-active-p)
9395 (buffer-substring (region-beginning) (region-end))
9396 (buffer-substring (point-at-bol) (point-at-eol))))
9397 ;; Only use search option if there is some text.
9398 (when (string-match "\\S-" txt)
9399 (setq cpltxt
9400 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9401 desc "NONE")))
9402 (setq link cpltxt))
9404 ((org-called-interactively-p 'interactive)
9405 (user-error "No method for storing a link from this buffer"))
9407 (t (setq link nil)))
9409 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9410 (setq link (or link cpltxt)
9411 desc (or desc cpltxt))
9412 (cond ((equal desc "NONE") (setq desc nil))
9413 ((string-match org-bracket-link-regexp desc)
9414 (setq desc (replace-regexp-in-string
9415 org-bracket-link-regexp
9416 (concat "\\3" (if (equal (length (match-string 0 desc))
9417 (length desc)) "*" "")) desc))))
9419 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9420 (progn
9421 (setq org-stored-links
9422 (cons (list link desc) org-stored-links))
9423 (message "Stored: %s" (or desc link))
9424 (when custom-id
9425 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9426 "::#" custom-id))
9427 (setq org-stored-links
9428 (cons (list link desc) org-stored-links))))
9429 (or agenda-link (and link (org-make-link-string link desc)))))))
9431 (defun org-store-link-props (&rest plist)
9432 "Store link properties, extract names and addresses."
9433 (let (x adr)
9434 (when (setq x (plist-get plist :from))
9435 (setq adr (mail-extract-address-components x))
9436 (setq plist (plist-put plist :fromname (car adr)))
9437 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9438 (when (setq x (plist-get plist :to))
9439 (setq adr (mail-extract-address-components x))
9440 (setq plist (plist-put plist :toname (car adr)))
9441 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9442 (let ((from (plist-get plist :from))
9443 (to (plist-get plist :to)))
9444 (when (and from to org-from-is-user-regexp)
9445 (setq plist
9446 (plist-put plist :fromto
9447 (if (string-match org-from-is-user-regexp from)
9448 (concat "to %t")
9449 (concat "from %f"))))))
9450 (setq org-store-link-plist plist))
9452 (defun org-add-link-props (&rest plist)
9453 "Add these properties to the link property list."
9454 (let (key value)
9455 (while plist
9456 (setq key (pop plist) value (pop plist))
9457 (setq org-store-link-plist
9458 (plist-put org-store-link-plist key value)))))
9460 (defun org-email-link-description (&optional fmt)
9461 "Return the description part of an email link.
9462 This takes information from `org-store-link-plist' and formats it
9463 according to FMT (default from `org-email-link-description-format')."
9464 (setq fmt (or fmt org-email-link-description-format))
9465 (let* ((p org-store-link-plist)
9466 (to (plist-get p :toaddress))
9467 (from (plist-get p :fromaddress))
9468 (table
9469 (list
9470 (cons "%c" (plist-get p :fromto))
9471 (cons "%F" (plist-get p :from))
9472 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9473 (cons "%T" (plist-get p :to))
9474 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9475 (cons "%s" (plist-get p :subject))
9476 (cons "%d" (plist-get p :date))
9477 (cons "%m" (plist-get p :message-id)))))
9478 (when (string-match "%c" fmt)
9479 ;; Check if the user wrote this message
9480 (if (and org-from-is-user-regexp from to
9481 (save-match-data (string-match org-from-is-user-regexp from)))
9482 (setq fmt (replace-match "to %t" t t fmt))
9483 (setq fmt (replace-match "from %f" t t fmt))))
9484 (org-replace-escapes fmt table)))
9486 (defun org-make-org-heading-search-string (&optional string)
9487 "Make search string for the current headline or STRING."
9488 (let ((s (or string
9489 (and (derived-mode-p 'org-mode)
9490 (save-excursion
9491 (org-back-to-heading t)
9492 (org-element-property :raw-value (org-element-at-point))))))
9493 (lines org-context-in-file-links))
9494 (or string (setq s (concat "*" s))) ; Add * for headlines
9495 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9496 (when (and string (integerp lines) (> lines 0))
9497 (let ((slines (org-split-string s "\n")))
9498 (when (< lines (length slines))
9499 (setq s (mapconcat
9500 'identity
9501 (reverse (nthcdr (- (length slines) lines)
9502 (reverse slines))) "\n")))))
9503 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9505 (defun org-make-link-string (link &optional description)
9506 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9507 (unless (string-match "\\S-" link)
9508 (error "Empty link"))
9509 (when (and description
9510 (stringp description)
9511 (not (string-match "\\S-" description)))
9512 (setq description nil))
9513 (when (stringp description)
9514 ;; Remove brackets from the description, they are fatal.
9515 (while (string-match "\\[" description)
9516 (setq description (replace-match "{" t t description)))
9517 (while (string-match "\\]" description)
9518 (setq description (replace-match "}" t t description))))
9519 (when (equal link description)
9520 ;; No description needed, it is identical
9521 (setq description nil))
9522 (when (and (not description)
9523 (not (string-match (org-image-file-name-regexp) link))
9524 (not (equal link (org-link-escape link))))
9525 (setq description (org-extract-attributes link)))
9526 (setq link
9527 (cond ((string-match (org-image-file-name-regexp) link) link)
9528 ((string-match org-link-types-re link)
9529 (concat (match-string 1 link)
9530 (org-link-escape (substring link (match-end 1)))))
9531 (t (org-link-escape link))))
9532 (concat "[[" link "]"
9533 (if description (concat "[" description "]") "")
9534 "]"))
9536 (defconst org-link-escape-chars
9537 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9538 "List of characters that should be escaped in link.
9539 This is the list that is used for internal purposes.")
9541 (defconst org-link-escape-chars-browser
9542 '(?\ )
9543 "List of escapes for characters that are problematic in links.
9544 This is the list that is used before handing over to the browser.")
9546 (defun org-link-escape (text &optional table merge)
9547 "Return percent escaped representation of TEXT.
9548 TEXT is a string with the text to escape.
9549 Optional argument TABLE is a list with characters that should be
9550 escaped. When nil, `org-link-escape-chars' is used.
9551 If optional argument MERGE is set, merge TABLE into
9552 `org-link-escape-chars'."
9553 (cond
9554 ((and table merge)
9555 (mapc (lambda (defchr)
9556 (unless (member defchr table)
9557 (setq table (cons defchr table)))) org-link-escape-chars))
9558 ((null table)
9559 (setq table org-link-escape-chars)))
9560 (mapconcat
9561 (lambda (char)
9562 (if (or (member char table)
9563 (and (or (< char 32) (= char 37) (> char 126))
9564 org-url-hexify-p))
9565 (mapconcat (lambda (sequence-element)
9566 (format "%%%.2X" sequence-element))
9567 (or (encode-coding-char char 'utf-8)
9568 (error "Unable to percent escape character: %s"
9569 (char-to-string char))) "")
9570 (char-to-string char))) text ""))
9572 (defun org-link-unescape (str)
9573 "Unhex hexified Unicode strings as returned from the JavaScript function
9574 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9575 (unless (and (null str) (string= "" str))
9576 (let ((pos 0) (case-fold-search t) unhexed)
9577 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9578 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9579 (setq str (replace-match unhexed t t str))
9580 (setq pos (+ pos (length unhexed))))))
9581 str)
9583 (defun org-link-unescape-compound (hex)
9584 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9585 Note: this function also decodes single byte encodings like
9586 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9587 (save-match-data
9588 (let* ((bytes (cdr (split-string hex "%")))
9589 (ret "")
9590 (eat 0)
9591 (sum 0))
9592 (while bytes
9593 (let* ((val (string-to-number (pop bytes) 16))
9594 (shift-xor
9595 (if (= 0 eat)
9596 (cond
9597 ((>= val 252) (cons 6 252))
9598 ((>= val 248) (cons 5 248))
9599 ((>= val 240) (cons 4 240))
9600 ((>= val 224) (cons 3 224))
9601 ((>= val 192) (cons 2 192))
9602 (t (cons 0 0)))
9603 (cons 6 128))))
9604 (if (>= val 192) (setq eat (car shift-xor)))
9605 (setq val (logxor val (cdr shift-xor)))
9606 (setq sum (+ (lsh sum (car shift-xor)) val))
9607 (if (> eat 0) (setq eat (- eat 1)))
9608 (cond
9609 ((= 0 eat) ;multi byte
9610 (setq ret (concat ret (org-char-to-string sum)))
9611 (setq sum 0))
9612 ((not bytes) ; single byte(s)
9613 (setq ret (org-link-unescape-single-byte-sequence hex))))
9614 )) ;; end (while bytes
9615 ret )))
9617 (defun org-link-unescape-single-byte-sequence (hex)
9618 "Unhexify hex-encoded single byte character sequences."
9619 (mapconcat (lambda (byte)
9620 (char-to-string (string-to-number byte 16)))
9621 (cdr (split-string hex "%")) ""))
9623 (defun org-xor (a b)
9624 "Exclusive or."
9625 (if a (not b) b))
9627 (defun org-fixup-message-id-for-http (s)
9628 "Replace special characters in a message id, so it can be used in an http query."
9629 (when (string-match "%" s)
9630 (setq s (mapconcat (lambda (c)
9631 (if (eq c ?%)
9632 "%25"
9633 (char-to-string c)))
9634 s "")))
9635 (while (string-match "<" s)
9636 (setq s (replace-match "%3C" t t s)))
9637 (while (string-match ">" s)
9638 (setq s (replace-match "%3E" t t s)))
9639 (while (string-match "@" s)
9640 (setq s (replace-match "%40" t t s)))
9643 (defun org-link-prettify (link)
9644 "Return a human-readable representation of LINK.
9645 The car of LINK must be a raw link the cdr of LINK must be either
9646 a link description or nil."
9647 (let ((desc (or (cadr link) "<no description>")))
9648 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9649 "<" (car link) ">")))
9651 ;;;###autoload
9652 (defun org-insert-link-global ()
9653 "Insert a link like Org-mode does.
9654 This command can be called in any mode to insert a link in Org-mode syntax."
9655 (interactive)
9656 (org-load-modules-maybe)
9657 (org-run-like-in-org-mode 'org-insert-link))
9659 (defun org-insert-all-links (&optional keep)
9660 "Insert all links in `org-stored-links'."
9661 (interactive "P")
9662 (let ((links (copy-sequence org-stored-links)) l)
9663 (while (setq l (if keep (pop links) (pop org-stored-links)))
9664 (insert "- ")
9665 (org-insert-link nil (car l) (cadr l))
9666 (insert "\n"))))
9668 (defun org-link-fontify-links-to-this-file ()
9669 "Fontify links to the current file in `org-stored-links'."
9670 (let ((f (buffer-file-name)) a b)
9671 (setq a (mapcar (lambda(l)
9672 (let ((ll (car l)))
9673 (when (and (string-match "^file:\\(.+\\)::" ll)
9674 (equal f (expand-file-name (match-string 1 ll))))
9675 ll)))
9676 org-stored-links))
9677 (when (featurep 'org-id)
9678 (setq b (mapcar (lambda(l)
9679 (let ((ll (car l)))
9680 (when (and (string-match "^id:\\(.+\\)$" ll)
9681 (equal f (expand-file-name
9682 (or (org-id-find-id-file
9683 (match-string 1 ll)) ""))))
9684 ll)))
9685 org-stored-links)))
9686 (mapcar (lambda(l)
9687 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9688 (delq nil (append a b)))))
9690 (defvar org-link-links-in-this-file nil)
9691 (defun org-insert-link (&optional complete-file link-location default-description)
9692 "Insert a link. At the prompt, enter the link.
9694 Completion can be used to insert any of the link protocol prefixes like
9695 http or ftp in use.
9697 The history can be used to select a link previously stored with
9698 `org-store-link'. When the empty string is entered (i.e. if you just
9699 press RET at the prompt), the link defaults to the most recently
9700 stored link. As SPC triggers completion in the minibuffer, you need to
9701 use M-SPC or C-q SPC to force the insertion of a space character.
9703 You will also be prompted for a description, and if one is given, it will
9704 be displayed in the buffer instead of the link.
9706 If there is already a link at point, this command will allow you to edit link
9707 and description parts.
9709 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9710 be selected using completion. The path to the file will be relative to the
9711 current directory if the file is in the current directory or a subdirectory.
9712 Otherwise, the link will be the absolute path as completed in the minibuffer
9713 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9714 option `org-link-file-path-type'.
9716 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9717 the current directory or below.
9719 With three \\[universal-argument] prefixes, negate the meaning of
9720 `org-keep-stored-link-after-insertion'.
9722 If `org-make-link-description-function' is non-nil, this function will be
9723 called with the link target, and the result will be the default
9724 link description.
9726 If the LINK-LOCATION parameter is non-nil, this value will be
9727 used as the link location instead of reading one interactively.
9729 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9730 be used as the default description."
9731 (interactive "P")
9732 (let* ((wcf (current-window-configuration))
9733 (origbuf (current-buffer))
9734 (region (if (org-region-active-p)
9735 (buffer-substring (region-beginning) (region-end))))
9736 (remove (and region (list (region-beginning) (region-end))))
9737 (desc region)
9738 tmphist ; byte-compile incorrectly complains about this
9739 (link link-location)
9740 (abbrevs org-link-abbrev-alist-local)
9741 entry file all-prefixes auto-desc)
9742 (cond
9743 (link-location) ; specified by arg, just use it.
9744 ((org-in-regexp org-bracket-link-regexp 1)
9745 ;; We do have a link at point, and we are going to edit it.
9746 (setq remove (list (match-beginning 0) (match-end 0)))
9747 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9748 (setq link (read-string "Link: "
9749 (org-link-unescape
9750 (org-match-string-no-properties 1)))))
9751 ((or (org-in-regexp org-angle-link-re)
9752 (org-in-regexp org-plain-link-re))
9753 ;; Convert to bracket link
9754 (setq remove (list (match-beginning 0) (match-end 0))
9755 link (read-string "Link: "
9756 (org-remove-angle-brackets (match-string 0)))))
9757 ((member complete-file '((4) (16)))
9758 ;; Completing read for file names.
9759 (setq link (org-file-complete-link complete-file)))
9761 ;; Read link, with completion for stored links.
9762 (org-link-fontify-links-to-this-file)
9763 (org-switch-to-buffer-other-window "*Org Links*")
9764 (with-current-buffer "*Org Links*"
9765 (erase-buffer)
9766 (insert "Insert a link.
9767 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9768 (when org-stored-links
9769 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9770 (insert (mapconcat 'org-link-prettify
9771 (reverse org-stored-links) "\n")))
9772 (goto-char (point-min)))
9773 (let ((cw (selected-window)))
9774 (select-window (get-buffer-window "*Org Links*" 'visible))
9775 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9776 (unless (pos-visible-in-window-p (point-max))
9777 (org-fit-window-to-buffer))
9778 (and (window-live-p cw) (select-window cw)))
9779 ;; Fake a link history, containing the stored links.
9780 (setq tmphist (append (mapcar 'car org-stored-links)
9781 org-insert-link-history))
9782 (setq all-prefixes (append (mapcar 'car abbrevs)
9783 (mapcar 'car org-link-abbrev-alist)
9784 org-link-types))
9785 (unwind-protect
9786 (progn
9787 (setq link
9788 (org-completing-read
9789 "Link: "
9790 (append
9791 (mapcar (lambda (x) (concat x ":"))
9792 all-prefixes)
9793 (mapcar 'car org-stored-links))
9794 nil nil nil
9795 'tmphist
9796 (caar org-stored-links)))
9797 (if (not (string-match "\\S-" link))
9798 (error "No link selected"))
9799 (mapc (lambda(l)
9800 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9801 org-stored-links)
9802 (if (or (member link all-prefixes)
9803 (and (equal ":" (substring link -1))
9804 (member (substring link 0 -1) all-prefixes)
9805 (setq link (substring link 0 -1))))
9806 (setq link (with-current-buffer origbuf
9807 (org-link-try-special-completion link)))))
9808 (set-window-configuration wcf)
9809 (kill-buffer "*Org Links*"))
9810 (setq entry (assoc link org-stored-links))
9811 (or entry (push link org-insert-link-history))
9812 (setq desc (or desc (nth 1 entry)))))
9814 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9815 (not org-keep-stored-link-after-insertion))
9816 (setq org-stored-links (delq (assoc link org-stored-links)
9817 org-stored-links)))
9819 (if (string-match org-plain-link-re link)
9820 ;; URL-like link, normalize the use of angular brackets.
9821 (setq link (org-remove-angle-brackets link)))
9823 ;; Check if we are linking to the current file with a search
9824 ;; option If yes, simplify the link by using only the search
9825 ;; option.
9826 (when (and buffer-file-name
9827 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9828 (let* ((path (match-string 1 link))
9829 (case-fold-search nil)
9830 (search (match-string 2 link)))
9831 (save-match-data
9832 (if (equal (file-truename buffer-file-name) (file-truename path))
9833 ;; We are linking to this same file, with a search option
9834 (setq link search)))))
9836 ;; Check if we can/should use a relative path. If yes, simplify the link
9837 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9838 (let* ((type (match-string 1 link))
9839 (path (match-string 2 link))
9840 (origpath path)
9841 (case-fold-search nil))
9842 (cond
9843 ((or (eq org-link-file-path-type 'absolute)
9844 (equal complete-file '(16)))
9845 (setq path (abbreviate-file-name (expand-file-name path))))
9846 ((eq org-link-file-path-type 'noabbrev)
9847 (setq path (expand-file-name path)))
9848 ((eq org-link-file-path-type 'relative)
9849 (setq path (file-relative-name path)))
9851 (save-match-data
9852 (if (string-match (concat "^" (regexp-quote
9853 (expand-file-name
9854 (file-name-as-directory
9855 default-directory))))
9856 (expand-file-name path))
9857 ;; We are linking a file with relative path name.
9858 (setq path (substring (expand-file-name path)
9859 (match-end 0)))
9860 (setq path (abbreviate-file-name (expand-file-name path)))))))
9861 (setq link (concat type path))
9862 (if (equal desc origpath)
9863 (setq desc path))))
9865 (if org-make-link-description-function
9866 (setq desc
9867 (or (condition-case nil
9868 (funcall org-make-link-description-function link desc)
9869 (error (progn (message "Can't get link description from `%s'"
9870 (symbol-name org-make-link-description-function))
9871 (sit-for 2) nil)))
9872 (read-string "Description: " default-description)))
9873 (if default-description (setq desc default-description)
9874 (setq desc (or (and auto-desc desc)
9875 (read-string "Description: " desc)))))
9877 (unless (string-match "\\S-" desc) (setq desc nil))
9878 (if remove (apply 'delete-region remove))
9879 (insert (org-make-link-string link desc))))
9881 (defun org-link-try-special-completion (type)
9882 "If there is completion support for link type TYPE, offer it."
9883 (let ((fun (intern (concat "org-" type "-complete-link"))))
9884 (if (functionp fun)
9885 (funcall fun)
9886 (read-string "Link (no completion support): " (concat type ":")))))
9888 (defun org-file-complete-link (&optional arg)
9889 "Create a file link using completion."
9890 (let (file link)
9891 (setq file (org-iread-file-name "File: "))
9892 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9893 (pwd1 (file-name-as-directory (abbreviate-file-name
9894 (expand-file-name ".")))))
9895 (cond
9896 ((equal arg '(16))
9897 (setq link (concat
9898 "file:"
9899 (abbreviate-file-name (expand-file-name file)))))
9900 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9901 (setq link (concat "file:" (match-string 1 file))))
9902 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9903 (expand-file-name file))
9904 (setq link (concat
9905 "file:" (match-string 1 (expand-file-name file)))))
9906 (t (setq link (concat "file:" file)))))
9907 link))
9909 (defun org-iread-file-name (&rest args)
9910 "Read-file-name using `ido-mode' speedup if available.
9911 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9912 See `read-file-name' for a description of parameters."
9913 (org-without-partial-completion
9914 (if (and org-completion-use-ido
9915 (fboundp 'ido-read-file-name)
9916 (boundp 'ido-mode) ido-mode
9917 (listp (second args)))
9918 (let ((ido-enter-matching-directory nil))
9919 (apply 'ido-read-file-name args))
9920 (apply 'read-file-name args))))
9922 (defun org-completing-read (&rest args)
9923 "Completing-read with SPACE being a normal character."
9924 (let ((enable-recursive-minibuffers t)
9925 (minibuffer-local-completion-map
9926 (copy-keymap minibuffer-local-completion-map)))
9927 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9928 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9929 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9930 (apply 'org-icompleting-read args)))
9932 (defun org-completing-read-no-i (&rest args)
9933 (let (org-completion-use-ido org-completion-use-iswitchb)
9934 (apply 'org-completing-read args)))
9936 (defun org-iswitchb-completing-read (prompt choices &rest args)
9937 "Use iswitch as a completing-read replacement to choose from choices.
9938 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9939 from."
9940 (let* ((iswitchb-use-virtual-buffers nil)
9941 (iswitchb-make-buflist-hook
9942 (lambda ()
9943 (setq iswitchb-temp-buflist choices))))
9944 (iswitchb-read-buffer prompt)))
9946 (defun org-icompleting-read (&rest args)
9947 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9948 (org-without-partial-completion
9949 (if (and org-completion-use-ido
9950 (fboundp 'ido-completing-read)
9951 (boundp 'ido-mode) ido-mode
9952 (listp (second args)))
9953 (let ((ido-enter-matching-directory nil))
9954 (apply 'ido-completing-read (concat (car args))
9955 (if (consp (car (nth 1 args)))
9956 (mapcar 'car (nth 1 args))
9957 (nth 1 args))
9958 (cddr args)))
9959 (if (and org-completion-use-iswitchb
9960 (boundp 'iswitchb-mode) iswitchb-mode
9961 (listp (second args)))
9962 (apply 'org-iswitchb-completing-read (concat (car args))
9963 (if (consp (car (nth 1 args)))
9964 (mapcar 'car (nth 1 args))
9965 (nth 1 args))
9966 (cddr args))
9967 (apply 'completing-read args)))))
9969 (defun org-extract-attributes (s)
9970 "Extract the attributes cookie from a string and set as text property."
9971 (let (a attr (start 0) key value)
9972 (save-match-data
9973 (when (string-match "{{\\([^}]+\\)}}$" s)
9974 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9975 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9976 (setq key (match-string 1 a) value (match-string 2 a)
9977 start (match-end 0)
9978 attr (plist-put attr (intern key) value))))
9979 (org-add-props s nil 'org-attr attr))
9982 (defun org-extract-attributes-from-string (tag)
9983 (let (key value attr)
9984 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9985 (setq key (match-string 1 tag) value (match-string 2 tag)
9986 tag (replace-match "" t t tag)
9987 attr (plist-put attr (intern key) value)))
9988 (cons tag attr)))
9990 (defun org-attributes-to-string (plist)
9991 "Format a property list into an HTML attribute list."
9992 (let ((s "") key value)
9993 (while plist
9994 (setq key (pop plist) value (pop plist))
9995 (and value
9996 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9999 ;;; Opening/following a link
10001 (defvar org-link-search-failed nil)
10003 (defvar org-open-link-functions nil
10004 "Hook for functions finding a plain text link.
10005 These functions must take a single argument, the link content.
10006 They will be called for links that look like [[link text][description]]
10007 when LINK TEXT does not have a protocol like \"http:\" and does not look
10008 like a filename (e.g. \"./blue.png\").
10010 These functions will be called *before* Org attempts to resolve the
10011 link by doing text searches in the current buffer - so if you want a
10012 link \"[[target]]\" to still find \"<<target>>\", your function should
10013 handle this as a special case.
10015 When the function does handle the link, it must return a non-nil value.
10016 If it decides that it is not responsible for this link, it must return
10017 nil to indicate that that Org-mode can continue with other options
10018 like exact and fuzzy text search.")
10020 (defun org-next-link (&optional search-backward)
10021 "Move forward to the next link.
10022 If the link is in hidden text, expose it."
10023 (interactive "P")
10024 (when (and org-link-search-failed (eq this-command last-command))
10025 (goto-char (point-min))
10026 (message "Link search wrapped back to beginning of buffer"))
10027 (setq org-link-search-failed nil)
10028 (let* ((pos (point))
10029 (ct (org-context))
10030 (a (assoc :link ct))
10031 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10032 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10033 ((looking-at org-any-link-re)
10034 ;; Don't stay stuck at link without an org-link face
10035 (forward-char (if search-backward -1 1))))
10036 (if (funcall srch-fun org-any-link-re nil t)
10037 (progn
10038 (goto-char (match-beginning 0))
10039 (if (outline-invisible-p) (org-show-context)))
10040 (goto-char pos)
10041 (setq org-link-search-failed t)
10042 (message "No further link found"))))
10044 (defun org-previous-link ()
10045 "Move backward to the previous link.
10046 If the link is in hidden text, expose it."
10047 (interactive)
10048 (funcall 'org-next-link t))
10050 (defun org-translate-link (s)
10051 "Translate a link string if a translation function has been defined."
10052 (if (and org-link-translation-function
10053 (fboundp org-link-translation-function)
10054 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10055 (progn
10056 (setq s (funcall org-link-translation-function
10057 (match-string 1 s) (match-string 2 s)))
10058 (concat (car s) ":" (cdr s)))
10061 (defun org-translate-link-from-planner (type path)
10062 "Translate a link from Emacs Planner syntax so that Org can follow it.
10063 This is still an experimental function, your mileage may vary."
10064 (cond
10065 ((member type '("http" "https" "news" "ftp"))
10066 ;; standard Internet links are the same.
10067 nil)
10068 ((and (equal type "irc") (string-match "^//" path))
10069 ;; Planner has two / at the beginning of an irc link, we have 1.
10070 ;; We should have zero, actually....
10071 (setq path (substring path 1)))
10072 ((and (equal type "lisp") (string-match "^/" path))
10073 ;; Planner has a slash, we do not.
10074 (setq type "elisp" path (substring path 1)))
10075 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10076 ;; A typical message link. Planner has the id after the final slash,
10077 ;; we separate it with a hash mark
10078 (setq path (concat (match-string 1 path) "#"
10079 (org-remove-angle-brackets (match-string 2 path)))))
10081 (cons type path))
10083 (defun org-find-file-at-mouse (ev)
10084 "Open file link or URL at mouse."
10085 (interactive "e")
10086 (mouse-set-point ev)
10087 (org-open-at-point 'in-emacs))
10089 (defun org-open-at-mouse (ev)
10090 "Open file link or URL at mouse.
10091 See the docstring of `org-open-file' for details."
10092 (interactive "e")
10093 (mouse-set-point ev)
10094 (if (eq major-mode 'org-agenda-mode)
10095 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10096 (org-open-at-point))
10098 (defvar org-window-config-before-follow-link nil
10099 "The window configuration before following a link.
10100 This is saved in case the need arises to restore it.")
10102 (defvar org-open-link-marker (make-marker)
10103 "Marker pointing to the location where `org-open-at-point; was called.")
10105 ;;;###autoload
10106 (defun org-open-at-point-global ()
10107 "Follow a link like Org-mode does.
10108 This command can be called in any mode to follow a link that has
10109 Org-mode syntax."
10110 (interactive)
10111 (org-run-like-in-org-mode 'org-open-at-point))
10113 ;;;###autoload
10114 (defun org-open-link-from-string (s &optional arg reference-buffer)
10115 "Open a link in the string S, as if it was in Org-mode."
10116 (interactive "sLink: \nP")
10117 (let ((reference-buffer (or reference-buffer (current-buffer))))
10118 (with-temp-buffer
10119 (let ((org-inhibit-startup (not reference-buffer)))
10120 (org-mode)
10121 (insert s)
10122 (goto-char (point-min))
10123 (when reference-buffer
10124 (setq org-link-abbrev-alist-local
10125 (with-current-buffer reference-buffer
10126 org-link-abbrev-alist-local)))
10127 (org-open-at-point arg reference-buffer)))))
10129 (defvar org-open-at-point-functions nil
10130 "Hook that is run when following a link at point.
10132 Functions in this hook must return t if they identify and follow
10133 a link at point. If they don't find anything interesting at point,
10134 they must return nil.")
10136 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10137 (defun org-open-at-point (&optional arg reference-buffer)
10138 "Open link at or after point.
10139 If there is no link at point, this function will search forward up to
10140 the end of the current line.
10141 Normally, files will be opened by an appropriate application. If the
10142 optional prefix argument ARG is non-nil, Emacs will visit the file.
10143 With a double prefix argument, try to open outside of Emacs, in the
10144 application the system uses for this file type."
10145 (interactive "P")
10146 ;; if in a code block, then open the block's results
10147 (unless (call-interactively #'org-babel-open-src-block-result)
10148 (org-load-modules-maybe)
10149 (move-marker org-open-link-marker (point))
10150 (setq org-window-config-before-follow-link (current-window-configuration))
10151 (org-remove-occur-highlights nil nil t)
10152 (cond
10153 ((and (org-at-heading-p)
10154 (not (org-at-timestamp-p t))
10155 (not (org-in-regexp
10156 (concat org-plain-link-re "\\|"
10157 org-bracket-link-regexp "\\|"
10158 org-angle-link-re "\\|"
10159 "[ \t]:[^ \t\n]+:[ \t]*$")))
10160 (not (get-text-property (point) 'org-linked-text)))
10161 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10162 (lk0 (car lkall))
10163 (lk (if (stringp lk0) (list lk0) lk0))
10164 (lkend (cdr lkall)))
10165 (mapcar (lambda(l)
10166 (search-forward l nil lkend)
10167 (goto-char (match-beginning 0))
10168 (org-open-at-point))
10169 lk))
10170 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10171 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10172 ((and (org-at-timestamp-p t)
10173 (not (org-in-regexp org-bracket-link-regexp)))
10174 (org-follow-timestamp-link))
10175 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10176 (not (org-in-regexp org-any-link-re)))
10177 (org-footnote-action))
10179 (let (type path link line search (pos (point)))
10180 (catch 'match
10181 (save-excursion
10182 (skip-chars-forward "^]\n\r")
10183 (when (org-in-regexp org-bracket-link-regexp 1)
10184 (setq link (org-extract-attributes
10185 (org-link-unescape (org-match-string-no-properties 1))))
10186 (while (string-match " *\n *" link)
10187 (setq link (replace-match " " t t link)))
10188 (setq link (org-link-expand-abbrev link))
10189 (cond
10190 ((or (file-name-absolute-p link)
10191 (string-match "^\\.\\.?/" link))
10192 (setq type "file" path link))
10193 ((string-match org-link-re-with-space3 link)
10194 (setq type (match-string 1 link) path (match-string 2 link)))
10195 ((string-match "^help:+\\(.+\\)" link)
10196 (setq type "help" path (match-string 1 link)))
10197 (t (setq type "thisfile" path link)))
10198 (throw 'match t)))
10200 (when (get-text-property (point) 'org-linked-text)
10201 (setq type "thisfile"
10202 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10203 (1+ (point)) (point))
10204 path (buffer-substring
10205 (or (previous-single-property-change pos 'org-linked-text)
10206 (point-min))
10207 (or (next-single-property-change pos 'org-linked-text)
10208 (point-max))))
10209 (throw 'match t))
10211 (save-excursion
10212 (when (or (org-in-regexp org-angle-link-re)
10213 (let ((match (org-in-regexp org-plain-link-re)))
10214 ;; Check a plain link is not within a bracket link
10215 (and match
10216 (save-excursion
10217 (progn
10218 (goto-char (car match))
10219 (not (org-in-regexp org-bracket-link-regexp))))))
10220 (let ((line_ending (save-excursion (end-of-line) (point))))
10221 ;; We are in a line before a plain or bracket link
10222 (or (re-search-forward org-plain-link-re line_ending t)
10223 (re-search-forward org-bracket-link-regexp line_ending t))))
10224 (setq type (match-string 1)
10225 path (org-link-unescape (match-string 2)))
10226 (throw 'match t)))
10227 (save-excursion
10228 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10229 (setq type "tags"
10230 path (match-string 1))
10231 (while (string-match ":" path)
10232 (setq path (replace-match "+" t t path)))
10233 (throw 'match t)))
10234 (when (org-in-regexp "<\\([^><\n]+\\)>")
10235 (setq type "tree-match"
10236 path (match-string 1))
10237 (throw 'match t)))
10238 (unless path
10239 (user-error "No link found"))
10241 ;; switch back to reference buffer
10242 ;; needed when if called in a temporary buffer through
10243 ;; org-open-link-from-string
10244 (with-current-buffer (or reference-buffer (current-buffer))
10246 ;; Remove any trailing spaces in path
10247 (if (string-match " +\\'" path)
10248 (setq path (replace-match "" t t path)))
10249 (if (and org-link-translation-function
10250 (fboundp org-link-translation-function))
10251 ;; Check if we need to translate the link
10252 (let ((tmp (funcall org-link-translation-function type path)))
10253 (setq type (car tmp) path (cdr tmp))))
10255 (cond
10257 ((assoc type org-link-protocols)
10258 (funcall (nth 1 (assoc type org-link-protocols)) path))
10260 ((equal type "help")
10261 (let ((f-or-v (intern path)))
10262 (cond ((fboundp f-or-v)
10263 (describe-function f-or-v))
10264 ((boundp f-or-v)
10265 (describe-variable f-or-v))
10266 (t (error "Not a known function or variable")))))
10268 ((equal type "mailto")
10269 (let ((cmd (car org-link-mailto-program))
10270 (args (cdr org-link-mailto-program)) args1
10271 (address path) (subject "") a)
10272 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10273 (setq address (match-string 1 path)
10274 subject (org-link-escape (match-string 2 path))))
10275 (while args
10276 (cond
10277 ((not (stringp (car args))) (push (pop args) args1))
10278 (t (setq a (pop args))
10279 (if (string-match "%a" a)
10280 (setq a (replace-match address t t a)))
10281 (if (string-match "%s" a)
10282 (setq a (replace-match subject t t a)))
10283 (push a args1))))
10284 (apply cmd (nreverse args1))))
10286 ((member type '("http" "https" "ftp" "news"))
10287 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10288 (org-link-escape
10289 path org-link-escape-chars-browser)
10290 path))))
10292 ((string= type "doi")
10293 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10294 (org-link-escape
10295 path org-link-escape-chars-browser)
10296 path))))
10298 ((member type '("message"))
10299 (browse-url (concat type ":" path)))
10301 ((string= type "tags")
10302 (org-tags-view arg path))
10304 ((string= type "tree-match")
10305 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10307 ((string= type "file")
10308 (if (string-match "::\\([0-9]+\\)\\'" path)
10309 (setq line (string-to-number (match-string 1 path))
10310 path (substring path 0 (match-beginning 0)))
10311 (if (string-match "::\\(.+\\)\\'" path)
10312 (setq search (match-string 1 path)
10313 path (substring path 0 (match-beginning 0)))))
10314 (if (string-match "[*?{]" (file-name-nondirectory path))
10315 (dired path)
10316 (org-open-file path arg line search)))
10318 ((string= type "shell")
10319 (let ((buf (generate-new-buffer "*Org Shell Output"))
10320 (cmd path))
10321 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10322 (string-match org-confirm-shell-link-not-regexp cmd))
10323 (not org-confirm-shell-link-function)
10324 (funcall org-confirm-shell-link-function
10325 (format "Execute \"%s\" in shell? "
10326 (org-add-props cmd nil
10327 'face 'org-warning))))
10328 (progn
10329 (message "Executing %s" cmd)
10330 (shell-command cmd buf)
10331 (if (featurep 'midnight)
10332 (setq clean-buffer-list-kill-buffer-names
10333 (cons buf clean-buffer-list-kill-buffer-names))))
10334 (error "Abort"))))
10336 ((string= type "elisp")
10337 (let ((cmd path))
10338 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10339 (string-match org-confirm-elisp-link-not-regexp cmd))
10340 (not org-confirm-elisp-link-function)
10341 (funcall org-confirm-elisp-link-function
10342 (format "Execute \"%s\" as elisp? "
10343 (org-add-props cmd nil
10344 'face 'org-warning))))
10345 (message "%s => %s" cmd
10346 (if (equal (string-to-char cmd) ?\()
10347 (eval (read cmd))
10348 (call-interactively (read cmd))))
10349 (error "Abort"))))
10351 ((and (string= type "thisfile")
10352 (run-hook-with-args-until-success
10353 'org-open-link-functions path)))
10355 ((string= type "thisfile")
10356 (if arg
10357 (switch-to-buffer-other-window
10358 (org-get-buffer-for-internal-link (current-buffer)))
10359 (org-mark-ring-push))
10360 (let ((cmd `(org-link-search
10361 ,path
10362 ,(cond ((equal arg '(4)) ''occur)
10363 ((equal arg '(16)) ''org-occur))
10364 ,pos)))
10365 (condition-case nil (let ((org-link-search-inhibit-query t))
10366 (eval cmd))
10367 (error (progn (widen) (eval cmd))))))
10369 (t (browse-url-at-point)))))))
10370 (move-marker org-open-link-marker nil)
10371 (run-hook-with-args 'org-follow-link-hook)))
10373 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10374 "Offer links in the current entry and return the selected link.
10375 If there is only one link, return it.
10376 If NTH is an integer, return the NTH link found.
10377 If ZERO is a string, check also this string for a link, and if
10378 there is one, return it."
10379 (with-current-buffer buffer
10380 (save-excursion
10381 (save-restriction
10382 (widen)
10383 (goto-char marker)
10384 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10385 "\\(" org-angle-link-re "\\)\\|"
10386 "\\(" org-plain-link-re "\\)"))
10387 (cnt ?0)
10388 (in-emacs (if (integerp nth) nil nth))
10389 have-zero end links link c)
10390 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10391 (push (match-string 0 zero) links)
10392 (setq cnt (1- cnt) have-zero t))
10393 (save-excursion
10394 (org-back-to-heading t)
10395 (setq end (save-excursion (outline-next-heading) (point)))
10396 (while (re-search-forward re end t)
10397 (push (match-string 0) links))
10398 (setq links (org-uniquify (reverse links))))
10399 (cond
10400 ((null links)
10401 (message "No links"))
10402 ((equal (length links) 1)
10403 (setq link (car links)))
10404 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10405 (setq link (nth (if have-zero nth (1- nth)) links)))
10406 (t ; we have to select a link
10407 (save-excursion
10408 (save-window-excursion
10409 (delete-other-windows)
10410 (with-output-to-temp-buffer "*Select Link*"
10411 (mapc (lambda (l)
10412 (if (not (string-match org-bracket-link-regexp l))
10413 (princ (format "[%c] %s\n" (incf cnt)
10414 (org-remove-angle-brackets l)))
10415 (if (match-end 3)
10416 (princ (format "[%c] %s (%s)\n" (incf cnt)
10417 (match-string 3 l) (match-string 1 l)))
10418 (princ (format "[%c] %s\n" (incf cnt)
10419 (match-string 1 l))))))
10420 links))
10421 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10422 (message "Select link to open, RET to open all:")
10423 (setq c (read-char-exclusive))
10424 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10425 (when (equal c ?q) (error "Abort"))
10426 (if (equal c ?\C-m)
10427 (setq link links)
10428 (setq nth (- c ?0))
10429 (if have-zero (setq nth (1+ nth)))
10430 (unless (and (integerp nth) (>= (length links) nth))
10431 (error "Invalid link selection"))
10432 (setq link (nth (1- nth) links)))))
10433 (cons link end))))))
10435 ;; Add special file links that specify the way of opening
10437 (org-add-link-type "file+sys" 'org-open-file-with-system)
10438 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10439 (defun org-open-file-with-system (path)
10440 "Open file at PATH using the system way of opening it."
10441 (org-open-file path 'system))
10442 (defun org-open-file-with-emacs (path)
10443 "Open file at PATH in Emacs."
10444 (org-open-file path 'emacs))
10447 ;;; File search
10449 (defvar org-create-file-search-functions nil
10450 "List of functions to construct the right search string for a file link.
10451 These functions are called in turn with point at the location to
10452 which the link should point.
10454 A function in the hook should first test if it would like to
10455 handle this file type, for example by checking the `major-mode'
10456 or the file extension. If it decides not to handle this file, it
10457 should just return nil to give other functions a chance. If it
10458 does handle the file, it must return the search string to be used
10459 when following the link. The search string will be part of the
10460 file link, given after a double colon, and `org-open-at-point'
10461 will automatically search for it. If special measures must be
10462 taken to make the search successful, another function should be
10463 added to the companion hook `org-execute-file-search-functions',
10464 which see.
10466 A function in this hook may also use `setq' to set the variable
10467 `description' to provide a suggestion for the descriptive text to
10468 be used for this link when it gets inserted into an Org-mode
10469 buffer with \\[org-insert-link].")
10471 (defvar org-execute-file-search-functions nil
10472 "List of functions to execute a file search triggered by a link.
10474 Functions added to this hook must accept a single argument, the
10475 search string that was part of the file link, the part after the
10476 double colon. The function must first check if it would like to
10477 handle this search, for example by checking the `major-mode' or
10478 the file extension. If it decides not to handle this search, it
10479 should just return nil to give other functions a chance. If it
10480 does handle the search, it must return a non-nil value to keep
10481 other functions from trying.
10483 Each function can access the current prefix argument through the
10484 variable `current-prefix-arg'. Note that a single prefix is used
10485 to force opening a link in Emacs, so it may be good to only use a
10486 numeric or double prefix to guide the search function.
10488 In case this is needed, a function in this hook can also restore
10489 the window configuration before `org-open-at-point' was called using:
10491 (set-window-configuration org-window-config-before-follow-link)")
10493 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10494 (defun org-link-search (s &optional type avoid-pos stealth)
10495 "Search for a link search option.
10496 If S is surrounded by forward slashes, it is interpreted as a
10497 regular expression. In org-mode files, this will create an `org-occur'
10498 sparse tree. In ordinary files, `occur' will be used to list matches.
10499 If the current buffer is in `dired-mode', grep will be used to search
10500 in all files. If AVOID-POS is given, ignore matches near that position.
10502 When optional argument STEALTH is non-nil, do not modify
10503 visibility around point, thus ignoring
10504 `org-show-hierarchy-above', `org-show-following-heading' and
10505 `org-show-siblings' variables."
10506 (let ((case-fold-search t)
10507 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10508 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10509 (append '(("") (" ") ("\t") ("\n"))
10510 org-emphasis-alist)
10511 "\\|") "\\)"))
10512 (pos (point))
10513 (pre nil) (post nil)
10514 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10515 (cond
10516 ;; First check if there are any special search functions
10517 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10518 ;; Now try the builtin stuff
10519 ((and (equal (string-to-char s0) ?#)
10520 (> (length s0) 1)
10521 (save-excursion
10522 (goto-char (point-min))
10523 (and
10524 (re-search-forward
10525 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10526 (setq type 'dedicated
10527 pos (match-beginning 0))))
10528 ;; There is an exact target for this
10529 (goto-char pos)
10530 (org-back-to-heading t)))
10531 ((save-excursion
10532 (goto-char (point-min))
10533 (and
10534 (re-search-forward
10535 (concat "<<" (regexp-quote s0) ">>") nil t)
10536 (setq type 'dedicated
10537 pos (match-beginning 0))))
10538 ;; There is an exact target for this
10539 (goto-char pos))
10540 ((save-excursion
10541 (goto-char (point-min))
10542 (and
10543 (re-search-forward
10544 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10545 (setq type 'dedicated pos (match-beginning 0))))
10546 ;; Found an invisible target.
10547 (goto-char pos))
10548 ((save-excursion
10549 (goto-char (point-min))
10550 (and
10551 (re-search-forward
10552 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10553 (setq type 'dedicated pos (match-beginning 0))))
10554 ;; Found an element with a matching #+name affiliated keyword.
10555 (goto-char pos))
10556 ((and (string-match "^(\\(.*\\))$" s0)
10557 (save-excursion
10558 (goto-char (point-min))
10559 (and
10560 (re-search-forward
10561 (concat "[^[]" (regexp-quote
10562 (format org-coderef-label-format
10563 (match-string 1 s0))))
10564 nil t)
10565 (setq type 'dedicated
10566 pos (1+ (match-beginning 0))))))
10567 ;; There is a coderef target for this
10568 (goto-char pos))
10569 ((string-match "^/\\(.*\\)/$" s)
10570 ;; A regular expression
10571 (cond
10572 ((derived-mode-p 'org-mode)
10573 (org-occur (match-string 1 s)))
10574 (t (org-do-occur (match-string 1 s)))))
10575 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10576 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10577 (goto-char (point-min))
10578 (cond
10579 ((let (case-fold-search)
10580 (re-search-forward (format org-complex-heading-regexp-format
10581 (regexp-quote s))
10582 nil t))
10583 ;; OK, found a match
10584 (setq type 'dedicated)
10585 (goto-char (match-beginning 0)))
10586 ((and (not org-link-search-inhibit-query)
10587 (eq org-link-search-must-match-exact-headline 'query-to-create)
10588 (y-or-n-p "No match - create this as a new heading? "))
10589 (goto-char (point-max))
10590 (or (bolp) (newline))
10591 (insert "* " s "\n")
10592 (beginning-of-line 0))
10594 (goto-char pos)
10595 (error "No match"))))
10597 ;; A normal search string
10598 (when (equal (string-to-char s) ?*)
10599 ;; Anchor on headlines, post may include tags.
10600 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10601 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10602 s (substring s 1)))
10603 (remove-text-properties
10604 0 (length s)
10605 '(face nil mouse-face nil keymap nil fontified nil) s)
10606 ;; Make a series of regular expressions to find a match
10607 (setq words (org-split-string s "[ \n\r\t]+")
10609 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10610 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10611 "\\)" markers)
10612 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10613 re2a (concat "[ \t\r\n]" re2a_)
10614 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10615 re4 (concat "[^a-zA-Z_]" re4_)
10617 re1 (concat pre re2 post)
10618 re3 (concat pre (if pre re4_ re4) post)
10619 re5 (concat pre ".*" re4)
10620 re2 (concat pre re2)
10621 re2a (concat pre (if pre re2a_ re2a))
10622 re4 (concat pre (if pre re4_ re4))
10623 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10624 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10625 re5 "\\)"
10627 (cond
10628 ((eq type 'org-occur) (org-occur reall))
10629 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10630 (t (goto-char (point-min))
10631 (setq type 'fuzzy)
10632 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10633 (org-search-not-self 1 re1 nil t)
10634 (org-search-not-self 1 re2 nil t)
10635 (org-search-not-self 1 re2a nil t)
10636 (org-search-not-self 1 re3 nil t)
10637 (org-search-not-self 1 re4 nil t)
10638 (org-search-not-self 1 re5 nil t)
10640 (goto-char (match-beginning 1))
10641 (goto-char pos)
10642 (error "No match"))))))
10643 (and (derived-mode-p 'org-mode)
10644 (not stealth)
10645 (org-show-context 'link-search))
10646 type))
10648 (defun org-search-not-self (group &rest args)
10649 "Execute `re-search-forward', but only accept matches that do not
10650 enclose the position of `org-open-link-marker'."
10651 (let ((m org-open-link-marker))
10652 (catch 'exit
10653 (while (apply 're-search-forward args)
10654 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10655 (goto-char (match-end group))
10656 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10657 (> (match-beginning 0) (marker-position m))
10658 (< (match-end 0) (marker-position m)))
10659 (save-match-data
10660 (or (not (org-in-regexp
10661 org-bracket-link-analytic-regexp 1))
10662 (not (match-end 4)) ; no description
10663 (and (<= (match-beginning 4) (point))
10664 (>= (match-end 4) (point))))))
10665 (throw 'exit (point))))))))
10667 (defun org-get-buffer-for-internal-link (buffer)
10668 "Return a buffer to be used for displaying the link target of internal links."
10669 (cond
10670 ((not org-display-internal-link-with-indirect-buffer)
10671 buffer)
10672 ((string-match "(Clone)$" (buffer-name buffer))
10673 (message "Buffer is already a clone, not making another one")
10674 ;; we also do not modify visibility in this case
10675 buffer)
10676 (t ; make a new indirect buffer for displaying the link
10677 (let* ((bn (buffer-name buffer))
10678 (ibn (concat bn "(Clone)"))
10679 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10680 (with-current-buffer ib (org-overview))
10681 ib))))
10683 (defun org-do-occur (regexp &optional cleanup)
10684 "Call the Emacs command `occur'.
10685 If CLEANUP is non-nil, remove the printout of the regular expression
10686 in the *Occur* buffer. This is useful if the regex is long and not useful
10687 to read."
10688 (occur regexp)
10689 (when cleanup
10690 (let ((cwin (selected-window)) win beg end)
10691 (when (setq win (get-buffer-window "*Occur*"))
10692 (select-window win))
10693 (goto-char (point-min))
10694 (when (re-search-forward "match[a-z]+" nil t)
10695 (setq beg (match-end 0))
10696 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10697 (setq end (1- (match-beginning 0)))))
10698 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10699 (goto-char (point-min))
10700 (select-window cwin))))
10702 ;;; The mark ring for links jumps
10704 (defvar org-mark-ring nil
10705 "Mark ring for positions before jumps in Org-mode.")
10706 (defvar org-mark-ring-last-goto nil
10707 "Last position in the mark ring used to go back.")
10708 ;; Fill and close the ring
10709 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10710 (loop for i from 1 to org-mark-ring-length do
10711 (push (make-marker) org-mark-ring))
10712 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10713 org-mark-ring)
10715 (defun org-mark-ring-push (&optional pos buffer)
10716 "Put the current position or POS into the mark ring and rotate it."
10717 (interactive)
10718 (setq pos (or pos (point)))
10719 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10720 (move-marker (car org-mark-ring)
10721 (or pos (point))
10722 (or buffer (current-buffer)))
10723 (message "%s"
10724 (substitute-command-keys
10725 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10727 (defun org-mark-ring-goto (&optional n)
10728 "Jump to the previous position in the mark ring.
10729 With prefix arg N, jump back that many stored positions. When
10730 called several times in succession, walk through the entire ring.
10731 Org-mode commands jumping to a different position in the current file,
10732 or to another Org-mode file, automatically push the old position
10733 onto the ring."
10734 (interactive "p")
10735 (let (p m)
10736 (if (eq last-command this-command)
10737 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10738 (setq p org-mark-ring))
10739 (setq org-mark-ring-last-goto p)
10740 (setq m (car p))
10741 (org-pop-to-buffer-same-window (marker-buffer m))
10742 (goto-char m)
10743 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10745 (defun org-remove-angle-brackets (s)
10746 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10747 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10749 (defun org-add-angle-brackets (s)
10750 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10751 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10753 (defun org-remove-double-quotes (s)
10754 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10755 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10758 ;;; Following specific links
10760 (defun org-follow-timestamp-link ()
10761 "Open an agenda view for the time-stamp date/range at point."
10762 (cond
10763 ((org-at-date-range-p t)
10764 (let ((org-agenda-start-on-weekday)
10765 (t1 (match-string 1))
10766 (t2 (match-string 2)) tt1 tt2)
10767 (setq tt1 (time-to-days (org-time-string-to-time t1))
10768 tt2 (time-to-days (org-time-string-to-time t2)))
10769 (let ((org-agenda-buffer-tmp-name
10770 (format "*Org Agenda(a:%s)"
10771 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10772 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10773 ((org-at-timestamp-p t)
10774 (let ((org-agenda-buffer-tmp-name
10775 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10776 (org-agenda-list nil (time-to-days (org-time-string-to-time
10777 (substring (match-string 1) 0 10)))
10778 1)))
10779 (t (error "This should not happen"))))
10782 ;;; Following file links
10783 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10784 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10785 (declare-function mailcap-mime-info
10786 "mailcap" (string &optional request no-decode))
10787 (defvar org-wait nil)
10788 (defun org-open-file (path &optional in-emacs line search)
10789 "Open the file at PATH.
10790 First, this expands any special file name abbreviations. Then the
10791 configuration variable `org-file-apps' is checked if it contains an
10792 entry for this file type, and if yes, the corresponding command is launched.
10794 If no application is found, Emacs simply visits the file.
10796 With optional prefix argument IN-EMACS, Emacs will visit the file.
10797 With a double \\[universal-argument] \\[universal-argument] \
10798 prefix arg, Org tries to avoid opening in Emacs
10799 and to use an external application to visit the file.
10801 Optional LINE specifies a line to go to, optional SEARCH a string
10802 to search for. If LINE or SEARCH is given, the file will be
10803 opened in Emacs, unless an entry from org-file-apps that makes
10804 use of groups in a regexp matches.
10806 If you want to change the way frames are used when following a
10807 link, please customize `org-link-frame-setup'.
10809 If the file does not exist, an error is thrown."
10810 (let* ((file (if (equal path "")
10811 buffer-file-name
10812 (substitute-in-file-name (expand-file-name path))))
10813 (file-apps (append org-file-apps (org-default-apps)))
10814 (apps (org-remove-if
10815 'org-file-apps-entry-match-against-dlink-p file-apps))
10816 (apps-dlink (org-remove-if-not
10817 'org-file-apps-entry-match-against-dlink-p file-apps))
10818 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10819 (dirp (if remp nil (file-directory-p file)))
10820 (file (if (and dirp org-open-directory-means-index-dot-org)
10821 (concat (file-name-as-directory file) "index.org")
10822 file))
10823 (a-m-a-p (assq 'auto-mode apps))
10824 (dfile (downcase file))
10825 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10826 (link (cond ((and (eq line nil)
10827 (eq search nil))
10828 file)
10829 (line
10830 (concat file "::" (number-to-string line)))
10831 (search
10832 (concat file "::" search))))
10833 (dlink (downcase link))
10834 (old-buffer (current-buffer))
10835 (old-pos (point))
10836 (old-mode major-mode)
10837 ext cmd link-match-data)
10838 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10839 (setq ext (match-string 1 dfile))
10840 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10841 (setq ext (match-string 1 dfile))))
10842 (cond
10843 ((member in-emacs '((16) system))
10844 (setq cmd (cdr (assoc 'system apps))))
10845 (in-emacs (setq cmd 'emacs))
10847 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10848 (and dirp (cdr (assoc 'directory apps)))
10849 ; first, try matching against apps-dlink
10850 ; if we get a match here, store the match data for later
10851 (let ((match (assoc-default dlink apps-dlink
10852 'string-match)))
10853 (if match
10854 (progn (setq link-match-data (match-data))
10855 match)
10856 (progn (setq in-emacs (or in-emacs line search))
10857 nil))) ; if we have no match in apps-dlink,
10858 ; always open the file in emacs if line or search
10859 ; is given (for backwards compatibility)
10860 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10861 'string-match)
10862 (cdr (assoc ext apps))
10863 (cdr (assoc t apps))))))
10864 (when (eq cmd 'system)
10865 (setq cmd (cdr (assoc 'system apps))))
10866 (when (eq cmd 'default)
10867 (setq cmd (cdr (assoc t apps))))
10868 (when (eq cmd 'mailcap)
10869 (require 'mailcap)
10870 (mailcap-parse-mailcaps)
10871 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10872 (command (mailcap-mime-info mime-type)))
10873 (if (stringp command)
10874 (setq cmd command)
10875 (setq cmd 'emacs))))
10876 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10877 (not (file-exists-p file))
10878 (not org-open-non-existing-files))
10879 (error "No such file: %s" file))
10880 (cond
10881 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10882 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10883 (while (string-match "['\"]%s['\"]" cmd)
10884 (setq cmd (replace-match "%s" t t cmd)))
10885 (while (string-match "%s" cmd)
10886 (setq cmd (replace-match
10887 (save-match-data
10888 (shell-quote-argument
10889 (convert-standard-filename file)))
10890 t t cmd)))
10892 ;; Replace "%1", "%2" etc. in command with group matches from regex
10893 (save-match-data
10894 (let ((match-index 1)
10895 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10896 (set-match-data link-match-data)
10897 (while (<= match-index number-of-groups)
10898 (let ((regex (concat "%" (number-to-string match-index)))
10899 (replace-with (match-string match-index dlink)))
10900 (while (string-match regex cmd)
10901 (setq cmd (replace-match replace-with t t cmd))))
10902 (setq match-index (+ match-index 1)))))
10904 (save-window-excursion
10905 (message "Running %s...done" cmd)
10906 (start-process-shell-command cmd nil cmd)
10907 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10908 ((or (stringp cmd)
10909 (eq cmd 'emacs))
10910 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10911 (widen)
10912 (if line (org-goto-line line)
10913 (if search (org-link-search search))))
10914 ((consp cmd)
10915 (let ((file (convert-standard-filename file)))
10916 (save-match-data
10917 (set-match-data link-match-data)
10918 (eval cmd))))
10919 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10920 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10921 (or (not (equal old-buffer (current-buffer)))
10922 (not (equal old-pos (point))))
10923 (org-mark-ring-push old-pos old-buffer))))
10925 (defun org-file-apps-entry-match-against-dlink-p (entry)
10926 "This function returns non-nil if `entry' uses a regular
10927 expression which should be matched against the whole link by
10928 org-open-file.
10930 It assumes that is the case when the entry uses a regular
10931 expression which has at least one grouping construct and the
10932 action is either a lisp form or a command string containing
10933 '%1', i.e. using at least one subexpression match as a
10934 parameter."
10935 (let ((selector (car entry))
10936 (action (cdr entry)))
10937 (if (stringp selector)
10938 (and (> (regexp-opt-depth selector) 0)
10939 (or (and (stringp action)
10940 (string-match "%[0-9]" action))
10941 (consp action)))
10942 nil)))
10944 (defun org-default-apps ()
10945 "Return the default applications for this operating system."
10946 (cond
10947 ((eq system-type 'darwin)
10948 org-file-apps-defaults-macosx)
10949 ((eq system-type 'windows-nt)
10950 org-file-apps-defaults-windowsnt)
10951 (t org-file-apps-defaults-gnu)))
10953 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10954 "Convert extensions to regular expressions in the cars of LIST.
10955 Also, weed out any non-string entries, because the return value is used
10956 only for regexp matching.
10957 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10958 point to the symbol `emacs', indicating that the file should
10959 be opened in Emacs."
10960 (append
10961 (delq nil
10962 (mapcar (lambda (x)
10963 (if (not (stringp (car x)))
10965 (if (string-match "\\W" (car x))
10967 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10968 list))
10969 (if add-auto-mode
10970 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10972 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10973 (defun org-file-remote-p (file)
10974 "Test whether FILE specifies a location on a remote system.
10975 Return non-nil if the location is indeed remote.
10977 For example, the filename \"/user@host:/foo\" specifies a location
10978 on the system \"/user@host:\"."
10979 (cond ((fboundp 'file-remote-p)
10980 (file-remote-p file))
10981 ((fboundp 'tramp-handle-file-remote-p)
10982 (tramp-handle-file-remote-p file))
10983 ((and (boundp 'ange-ftp-name-format)
10984 (string-match (car ange-ftp-name-format) file))
10985 t)))
10988 ;;;; Refiling
10990 (defun org-get-org-file ()
10991 "Read a filename, with default directory `org-directory'."
10992 (let ((default (or org-default-notes-file remember-data-file)))
10993 (read-file-name (format "File name [%s]: " default)
10994 (file-name-as-directory org-directory)
10995 default)))
10997 (defun org-notes-order-reversed-p ()
10998 "Check if the current file should receive notes in reversed order."
10999 (cond
11000 ((not org-reverse-note-order) nil)
11001 ((eq t org-reverse-note-order) t)
11002 ((not (listp org-reverse-note-order)) nil)
11003 (t (catch 'exit
11004 (let ((all org-reverse-note-order)
11005 entry)
11006 (while (setq entry (pop all))
11007 (if (string-match (car entry) buffer-file-name)
11008 (throw 'exit (cdr entry))))
11009 nil)))))
11011 (defvar org-refile-target-table nil
11012 "The list of refile targets, created by `org-refile'.")
11014 (defvar org-agenda-new-buffers nil
11015 "Buffers created to visit agenda files.")
11017 (defvar org-refile-cache nil
11018 "Cache for refile targets.")
11020 (defvar org-refile-markers nil
11021 "All the markers used for caching refile locations.")
11023 (defun org-refile-marker (pos)
11024 "Get a new refile marker, but only if caching is in use."
11025 (if (not org-refile-use-cache)
11027 (let ((m (make-marker)))
11028 (move-marker m pos)
11029 (push m org-refile-markers)
11030 m)))
11032 (defun org-refile-cache-clear ()
11033 "Clear the refile cache and disable all the markers."
11034 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11035 (setq org-refile-markers nil)
11036 (setq org-refile-cache nil)
11037 (message "Refile cache has been cleared"))
11039 (defun org-refile-cache-check-set (set)
11040 "Check if all the markers in the cache still have live buffers."
11041 (let (marker)
11042 (catch 'exit
11043 (while (and set (setq marker (nth 3 (pop set))))
11044 ;; if org-refile-use-outline-path is 'file, marker may be nil
11045 (when (and marker (null (marker-buffer marker)))
11046 (message "not found") (sit-for 3)
11047 (throw 'exit nil)))
11048 t)))
11050 (defun org-refile-cache-put (set &rest identifiers)
11051 "Push the refile targets SET into the cache, under IDENTIFIERS."
11052 (let* ((key (sha1 (prin1-to-string identifiers)))
11053 (entry (assoc key org-refile-cache)))
11054 (if entry
11055 (setcdr entry set)
11056 (push (cons key set) org-refile-cache))))
11058 (defun org-refile-cache-get (&rest identifiers)
11059 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11060 (cond
11061 ((not org-refile-cache) nil)
11062 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11064 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11065 org-refile-cache))))
11066 (and set (org-refile-cache-check-set set) set)))))
11068 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11069 "Produce a table with refile targets."
11070 (let ((case-fold-search nil)
11071 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11072 (entries (or org-refile-targets '((nil . (:level . 1)))))
11073 targets tgs txt re files f desc descre fast-path-p level pos0)
11074 (message "Getting targets...")
11075 (with-current-buffer (or default-buffer (current-buffer))
11076 (while (setq entry (pop entries))
11077 (setq files (car entry) desc (cdr entry))
11078 (setq fast-path-p nil)
11079 (cond
11080 ((null files) (setq files (list (current-buffer))))
11081 ((eq files 'org-agenda-files)
11082 (setq files (org-agenda-files 'unrestricted)))
11083 ((and (symbolp files) (fboundp files))
11084 (setq files (funcall files)))
11085 ((and (symbolp files) (boundp files))
11086 (setq files (symbol-value files))))
11087 (if (stringp files) (setq files (list files)))
11088 (cond
11089 ((eq (car desc) :tag)
11090 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11091 ((eq (car desc) :todo)
11092 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11093 ((eq (car desc) :regexp)
11094 (setq descre (cdr desc)))
11095 ((eq (car desc) :level)
11096 (setq descre (concat "^\\*\\{" (number-to-string
11097 (if org-odd-levels-only
11098 (1- (* 2 (cdr desc)))
11099 (cdr desc)))
11100 "\\}[ \t]")))
11101 ((eq (car desc) :maxlevel)
11102 (setq fast-path-p t)
11103 (setq descre (concat "^\\*\\{1," (number-to-string
11104 (if org-odd-levels-only
11105 (1- (* 2 (cdr desc)))
11106 (cdr desc)))
11107 "\\}[ \t]")))
11108 (t (error "Bad refiling target description %s" desc)))
11109 (while (setq f (pop files))
11110 (with-current-buffer
11111 (if (bufferp f) f (org-get-agenda-file-buffer f))
11113 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11114 (progn
11115 (if (bufferp f) (setq f (buffer-file-name
11116 (buffer-base-buffer f))))
11117 (setq f (and f (expand-file-name f)))
11118 (if (eq org-refile-use-outline-path 'file)
11119 (push (list (file-name-nondirectory f) f nil nil) tgs))
11120 (save-excursion
11121 (save-restriction
11122 (widen)
11123 (goto-char (point-min))
11124 (while (re-search-forward descre nil t)
11125 (goto-char (setq pos0 (point-at-bol)))
11126 (catch 'next
11127 (when org-refile-target-verify-function
11128 (save-match-data
11129 (or (funcall org-refile-target-verify-function)
11130 (throw 'next t))))
11131 (when (and (looking-at org-complex-heading-regexp)
11132 (not (member (match-string 4) excluded-entries))
11133 (match-string 4))
11134 (setq level (org-reduced-level
11135 (- (match-end 1) (match-beginning 1)))
11136 txt (org-link-display-format (match-string 4))
11137 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11138 re (format org-complex-heading-regexp-format
11139 (regexp-quote (match-string 4))))
11140 (when org-refile-use-outline-path
11141 (setq txt (mapconcat
11142 'org-protect-slash
11143 (append
11144 (if (eq org-refile-use-outline-path
11145 'file)
11146 (list (file-name-nondirectory
11147 (buffer-file-name
11148 (buffer-base-buffer))))
11149 (if (eq org-refile-use-outline-path
11150 'full-file-path)
11151 (list (buffer-file-name
11152 (buffer-base-buffer)))))
11153 (org-get-outline-path fast-path-p
11154 level txt)
11155 (list txt))
11156 "/")))
11157 (push (list txt f re (org-refile-marker (point)))
11158 tgs)))
11159 (when (= (point) pos0)
11160 ;; verification function has not moved point
11161 (goto-char (point-at-eol))))))))
11162 (when org-refile-use-cache
11163 (org-refile-cache-put tgs (buffer-file-name) descre))
11164 (setq targets (append tgs targets))
11165 ))))
11166 (message "Getting targets...done")
11167 (nreverse targets)))
11169 (defun org-protect-slash (s)
11170 (while (string-match "/" s)
11171 (setq s (replace-match "\\" t t s)))
11174 (defvar org-olpa (make-vector 20 nil))
11176 (defun org-get-outline-path (&optional fastp level heading)
11177 "Return the outline path to the current entry, as a list.
11179 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11180 routine which makes outline path derivations for an entire file,
11181 avoiding backtracing. Refile target collection makes use of that."
11182 (if fastp
11183 (progn
11184 (if (> level 19)
11185 (error "Outline path failure, more than 19 levels"))
11186 (loop for i from level upto 19 do
11187 (aset org-olpa i nil))
11188 (prog1
11189 (delq nil (append org-olpa nil))
11190 (aset org-olpa level heading)))
11191 (let (rtn case-fold-search)
11192 (save-excursion
11193 (save-restriction
11194 (widen)
11195 (while (org-up-heading-safe)
11196 (when (looking-at org-complex-heading-regexp)
11197 (push (org-match-string-no-properties 4) rtn)))
11198 rtn)))))
11200 (defun org-format-outline-path (path &optional width prefix separator)
11201 "Format the outline path PATH for display.
11202 WIDTH is the maximum number of characters that is available.
11203 PREFIX is a prefix to be included in the returned string,
11204 such as the file name.
11205 SEPARATOR is inserted between the different parts of the path,
11206 the default is \"/\"."
11207 (setq width (or width 79))
11208 (if prefix (setq width (- width (length prefix))))
11209 (if (not path)
11210 (or prefix "")
11211 (let* ((nsteps (length path))
11212 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11213 (maxwidth (if (<= total-width width)
11214 10000 ;; everything fits
11215 ;; we need to shorten the level headings
11216 (/ (- width nsteps) nsteps)))
11217 (org-odd-levels-only nil)
11218 (n 0)
11219 (total (1+ (length prefix))))
11220 (setq maxwidth (max maxwidth 10))
11221 (concat prefix
11222 (if prefix (or separator "/"))
11223 (mapconcat
11224 (lambda (h)
11225 (setq n (1+ n))
11226 (if (and (= n nsteps) (< maxwidth 10000))
11227 (setq maxwidth (- total-width total)))
11228 (if (< (length h) maxwidth)
11229 (progn (setq total (+ total (length h) 1)) h)
11230 (setq h (substring h 0 (- maxwidth 2))
11231 total (+ total maxwidth 1))
11232 (if (string-match "[ \t]+\\'" h)
11233 (setq h (substring h 0 (match-beginning 0))))
11234 (setq h (concat h "..")))
11235 (org-add-props h nil 'face
11236 (nth (% (1- n) org-n-level-faces)
11237 org-level-faces))
11239 path (or separator "/"))))))
11241 (defun org-display-outline-path (&optional file current separator just-return-string)
11242 "Display the current outline path in the echo area.
11244 If FILE is non-nil, prepend the output with the file name.
11245 If CURRENT is non-nil, append the current heading to the output.
11246 SEPARATOR is passed through to `org-format-outline-path'. It separates
11247 the different parts of the path and defaults to \"/\".
11248 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11249 (interactive "P")
11250 (let* (case-fold-search
11251 message-log-max ; Don't populate the *Messages* buffer
11252 (bfn (buffer-file-name (buffer-base-buffer)))
11253 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11254 res)
11255 (if current (setq path (append path
11256 (save-excursion
11257 (org-back-to-heading t)
11258 (if (looking-at org-complex-heading-regexp)
11259 (list (match-string 4)))))))
11260 (setq res
11261 (org-format-outline-path
11262 path
11263 (1- (frame-width))
11264 (and file bfn (concat (file-name-nondirectory bfn) separator))
11265 separator))
11266 (if just-return-string
11267 (org-no-properties res)
11268 (message "%s" res))))
11270 (defvar org-refile-history nil
11271 "History for refiling operations.")
11273 (defvar org-after-refile-insert-hook nil
11274 "Hook run after `org-refile' has inserted its stuff at the new location.
11275 Note that this is still *before* the stuff will be removed from
11276 the *old* location.")
11278 (defvar org-capture-last-stored-marker)
11279 (defvar org-refile-keep nil
11280 "Non-nil means `org-refile' will copy instead of refile.")
11282 (defun org-copy ()
11283 "Like `org-refile', but copy."
11284 (interactive)
11285 (let ((org-refile-keep t))
11286 (funcall 'org-refile nil nil nil "Copy")))
11288 (defun org-refile (&optional goto default-buffer rfloc msg)
11289 "Move the entry or entries at point to another heading.
11290 The list of target headings is compiled using the information in
11291 `org-refile-targets', which see.
11293 At the target location, the entry is filed as a subitem of the target
11294 heading. Depending on `org-reverse-note-order', the new subitem will
11295 either be the first or the last subitem.
11297 If there is an active region, all entries in that region will be moved.
11298 However, the region must fulfill the requirement that the first heading
11299 is the first one sets the top-level of the moved text - at most siblings
11300 below it are allowed.
11302 With prefix arg GOTO, the command will only visit the target location
11303 and not actually move anything.
11305 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11306 go to the location where the last refiling operation has put the subtree.
11307 With a prefix argument of `2', refile to the running clock.
11309 RFLOC can be a refile location obtained in a different way.
11311 MSG is a string to replace \"Refile\" in the default prompt with
11312 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11314 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11316 If you are using target caching (see `org-refile-use-cache'),
11317 you have to clear the target cache in order to find new targets.
11318 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11319 prefix argument (`C-u C-u C-u C-c C-w')."
11321 (interactive "P")
11322 (if (member goto '(0 (64)))
11323 (org-refile-cache-clear)
11324 (let* ((actionmsg (or msg "Refile"))
11325 (cbuf (current-buffer))
11326 (regionp (org-region-active-p))
11327 (region-start (and regionp (region-beginning)))
11328 (region-end (and regionp (region-end)))
11329 (region-length (and regionp (- region-end region-start)))
11330 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11331 pos it nbuf file re level reversed)
11332 (setq last-command nil)
11333 (when regionp
11334 (goto-char region-start)
11335 (or (bolp) (goto-char (point-at-bol)))
11336 (setq region-start (point))
11337 (unless (or (org-kill-is-subtree-p
11338 (buffer-substring region-start region-end))
11339 (prog1 org-refile-active-region-within-subtree
11340 (org-toggle-heading)))
11341 (error "The region is not a (sequence of) subtree(s)")))
11342 (if (equal goto '(16))
11343 (org-refile-goto-last-stored)
11344 (when (or
11345 (and (equal goto 2)
11346 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11347 (prog1
11348 (setq it (list (or org-clock-heading "running clock")
11349 (buffer-file-name
11350 (marker-buffer org-clock-hd-marker))
11352 (marker-position org-clock-hd-marker)))
11353 (setq goto nil)))
11354 (setq it (or rfloc
11355 (let (heading-text)
11356 (save-excursion
11357 (unless goto
11358 (org-back-to-heading t)
11359 (setq heading-text
11360 (nth 4 (org-heading-components))))
11362 (org-refile-get-location
11363 (cond (goto "Goto")
11364 (regionp (concat actionmsg " region to"))
11365 (t (concat actionmsg " subtree \""
11366 heading-text "\" to")))
11367 default-buffer
11368 (and (not (equal '(4) goto))
11369 org-refile-allow-creating-parent-nodes)
11370 goto))))))
11371 (setq file (nth 1 it)
11372 re (nth 2 it)
11373 pos (nth 3 it))
11374 (if (and (not goto)
11376 (equal (buffer-file-name) file)
11377 (if regionp
11378 (and (>= pos region-start)
11379 (<= pos region-end))
11380 (and (>= pos (point))
11381 (< pos (save-excursion
11382 (org-end-of-subtree t t))))))
11383 (error "Cannot refile to position inside the tree or region"))
11385 (setq nbuf (or (find-buffer-visiting file)
11386 (find-file-noselect file)))
11387 (if goto
11388 (progn
11389 (org-pop-to-buffer-same-window nbuf)
11390 (goto-char pos)
11391 (org-show-context 'org-goto))
11392 (if regionp
11393 (progn
11394 (org-kill-new (buffer-substring region-start region-end))
11395 (org-save-markers-in-region region-start region-end))
11396 (org-copy-subtree 1 nil t))
11397 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11398 (find-file-noselect file)))
11399 (setq reversed (org-notes-order-reversed-p))
11400 (save-excursion
11401 (save-restriction
11402 (widen)
11403 (if pos
11404 (progn
11405 (goto-char pos)
11406 (looking-at org-outline-regexp)
11407 (setq level (org-get-valid-level (funcall outline-level) 1))
11408 (goto-char
11409 (if reversed
11410 (or (outline-next-heading) (point-max))
11411 (or (save-excursion (org-get-next-sibling))
11412 (org-end-of-subtree t t)
11413 (point-max)))))
11414 (setq level 1)
11415 (if (not reversed)
11416 (goto-char (point-max))
11417 (goto-char (point-min))
11418 (or (outline-next-heading) (goto-char (point-max)))))
11419 (if (not (bolp)) (newline))
11420 (org-paste-subtree level)
11421 (when org-log-refile
11422 (org-add-log-setup 'refile nil nil 'findpos
11423 org-log-refile)
11424 (unless (eq org-log-refile 'note)
11425 (save-excursion (org-add-log-note))))
11426 (and org-auto-align-tags
11427 (let ((org-loop-over-headlines-in-active-region nil))
11428 (org-set-tags nil t)))
11429 (with-demoted-errors
11430 (bookmark-set "org-refile-last-stored"))
11431 ;; If we are refiling for capture, make sure that the
11432 ;; last-capture pointers point here
11433 (when (org-bound-and-true-p org-refile-for-capture)
11434 (with-demoted-errors
11435 (bookmark-set "org-capture-last-stored-marker"))
11436 (move-marker org-capture-last-stored-marker (point)))
11437 (if (fboundp 'deactivate-mark) (deactivate-mark))
11438 (run-hooks 'org-after-refile-insert-hook))))
11439 (unless org-refile-keep
11440 (if regionp
11441 (delete-region (point) (+ (point) region-length))
11442 (org-cut-subtree)))
11443 (when (featurep 'org-inlinetask)
11444 (org-inlinetask-remove-END-maybe))
11445 (setq org-markers-to-move nil)
11446 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11448 (defun org-refile-goto-last-stored ()
11449 "Go to the location where the last refile was stored."
11450 (interactive)
11451 (bookmark-jump "org-refile-last-stored")
11452 (message "This is the location of the last refile"))
11454 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11455 no-exclude)
11456 "Prompt the user for a refile location, using PROMPT.
11457 PROMPT should not be suffixed with a colon and a space, because
11458 this function appends the default value from
11459 `org-refile-history' automatically, if that is not empty.
11460 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11461 this is used for the GOTO interface."
11462 (let ((org-refile-targets org-refile-targets)
11463 (org-refile-use-outline-path org-refile-use-outline-path)
11464 excluded-entries)
11465 (when (and (derived-mode-p 'org-mode)
11466 (not org-refile-use-cache)
11467 (not no-exclude))
11468 (org-map-tree
11469 (lambda()
11470 (setq excluded-entries
11471 (append excluded-entries (list (org-get-heading t t)))))))
11472 (setq org-refile-target-table
11473 (org-refile-get-targets default-buffer excluded-entries)))
11474 (unless org-refile-target-table
11475 (error "No refile targets"))
11476 (let* ((cbuf (current-buffer))
11477 (partial-completion-mode nil)
11478 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11479 (cfunc (if (and org-refile-use-outline-path
11480 org-outline-path-complete-in-steps)
11481 'org-olpath-completing-read
11482 'org-icompleting-read))
11483 (extra (if org-refile-use-outline-path "/" ""))
11484 (cbnex (concat (buffer-name) extra))
11485 (filename (and cfn (expand-file-name cfn)))
11486 (tbl (mapcar
11487 (lambda (x)
11488 (if (and (not (member org-refile-use-outline-path
11489 '(file full-file-path)))
11490 (not (equal filename (nth 1 x))))
11491 (cons (concat (car x) extra " ("
11492 (file-name-nondirectory (nth 1 x)) ")")
11493 (cdr x))
11494 (cons (concat (car x) extra) (cdr x))))
11495 org-refile-target-table))
11496 (completion-ignore-case t)
11497 cdef
11498 (prompt (concat prompt
11499 (or (and (car org-refile-history)
11500 (concat " (default " (car org-refile-history) ")"))
11501 (and (assoc cbnex tbl) (setq cdef cbnex)
11502 (concat " (default " cbnex ")"))) ": "))
11503 pa answ parent-target child parent old-hist)
11504 (setq old-hist org-refile-history)
11505 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11506 nil 'org-refile-history (or cdef (car org-refile-history))))
11507 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11508 (org-refile-check-position pa)
11509 (if pa
11510 (progn
11511 (when (or (not org-refile-history)
11512 (not (eq old-hist org-refile-history))
11513 (not (equal (car pa) (car org-refile-history))))
11514 (setq org-refile-history
11515 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11516 org-refile-history
11517 (cdr org-refile-history))))
11518 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11519 (pop org-refile-history)))
11521 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11522 (progn
11523 (setq parent (match-string 1 answ)
11524 child (match-string 2 answ))
11525 (setq parent-target (or (assoc parent tbl)
11526 (assoc (concat parent "/") tbl)))
11527 (when (and parent-target
11528 (or (eq new-nodes t)
11529 (and (eq new-nodes 'confirm)
11530 (y-or-n-p (format "Create new node \"%s\"? "
11531 child)))))
11532 (org-refile-new-child parent-target child)))
11533 (error "Invalid target location")))))
11535 (declare-function org-string-nw-p "org-macs" (s))
11536 (defun org-refile-check-position (refile-pointer)
11537 "Check if the refile pointer matches the headline to which it points."
11538 (let* ((file (nth 1 refile-pointer))
11539 (re (nth 2 refile-pointer))
11540 (pos (nth 3 refile-pointer))
11541 buffer)
11542 (if (and (not (markerp pos)) (not file))
11543 (error "Please save the buffer to a file before refiling")
11544 (when (org-string-nw-p re)
11545 (setq buffer (if (markerp pos)
11546 (marker-buffer pos)
11547 (or (find-buffer-visiting file)
11548 (find-file-noselect file))))
11549 (with-current-buffer buffer
11550 (save-excursion
11551 (save-restriction
11552 (widen)
11553 (goto-char pos)
11554 (beginning-of-line 1)
11555 (unless (org-looking-at-p re)
11556 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11558 (defun org-refile-new-child (parent-target child)
11559 "Use refile target PARENT-TARGET to add new CHILD below it."
11560 (unless parent-target
11561 (error "Cannot find parent for new node"))
11562 (let ((file (nth 1 parent-target))
11563 (pos (nth 3 parent-target))
11564 level)
11565 (with-current-buffer (or (find-buffer-visiting file)
11566 (find-file-noselect file))
11567 (save-excursion
11568 (save-restriction
11569 (widen)
11570 (if pos
11571 (goto-char pos)
11572 (goto-char (point-max))
11573 (if (not (bolp)) (newline)))
11574 (when (looking-at org-outline-regexp)
11575 (setq level (funcall outline-level))
11576 (org-end-of-subtree t t))
11577 (org-back-over-empty-lines)
11578 (insert "\n" (make-string
11579 (if pos (org-get-valid-level level 1) 1) ?*)
11580 " " child "\n")
11581 (beginning-of-line 0)
11582 (list (concat (car parent-target) "/" child) file "" (point)))))))
11584 (defun org-olpath-completing-read (prompt collection &rest args)
11585 "Read an outline path like a file name."
11586 (let ((thetable collection)
11587 (org-completion-use-ido nil) ; does not work with ido.
11588 (org-completion-use-iswitchb nil)) ; or iswitchb
11589 (apply
11590 'org-icompleting-read prompt
11591 (lambda (string predicate &optional flag)
11592 (let (rtn r f (l (length string)))
11593 (cond
11594 ((eq flag nil)
11595 ;; try completion
11596 (try-completion string thetable))
11597 ((eq flag t)
11598 ;; all-completions
11599 (setq rtn (all-completions string thetable predicate))
11600 (mapcar
11601 (lambda (x)
11602 (setq r (substring x l))
11603 (if (string-match " ([^)]*)$" x)
11604 (setq f (match-string 0 x))
11605 (setq f ""))
11606 (if (string-match "/" r)
11607 (concat string (substring r 0 (match-end 0)) f)
11609 rtn))
11610 ((eq flag 'lambda)
11611 ;; exact match?
11612 (assoc string thetable)))))
11613 args)))
11615 ;;;; Dynamic blocks
11617 (defun org-find-dblock (name)
11618 "Find the first dynamic block with name NAME in the buffer.
11619 If not found, stay at current position and return nil."
11620 (let ((case-fold-search t) pos)
11621 (save-excursion
11622 (goto-char (point-min))
11623 (setq pos (and (re-search-forward
11624 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11625 (match-beginning 0))))
11626 (if pos (goto-char pos))
11627 pos))
11629 (defconst org-dblock-start-re
11630 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11631 "Matches the start line of a dynamic block, with parameters.")
11633 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11634 "Matches the end of a dynamic block.")
11636 (defun org-create-dblock (plist)
11637 "Create a dynamic block section, with parameters taken from PLIST.
11638 PLIST must contain a :name entry which is used as name of the block."
11639 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11640 (end-of-line 1)
11641 (newline))
11642 (let ((col (current-column))
11643 (name (plist-get plist :name)))
11644 (insert "#+BEGIN: " name)
11645 (while plist
11646 (if (eq (car plist) :name)
11647 (setq plist (cddr plist))
11648 (insert " " (prin1-to-string (pop plist)))))
11649 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11650 (beginning-of-line -2)))
11652 (defun org-prepare-dblock ()
11653 "Prepare dynamic block for refresh.
11654 This empties the block, puts the cursor at the insert position and returns
11655 the property list including an extra property :name with the block name."
11656 (unless (looking-at org-dblock-start-re)
11657 (error "Not at a dynamic block"))
11658 (let* ((begdel (1+ (match-end 0)))
11659 (name (org-no-properties (match-string 1)))
11660 (params (append (list :name name)
11661 (read (concat "(" (match-string 3) ")")))))
11662 (save-excursion
11663 (beginning-of-line 1)
11664 (skip-chars-forward " \t")
11665 (setq params (plist-put params :indentation-column (current-column))))
11666 (unless (re-search-forward org-dblock-end-re nil t)
11667 (error "Dynamic block not terminated"))
11668 (setq params
11669 (append params
11670 (list :content (buffer-substring
11671 begdel (match-beginning 0)))))
11672 (delete-region begdel (match-beginning 0))
11673 (goto-char begdel)
11674 (open-line 1)
11675 params))
11677 (defun org-map-dblocks (&optional command)
11678 "Apply COMMAND to all dynamic blocks in the current buffer.
11679 If COMMAND is not given, use `org-update-dblock'."
11680 (let ((cmd (or command 'org-update-dblock)))
11681 (save-excursion
11682 (goto-char (point-min))
11683 (while (re-search-forward org-dblock-start-re nil t)
11684 (goto-char (match-beginning 0))
11685 (save-excursion
11686 (condition-case nil
11687 (funcall cmd)
11688 (error (message "Error during update of dynamic block"))))
11689 (unless (re-search-forward org-dblock-end-re nil t)
11690 (error "Dynamic block not terminated"))))))
11692 (defun org-dblock-update (&optional arg)
11693 "User command for updating dynamic blocks.
11694 Update the dynamic block at point. With prefix ARG, update all dynamic
11695 blocks in the buffer."
11696 (interactive "P")
11697 (if arg
11698 (org-update-all-dblocks)
11699 (or (looking-at org-dblock-start-re)
11700 (org-beginning-of-dblock))
11701 (org-update-dblock)))
11703 (defun org-update-dblock ()
11704 "Update the dynamic block at point.
11705 This means to empty the block, parse for parameters and then call
11706 the correct writing function."
11707 (interactive)
11708 (save-window-excursion
11709 (let* ((pos (point))
11710 (line (org-current-line))
11711 (params (org-prepare-dblock))
11712 (name (plist-get params :name))
11713 (indent (plist-get params :indentation-column))
11714 (cmd (intern (concat "org-dblock-write:" name))))
11715 (message "Updating dynamic block `%s' at line %d..." name line)
11716 (funcall cmd params)
11717 (message "Updating dynamic block `%s' at line %d...done" name line)
11718 (goto-char pos)
11719 (when (and indent (> indent 0))
11720 (setq indent (make-string indent ?\ ))
11721 (save-excursion
11722 (org-beginning-of-dblock)
11723 (forward-line 1)
11724 (while (not (looking-at org-dblock-end-re))
11725 (insert indent)
11726 (beginning-of-line 2))
11727 (when (looking-at org-dblock-end-re)
11728 (and (looking-at "[ \t]+")
11729 (replace-match ""))
11730 (insert indent)))))))
11732 (defun org-beginning-of-dblock ()
11733 "Find the beginning of the dynamic block at point.
11734 Error if there is no such block at point."
11735 (let ((pos (point))
11736 beg)
11737 (end-of-line 1)
11738 (if (and (re-search-backward org-dblock-start-re nil t)
11739 (setq beg (match-beginning 0))
11740 (re-search-forward org-dblock-end-re nil t)
11741 (> (match-end 0) pos))
11742 (goto-char beg)
11743 (goto-char pos)
11744 (error "Not in a dynamic block"))))
11746 (defun org-update-all-dblocks ()
11747 "Update all dynamic blocks in the buffer.
11748 This function can be used in a hook."
11749 (interactive)
11750 (when (derived-mode-p 'org-mode)
11751 (org-map-dblocks 'org-update-dblock)))
11754 ;;;; Completion
11756 (defun org-get-export-keywords ()
11757 "Return a list of all currently understood export keywords.
11758 Export keywords include options, block names, attributes and
11759 keywords relative to each registered export back-end."
11760 (delq nil
11761 (let (keywords)
11762 (mapc
11763 (lambda (back-end)
11764 (let ((props (cdr back-end)))
11765 ;; Back-end name (for keywords, like #+LATEX:)
11766 (push (upcase (symbol-name (car back-end))) keywords)
11767 ;; Back-end options.
11768 (mapc (lambda (option) (push (cadr option) keywords))
11769 (plist-get (cdr back-end) :options-alist))))
11770 (org-bound-and-true-p org-export-registered-backends))
11771 keywords)))
11773 (defconst org-options-keywords
11774 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11775 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11776 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11777 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11778 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11780 (defcustom org-structure-template-alist
11781 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11782 "<src lang=\"?\">\n\n</src>")
11783 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11784 "<example>\n?\n</example>")
11785 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11786 "<quote>\n?\n</quote>")
11787 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11788 "<verse>\n?\n</verse>")
11789 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11790 "<verbatim>\n?\n</verbatim>")
11791 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11792 "<center>\n?\n</center>")
11793 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11794 "<literal style=\"latex\">\n?\n</literal>")
11795 ("L" "#+LaTeX: "
11796 "<literal style=\"latex\">?</literal>")
11797 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11798 "<literal style=\"html\">\n?\n</literal>")
11799 ("H" "#+HTML: "
11800 "<literal style=\"html\">?</literal>")
11801 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11802 ("A" "#+ASCII: ")
11803 ("i" "#+INDEX: ?"
11804 "#+INDEX: ?")
11805 ("I" "#+INCLUDE: %file ?"
11806 "<include file=%file markup=\"?\">"))
11807 "Structure completion elements.
11808 This is a list of abbreviation keys and values. The value gets inserted
11809 if you type `<' followed by the key and then press the completion key,
11810 usually `M-TAB'. %file will be replaced by a file name after prompting
11811 for the file using completion. The cursor will be placed at the position
11812 of the `?` in the template.
11813 There are two templates for each key, the first uses the original Org syntax,
11814 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11815 the default when the /org-mtags.el/ module has been loaded. See also the
11816 variable `org-mtags-prefer-muse-templates'."
11817 :group 'org-completion
11818 :type '(repeat
11819 (string :tag "Key")
11820 (string :tag "Template")
11821 (string :tag "Muse Template")))
11823 (defun org-try-structure-completion ()
11824 "Try to complete a structure template before point.
11825 This looks for strings like \"<e\" on an otherwise empty line and
11826 expands them."
11827 (let ((l (buffer-substring (point-at-bol) (point)))
11829 (when (and (looking-at "[ \t]*$")
11830 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11831 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11832 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11833 (match-beginning 1)) a)
11834 t)))
11836 (defun org-complete-expand-structure-template (start cell)
11837 "Expand a structure template."
11838 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11839 (rpl (nth (if musep 2 1) cell))
11840 (ind ""))
11841 (delete-region start (point))
11842 (when (string-match "\\`#\\+" rpl)
11843 (cond
11844 ((bolp))
11845 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11846 (setq ind (buffer-substring (point-at-bol) (point))))
11847 (t (newline))))
11848 (setq start (point))
11849 (if (string-match "%file" rpl)
11850 (setq rpl (replace-match
11851 (concat
11852 "\""
11853 (save-match-data
11854 (abbreviate-file-name (read-file-name "Include file: ")))
11855 "\"")
11856 t t rpl)))
11857 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11858 (concat "\n" ind)))
11859 (insert rpl)
11860 (if (re-search-backward "\\?" start t) (delete-char 1))))
11862 ;;;; TODO, DEADLINE, Comments
11864 (defun org-toggle-comment ()
11865 "Change the COMMENT state of an entry."
11866 (interactive)
11867 (save-excursion
11868 (org-back-to-heading)
11869 (let (case-fold-search)
11870 (cond
11871 ((looking-at (format org-heading-keyword-regexp-format
11872 org-comment-string))
11873 (goto-char (match-end 1))
11874 (looking-at (concat " +" org-comment-string))
11875 (replace-match "" t t)
11876 (when (eolp) (insert " ")))
11877 ((looking-at org-outline-regexp)
11878 (goto-char (match-end 0))
11879 (insert org-comment-string " "))))))
11881 (defvar org-last-todo-state-is-todo nil
11882 "This is non-nil when the last TODO state change led to a TODO state.
11883 If the last change removed the TODO tag or switched to DONE, then
11884 this is nil.")
11886 (defvar org-setting-tags nil) ; dynamically skipped
11888 (defvar org-todo-setup-filter-hook nil
11889 "Hook for functions that pre-filter todo specs.
11890 Each function takes a todo spec and returns either nil or the spec
11891 transformed into canonical form." )
11893 (defvar org-todo-get-default-hook nil
11894 "Hook for functions that get a default item for todo.
11895 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11896 nil or a string to be used for the todo mark." )
11898 (defvar org-agenda-headline-snapshot-before-repeat)
11900 (defun org-current-effective-time ()
11901 "Return current time adjusted for `org-extend-today-until' variable."
11902 (let* ((ct (org-current-time))
11903 (dct (decode-time ct))
11904 (ct1
11905 (cond
11906 (org-use-last-clock-out-time-as-effective-time
11907 (or (org-clock-get-last-clock-out-time) ct))
11908 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11909 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11910 (t ct))))
11911 ct1))
11913 (defun org-todo-yesterday (&optional arg)
11914 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11915 (interactive "P")
11916 (if (eq major-mode 'org-agenda-mode)
11917 (apply 'org-agenda-todo-yesterday arg)
11918 (let* ((hour (third (decode-time
11919 (org-current-time))))
11920 (org-extend-today-until (1+ hour)))
11921 (org-todo arg))))
11923 (defvar org-block-entry-blocking ""
11924 "First entry preventing the TODO state change.")
11926 (defun org-todo (&optional arg)
11927 "Change the TODO state of an item.
11928 The state of an item is given by a keyword at the start of the heading,
11929 like
11930 *** TODO Write paper
11931 *** DONE Call mom
11933 The different keywords are specified in the variable `org-todo-keywords'.
11934 By default the available states are \"TODO\" and \"DONE\".
11935 So for this example: when the item starts with TODO, it is changed to DONE.
11936 When it starts with DONE, the DONE is removed. And when neither TODO nor
11937 DONE are present, add TODO at the beginning of the heading.
11939 With \\[universal-argument] prefix arg, use completion to determine the new \
11940 state.
11941 With numeric prefix arg, switch to that state.
11942 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11943 keywords (nextset).
11944 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11945 With a numeric prefix arg of 0, inhibit note taking for the change.
11947 For calling through lisp, arg is also interpreted in the following way:
11948 'none -> empty state
11949 \"\"(empty string) -> switch to empty state
11950 'done -> switch to DONE
11951 'nextset -> switch to the next set of keywords
11952 'previousset -> switch to the previous set of keywords
11953 \"WAITING\" -> switch to the specified keyword, but only if it
11954 really is a member of `org-todo-keywords'."
11955 (interactive "P")
11956 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11957 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11958 'region-start-level 'region))
11959 org-loop-over-headlines-in-active-region)
11960 (org-map-entries
11961 `(org-todo ,arg)
11962 org-loop-over-headlines-in-active-region
11963 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11964 (if (equal arg '(16)) (setq arg 'nextset))
11965 (let ((org-blocker-hook org-blocker-hook)
11966 commentp
11967 case-fold-search)
11968 (when (equal arg '(64))
11969 (setq arg nil org-blocker-hook nil))
11970 (when (and org-blocker-hook
11971 (or org-inhibit-blocking
11972 (org-entry-get nil "NOBLOCKING")))
11973 (setq org-blocker-hook nil))
11974 (save-excursion
11975 (catch 'exit
11976 (org-back-to-heading t)
11977 (when (looking-at (concat "^\\*+ " org-comment-string))
11978 (org-toggle-comment)
11979 (setq commentp t))
11980 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11981 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11982 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11983 (let* ((match-data (match-data))
11984 (startpos (point-at-bol))
11985 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11986 (org-log-done org-log-done)
11987 (org-log-repeat org-log-repeat)
11988 (org-todo-log-states org-todo-log-states)
11989 (org-inhibit-logging
11990 (if (equal arg 0)
11991 (progn (setq arg nil) 'note) org-inhibit-logging))
11992 (this (match-string 1))
11993 (hl-pos (match-beginning 0))
11994 (head (org-get-todo-sequence-head this))
11995 (ass (assoc head org-todo-kwd-alist))
11996 (interpret (nth 1 ass))
11997 (done-word (nth 3 ass))
11998 (final-done-word (nth 4 ass))
11999 (org-last-state (or this ""))
12000 (completion-ignore-case t)
12001 (member (member this org-todo-keywords-1))
12002 (tail (cdr member))
12003 (org-state (cond
12004 ((and org-todo-key-trigger
12005 (or (and (equal arg '(4))
12006 (eq org-use-fast-todo-selection 'prefix))
12007 (and (not arg) org-use-fast-todo-selection
12008 (not (eq org-use-fast-todo-selection
12009 'prefix)))))
12010 ;; Use fast selection
12011 (org-fast-todo-selection))
12012 ((and (equal arg '(4))
12013 (or (not org-use-fast-todo-selection)
12014 (not org-todo-key-trigger)))
12015 ;; Read a state with completion
12016 (org-icompleting-read
12017 "State: " (mapcar (lambda(x) (list x))
12018 org-todo-keywords-1)
12019 nil t))
12020 ((eq arg 'right)
12021 (if this
12022 (if tail (car tail) nil)
12023 (car org-todo-keywords-1)))
12024 ((eq arg 'left)
12025 (if (equal member org-todo-keywords-1)
12027 (if this
12028 (nth (- (length org-todo-keywords-1)
12029 (length tail) 2)
12030 org-todo-keywords-1)
12031 (org-last org-todo-keywords-1))))
12032 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12033 (setq arg nil))) ; hack to fall back to cycling
12034 (arg
12035 ;; user or caller requests a specific state
12036 (cond
12037 ((equal arg "") nil)
12038 ((eq arg 'none) nil)
12039 ((eq arg 'done) (or done-word (car org-done-keywords)))
12040 ((eq arg 'nextset)
12041 (or (car (cdr (member head org-todo-heads)))
12042 (car org-todo-heads)))
12043 ((eq arg 'previousset)
12044 (let ((org-todo-heads (reverse org-todo-heads)))
12045 (or (car (cdr (member head org-todo-heads)))
12046 (car org-todo-heads))))
12047 ((car (member arg org-todo-keywords-1)))
12048 ((stringp arg)
12049 (error "State `%s' not valid in this file" arg))
12050 ((nth (1- (prefix-numeric-value arg))
12051 org-todo-keywords-1))))
12052 ((null member) (or head (car org-todo-keywords-1)))
12053 ((equal this final-done-word) nil) ;; -> make empty
12054 ((null tail) nil) ;; -> first entry
12055 ((memq interpret '(type priority))
12056 (if (eq this-command last-command)
12057 (car tail)
12058 (if (> (length tail) 0)
12059 (or done-word (car org-done-keywords))
12060 nil)))
12062 (car tail))))
12063 (org-state (or
12064 (run-hook-with-args-until-success
12065 'org-todo-get-default-hook org-state org-last-state)
12066 org-state))
12067 (next (if org-state (concat " " org-state " ") " "))
12068 (change-plist (list :type 'todo-state-change :from this :to org-state
12069 :position startpos))
12070 dolog now-done-p)
12071 (when org-blocker-hook
12072 (setq org-last-todo-state-is-todo
12073 (not (member this org-done-keywords)))
12074 (unless (save-excursion
12075 (save-match-data
12076 (org-with-wide-buffer
12077 (run-hook-with-args-until-failure
12078 'org-blocker-hook change-plist))))
12079 (if (org-called-interactively-p 'interactive)
12080 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12081 this org-state org-block-entry-blocking)
12082 ;; fail silently
12083 (message "TODO state change from %s to %s blocked (by \"%s\")"
12084 this org-state org-block-entry-blocking)
12085 (throw 'exit nil))))
12086 (store-match-data match-data)
12087 (replace-match next t t)
12088 (unless (pos-visible-in-window-p hl-pos)
12089 (message "TODO state changed to %s" (org-trim next)))
12090 (unless head
12091 (setq head (org-get-todo-sequence-head org-state)
12092 ass (assoc head org-todo-kwd-alist)
12093 interpret (nth 1 ass)
12094 done-word (nth 3 ass)
12095 final-done-word (nth 4 ass)))
12096 (when (memq arg '(nextset previousset))
12097 (message "Keyword-Set %d/%d: %s"
12098 (- (length org-todo-sets) -1
12099 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12100 (length org-todo-sets)
12101 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12102 (setq org-last-todo-state-is-todo
12103 (not (member org-state org-done-keywords)))
12104 (setq now-done-p (and (member org-state org-done-keywords)
12105 (not (member this org-done-keywords))))
12106 (and logging (org-local-logging logging))
12107 (when (and (or org-todo-log-states org-log-done)
12108 (not (eq org-inhibit-logging t))
12109 (not (memq arg '(nextset previousset))))
12110 ;; we need to look at recording a time and note
12111 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12112 (nth 2 (assoc this org-todo-log-states))))
12113 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12114 (setq dolog 'time))
12115 (when (and org-state
12116 (member org-state org-not-done-keywords)
12117 (not (member this org-not-done-keywords)))
12118 ;; This is now a todo state and was not one before
12119 ;; If there was a CLOSED time stamp, get rid of it.
12120 (org-add-planning-info nil nil 'closed))
12121 (when (and now-done-p org-log-done)
12122 ;; It is now done, and it was not done before
12123 (org-add-planning-info 'closed (org-current-effective-time))
12124 (if (and (not dolog) (eq 'note org-log-done))
12125 (org-add-log-setup 'done org-state this 'findpos 'note)))
12126 (when (and org-state dolog)
12127 ;; This is a non-nil state, and we need to log it
12128 (org-add-log-setup 'state org-state this 'findpos dolog)))
12129 ;; Fixup tag positioning
12130 (org-todo-trigger-tag-changes org-state)
12131 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12132 (when org-provide-todo-statistics
12133 (org-update-parent-todo-statistics))
12134 (run-hooks 'org-after-todo-state-change-hook)
12135 (if (and arg (not (member org-state org-done-keywords)))
12136 (setq head (org-get-todo-sequence-head org-state)))
12137 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12138 ;; Do we need to trigger a repeat?
12139 (when now-done-p
12140 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12141 ;; This is for the agenda, take a snapshot of the headline.
12142 (save-match-data
12143 (setq org-agenda-headline-snapshot-before-repeat
12144 (org-get-heading))))
12145 (org-auto-repeat-maybe org-state))
12146 ;; Fixup cursor location if close to the keyword
12147 (if (and (outline-on-heading-p)
12148 (not (bolp))
12149 (save-excursion (beginning-of-line 1)
12150 (looking-at org-todo-line-regexp))
12151 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12152 (progn
12153 (goto-char (or (match-end 2) (match-end 1)))
12154 (and (looking-at " ") (just-one-space))))
12155 (when org-trigger-hook
12156 (save-excursion
12157 (run-hook-with-args 'org-trigger-hook change-plist)))
12158 (when commentp (org-toggle-comment))))))))
12160 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12161 "Block turning an entry into a TODO, using the hierarchy.
12162 This checks whether the current task should be blocked from state
12163 changes. Such blocking occurs when:
12165 1. The task has children which are not all in a completed state.
12167 2. A task has a parent with the property :ORDERED:, and there
12168 are siblings prior to the current task with incomplete
12169 status.
12171 3. The parent of the task is blocked because it has siblings that should
12172 be done first, or is child of a block grandparent TODO entry."
12174 (if (not org-enforce-todo-dependencies)
12175 t ; if locally turned off don't block
12176 (catch 'dont-block
12177 ;; If this is not a todo state change, or if this entry is already DONE,
12178 ;; do not block
12179 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12180 (member (plist-get change-plist :from)
12181 (cons 'done org-done-keywords))
12182 (member (plist-get change-plist :to)
12183 (cons 'todo org-not-done-keywords))
12184 (not (plist-get change-plist :to)))
12185 (throw 'dont-block t))
12186 ;; If this task has children, and any are undone, it's blocked
12187 (save-excursion
12188 (org-back-to-heading t)
12189 (let ((this-level (funcall outline-level)))
12190 (outline-next-heading)
12191 (let ((child-level (funcall outline-level)))
12192 (while (and (not (eobp))
12193 (> child-level this-level))
12194 ;; this todo has children, check whether they are all
12195 ;; completed
12196 (if (and (not (org-entry-is-done-p))
12197 (org-entry-is-todo-p))
12198 (progn (setq org-block-entry-blocking (org-get-heading))
12199 (throw 'dont-block nil)))
12200 (outline-next-heading)
12201 (setq child-level (funcall outline-level))))))
12202 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12203 ;; any previous siblings are undone, it's blocked
12204 (save-excursion
12205 (org-back-to-heading t)
12206 (let* ((pos (point))
12207 (parent-pos (and (org-up-heading-safe) (point))))
12208 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12209 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12210 (forward-line 1)
12211 (re-search-forward org-not-done-heading-regexp pos t))
12212 (setq org-block-entry-blocking (match-string 0))
12213 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12214 ;; Search further up the hierarchy, to see if an ancestor is blocked
12215 (while t
12216 (goto-char parent-pos)
12217 (if (not (looking-at org-not-done-heading-regexp))
12218 (throw 'dont-block t)) ; do not block, parent is not a TODO
12219 (setq pos (point))
12220 (setq parent-pos (and (org-up-heading-safe) (point)))
12221 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12222 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12223 (forward-line 1)
12224 (re-search-forward org-not-done-heading-regexp pos t)
12225 (setq org-block-entry-blocking (org-get-heading)))
12226 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12228 (defcustom org-track-ordered-property-with-tag nil
12229 "Should the ORDERED property also be shown as a tag?
12230 The ORDERED property decides if an entry should require subtasks to be
12231 completed in sequence. Since a property is not very visible, setting
12232 this option means that toggling the ORDERED property with the command
12233 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12234 not relevant for the behavior, but it makes things more visible.
12236 Note that toggling the tag with tags commands will not change the property
12237 and therefore not influence behavior!
12239 This can be t, meaning the tag ORDERED should be used, It can also be a
12240 string to select a different tag for this task."
12241 :group 'org-todo
12242 :type '(choice
12243 (const :tag "No tracking" nil)
12244 (const :tag "Track with ORDERED tag" t)
12245 (string :tag "Use other tag")))
12247 (defun org-toggle-ordered-property ()
12248 "Toggle the ORDERED property of the current entry.
12249 For better visibility, you can track the value of this property with a tag.
12250 See variable `org-track-ordered-property-with-tag'."
12251 (interactive)
12252 (let* ((t1 org-track-ordered-property-with-tag)
12253 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12254 (save-excursion
12255 (org-back-to-heading)
12256 (if (org-entry-get nil "ORDERED")
12257 (progn
12258 (org-delete-property "ORDERED" "PROPERTIES")
12259 (and tag (org-toggle-tag tag 'off))
12260 (message "Subtasks can be completed in arbitrary order"))
12261 (org-entry-put nil "ORDERED" "t")
12262 (and tag (org-toggle-tag tag 'on))
12263 (message "Subtasks must be completed in sequence")))))
12265 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12266 (defun org-block-todo-from-checkboxes (change-plist)
12267 "Block turning an entry into a TODO, using checkboxes.
12268 This checks whether the current task should be blocked from state
12269 changes because there are unchecked boxes in this entry."
12270 (if (not org-enforce-todo-checkbox-dependencies)
12271 t ; if locally turned off don't block
12272 (catch 'dont-block
12273 ;; If this is not a todo state change, or if this entry is already DONE,
12274 ;; do not block
12275 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12276 (member (plist-get change-plist :from)
12277 (cons 'done org-done-keywords))
12278 (member (plist-get change-plist :to)
12279 (cons 'todo org-not-done-keywords))
12280 (not (plist-get change-plist :to)))
12281 (throw 'dont-block t))
12282 ;; If this task has checkboxes that are not checked, it's blocked
12283 (save-excursion
12284 (org-back-to-heading t)
12285 (let ((beg (point)) end)
12286 (outline-next-heading)
12287 (setq end (point))
12288 (goto-char beg)
12289 (if (org-list-search-forward
12290 (concat (org-item-beginning-re)
12291 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12292 "\\[[- ]\\]")
12293 end t)
12294 (progn
12295 (if (boundp 'org-blocked-by-checkboxes)
12296 (setq org-blocked-by-checkboxes t))
12297 (throw 'dont-block nil)))))
12298 t))) ; do not block
12300 (defun org-entry-blocked-p ()
12301 "Is the current entry blocked?"
12302 (org-with-silent-modifications
12303 (if (org-entry-get nil "NOBLOCKING")
12304 nil ;; Never block this entry
12305 (not (run-hook-with-args-until-failure
12306 'org-blocker-hook
12307 (list :type 'todo-state-change
12308 :position (point)
12309 :from 'todo
12310 :to 'done))))))
12312 (defun org-update-statistics-cookies (all)
12313 "Update the statistics cookie, either from TODO or from checkboxes.
12314 This should be called with the cursor in a line with a statistics cookie."
12315 (interactive "P")
12316 (if all
12317 (progn
12318 (org-update-checkbox-count 'all)
12319 (org-map-entries 'org-update-parent-todo-statistics))
12320 (if (not (org-at-heading-p))
12321 (org-update-checkbox-count)
12322 (let ((pos (point-marker))
12323 end l1 l2)
12324 (ignore-errors (org-back-to-heading t))
12325 (if (not (org-at-heading-p))
12326 (org-update-checkbox-count)
12327 (setq l1 (org-outline-level))
12328 (setq end (save-excursion
12329 (outline-next-heading)
12330 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12331 (point)))
12332 (if (and (save-excursion
12333 (re-search-forward
12334 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12335 (not (save-excursion (re-search-forward
12336 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12337 (org-update-checkbox-count)
12338 (if (and l2 (> l2 l1))
12339 (progn
12340 (goto-char end)
12341 (org-update-parent-todo-statistics))
12342 (goto-char pos)
12343 (beginning-of-line 1)
12344 (while (re-search-forward
12345 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12346 (point-at-eol) t)
12347 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12348 (goto-char pos)
12349 (move-marker pos nil)))))
12351 (defvar org-entry-property-inherited-from) ;; defined below
12352 (defun org-update-parent-todo-statistics ()
12353 "Update any statistics cookie in the parent of the current headline.
12354 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12355 the entire subtree and this will travel up the hierarchy and update
12356 statistics everywhere."
12357 (let* ((prop (save-excursion (org-up-heading-safe)
12358 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12359 (recursive (or (not org-hierarchical-todo-statistics)
12360 (and prop (string-match "\\<recursive\\>" prop))))
12361 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12363 (first t)
12364 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12365 level ltoggle l1 new ndel
12366 (cnt-all 0) (cnt-done 0) is-percent kwd
12367 checkbox-beg ov ovs ove cookie-present)
12368 (catch 'exit
12369 (save-excursion
12370 (beginning-of-line 1)
12371 (setq ltoggle (funcall outline-level))
12372 ;; Three situations are to consider:
12374 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12375 ;; to the top-level ancestor on the headline;
12377 ;; 2. If parent has "recursive" property, repeat up to the
12378 ;; headline setting that property, taking inheritance into
12379 ;; account;
12381 ;; 3. Else, move up to direct parent and proceed only once.
12382 (while (and (setq level (org-up-heading-safe))
12383 (or recursive first)
12384 (>= (point) lim))
12385 (setq first nil cookie-present nil)
12386 (unless (and level
12387 (not (string-match
12388 "\\<checkbox\\>"
12389 (downcase (or (org-entry-get nil "COOKIE_DATA")
12390 "")))))
12391 (throw 'exit nil))
12392 (while (re-search-forward box-re (point-at-eol) t)
12393 (setq cnt-all 0 cnt-done 0 cookie-present t)
12394 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12395 (save-match-data
12396 (unless (outline-next-heading) (throw 'exit nil))
12397 (while (and (looking-at org-complex-heading-regexp)
12398 (> (setq l1 (length (match-string 1))) level))
12399 (setq kwd (and (or recursive (= l1 ltoggle))
12400 (match-string 2)))
12401 (if (or (eq org-provide-todo-statistics 'all-headlines)
12402 (and (listp org-provide-todo-statistics)
12403 (or (member kwd org-provide-todo-statistics)
12404 (member kwd org-done-keywords))))
12405 (setq cnt-all (1+ cnt-all))
12406 (if (eq org-provide-todo-statistics t)
12407 (and kwd (setq cnt-all (1+ cnt-all)))))
12408 (and (member kwd org-done-keywords)
12409 (setq cnt-done (1+ cnt-done)))
12410 (outline-next-heading)))
12411 (setq new
12412 (if is-percent
12413 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12414 (format "[%d/%d]" cnt-done cnt-all))
12415 ndel (- (match-end 0) checkbox-beg))
12416 ;; handle overlays when updating cookie from column view
12417 (when (setq ov (car (overlays-at checkbox-beg)))
12418 (setq ovs (overlay-start ov) ove (overlay-end ov))
12419 (delete-overlay ov))
12420 (goto-char checkbox-beg)
12421 (insert new)
12422 (delete-region (point) (+ (point) ndel))
12423 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12424 (when ov (move-overlay ov ovs ove)))
12425 (when cookie-present
12426 (run-hook-with-args 'org-after-todo-statistics-hook
12427 cnt-done (- cnt-all cnt-done))))))
12428 (run-hooks 'org-todo-statistics-hook)))
12430 (defvar org-after-todo-statistics-hook nil
12431 "Hook that is called after a TODO statistics cookie has been updated.
12432 Each function is called with two arguments: the number of not-done entries
12433 and the number of done entries.
12435 For example, the following function, when added to this hook, will switch
12436 an entry to DONE when all children are done, and back to TODO when new
12437 entries are set to a TODO status. Note that this hook is only called
12438 when there is a statistics cookie in the headline!
12440 (defun org-summary-todo (n-done n-not-done)
12441 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12442 (let (org-log-done org-log-states) ; turn off logging
12443 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12446 (defvar org-todo-statistics-hook nil
12447 "Hook that is run whenever Org thinks TODO statistics should be updated.
12448 This hook runs even if there is no statistics cookie present, in which case
12449 `org-after-todo-statistics-hook' would not run.")
12451 (defun org-todo-trigger-tag-changes (state)
12452 "Apply the changes defined in `org-todo-state-tags-triggers'."
12453 (let ((l org-todo-state-tags-triggers)
12454 changes)
12455 (when (or (not state) (equal state ""))
12456 (setq changes (append changes (cdr (assoc "" l)))))
12457 (when (and (stringp state) (> (length state) 0))
12458 (setq changes (append changes (cdr (assoc state l)))))
12459 (when (member state org-not-done-keywords)
12460 (setq changes (append changes (cdr (assoc 'todo l)))))
12461 (when (member state org-done-keywords)
12462 (setq changes (append changes (cdr (assoc 'done l)))))
12463 (dolist (c changes)
12464 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12466 (defun org-local-logging (value)
12467 "Get logging settings from a property VALUE."
12468 (let* (words w a)
12469 ;; directly set the variables, they are already local.
12470 (setq org-log-done nil
12471 org-log-repeat nil
12472 org-todo-log-states nil)
12473 (setq words (org-split-string value))
12474 (while (setq w (pop words))
12475 (cond
12476 ((setq a (assoc w org-startup-options))
12477 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12478 (set (nth 1 a) (nth 2 a))))
12479 ((setq a (org-extract-log-state-settings w))
12480 (and (member (car a) org-todo-keywords-1)
12481 (push a org-todo-log-states)))))))
12483 (defun org-get-todo-sequence-head (kwd)
12484 "Return the head of the TODO sequence to which KWD belongs.
12485 If KWD is not set, check if there is a text property remembering the
12486 right sequence."
12487 (let (p)
12488 (cond
12489 ((not kwd)
12490 (or (get-text-property (point-at-bol) 'org-todo-head)
12491 (progn
12492 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12493 nil (point-at-eol)))
12494 (get-text-property p 'org-todo-head))))
12495 ((not (member kwd org-todo-keywords-1))
12496 (car org-todo-keywords-1))
12497 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12499 (defun org-fast-todo-selection ()
12500 "Fast TODO keyword selection with single keys.
12501 Returns the new TODO keyword, or nil if no state change should occur."
12502 (let* ((fulltable org-todo-key-alist)
12503 (done-keywords org-done-keywords) ;; needed for the faces.
12504 (maxlen (apply 'max (mapcar
12505 (lambda (x)
12506 (if (stringp (car x)) (string-width (car x)) 0))
12507 fulltable)))
12508 (expert nil)
12509 (fwidth (+ maxlen 3 1 3))
12510 (ncol (/ (- (window-width) 4) fwidth))
12511 tg cnt e c tbl
12512 groups ingroup)
12513 (save-excursion
12514 (save-window-excursion
12515 (if expert
12516 (set-buffer (get-buffer-create " *Org todo*"))
12517 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12518 (erase-buffer)
12519 (org-set-local 'org-done-keywords done-keywords)
12520 (setq tbl fulltable cnt 0)
12521 (while (setq e (pop tbl))
12522 (cond
12523 ((equal e '(:startgroup))
12524 (push '() groups) (setq ingroup t)
12525 (when (not (= cnt 0))
12526 (setq cnt 0)
12527 (insert "\n"))
12528 (insert "{ "))
12529 ((equal e '(:endgroup))
12530 (setq ingroup nil cnt 0)
12531 (insert "}\n"))
12532 ((equal e '(:newline))
12533 (when (not (= cnt 0))
12534 (setq cnt 0)
12535 (insert "\n")
12536 (setq e (car tbl))
12537 (while (equal (car tbl) '(:newline))
12538 (insert "\n")
12539 (setq tbl (cdr tbl)))))
12541 (setq tg (car e) c (cdr e))
12542 (if ingroup (push tg (car groups)))
12543 (setq tg (org-add-props tg nil 'face
12544 (org-get-todo-face tg)))
12545 (if (and (= cnt 0) (not ingroup)) (insert " "))
12546 (insert "[" c "] " tg (make-string
12547 (- fwidth 4 (length tg)) ?\ ))
12548 (when (= (setq cnt (1+ cnt)) ncol)
12549 (insert "\n")
12550 (if ingroup (insert " "))
12551 (setq cnt 0)))))
12552 (insert "\n")
12553 (goto-char (point-min))
12554 (if (not expert) (org-fit-window-to-buffer))
12555 (message "[a-z..]:Set [SPC]:clear")
12556 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12557 (cond
12558 ((or (= c ?\C-g)
12559 (and (= c ?q) (not (rassoc c fulltable))))
12560 (setq quit-flag t))
12561 ((= c ?\ ) nil)
12562 ((setq e (rassoc c fulltable) tg (car e))
12564 (t (setq quit-flag t)))))))
12566 (defun org-entry-is-todo-p ()
12567 (member (org-get-todo-state) org-not-done-keywords))
12569 (defun org-entry-is-done-p ()
12570 (member (org-get-todo-state) org-done-keywords))
12572 (defun org-get-todo-state ()
12573 (save-excursion
12574 (org-back-to-heading t)
12575 (and (looking-at org-todo-line-regexp)
12576 (match-end 2)
12577 (match-string 2))))
12579 (defun org-at-date-range-p (&optional inactive-ok)
12580 "Is the cursor inside a date range?"
12581 (interactive)
12582 (save-excursion
12583 (catch 'exit
12584 (let ((pos (point)))
12585 (skip-chars-backward "^[<\r\n")
12586 (skip-chars-backward "<[")
12587 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12588 (>= (match-end 0) pos)
12589 (throw 'exit t))
12590 (skip-chars-backward "^<[\r\n")
12591 (skip-chars-backward "<[")
12592 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12593 (>= (match-end 0) pos)
12594 (throw 'exit t)))
12595 nil)))
12597 (defun org-get-repeat (&optional tagline)
12598 "Check if there is a deadline/schedule with repeater in this entry."
12599 (save-match-data
12600 (save-excursion
12601 (org-back-to-heading t)
12602 (and (re-search-forward (if tagline
12603 (concat tagline "\\s-*" org-repeat-re)
12604 org-repeat-re)
12605 (org-entry-end-position) t)
12606 (match-string-no-properties 1)))))
12608 (defvar org-last-changed-timestamp)
12609 (defvar org-last-inserted-timestamp)
12610 (defvar org-log-post-message)
12611 (defvar org-log-note-purpose)
12612 (defvar org-log-note-how)
12613 (defvar org-log-note-extra)
12614 (defun org-auto-repeat-maybe (done-word)
12615 "Check if the current headline contains a repeated deadline/schedule.
12616 If yes, set TODO state back to what it was and change the base date
12617 of repeating deadline/scheduled time stamps to new date.
12618 This function is run automatically after each state change to a DONE state."
12619 ;; last-state is dynamically scoped into this function
12620 (let* ((repeat (org-get-repeat))
12621 (aa (assoc org-last-state org-todo-kwd-alist))
12622 (interpret (nth 1 aa))
12623 (head (nth 2 aa))
12624 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12625 (msg "Entry repeats: ")
12626 (org-log-done nil)
12627 (org-todo-log-states nil)
12628 re type n what ts time to-state)
12629 (when repeat
12630 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12631 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12632 org-todo-repeat-to-state))
12633 (unless (and to-state (member to-state org-todo-keywords-1))
12634 (setq to-state (if (eq interpret 'type) org-last-state head)))
12635 (org-todo to-state)
12636 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12637 (org-entry-put nil "LAST_REPEAT" (format-time-string
12638 (org-time-stamp-format t t))))
12639 (when org-log-repeat
12640 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12641 (memq 'org-add-log-note post-command-hook))
12642 ;; OK, we are already setup for some record
12643 (if (eq org-log-repeat 'note)
12644 ;; make sure we take a note, not only a time stamp
12645 (setq org-log-note-how 'note))
12646 ;; Set up for taking a record
12647 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12648 org-last-state
12649 'findpos org-log-repeat)))
12650 (org-back-to-heading t)
12651 (org-add-planning-info nil nil 'closed)
12652 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12653 org-deadline-time-regexp "\\)\\|\\("
12654 org-ts-regexp "\\)"))
12655 (while (re-search-forward
12656 re (save-excursion (outline-next-heading) (point)) t)
12657 (setq type (if (match-end 1) org-scheduled-string
12658 (if (match-end 3) org-deadline-string "Plain:"))
12659 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12660 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12661 (setq n (string-to-number (match-string 2 ts))
12662 what (match-string 3 ts))
12663 (if (equal what "w") (setq n (* n 7) what "d"))
12664 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12665 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12666 ;; Preparation, see if we need to modify the start date for the change
12667 (when (match-end 1)
12668 (setq time (save-match-data (org-time-string-to-time ts)))
12669 (cond
12670 ((equal (match-string 1 ts) ".")
12671 ;; Shift starting date to today
12672 (org-timestamp-change
12673 (- (org-today) (time-to-days time))
12674 'day))
12675 ((equal (match-string 1 ts) "+")
12676 (let ((nshiftmax 10) (nshift 0))
12677 (while (or (= nshift 0)
12678 (<= (time-to-days time)
12679 (time-to-days (current-time))))
12680 (when (= (incf nshift) nshiftmax)
12681 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12682 (error "Abort")))
12683 (org-timestamp-change n (cdr (assoc what whata)))
12684 (org-at-timestamp-p t)
12685 (setq ts (match-string 1))
12686 (setq time (save-match-data (org-time-string-to-time ts)))))
12687 (org-timestamp-change (- n) (cdr (assoc what whata)))
12688 ;; rematch, so that we have everything in place for the real shift
12689 (org-at-timestamp-p t)
12690 (setq ts (match-string 1))
12691 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12692 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12693 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12694 (setq org-log-post-message msg)
12695 (message "%s" msg))))
12697 (defun org-show-todo-tree (arg)
12698 "Make a compact tree which shows all headlines marked with TODO.
12699 The tree will show the lines where the regexp matches, and all higher
12700 headlines above the match.
12701 With a \\[universal-argument] prefix, prompt for a regexp to match.
12702 With a numeric prefix N, construct a sparse tree for the Nth element
12703 of `org-todo-keywords-1'."
12704 (interactive "P")
12705 (let ((case-fold-search nil)
12706 (kwd-re
12707 (cond ((null arg) org-not-done-regexp)
12708 ((equal arg '(4))
12709 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12710 (mapcar 'list org-todo-keywords-1))))
12711 (concat "\\("
12712 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12713 "\\)\\>")))
12714 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12715 (regexp-quote (nth (1- (prefix-numeric-value arg))
12716 org-todo-keywords-1)))
12717 (t (error "Invalid prefix argument: %s" arg)))))
12718 (message "%d TODO entries found"
12719 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12721 (defun org-deadline (arg &optional time)
12722 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12723 With one universal prefix argument, remove any deadline from the item.
12724 With two universal prefix arguments, prompt for a warning delay.
12725 With argument TIME, set the deadline at the corresponding date. TIME
12726 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12727 (interactive "P")
12728 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12729 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12730 'region-start-level 'region))
12731 org-loop-over-headlines-in-active-region)
12732 (org-map-entries
12733 `(org-deadline ',arg ,time)
12734 org-loop-over-headlines-in-active-region
12735 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12736 (let* ((old-date (org-entry-get nil "DEADLINE"))
12737 (old-date-time (if old-date (org-time-string-to-time old-date)))
12738 (repeater (and old-date
12739 (string-match
12740 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12741 old-date)
12742 (match-string 1 old-date))))
12743 (cond
12744 ((equal arg '(4))
12745 (when (and old-date org-log-redeadline)
12746 (org-add-log-setup 'deldeadline nil old-date 'findpos
12747 org-log-redeadline))
12748 (org-remove-timestamp-with-keyword org-deadline-string)
12749 (message "Item no longer has a deadline."))
12750 ((equal arg '(16))
12751 (save-excursion
12752 (if (re-search-forward
12753 org-deadline-time-regexp
12754 (save-excursion (outline-next-heading) (point)) t)
12755 (let* ((rpl0 (match-string 1))
12756 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12757 (replace-match
12758 (concat org-deadline-string
12759 " <" rpl
12760 (format " -%dd"
12761 (abs
12762 (- (time-to-days
12763 (save-match-data
12764 (org-read-date nil t nil "Warn starting from" old-date-time)))
12765 (time-to-days old-date-time))))
12766 ">") t t))
12767 (user-error "No deadline information to update"))))
12769 (org-add-planning-info 'deadline time 'closed)
12770 (when (and old-date org-log-redeadline
12771 (not (equal old-date
12772 (substring org-last-inserted-timestamp 1 -1))))
12773 (org-add-log-setup 'redeadline nil old-date 'findpos
12774 org-log-redeadline))
12775 (when repeater
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (when (re-search-forward (concat org-deadline-string " "
12779 org-last-inserted-timestamp)
12780 (save-excursion
12781 (outline-next-heading) (point)) t)
12782 (goto-char (1- (match-end 0)))
12783 (insert " " repeater)
12784 (setq org-last-inserted-timestamp
12785 (concat (substring org-last-inserted-timestamp 0 -1)
12786 " " repeater
12787 (substring org-last-inserted-timestamp -1))))))
12788 (message "Deadline on %s" org-last-inserted-timestamp))))))
12790 (defun org-schedule (arg &optional time)
12791 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12792 With one universal prefix argument, remove any scheduling date from the item.
12793 With two universal prefix arguments, prompt for a delay cookie.
12794 With argument TIME, scheduled at the corresponding date. TIME can
12795 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12796 (interactive "P")
12797 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12798 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12799 'region-start-level 'region))
12800 org-loop-over-headlines-in-active-region)
12801 (org-map-entries
12802 `(org-schedule ',arg ,time)
12803 org-loop-over-headlines-in-active-region
12804 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12805 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12806 (old-date-time (if old-date (org-time-string-to-time old-date)))
12807 (repeater (and old-date
12808 (string-match
12809 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12810 old-date)
12811 (match-string 1 old-date))))
12812 (cond
12813 ((equal arg '(4))
12814 (progn
12815 (when (and old-date org-log-reschedule)
12816 (org-add-log-setup 'delschedule nil old-date 'findpos
12817 org-log-reschedule))
12818 (org-remove-timestamp-with-keyword org-scheduled-string)
12819 (message "Item is no longer scheduled.")))
12820 ((equal arg '(16))
12821 (save-excursion
12822 (if (re-search-forward
12823 org-scheduled-time-regexp
12824 (save-excursion (outline-next-heading) (point)) t)
12825 (let* ((rpl0 (match-string 1))
12826 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12827 (replace-match
12828 (concat org-scheduled-string
12829 " <" rpl
12830 (format " -%dd"
12831 (abs
12832 (- (time-to-days
12833 (save-match-data
12834 (org-read-date nil t nil "Delay until" old-date-time)))
12835 (time-to-days old-date-time))))
12836 ">") t t))
12837 (user-error "No scheduled information to update"))))
12839 (org-add-planning-info 'scheduled time 'closed)
12840 (when (and old-date org-log-reschedule
12841 (not (equal old-date
12842 (substring org-last-inserted-timestamp 1 -1))))
12843 (org-add-log-setup 'reschedule nil old-date 'findpos
12844 org-log-reschedule))
12845 (when repeater
12846 (save-excursion
12847 (org-back-to-heading t)
12848 (when (re-search-forward (concat org-scheduled-string " "
12849 org-last-inserted-timestamp)
12850 (save-excursion
12851 (outline-next-heading) (point)) t)
12852 (goto-char (1- (match-end 0)))
12853 (insert " " repeater)
12854 (setq org-last-inserted-timestamp
12855 (concat (substring org-last-inserted-timestamp 0 -1)
12856 " " repeater
12857 (substring org-last-inserted-timestamp -1))))))
12858 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12860 (defun org-get-scheduled-time (pom &optional inherit)
12861 "Get the scheduled time as a time tuple, of a format suitable
12862 for calling org-schedule with, or if there is no scheduling,
12863 returns nil."
12864 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12865 (when time
12866 (apply 'encode-time (org-parse-time-string time)))))
12868 (defun org-get-deadline-time (pom &optional inherit)
12869 "Get the deadline as a time tuple, of a format suitable for
12870 calling org-deadline with, or if there is no scheduling, returns
12871 nil."
12872 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12873 (when time
12874 (apply 'encode-time (org-parse-time-string time)))))
12876 (defun org-remove-timestamp-with-keyword (keyword)
12877 "Remove all time stamps with KEYWORD in the current entry."
12878 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12879 beg)
12880 (save-excursion
12881 (org-back-to-heading t)
12882 (setq beg (point))
12883 (outline-next-heading)
12884 (while (re-search-backward re beg t)
12885 (replace-match "")
12886 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12887 (equal (char-before) ?\ ))
12888 (backward-delete-char 1)
12889 (if (string-match "^[ \t]*$" (buffer-substring
12890 (point-at-bol) (point-at-eol)))
12891 (delete-region (point-at-bol)
12892 (min (point-max) (1+ (point-at-eol))))))))))
12894 (defun org-add-planning-info (what &optional time &rest remove)
12895 "Insert new timestamp with keyword in the line directly after the headline.
12896 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12897 If non is given, the user is prompted for a date.
12898 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12899 be removed."
12900 (interactive)
12901 (let (org-time-was-given org-end-time-was-given ts
12902 end default-time default-input)
12904 (catch 'exit
12905 (when (and (memq what '(scheduled deadline))
12906 (or (not time)
12907 (and (stringp time)
12908 (string-match "^[-+]+[0-9]" time))))
12909 ;; Try to get a default date/time from existing timestamp
12910 (save-excursion
12911 (org-back-to-heading t)
12912 (setq end (save-excursion (outline-next-heading) (point)))
12913 (when (re-search-forward (if (eq what 'scheduled)
12914 org-scheduled-time-regexp
12915 org-deadline-time-regexp)
12916 end t)
12917 (setq ts (match-string 1)
12918 default-time
12919 (apply 'encode-time (org-parse-time-string ts))
12920 default-input (and ts (org-get-compact-tod ts))))))
12921 (when what
12922 (setq time
12923 (if (stringp time)
12924 ;; This is a string (relative or absolute), set proper date
12925 (apply 'encode-time
12926 (org-read-date-analyze
12927 time default-time (decode-time default-time)))
12928 ;; If necessary, get the time from the user
12929 (or time (org-read-date nil 'to-time nil nil
12930 default-time default-input)))))
12932 (when (and org-insert-labeled-timestamps-at-point
12933 (member what '(scheduled deadline)))
12934 (insert
12935 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12936 (org-insert-time-stamp time org-time-was-given
12937 nil nil nil (list org-end-time-was-given))
12938 (setq what nil))
12939 (save-excursion
12940 (save-restriction
12941 (let (col list elt ts buffer-invisibility-spec)
12942 (org-back-to-heading t)
12943 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12944 (goto-char (match-end 1))
12945 (setq col (current-column))
12946 (goto-char (match-end 0))
12947 (if (eobp) (insert "\n") (forward-char 1))
12948 (when (and (not what)
12949 (not (looking-at
12950 (concat "[ \t]*"
12951 org-keyword-time-not-clock-regexp))))
12952 ;; Nothing to add, nothing to remove...... :-)
12953 (throw 'exit nil))
12954 (if (and (not (looking-at org-outline-regexp))
12955 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12956 "[^\r\n]*"))
12957 (not (equal (match-string 1) org-clock-string)))
12958 (narrow-to-region (match-beginning 0) (match-end 0))
12959 (insert-before-markers "\n")
12960 (backward-char 1)
12961 (narrow-to-region (point) (point))
12962 (and org-adapt-indentation (org-indent-to-column col)))
12963 ;; Check if we have to remove something.
12964 (setq list (cons what remove))
12965 (while list
12966 (setq elt (pop list))
12967 (when (or (and (eq elt 'scheduled)
12968 (re-search-forward org-scheduled-time-regexp nil t))
12969 (and (eq elt 'deadline)
12970 (re-search-forward org-deadline-time-regexp nil t))
12971 (and (eq elt 'closed)
12972 (re-search-forward org-closed-time-regexp nil t)))
12973 (replace-match "")
12974 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12975 (and (looking-at "[ \t]+") (replace-match ""))
12976 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12977 (when what
12978 (insert
12979 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12980 (cond ((eq what 'scheduled) org-scheduled-string)
12981 ((eq what 'deadline) org-deadline-string)
12982 ((eq what 'closed) org-closed-string))
12983 " ")
12984 (setq ts (org-insert-time-stamp
12985 time
12986 (or org-time-was-given
12987 (and (eq what 'closed) org-log-done-with-time))
12988 (eq what 'closed)
12989 nil nil (list org-end-time-was-given)))
12990 (insert
12991 (if (not (or (bolp) (eq (char-before) ?\ )
12992 (memq (char-after) '(32 10))
12993 (eobp))) " " ""))
12994 (end-of-line 1))
12995 (goto-char (point-min))
12996 (widen)
12997 (if (and (looking-at "[ \t]*\n")
12998 (equal (char-before) ?\n))
12999 (delete-region (1- (point)) (point-at-eol)))
13000 ts))))))
13002 (defvar org-log-note-marker (make-marker))
13003 (defvar org-log-note-purpose nil)
13004 (defvar org-log-note-state nil)
13005 (defvar org-log-note-previous-state nil)
13006 (defvar org-log-note-how nil)
13007 (defvar org-log-note-extra nil)
13008 (defvar org-log-note-window-configuration nil)
13009 (defvar org-log-note-return-to (make-marker))
13010 (defvar org-log-note-effective-time nil
13011 "Remembered current time so that dynamically scoped
13012 `org-extend-today-until' affects tha timestamps in state change
13013 log")
13015 (defvar org-log-post-message nil
13016 "Message to be displayed after a log note has been stored.
13017 The auto-repeater uses this.")
13019 (defun org-add-note ()
13020 "Add a note to the current entry.
13021 This is done in the same way as adding a state change note."
13022 (interactive)
13023 (org-add-log-setup 'note nil nil 'findpos nil))
13025 (defvar org-property-end-re)
13026 (defun org-add-log-setup (&optional purpose state prev-state
13027 findpos how extra)
13028 "Set up the post command hook to take a note.
13029 If this is about to TODO state change, the new state is expected in STATE.
13030 When FINDPOS is non-nil, find the correct position for the note in
13031 the current entry. If not, assume that it can be inserted at point.
13032 HOW is an indicator what kind of note should be created.
13033 EXTRA is additional text that will be inserted into the notes buffer."
13034 (let* ((org-log-into-drawer (org-log-into-drawer))
13035 (drawer (cond ((stringp org-log-into-drawer)
13036 org-log-into-drawer)
13037 (org-log-into-drawer "LOGBOOK"))))
13038 (save-restriction
13039 (save-excursion
13040 (when findpos
13041 (org-back-to-heading t)
13042 (narrow-to-region (point) (save-excursion
13043 (outline-next-heading) (point)))
13044 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13045 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13046 "[^\r\n]*\\)?"))
13047 (goto-char (match-end 0))
13048 (cond
13049 (drawer
13050 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13051 nil t)
13052 (progn
13053 (goto-char (match-end 0))
13054 (or org-log-states-order-reversed
13055 (and (re-search-forward org-property-end-re nil t)
13056 (goto-char (1- (match-beginning 0))))))
13057 (insert "\n:" drawer ":\n:END:")
13058 (beginning-of-line 0)
13059 (org-indent-line)
13060 (beginning-of-line 2)
13061 (org-indent-line)
13062 (end-of-line 0)))
13063 ((and org-log-state-notes-insert-after-drawers
13064 (save-excursion
13065 (forward-line) (looking-at org-drawer-regexp)))
13066 (forward-line)
13067 (while (looking-at org-drawer-regexp)
13068 (goto-char (match-end 0))
13069 (re-search-forward org-property-end-re (point-max) t)
13070 (forward-line))
13071 (forward-line -1)))
13072 (unless org-log-states-order-reversed
13073 (and (= (char-after) ?\n) (forward-char 1))
13074 (org-skip-over-state-notes)
13075 (skip-chars-backward " \t\n\r")))
13076 (move-marker org-log-note-marker (point))
13077 (setq org-log-note-purpose purpose
13078 org-log-note-state state
13079 org-log-note-previous-state prev-state
13080 org-log-note-how how
13081 org-log-note-extra extra
13082 org-log-note-effective-time (org-current-effective-time))
13083 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13085 (defun org-skip-over-state-notes ()
13086 "Skip past the list of State notes in an entry."
13087 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13088 (when (ignore-errors (goto-char (org-in-item-p)))
13089 (let* ((struct (org-list-struct))
13090 (prevs (org-list-prevs-alist struct)))
13091 (while (looking-at "[ \t]*- State")
13092 (goto-char (or (org-list-get-next-item (point) struct prevs)
13093 (org-list-get-item-end (point) struct)))))))
13095 (defun org-add-log-note (&optional purpose)
13096 "Pop up a window for taking a note, and add this note later at point."
13097 (remove-hook 'post-command-hook 'org-add-log-note)
13098 (setq org-log-note-window-configuration (current-window-configuration))
13099 (delete-other-windows)
13100 (move-marker org-log-note-return-to (point))
13101 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13102 (goto-char org-log-note-marker)
13103 (org-switch-to-buffer-other-window "*Org Note*")
13104 (erase-buffer)
13105 (if (memq org-log-note-how '(time state))
13106 (let (current-prefix-arg) (org-store-log-note))
13107 (let ((org-inhibit-startup t)) (org-mode))
13108 (insert (format "# Insert note for %s.
13109 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13110 (cond
13111 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13112 ((eq org-log-note-purpose 'done) "closed todo item")
13113 ((eq org-log-note-purpose 'state)
13114 (format "state change from \"%s\" to \"%s\""
13115 (or org-log-note-previous-state "")
13116 (or org-log-note-state "")))
13117 ((eq org-log-note-purpose 'reschedule)
13118 "rescheduling")
13119 ((eq org-log-note-purpose 'delschedule)
13120 "no longer scheduled")
13121 ((eq org-log-note-purpose 'redeadline)
13122 "changing deadline")
13123 ((eq org-log-note-purpose 'deldeadline)
13124 "removing deadline")
13125 ((eq org-log-note-purpose 'refile)
13126 "refiling")
13127 ((eq org-log-note-purpose 'note)
13128 "this entry")
13129 (t (error "This should not happen")))))
13130 (if org-log-note-extra (insert org-log-note-extra))
13131 (org-set-local 'org-finish-function 'org-store-log-note)
13132 (run-hooks 'org-log-buffer-setup-hook)))
13134 (defvar org-note-abort nil) ; dynamically scoped
13135 (defun org-store-log-note ()
13136 "Finish taking a log note, and insert it to where it belongs."
13137 (let ((txt (buffer-string)))
13138 (kill-buffer (current-buffer))
13139 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13140 lines ind bul)
13141 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13142 (setq txt (replace-match "" t t txt)))
13143 (if (string-match "\\s-+\\'" txt)
13144 (setq txt (replace-match "" t t txt)))
13145 (setq lines (org-split-string txt "\n"))
13146 (when (and note (string-match "\\S-" note))
13147 (setq note
13148 (org-replace-escapes
13149 note
13150 (list (cons "%u" (user-login-name))
13151 (cons "%U" user-full-name)
13152 (cons "%t" (format-time-string
13153 (org-time-stamp-format 'long 'inactive)
13154 org-log-note-effective-time))
13155 (cons "%T" (format-time-string
13156 (org-time-stamp-format 'long nil)
13157 org-log-note-effective-time))
13158 (cons "%d" (format-time-string
13159 (org-time-stamp-format nil 'inactive)
13160 org-log-note-effective-time))
13161 (cons "%D" (format-time-string
13162 (org-time-stamp-format nil nil)
13163 org-log-note-effective-time))
13164 (cons "%s" (if org-log-note-state
13165 (concat "\"" org-log-note-state "\"")
13166 ""))
13167 (cons "%S" (if org-log-note-previous-state
13168 (concat "\"" org-log-note-previous-state "\"")
13169 "\"\"")))))
13170 (if lines (setq note (concat note " \\\\")))
13171 (push note lines))
13172 (when (or current-prefix-arg org-note-abort)
13173 (when org-log-into-drawer
13174 (org-remove-empty-drawer-at
13175 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13176 org-log-note-marker))
13177 (setq lines nil))
13178 (when lines
13179 (with-current-buffer (marker-buffer org-log-note-marker)
13180 (save-excursion
13181 (goto-char org-log-note-marker)
13182 (move-marker org-log-note-marker nil)
13183 (end-of-line 1)
13184 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13185 (setq ind (save-excursion
13186 (if (ignore-errors (goto-char (org-in-item-p)))
13187 (let ((struct (org-list-struct)))
13188 (org-list-get-ind
13189 (org-list-get-top-point struct) struct))
13190 (skip-chars-backward " \r\t\n")
13191 (cond
13192 ((and (org-at-heading-p)
13193 org-adapt-indentation)
13194 (1+ (org-current-level)))
13195 ((org-at-heading-p) 0)
13196 (t (org-get-indentation))))))
13197 (setq bul (org-list-bullet-string "-"))
13198 (org-indent-line-to ind)
13199 (insert bul (pop lines))
13200 (let ((ind-body (+ (length bul) ind)))
13201 (while lines
13202 (insert "\n")
13203 (org-indent-line-to ind-body)
13204 (insert (pop lines))))
13205 (message "Note stored")
13206 (org-back-to-heading t)
13207 (org-cycle-hide-drawers 'children))))))
13208 (set-window-configuration org-log-note-window-configuration)
13209 (with-current-buffer (marker-buffer org-log-note-return-to)
13210 (goto-char org-log-note-return-to))
13211 (move-marker org-log-note-return-to nil)
13212 (and org-log-post-message (message "%s" org-log-post-message)))
13214 (defun org-remove-empty-drawer-at (drawer pos)
13215 "Remove an empty drawer DRAWER at position POS.
13216 POS may also be a marker."
13217 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13218 (save-excursion
13219 (save-restriction
13220 (widen)
13221 (goto-char pos)
13222 (if (org-in-regexp
13223 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13224 (replace-match ""))))))
13226 (defvar org-ts-type nil)
13227 (defun org-sparse-tree (&optional arg type)
13228 "Create a sparse tree, prompt for the details.
13229 This command can create sparse trees. You first need to select the type
13230 of match used to create the tree:
13232 t Show all TODO entries.
13233 T Show entries with a specific TODO keyword.
13234 m Show entries selected by a tags/property match.
13235 p Enter a property name and its value (both with completion on existing
13236 names/values) and show entries with that property.
13237 r Show entries matching a regular expression (`/' can be used as well).
13238 b Show deadlines and scheduled items before a date.
13239 a Show deadlines and scheduled items after a date.
13240 d Show deadlines due within `org-deadline-warning-days'.
13241 D Show deadlines and scheduled items between a date range."
13242 (interactive "P")
13243 (let (ans kwd value ts-type)
13244 (setq type (or type org-sparse-tree-default-date-type))
13245 (setq org-ts-type type)
13246 (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"
13247 (cond ((eq type 'all) "all timestamps")
13248 ((eq type 'scheduled) "only scheduled")
13249 ((eq type 'deadline) "only deadline")
13250 ((eq type 'active) "only active timestamps")
13251 ((eq type 'inactive) "only inactive timestamps")
13252 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13253 (t "scheduled/deadline")))
13254 (setq ans (read-char-exclusive))
13255 (cond
13256 ((equal ans ?c)
13257 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13258 ((equal ans ?d)
13259 (call-interactively 'org-check-deadlines))
13260 ((equal ans ?b)
13261 (call-interactively 'org-check-before-date))
13262 ((equal ans ?a)
13263 (call-interactively 'org-check-after-date))
13264 ((equal ans ?D)
13265 (call-interactively 'org-check-dates-range))
13266 ((equal ans ?t)
13267 (call-interactively 'org-show-todo-tree))
13268 ((equal ans ?T)
13269 (org-show-todo-tree '(4)))
13270 ((member ans '(?T ?m))
13271 (call-interactively 'org-match-sparse-tree))
13272 ((member ans '(?p ?P))
13273 (setq kwd (org-icompleting-read "Property: "
13274 (mapcar 'list (org-buffer-property-keys))))
13275 (setq value (org-icompleting-read "Value: "
13276 (mapcar 'list (org-property-values kwd))))
13277 (unless (string-match "\\`{.*}\\'" value)
13278 (setq value (concat "\"" value "\"")))
13279 (org-match-sparse-tree arg (concat kwd "=" value)))
13280 ((member ans '(?r ?R ?/))
13281 (call-interactively 'org-occur))
13282 (t (error "No such sparse tree command \"%c\"" ans)))))
13284 (defvar org-occur-highlights nil
13285 "List of overlays used for occur matches.")
13286 (make-variable-buffer-local 'org-occur-highlights)
13287 (defvar org-occur-parameters nil
13288 "Parameters of the active org-occur calls.
13289 This is a list, each call to org-occur pushes as cons cell,
13290 containing the regular expression and the callback, onto the list.
13291 The list can contain several entries if `org-occur' has been called
13292 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13293 will only contain one set of parameters. When the highlights are
13294 removed (for example with `C-c C-c', or with the next edit (depending
13295 on `org-remove-highlights-with-change'), this variable is emptied
13296 as well.")
13297 (make-variable-buffer-local 'org-occur-parameters)
13299 (defun org-occur (regexp &optional keep-previous callback)
13300 "Make a compact tree which shows all matches of REGEXP.
13301 The tree will show the lines where the regexp matches, and all higher
13302 headlines above the match. It will also show the heading after the match,
13303 to make sure editing the matching entry is easy.
13304 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13305 call to `org-occur' will be kept, to allow stacking of calls to this
13306 command.
13307 If CALLBACK is non-nil, it is a function which is called to confirm
13308 that the match should indeed be shown."
13309 (interactive "sRegexp: \nP")
13310 (when (equal regexp "")
13311 (error "Regexp cannot be empty"))
13312 (unless keep-previous
13313 (org-remove-occur-highlights nil nil t))
13314 (push (cons regexp callback) org-occur-parameters)
13315 (let ((cnt 0))
13316 (save-excursion
13317 (goto-char (point-min))
13318 (if (or (not keep-previous) ; do not want to keep
13319 (not org-occur-highlights)) ; no previous matches
13320 ;; hide everything
13321 (org-overview))
13322 (while (re-search-forward regexp nil t)
13323 (when (or (not callback)
13324 (save-match-data (funcall callback)))
13325 (setq cnt (1+ cnt))
13326 (when org-highlight-sparse-tree-matches
13327 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13328 (org-show-context 'occur-tree))))
13329 (when org-remove-highlights-with-change
13330 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13331 nil 'local))
13332 (unless org-sparse-tree-open-archived-trees
13333 (org-hide-archived-subtrees (point-min) (point-max)))
13334 (run-hooks 'org-occur-hook)
13335 (if (org-called-interactively-p 'interactive)
13336 (message "%d match(es) for regexp %s" cnt regexp))
13337 cnt))
13339 (defun org-occur-next-match (&optional n reset)
13340 "Function for `next-error-function' to find sparse tree matches.
13341 N is the number of matches to move, when negative move backwards.
13342 RESET is entirely ignored - this function always goes back to the
13343 starting point when no match is found."
13344 (let* ((limit (if (< n 0) (point-min) (point-max)))
13345 (search-func (if (< n 0)
13346 'previous-single-char-property-change
13347 'next-single-char-property-change))
13348 (n (abs n))
13349 (pos (point))
13351 (catch 'exit
13352 (while (setq p1 (funcall search-func (point) 'org-type))
13353 (when (equal p1 limit)
13354 (goto-char pos)
13355 (error "No more matches"))
13356 (when (equal (get-char-property p1 'org-type) 'org-occur)
13357 (setq n (1- n))
13358 (when (= n 0)
13359 (goto-char p1)
13360 (throw 'exit (point))))
13361 (goto-char p1))
13362 (goto-char p1)
13363 (error "No more matches"))))
13365 (defun org-show-context (&optional key)
13366 "Make sure point and context are visible.
13367 How much context is shown depends upon the variables
13368 `org-show-hierarchy-above', `org-show-following-heading',
13369 `org-show-entry-below' and `org-show-siblings'."
13370 (let ((heading-p (org-at-heading-p t))
13371 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13372 (following-p (org-get-alist-option org-show-following-heading key))
13373 (entry-p (org-get-alist-option org-show-entry-below key))
13374 (siblings-p (org-get-alist-option org-show-siblings key)))
13375 ;; Show heading or entry text
13376 (if (and heading-p (not entry-p))
13377 (org-flag-heading nil) ; only show the heading
13378 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13379 (org-show-hidden-entry))) ; show entire entry
13380 (when following-p
13381 ;; Show next sibling, or heading below text
13382 (save-excursion
13383 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13384 (org-flag-heading nil))))
13385 (when siblings-p (org-show-siblings))
13386 (when hierarchy-p
13387 ;; show all higher headings, possibly with siblings
13388 (save-excursion
13389 (while (and (condition-case nil
13390 (progn (org-up-heading-all 1) t)
13391 (error nil))
13392 (not (bobp)))
13393 (org-flag-heading nil)
13394 (when siblings-p (org-show-siblings)))))
13395 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13397 (defvar org-reveal-start-hook nil
13398 "Hook run before revealing a location.")
13400 (defun org-reveal (&optional siblings)
13401 "Show current entry, hierarchy above it, and the following headline.
13402 This can be used to show a consistent set of context around locations
13403 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13404 not t for the search context.
13406 With optional argument SIBLINGS, on each level of the hierarchy all
13407 siblings are shown. This repairs the tree structure to what it would
13408 look like when opened with hierarchical calls to `org-cycle'.
13409 With double optional argument \\[universal-argument] \\[universal-argument], \
13410 go to the parent and show the
13411 entire tree."
13412 (interactive "P")
13413 (run-hooks 'org-reveal-start-hook)
13414 (let ((org-show-hierarchy-above t)
13415 (org-show-following-heading t)
13416 (org-show-siblings (if siblings t org-show-siblings)))
13417 (org-show-context nil))
13418 (when (equal siblings '(16))
13419 (save-excursion
13420 (when (org-up-heading-safe)
13421 (org-show-subtree)
13422 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13424 (defun org-highlight-new-match (beg end)
13425 "Highlight from BEG to END and mark the highlight is an occur headline."
13426 (let ((ov (make-overlay beg end)))
13427 (overlay-put ov 'face 'secondary-selection)
13428 (overlay-put ov 'org-type 'org-occur)
13429 (push ov org-occur-highlights)))
13431 (defun org-remove-occur-highlights (&optional beg end noremove)
13432 "Remove the occur highlights from the buffer.
13433 BEG and END are ignored. If NOREMOVE is nil, remove this function
13434 from the `before-change-functions' in the current buffer."
13435 (interactive)
13436 (unless org-inhibit-highlight-removal
13437 (mapc 'delete-overlay org-occur-highlights)
13438 (setq org-occur-highlights nil)
13439 (setq org-occur-parameters nil)
13440 (unless noremove
13441 (remove-hook 'before-change-functions
13442 'org-remove-occur-highlights 'local))))
13444 ;;;; Priorities
13446 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13447 "Regular expression matching the priority indicator.")
13449 (defvar org-remove-priority-next-time nil)
13451 (defun org-priority-up ()
13452 "Increase the priority of the current item."
13453 (interactive)
13454 (org-priority 'up))
13456 (defun org-priority-down ()
13457 "Decrease the priority of the current item."
13458 (interactive)
13459 (org-priority 'down))
13461 (defun org-priority (&optional action show)
13462 "Change the priority of an item.
13463 ACTION can be `set', `up', `down', or a character."
13464 (interactive "P")
13465 (if (equal action '(4))
13466 (org-show-priority)
13467 (unless org-enable-priority-commands
13468 (error "Priority commands are disabled"))
13469 (setq action (or action 'set))
13470 (let (current new news have remove)
13471 (save-excursion
13472 (org-back-to-heading t)
13473 (if (looking-at org-priority-regexp)
13474 (setq current (string-to-char (match-string 2))
13475 have t))
13476 (cond
13477 ((eq action 'remove)
13478 (setq remove t new ?\ ))
13479 ((or (eq action 'set)
13480 (if (featurep 'xemacs) (characterp action) (integerp action)))
13481 (if (not (eq action 'set))
13482 (setq new action)
13483 (message "Priority %c-%c, SPC to remove: "
13484 org-highest-priority org-lowest-priority)
13485 (save-match-data
13486 (setq new (read-char-exclusive))))
13487 (if (and (= (upcase org-highest-priority) org-highest-priority)
13488 (= (upcase org-lowest-priority) org-lowest-priority))
13489 (setq new (upcase new)))
13490 (cond ((equal new ?\ ) (setq remove t))
13491 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13492 (error "Priority must be between `%c' and `%c'"
13493 org-highest-priority org-lowest-priority))))
13494 ((eq action 'up)
13495 (setq new (if have
13496 (1- current) ; normal cycling
13497 ;; last priority was empty
13498 (if (eq last-command this-command)
13499 org-lowest-priority ; wrap around empty to lowest
13500 ;; default
13501 (if org-priority-start-cycle-with-default
13502 org-default-priority
13503 (1- org-default-priority))))))
13504 ((eq action 'down)
13505 (setq new (if have
13506 (1+ current) ; normal cycling
13507 ;; last priority was empty
13508 (if (eq last-command this-command)
13509 org-highest-priority ; wrap around empty to highest
13510 ;; default
13511 (if org-priority-start-cycle-with-default
13512 org-default-priority
13513 (1+ org-default-priority))))))
13514 (t (error "Invalid action")))
13515 (if (or (< (upcase new) org-highest-priority)
13516 (> (upcase new) org-lowest-priority))
13517 (if (and (memq action '(up down))
13518 (not have) (not (eq last-command this-command)))
13519 ;; `new' is from default priority
13520 (error
13521 "The default can not be set, see `org-default-priority' why")
13522 ;; normal cycling: `new' is beyond highest/lowest priority
13523 ;; and is wrapped around to the empty priority
13524 (setq remove t)))
13525 (setq news (format "%c" new))
13526 (if have
13527 (if remove
13528 (replace-match "" t t nil 1)
13529 (replace-match news t t nil 2))
13530 (if remove
13531 (error "No priority cookie found in line")
13532 (let ((case-fold-search nil))
13533 (looking-at org-todo-line-regexp))
13534 (if (match-end 2)
13535 (progn
13536 (goto-char (match-end 2))
13537 (insert " [#" news "]"))
13538 (goto-char (match-beginning 3))
13539 (insert "[#" news "] "))))
13540 (org-preserve-lc (org-set-tags nil 'align)))
13541 (if remove
13542 (message "Priority removed")
13543 (message "Priority of current item set to %s" news)))))
13545 (defun org-show-priority ()
13546 "Show the priority of the current item.
13547 This priority is composed of the main priority given with the [#A] cookies,
13548 and by additional input from the age of a schedules or deadline entry."
13549 (interactive)
13550 (let ((pri (if (eq major-mode 'org-agenda-mode)
13551 (org-get-at-bol 'priority)
13552 (save-excursion
13553 (save-match-data
13554 (beginning-of-line)
13555 (and (looking-at org-heading-regexp)
13556 (org-get-priority (match-string 0))))))))
13557 (message "Priority is %d" (if pri pri -1000))))
13559 (defun org-get-priority (s)
13560 "Find priority cookie and return priority."
13561 (save-match-data
13562 (if (functionp org-get-priority-function)
13563 (funcall org-get-priority-function)
13564 (if (not (string-match org-priority-regexp s))
13565 (* 1000 (- org-lowest-priority org-default-priority))
13566 (* 1000 (- org-lowest-priority
13567 (string-to-char (match-string 2 s))))))))
13569 ;;;; Tags
13571 (defvar org-agenda-archives-mode)
13572 (defvar org-map-continue-from nil
13573 "Position from where mapping should continue.
13574 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13576 (defvar org-scanner-tags nil
13577 "The current tag list while the tags scanner is running.")
13578 (defvar org-trust-scanner-tags nil
13579 "Should `org-get-tags-at' use the tags for the scanner.
13580 This is for internal dynamical scoping only.
13581 When this is non-nil, the function `org-get-tags-at' will return the value
13582 of `org-scanner-tags' instead of building the list by itself. This
13583 can lead to large speed-ups when the tags scanner is used in a file with
13584 many entries, and when the list of tags is retrieved, for example to
13585 obtain a list of properties. Building the tags list for each entry in such
13586 a file becomes an N^2 operation - but with this variable set, it scales
13587 as N.")
13589 (defun org-scan-tags (action matcher todo-only &optional start-level)
13590 "Sca headline tags with inheritance and produce output ACTION.
13592 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13593 or `agenda' to produce an entry list for an agenda view. It can also be
13594 a Lisp form or a function that should be called at each matched headline, in
13595 this case the return value is a list of all return values from these calls.
13597 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13598 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13599 only lines with a not-done TODO keyword are included in the output.
13600 This should be the same variable that was scoped into
13601 and set by `org-make-tags-matcher' when it constructed MATCHER.
13603 START-LEVEL can be a string with asterisks, reducing the scope to
13604 headlines matching this string."
13605 (require 'org-agenda)
13606 (let* ((re (concat "^"
13607 (if start-level
13608 ;; Get the correct level to match
13609 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13610 org-outline-regexp)
13611 " *\\(\\<\\("
13612 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13613 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13614 (props (list 'face 'default
13615 'done-face 'org-agenda-done
13616 'undone-face 'default
13617 'mouse-face 'highlight
13618 'org-not-done-regexp org-not-done-regexp
13619 'org-todo-regexp org-todo-regexp
13620 'org-complex-heading-regexp org-complex-heading-regexp
13621 'help-echo
13622 (format "mouse-2 or RET jump to org file %s"
13623 (abbreviate-file-name
13624 (or (buffer-file-name (buffer-base-buffer))
13625 (buffer-name (buffer-base-buffer)))))))
13626 (case-fold-search nil)
13627 (org-map-continue-from nil)
13628 lspos tags tags-list
13629 (tags-alist (list (cons 0 org-file-tags)))
13630 (llast 0) rtn rtn1 level category i txt
13631 todo marker entry priority)
13632 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13633 (setq action (list 'lambda nil action)))
13634 (save-excursion
13635 (goto-char (point-min))
13636 (when (eq action 'sparse-tree)
13637 (org-overview)
13638 (org-remove-occur-highlights))
13639 (while (re-search-forward re nil t)
13640 (setq org-map-continue-from nil)
13641 (catch :skip
13642 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13643 tags (if (match-end 4) (org-match-string-no-properties 4)))
13644 (goto-char (setq lspos (match-beginning 0)))
13645 (setq level (org-reduced-level (org-outline-level))
13646 category (org-get-category))
13647 (setq i llast llast level)
13648 ;; remove tag lists from same and sublevels
13649 (while (>= i level)
13650 (when (setq entry (assoc i tags-alist))
13651 (setq tags-alist (delete entry tags-alist)))
13652 (setq i (1- i)))
13653 ;; add the next tags
13654 (when tags
13655 (setq tags (org-split-string tags ":")
13656 tags-alist
13657 (cons (cons level tags) tags-alist)))
13658 ;; compile tags for current headline
13659 (setq tags-list
13660 (if org-use-tag-inheritance
13661 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13662 tags)
13663 org-scanner-tags tags-list)
13664 (when org-use-tag-inheritance
13665 (setcdr (car tags-alist)
13666 (mapcar (lambda (x)
13667 (setq x (copy-sequence x))
13668 (org-add-prop-inherited x))
13669 (cdar tags-alist))))
13670 (when (and tags org-use-tag-inheritance
13671 (or (not (eq t org-use-tag-inheritance))
13672 org-tags-exclude-from-inheritance))
13673 ;; selective inheritance, remove uninherited ones
13674 (setcdr (car tags-alist)
13675 (org-remove-uninherited-tags (cdar tags-alist))))
13676 (when (and
13678 ;; eval matcher only when the todo condition is OK
13679 (and (or (not todo-only) (member todo org-not-done-keywords))
13680 (let ((case-fold-search t) (org-trust-scanner-tags t))
13681 (eval matcher)))
13683 ;; Call the skipper, but return t if it does not skip,
13684 ;; so that the `and' form continues evaluating
13685 (progn
13686 (unless (eq action 'sparse-tree) (org-agenda-skip))
13689 ;; Check if timestamps are deselecting this entry
13690 (or (not todo-only)
13691 (and (member todo org-not-done-keywords)
13692 (or (not org-agenda-tags-todo-honor-ignore-options)
13693 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13695 ;; select this headline
13696 (cond
13697 ((eq action 'sparse-tree)
13698 (and org-highlight-sparse-tree-matches
13699 (org-get-heading) (match-end 0)
13700 (org-highlight-new-match
13701 (match-beginning 1) (match-end 1)))
13702 (org-show-context 'tags-tree))
13703 ((eq action 'agenda)
13704 (setq txt (org-agenda-format-item
13706 (concat
13707 (if (eq org-tags-match-list-sublevels 'indented)
13708 (make-string (1- level) ?.) "")
13709 (org-get-heading))
13710 level category
13711 tags-list)
13712 priority (org-get-priority txt))
13713 (goto-char lspos)
13714 (setq marker (org-agenda-new-marker))
13715 (org-add-props txt props
13716 'org-marker marker 'org-hd-marker marker 'org-category category
13717 'todo-state todo
13718 'priority priority 'type "tagsmatch")
13719 (push txt rtn))
13720 ((functionp action)
13721 (setq org-map-continue-from nil)
13722 (save-excursion
13723 (setq rtn1 (funcall action))
13724 (push rtn1 rtn)))
13725 (t (error "Invalid action")))
13727 ;; if we are to skip sublevels, jump to end of subtree
13728 (unless org-tags-match-list-sublevels
13729 (org-end-of-subtree t)
13730 (backward-char 1))))
13731 ;; Get the correct position from where to continue
13732 (if org-map-continue-from
13733 (goto-char org-map-continue-from)
13734 (and (= (point) lspos) (end-of-line 1)))))
13735 (when (and (eq action 'sparse-tree)
13736 (not org-sparse-tree-open-archived-trees))
13737 (org-hide-archived-subtrees (point-min) (point-max)))
13738 (nreverse rtn)))
13740 (defun org-remove-uninherited-tags (tags)
13741 "Remove all tags that are not inherited from the list TAGS."
13742 (cond
13743 ((eq org-use-tag-inheritance t)
13744 (if org-tags-exclude-from-inheritance
13745 (org-delete-all org-tags-exclude-from-inheritance tags)
13746 tags))
13747 ((not org-use-tag-inheritance) nil)
13748 ((stringp org-use-tag-inheritance)
13749 (delq nil (mapcar
13750 (lambda (x)
13751 (if (and (string-match org-use-tag-inheritance x)
13752 (not (member x org-tags-exclude-from-inheritance)))
13753 x nil))
13754 tags)))
13755 ((listp org-use-tag-inheritance)
13756 (delq nil (mapcar
13757 (lambda (x)
13758 (if (member x org-use-tag-inheritance) x nil))
13759 tags)))))
13761 (defun org-match-sparse-tree (&optional todo-only match)
13762 "Create a sparse tree according to tags string MATCH.
13763 MATCH can contain positive and negative selection of tags, like
13764 \"+WORK+URGENT-WITHBOSS\".
13765 If optional argument TODO-ONLY is non-nil, only select lines that are
13766 also TODO lines."
13767 (interactive "P")
13768 (org-agenda-prepare-buffers (list (current-buffer)))
13769 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13771 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13773 (defvar org-cached-props nil)
13774 (defun org-cached-entry-get (pom property)
13775 (if (or (eq t org-use-property-inheritance)
13776 (and (stringp org-use-property-inheritance)
13777 (string-match org-use-property-inheritance property))
13778 (and (listp org-use-property-inheritance)
13779 (member property org-use-property-inheritance)))
13780 ;; Caching is not possible, check it directly
13781 (org-entry-get pom property 'inherit)
13782 ;; Get all properties, so that we can do complicated checks easily
13783 (cdr (assoc property (or org-cached-props
13784 (setq org-cached-props
13785 (org-entry-properties pom)))))))
13787 (defun org-global-tags-completion-table (&optional files)
13788 "Return the list of all tags in all agenda buffer/files.
13789 Optional FILES argument is a list of files which can be used
13790 instead of the agenda files."
13791 (save-excursion
13792 (org-uniquify
13793 (delq nil
13794 (apply 'append
13795 (mapcar
13796 (lambda (file)
13797 (set-buffer (find-file-noselect file))
13798 (append (org-get-buffer-tags)
13799 (mapcar (lambda (x) (if (stringp (car-safe x))
13800 (list (car-safe x)) nil))
13801 org-tag-alist)))
13802 (if (and files (car files))
13803 files
13804 (org-agenda-files))))))))
13806 (defun org-make-tags-matcher (match)
13807 "Create the TAGS/TODO matcher form for the selection string MATCH.
13809 The variable `todo-only' is scoped dynamically into this function.
13810 It will be set to t if the matcher restricts matching to TODO entries,
13811 otherwise will not be touched.
13813 Returns a cons of the selection string MATCH and the constructed
13814 lisp form implementing the matcher. The matcher is to be evaluated
13815 at an Org entry, with point on the headline, and returns t if the
13816 entry matches the selection string MATCH. The returned lisp form
13817 references two variables with information about the entry, which
13818 must be bound around the form's evaluation: todo, the TODO keyword
13819 at the entry (or nil of none); and tags-list, the list of all tags
13820 at the entry including inherited ones. Additionally, the category
13821 of the entry (if any) must be specified as the text property
13822 'org-category on the headline.
13824 See also `org-scan-tags'.
13826 (declare (special todo-only))
13827 (unless (boundp 'todo-only)
13828 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13829 (unless match
13830 ;; Get a new match request, with completion
13831 (let ((org-last-tags-completion-table
13832 (org-global-tags-completion-table)))
13833 (setq match (org-completing-read-no-i
13834 "Match: " 'org-tags-completion-function nil nil nil
13835 'org-tags-history))))
13837 ;; Parse the string and create a lisp form
13838 (let ((match0 match)
13839 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13840 minus tag mm
13841 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13842 orterms term orlist re-p str-p level-p level-op time-p
13843 prop-p pn pv po gv rest)
13844 (if (string-match "/+" match)
13845 ;; match contains also a todo-matching request
13846 (progn
13847 (setq tagsmatch (substring match 0 (match-beginning 0))
13848 todomatch (substring match (match-end 0)))
13849 (if (string-match "^!" todomatch)
13850 (setq todo-only t todomatch (substring todomatch 1)))
13851 (if (string-match "^\\s-*$" todomatch)
13852 (setq todomatch nil)))
13853 ;; only matching tags
13854 (setq tagsmatch match todomatch nil))
13856 ;; Make the tags matcher
13857 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13858 (setq tagsmatcher t)
13859 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13860 (while (setq term (pop orterms))
13861 (while (and (equal (substring term -1) "\\") orterms)
13862 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13863 (while (string-match re term)
13864 (setq rest (substring term (match-end 0))
13865 minus (and (match-end 1)
13866 (equal (match-string 1 term) "-"))
13867 tag (save-match-data (replace-regexp-in-string
13868 "\\\\-" "-"
13869 (match-string 2 term)))
13870 re-p (equal (string-to-char tag) ?{)
13871 level-p (match-end 4)
13872 prop-p (match-end 5)
13873 mm (cond
13874 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13875 (level-p
13876 (setq level-op (org-op-to-function (match-string 3 term)))
13877 `(,level-op level ,(string-to-number
13878 (match-string 4 term))))
13879 (prop-p
13880 (setq pn (match-string 5 term)
13881 po (match-string 6 term)
13882 pv (match-string 7 term)
13883 re-p (equal (string-to-char pv) ?{)
13884 str-p (equal (string-to-char pv) ?\")
13885 time-p (save-match-data
13886 (string-match "^\"[[<].*[]>]\"$" pv))
13887 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13888 (if time-p (setq pv (org-matcher-time pv)))
13889 (setq po (org-op-to-function po (if time-p 'time str-p)))
13890 (cond
13891 ((equal pn "CATEGORY")
13892 (setq gv '(get-text-property (point) 'org-category)))
13893 ((equal pn "TODO")
13894 (setq gv 'todo))
13896 (setq gv `(org-cached-entry-get nil ,pn))))
13897 (if re-p
13898 (if (eq po 'org<>)
13899 `(not (string-match ,pv (or ,gv "")))
13900 `(string-match ,pv (or ,gv "")))
13901 (if str-p
13902 `(,po (or ,gv "") ,pv)
13903 `(,po (string-to-number (or ,gv ""))
13904 ,(string-to-number pv) ))))
13905 (t `(member ,tag tags-list)))
13906 mm (if minus (list 'not mm) mm)
13907 term rest)
13908 (push mm tagsmatcher))
13909 (push (if (> (length tagsmatcher) 1)
13910 (cons 'and tagsmatcher)
13911 (car tagsmatcher))
13912 orlist)
13913 (setq tagsmatcher nil))
13914 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13915 (setq tagsmatcher
13916 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13917 ;; Make the todo matcher
13918 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13919 (setq todomatcher t)
13920 (setq orterms (org-split-string todomatch "|") orlist nil)
13921 (while (setq term (pop orterms))
13922 (while (string-match re term)
13923 (setq minus (and (match-end 1)
13924 (equal (match-string 1 term) "-"))
13925 kwd (match-string 2 term)
13926 re-p (equal (string-to-char kwd) ?{)
13927 term (substring term (match-end 0))
13928 mm (if re-p
13929 `(string-match ,(substring kwd 1 -1) todo)
13930 (list 'equal 'todo kwd))
13931 mm (if minus (list 'not mm) mm))
13932 (push mm todomatcher))
13933 (push (if (> (length todomatcher) 1)
13934 (cons 'and todomatcher)
13935 (car todomatcher))
13936 orlist)
13937 (setq todomatcher nil))
13938 (setq todomatcher (if (> (length orlist) 1)
13939 (cons 'or orlist) (car orlist))))
13941 ;; Return the string and lisp forms of the matcher
13942 (setq matcher (if todomatcher
13943 (list 'and tagsmatcher todomatcher)
13944 tagsmatcher))
13945 (when todo-only
13946 (setq matcher (list 'and '(member todo org-not-done-keywords)
13947 matcher)))
13948 (cons match0 matcher)))
13950 (defun org-op-to-function (op &optional stringp)
13951 "Turn an operator into the appropriate function."
13952 (setq op
13953 (cond
13954 ((equal op "<" ) '(< string< org-time<))
13955 ((equal op ">" ) '(> org-string> org-time>))
13956 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13957 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13958 ((member op '("=" "==")) '(= string= org-time=))
13959 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13960 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13962 (defun org<> (a b) (not (= a b)))
13963 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13964 (defun org-string>= (a b) (not (string< a b)))
13965 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13966 (defun org-string<> (a b) (not (string= a b)))
13967 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13968 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13969 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13970 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13971 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13972 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13973 (defun org-2ft (s)
13974 "Convert S to a floating point time.
13975 If S is already a number, just return it. If it is a string, parse
13976 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13977 (cond
13978 ((numberp s) s)
13979 ((stringp s)
13980 (condition-case nil
13981 (float-time (apply 'encode-time (org-parse-time-string s)))
13982 (error 0.)))
13983 (t 0.)))
13985 (defun org-time-today ()
13986 "Time in seconds today at 0:00.
13987 Returns the float number of seconds since the beginning of the
13988 epoch to the beginning of today (00:00)."
13989 (float-time (apply 'encode-time
13990 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13992 (defun org-matcher-time (s)
13993 "Interpret a time comparison value."
13994 (save-match-data
13995 (cond
13996 ((string= s "<now>") (float-time))
13997 ((string= s "<today>") (org-time-today))
13998 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13999 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14000 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14001 (+ (org-time-today)
14002 (* (string-to-number (match-string 1 s))
14003 (cdr (assoc (match-string 2 s)
14004 '(("d" . 86400.0) ("w" . 604800.0)
14005 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14006 (t (org-2ft s)))))
14008 (defun org-match-any-p (re list)
14009 "Does re match any element of list?"
14010 (setq list (mapcar (lambda (x) (string-match re x)) list))
14011 (delq nil list))
14013 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14014 (defvar org-tags-overlay (make-overlay 1 1))
14015 (org-detach-overlay org-tags-overlay)
14017 (defun org-get-local-tags-at (&optional pos)
14018 "Get a list of tags defined in the current headline."
14019 (org-get-tags-at pos 'local))
14021 (defun org-get-local-tags ()
14022 "Get a list of tags defined in the current headline."
14023 (org-get-tags-at nil 'local))
14025 (defun org-get-tags-at (&optional pos local)
14026 "Get a list of all headline tags applicable at POS.
14027 POS defaults to point. If tags are inherited, the list contains
14028 the targets in the same sequence as the headlines appear, i.e.
14029 the tags of the current headline come last.
14030 When LOCAL is non-nil, only return tags from the current headline,
14031 ignore inherited ones."
14032 (interactive)
14033 (if (and org-trust-scanner-tags
14034 (or (not pos) (equal pos (point)))
14035 (not local))
14036 org-scanner-tags
14037 (let (tags ltags lastpos parent)
14038 (save-excursion
14039 (save-restriction
14040 (widen)
14041 (goto-char (or pos (point)))
14042 (save-match-data
14043 (catch 'done
14044 (condition-case nil
14045 (progn
14046 (org-back-to-heading t)
14047 (while (not (equal lastpos (point)))
14048 (setq lastpos (point))
14049 (when (looking-at
14050 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14051 (setq ltags (org-split-string
14052 (org-match-string-no-properties 1) ":"))
14053 (when parent
14054 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14055 (setq tags (append
14056 (if parent
14057 (org-remove-uninherited-tags ltags)
14058 ltags)
14059 tags)))
14060 (or org-use-tag-inheritance (throw 'done t))
14061 (if local (throw 'done t))
14062 (or (org-up-heading-safe) (error nil))
14063 (setq parent t)))
14064 (error nil)))))
14065 (if local
14066 tags
14067 (reverse (delete-dups
14068 (reverse (append
14069 (org-remove-uninherited-tags
14070 org-file-tags) tags)))))))))
14072 (defun org-add-prop-inherited (s)
14073 (add-text-properties 0 (length s) '(inherited t) s)
14076 (defun org-toggle-tag (tag &optional onoff)
14077 "Toggle the tag TAG for the current line.
14078 If ONOFF is `on' or `off', don't toggle but set to this state."
14079 (let (res current)
14080 (save-excursion
14081 (org-back-to-heading t)
14082 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14083 (point-at-eol) t)
14084 (progn
14085 (setq current (match-string 1))
14086 (replace-match ""))
14087 (setq current ""))
14088 (setq current (nreverse (org-split-string current ":")))
14089 (cond
14090 ((eq onoff 'on)
14091 (setq res t)
14092 (or (member tag current) (push tag current)))
14093 ((eq onoff 'off)
14094 (or (not (member tag current)) (setq current (delete tag current))))
14095 (t (if (member tag current)
14096 (setq current (delete tag current))
14097 (setq res t)
14098 (push tag current))))
14099 (end-of-line 1)
14100 (if current
14101 (progn
14102 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14103 (org-set-tags nil t))
14104 (delete-horizontal-space))
14105 (run-hooks 'org-after-tags-change-hook))
14106 res))
14108 (defun org-align-tags-here (to-col)
14109 ;; Assumes that this is a headline
14110 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14111 (beginning-of-line 1)
14112 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14113 (< pos (match-beginning 2)))
14114 (progn
14115 (setq tags-l (- (match-end 2) (match-beginning 2)))
14116 (goto-char (match-beginning 1))
14117 (insert " ")
14118 (delete-region (point) (1+ (match-beginning 2)))
14119 (setq ncol (max (current-column)
14120 (1+ col)
14121 (if (> to-col 0)
14122 to-col
14123 (- (abs to-col) tags-l))))
14124 (setq p (point))
14125 (insert (make-string (- ncol (current-column)) ?\ ))
14126 (setq ncol (current-column))
14127 (when indent-tabs-mode (tabify p (point-at-eol)))
14128 (org-move-to-column (min ncol col) t))
14129 (goto-char pos))))
14131 (defun org-set-tags-command (&optional arg just-align)
14132 "Call the set-tags command for the current entry."
14133 (interactive "P")
14134 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14135 (org-set-tags arg just-align)
14136 (save-excursion
14137 (unless (and (org-region-active-p)
14138 org-loop-over-headlines-in-active-region)
14139 (org-back-to-heading t))
14140 (org-set-tags arg just-align))))
14142 (defun org-set-tags-to (data)
14143 "Set the tags of the current entry to DATA, replacing the current tags.
14144 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14145 If DATA is nil or the empty string, any tags will be removed."
14146 (interactive "sTags: ")
14147 (setq data
14148 (cond
14149 ((eq data nil) "")
14150 ((equal data "") "")
14151 ((stringp data)
14152 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14153 ":"))
14154 ((listp data)
14155 (concat ":" (mapconcat 'identity data ":") ":"))))
14156 (when data
14157 (save-excursion
14158 (org-back-to-heading t)
14159 (when (looking-at org-complex-heading-regexp)
14160 (if (match-end 5)
14161 (progn
14162 (goto-char (match-beginning 5))
14163 (insert data)
14164 (delete-region (point) (point-at-eol))
14165 (org-set-tags nil 'align))
14166 (goto-char (point-at-eol))
14167 (insert " " data)
14168 (org-set-tags nil 'align)))
14169 (beginning-of-line 1)
14170 (if (looking-at ".*?\\([ \t]+\\)$")
14171 (delete-region (match-beginning 1) (match-end 1))))))
14173 (defun org-align-all-tags ()
14174 "Align the tags i all headings."
14175 (interactive)
14176 (save-excursion
14177 (or (ignore-errors (org-back-to-heading t))
14178 (outline-next-heading))
14179 (if (org-at-heading-p)
14180 (org-set-tags t)
14181 (message "No headings"))))
14183 (defvar org-indent-indentation-per-level)
14184 (defun org-set-tags (&optional arg just-align)
14185 "Set the tags for the current headline.
14186 With prefix ARG, realign all tags in headings in the current buffer."
14187 (interactive "P")
14188 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14189 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14190 'region-start-level 'region))
14191 org-loop-over-headlines-in-active-region)
14192 (org-map-entries
14193 ;; We don't use ARG and JUST-ALIGN here these args are not
14194 ;; useful when looping over headlines
14195 `(org-set-tags)
14196 org-loop-over-headlines-in-active-region
14197 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14198 (let* ((re org-outline-regexp-bol)
14199 (current (unless arg (org-get-tags-string)))
14200 (col (current-column))
14201 (org-setting-tags t)
14202 table current-tags inherited-tags ; computed below when needed
14203 tags p0 c0 c1 rpl di tc level)
14204 (if arg
14205 (save-excursion
14206 (goto-char (point-min))
14207 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14208 (while (re-search-forward re nil t)
14209 (org-set-tags nil t)
14210 (end-of-line 1)))
14211 (message "All tags realigned to column %d" org-tags-column))
14212 (if just-align
14213 (setq tags current)
14214 ;; Get a new set of tags from the user
14215 (save-excursion
14216 (setq table (append org-tag-persistent-alist
14217 (or org-tag-alist (org-get-buffer-tags))
14218 (and
14219 org-complete-tags-always-offer-all-agenda-tags
14220 (org-global-tags-completion-table
14221 (org-agenda-files))))
14222 org-last-tags-completion-table table
14223 current-tags (org-split-string current ":")
14224 inherited-tags (nreverse
14225 (nthcdr (length current-tags)
14226 (nreverse (org-get-tags-at))))
14227 tags
14228 (if (or (eq t org-use-fast-tag-selection)
14229 (and org-use-fast-tag-selection
14230 (delq nil (mapcar 'cdr table))))
14231 (org-fast-tag-selection
14232 current-tags inherited-tags table
14233 (if org-fast-tag-selection-include-todo
14234 org-todo-key-alist))
14235 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14236 (org-trim
14237 (org-icompleting-read "Tags: "
14238 'org-tags-completion-function
14239 nil nil current 'org-tags-history))))))
14240 (while (string-match "[-+&]+" tags)
14241 ;; No boolean logic, just a list
14242 (setq tags (replace-match ":" t t tags))))
14244 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14246 (if org-tags-sort-function
14247 (setq tags (mapconcat 'identity
14248 (sort (org-split-string
14249 tags (org-re "[^[:alnum:]_@#%]+"))
14250 org-tags-sort-function) ":")))
14252 (if (string-match "\\`[\t ]*\\'" tags)
14253 (setq tags "")
14254 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14255 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14257 ;; Insert new tags at the correct column
14258 (beginning-of-line 1)
14259 (setq level (or (and (looking-at org-outline-regexp)
14260 (- (match-end 0) (point) 1))
14262 (cond
14263 ((and (equal current "") (equal tags "")))
14264 ((re-search-forward
14265 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14266 (point-at-eol) t)
14267 (if (equal tags "")
14268 (setq rpl "")
14269 (goto-char (match-beginning 0))
14270 (setq c0 (current-column)
14271 ;; compute offset for the case of org-indent-mode active
14272 di (if org-indent-mode
14273 (* (1- org-indent-indentation-per-level) (1- level))
14275 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14276 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14277 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14278 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14279 (replace-match rpl t t)
14280 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14281 tags)
14282 (t (error "Tags alignment failed")))
14283 (org-move-to-column col)
14284 (unless just-align
14285 (run-hooks 'org-after-tags-change-hook))))))
14287 (defun org-change-tag-in-region (beg end tag off)
14288 "Add or remove TAG for each entry in the region.
14289 This works in the agenda, and also in an org-mode buffer."
14290 (interactive
14291 (list (region-beginning) (region-end)
14292 (let ((org-last-tags-completion-table
14293 (if (derived-mode-p 'org-mode)
14294 (org-get-buffer-tags)
14295 (org-global-tags-completion-table))))
14296 (org-icompleting-read
14297 "Tag: " 'org-tags-completion-function nil nil nil
14298 'org-tags-history))
14299 (progn
14300 (message "[s]et or [r]emove? ")
14301 (equal (read-char-exclusive) ?r))))
14302 (if (fboundp 'deactivate-mark) (deactivate-mark))
14303 (let ((agendap (equal major-mode 'org-agenda-mode))
14304 l1 l2 m buf pos newhead (cnt 0))
14305 (goto-char end)
14306 (setq l2 (1- (org-current-line)))
14307 (goto-char beg)
14308 (setq l1 (org-current-line))
14309 (loop for l from l1 to l2 do
14310 (org-goto-line l)
14311 (setq m (get-text-property (point) 'org-hd-marker))
14312 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14313 (and agendap m))
14314 (setq buf (if agendap (marker-buffer m) (current-buffer))
14315 pos (if agendap m (point)))
14316 (with-current-buffer buf
14317 (save-excursion
14318 (save-restriction
14319 (goto-char pos)
14320 (setq cnt (1+ cnt))
14321 (org-toggle-tag tag (if off 'off 'on))
14322 (setq newhead (org-get-heading)))))
14323 (and agendap (org-agenda-change-all-lines newhead m))))
14324 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14326 (defun org-tags-completion-function (string predicate &optional flag)
14327 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14328 (confirm (lambda (x) (stringp (car x)))))
14329 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14330 (setq s1 (match-string 1 string)
14331 s2 (match-string 2 string))
14332 (setq s1 "" s2 string))
14333 (cond
14334 ((eq flag nil)
14335 ;; try completion
14336 (setq rtn (try-completion s2 ctable confirm))
14337 (if (stringp rtn)
14338 (setq rtn
14339 (concat s1 s2 (substring rtn (length s2))
14340 (if (and org-add-colon-after-tag-completion
14341 (assoc rtn ctable))
14342 ":" ""))))
14343 rtn)
14344 ((eq flag t)
14345 ;; all-completions
14346 (all-completions s2 ctable confirm)
14348 ((eq flag 'lambda)
14349 ;; exact match?
14350 (assoc s2 ctable)))
14353 (defun org-fast-tag-insert (kwd tags face &optional end)
14354 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14355 (insert (format "%-12s" (concat kwd ":"))
14356 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14357 (or end "")))
14359 (defun org-fast-tag-show-exit (flag)
14360 (save-excursion
14361 (org-goto-line 3)
14362 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14363 (replace-match ""))
14364 (when flag
14365 (end-of-line 1)
14366 (org-move-to-column (- (window-width) 19) t)
14367 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14369 (defun org-set-current-tags-overlay (current prefix)
14370 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14371 (if (featurep 'xemacs)
14372 (org-overlay-display org-tags-overlay (concat prefix s)
14373 'secondary-selection)
14374 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14375 (org-overlay-display org-tags-overlay (concat prefix s)))))
14377 (defvar org-last-tag-selection-key nil)
14378 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14379 "Fast tag selection with single keys.
14380 CURRENT is the current list of tags in the headline, INHERITED is the
14381 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14382 possibly with grouping information. TODO-TABLE is a similar table with
14383 TODO keywords, should these have keys assigned to them.
14384 If the keys are nil, a-z are automatically assigned.
14385 Returns the new tags string, or nil to not change the current settings."
14386 (let* ((fulltable (append table todo-table))
14387 (maxlen (apply 'max (mapcar
14388 (lambda (x)
14389 (if (stringp (car x)) (string-width (car x)) 0))
14390 fulltable)))
14391 (buf (current-buffer))
14392 (expert (eq org-fast-tag-selection-single-key 'expert))
14393 (buffer-tags nil)
14394 (fwidth (+ maxlen 3 1 3))
14395 (ncol (/ (- (window-width) 4) fwidth))
14396 (i-face 'org-done)
14397 (c-face 'org-todo)
14398 tg cnt e c char c1 c2 ntable tbl rtn
14399 ov-start ov-end ov-prefix
14400 (exit-after-next org-fast-tag-selection-single-key)
14401 (done-keywords org-done-keywords)
14402 groups ingroup)
14403 (save-excursion
14404 (beginning-of-line 1)
14405 (if (looking-at
14406 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14407 (setq ov-start (match-beginning 1)
14408 ov-end (match-end 1)
14409 ov-prefix "")
14410 (setq ov-start (1- (point-at-eol))
14411 ov-end (1+ ov-start))
14412 (skip-chars-forward "^\n\r")
14413 (setq ov-prefix
14414 (concat
14415 (buffer-substring (1- (point)) (point))
14416 (if (> (current-column) org-tags-column)
14418 (make-string (- org-tags-column (current-column)) ?\ ))))))
14419 (move-overlay org-tags-overlay ov-start ov-end)
14420 (save-window-excursion
14421 (if expert
14422 (set-buffer (get-buffer-create " *Org tags*"))
14423 (delete-other-windows)
14424 (split-window-vertically)
14425 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14426 (erase-buffer)
14427 (org-set-local 'org-done-keywords done-keywords)
14428 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14429 (org-fast-tag-insert "Current" current c-face "\n\n")
14430 (org-fast-tag-show-exit exit-after-next)
14431 (org-set-current-tags-overlay current ov-prefix)
14432 (setq tbl fulltable char ?a cnt 0)
14433 (while (setq e (pop tbl))
14434 (cond
14435 ((equal (car e) :startgroup)
14436 (push '() groups) (setq ingroup t)
14437 (when (not (= cnt 0))
14438 (setq cnt 0)
14439 (insert "\n"))
14440 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14441 ((equal (car e) :endgroup)
14442 (setq ingroup nil cnt 0)
14443 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14444 ((equal e '(:newline))
14445 (when (not (= cnt 0))
14446 (setq cnt 0)
14447 (insert "\n")
14448 (setq e (car tbl))
14449 (while (equal (car tbl) '(:newline))
14450 (insert "\n")
14451 (setq tbl (cdr tbl)))))
14453 (setq tg (copy-sequence (car e)) c2 nil)
14454 (if (cdr e)
14455 (setq c (cdr e))
14456 ;; automatically assign a character.
14457 (setq c1 (string-to-char
14458 (downcase (substring
14459 tg (if (= (string-to-char tg) ?@) 1 0)))))
14460 (if (or (rassoc c1 ntable) (rassoc c1 table))
14461 (while (or (rassoc char ntable) (rassoc char table))
14462 (setq char (1+ char)))
14463 (setq c2 c1))
14464 (setq c (or c2 char)))
14465 (if ingroup (push tg (car groups)))
14466 (setq tg (org-add-props tg nil 'face
14467 (cond
14468 ((not (assoc tg table))
14469 (org-get-todo-face tg))
14470 ((member tg current) c-face)
14471 ((member tg inherited) i-face))))
14472 (if (and (= cnt 0) (not ingroup)) (insert " "))
14473 (insert "[" c "] " tg (make-string
14474 (- fwidth 4 (length tg)) ?\ ))
14475 (push (cons tg c) ntable)
14476 (when (= (setq cnt (1+ cnt)) ncol)
14477 (insert "\n")
14478 (if ingroup (insert " "))
14479 (setq cnt 0)))))
14480 (setq ntable (nreverse ntable))
14481 (insert "\n")
14482 (goto-char (point-min))
14483 (if (not expert) (org-fit-window-to-buffer))
14484 (setq rtn
14485 (catch 'exit
14486 (while t
14487 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14488 (if (not groups) "no " "")
14489 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14490 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14491 (setq org-last-tag-selection-key c)
14492 (cond
14493 ((= c ?\r) (throw 'exit t))
14494 ((= c ?!)
14495 (setq groups (not groups))
14496 (goto-char (point-min))
14497 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14498 ((= c ?\C-c)
14499 (if (not expert)
14500 (org-fast-tag-show-exit
14501 (setq exit-after-next (not exit-after-next)))
14502 (setq expert nil)
14503 (delete-other-windows)
14504 (set-window-buffer (split-window-vertically) " *Org tags*")
14505 (org-switch-to-buffer-other-window " *Org tags*")
14506 (org-fit-window-to-buffer)))
14507 ((or (= c ?\C-g)
14508 (and (= c ?q) (not (rassoc c ntable))))
14509 (org-detach-overlay org-tags-overlay)
14510 (setq quit-flag t))
14511 ((= c ?\ )
14512 (setq current nil)
14513 (if exit-after-next (setq exit-after-next 'now)))
14514 ((= c ?\t)
14515 (condition-case nil
14516 (setq tg (org-icompleting-read
14517 "Tag: "
14518 (or buffer-tags
14519 (with-current-buffer buf
14520 (org-get-buffer-tags)))))
14521 (quit (setq tg "")))
14522 (when (string-match "\\S-" tg)
14523 (add-to-list 'buffer-tags (list tg))
14524 (if (member tg current)
14525 (setq current (delete tg current))
14526 (push tg current)))
14527 (if exit-after-next (setq exit-after-next 'now)))
14528 ((setq e (rassoc c todo-table) tg (car e))
14529 (with-current-buffer buf
14530 (save-excursion (org-todo tg)))
14531 (if exit-after-next (setq exit-after-next 'now)))
14532 ((setq e (rassoc c ntable) tg (car e))
14533 (if (member tg current)
14534 (setq current (delete tg current))
14535 (loop for g in groups do
14536 (if (member tg g)
14537 (mapc (lambda (x)
14538 (setq current (delete x current)))
14539 g)))
14540 (push tg current))
14541 (if exit-after-next (setq exit-after-next 'now))))
14543 ;; Create a sorted list
14544 (setq current
14545 (sort current
14546 (lambda (a b)
14547 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14548 (if (eq exit-after-next 'now) (throw 'exit t))
14549 (goto-char (point-min))
14550 (beginning-of-line 2)
14551 (delete-region (point) (point-at-eol))
14552 (org-fast-tag-insert "Current" current c-face)
14553 (org-set-current-tags-overlay current ov-prefix)
14554 (while (re-search-forward
14555 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14556 (setq tg (match-string 1))
14557 (add-text-properties
14558 (match-beginning 1) (match-end 1)
14559 (list 'face
14560 (cond
14561 ((member tg current) c-face)
14562 ((member tg inherited) i-face)
14563 (t (get-text-property (match-beginning 1) 'face))))))
14564 (goto-char (point-min)))))
14565 (org-detach-overlay org-tags-overlay)
14566 (if rtn
14567 (mapconcat 'identity current ":")
14568 nil))))
14570 (defun org-get-tags-string ()
14571 "Get the TAGS string in the current headline."
14572 (unless (org-at-heading-p t)
14573 (error "Not on a heading"))
14574 (save-excursion
14575 (beginning-of-line 1)
14576 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14577 (org-match-string-no-properties 1)
14578 "")))
14580 (defun org-get-tags ()
14581 "Get the list of tags specified in the current headline."
14582 (org-split-string (org-get-tags-string) ":"))
14584 (defun org-get-buffer-tags ()
14585 "Get a table of all tags used in the buffer, for completion."
14586 (let (tags)
14587 (save-excursion
14588 (goto-char (point-min))
14589 (while (re-search-forward
14590 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14591 (when (equal (char-after (point-at-bol 0)) ?*)
14592 (mapc (lambda (x) (add-to-list 'tags x))
14593 (org-split-string (org-match-string-no-properties 1) ":")))))
14594 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14595 (mapcar 'list tags)))
14597 ;;;; The mapping API
14599 (defun org-map-entries (func &optional match scope &rest skip)
14600 "Call FUNC at each headline selected by MATCH in SCOPE.
14602 FUNC is a function or a lisp form. The function will be called without
14603 arguments, with the cursor positioned at the beginning of the headline.
14604 The return values of all calls to the function will be collected and
14605 returned as a list.
14607 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14608 does not need to preserve point. After evaluation, the cursor will be
14609 moved to the end of the line (presumably of the headline of the
14610 processed entry) and search continues from there. Under some
14611 circumstances, this may not produce the wanted results. For example,
14612 if you have removed (e.g. archived) the current (sub)tree it could
14613 mean that the next entry will be skipped entirely. In such cases, you
14614 can specify the position from where search should continue by making
14615 FUNC set the variable `org-map-continue-from' to the desired buffer
14616 position.
14618 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14619 Only headlines that are matched by this query will be considered during
14620 the iteration. When MATCH is nil or t, all headlines will be
14621 visited by the iteration.
14623 SCOPE determines the scope of this command. It can be any of:
14625 nil The current buffer, respecting the restriction if any
14626 tree The subtree started with the entry at point
14627 region The entries within the active region, if any
14628 region-start-level
14629 The entries within the active region, but only those at
14630 the same level than the first one.
14631 file The current buffer, without restriction
14632 file-with-archives
14633 The current buffer, and any archives associated with it
14634 agenda All agenda files
14635 agenda-with-archives
14636 All agenda files with any archive files associated with them
14637 \(file1 file2 ...)
14638 If this is a list, all files in the list will be scanned
14640 The remaining args are treated as settings for the skipping facilities of
14641 the scanner. The following items can be given here:
14643 archive skip trees with the archive tag
14644 comment skip trees with the COMMENT keyword
14645 function or Emacs Lisp form:
14646 will be used as value for `org-agenda-skip-function', so
14647 whenever the function returns a position, FUNC will not be
14648 called for that entry and search will continue from the
14649 position returned
14651 If your function needs to retrieve the tags including inherited tags
14652 at the *current* entry, you can use the value of the variable
14653 `org-scanner-tags' which will be much faster than getting the value
14654 with `org-get-tags-at'. If your function gets properties with
14655 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14656 to t around the call to `org-entry-properties' to get the same speedup.
14657 Note that if your function moves around to retrieve tags and properties at
14658 a *different* entry, you cannot use these techniques."
14659 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14660 (not (org-region-active-p)))
14661 (let* ((org-agenda-archives-mode nil) ; just to make sure
14662 (org-agenda-skip-archived-trees (memq 'archive skip))
14663 (org-agenda-skip-comment-trees (memq 'comment skip))
14664 (org-agenda-skip-function
14665 (car (org-delete-all '(comment archive) skip)))
14666 (org-tags-match-list-sublevels t)
14667 (start-level (eq scope 'region-start-level))
14668 matcher file res
14669 org-todo-keywords-for-agenda
14670 org-done-keywords-for-agenda
14671 org-todo-keyword-alist-for-agenda
14672 org-drawers-for-agenda
14673 org-tag-alist-for-agenda
14674 todo-only)
14676 (cond
14677 ((eq match t) (setq matcher t))
14678 ((eq match nil) (setq matcher t))
14679 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14681 (save-window-excursion
14682 (save-restriction
14683 (cond ((eq scope 'tree)
14684 (org-back-to-heading t)
14685 (org-narrow-to-subtree)
14686 (setq scope nil))
14687 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14688 (org-region-active-p))
14689 ;; If needed, set start-level to a string like "2"
14690 (when start-level
14691 (save-excursion
14692 (goto-char (region-beginning))
14693 (unless (org-at-heading-p) (outline-next-heading))
14694 (setq start-level (org-current-level))))
14695 (narrow-to-region (region-beginning)
14696 (save-excursion
14697 (goto-char (region-end))
14698 (unless (and (bolp) (org-at-heading-p))
14699 (outline-next-heading))
14700 (point)))
14701 (setq scope nil)))
14703 (if (not scope)
14704 (progn
14705 (org-agenda-prepare-buffers
14706 (list (buffer-file-name (current-buffer))))
14707 (setq res (org-scan-tags func matcher todo-only start-level)))
14708 ;; Get the right scope
14709 (cond
14710 ((and scope (listp scope) (symbolp (car scope)))
14711 (setq scope (eval scope)))
14712 ((eq scope 'agenda)
14713 (setq scope (org-agenda-files t)))
14714 ((eq scope 'agenda-with-archives)
14715 (setq scope (org-agenda-files t))
14716 (setq scope (org-add-archive-files scope)))
14717 ((eq scope 'file)
14718 (setq scope (list (buffer-file-name))))
14719 ((eq scope 'file-with-archives)
14720 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14721 (org-agenda-prepare-buffers scope)
14722 (while (setq file (pop scope))
14723 (with-current-buffer (org-find-base-buffer-visiting file)
14724 (save-excursion
14725 (save-restriction
14726 (widen)
14727 (goto-char (point-min))
14728 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14729 res)))
14731 ;;;; Properties
14733 ;;; Setting and retrieving properties
14735 (defconst org-special-properties
14736 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14737 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14738 "The special properties valid in Org-mode.
14740 These are properties that are not defined in the property drawer,
14741 but in some other way.")
14743 (defconst org-default-properties
14744 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14745 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14746 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14747 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14748 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14749 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14750 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14751 "Some properties that are used by Org-mode for various purposes.
14752 Being in this list makes sure that they are offered for completion.")
14754 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14755 "Regular expression matching the first line of a property drawer.")
14757 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14758 "Regular expression matching the last line of a property drawer.")
14760 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14761 "Regular expression matching the first line of a property drawer.")
14763 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14764 "Regular expression matching the first line of a property drawer.")
14766 (defconst org-property-drawer-re
14767 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14768 org-property-end-re "\\)\n?")
14769 "Matches an entire property drawer.")
14771 (defconst org-clock-drawer-re
14772 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14773 org-property-end-re "\\)\n?")
14774 "Matches an entire clock drawer.")
14776 (defsubst org-re-property (property)
14777 "Return a regexp matching a PROPERTY line.
14778 Match group 1 will be set to the value."
14779 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14781 (defsubst org-re-property-keyword (property)
14782 "Return a regexp matching a PROPERTY line, possibly with no
14783 value for the property."
14784 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14786 (defun org-property-action ()
14787 "Do an action on properties."
14788 (interactive)
14789 (let (c)
14790 (org-at-property-p)
14791 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14792 (setq c (read-char-exclusive))
14793 (cond
14794 ((equal c ?s)
14795 (call-interactively 'org-set-property))
14796 ((equal c ?d)
14797 (call-interactively 'org-delete-property))
14798 ((equal c ?D)
14799 (call-interactively 'org-delete-property-globally))
14800 ((equal c ?c)
14801 (call-interactively 'org-compute-property-at-point))
14802 (t (error "No such property action %c" c)))))
14804 (defun org-inc-effort ()
14805 "Increment the value of the effort property in the current entry."
14806 (interactive)
14807 (org-set-effort nil t))
14809 (defvar org-clock-effort) ;; Defined in org-clock.el
14810 (defvar org-clock-current-task) ;; Defined in org-clock.el
14811 (defun org-set-effort (&optional value increment)
14812 "Set the effort property of the current entry.
14813 With numerical prefix arg, use the nth allowed value, 0 stands for the
14814 10th allowed value.
14816 When INCREMENT is non-nil, set the property to the next allowed value."
14817 (interactive "P")
14818 (if (equal value 0) (setq value 10))
14819 (let* ((completion-ignore-case t)
14820 (prop org-effort-property)
14821 (cur (org-entry-get nil prop))
14822 (allowed (org-property-get-allowed-values nil prop 'table))
14823 (existing (mapcar 'list (org-property-values prop)))
14824 (heading (nth 4 (org-heading-components)))
14826 (val (cond
14827 ((stringp value) value)
14828 ((and allowed (integerp value))
14829 (or (car (nth (1- value) allowed))
14830 (car (org-last allowed))))
14831 ((and allowed increment)
14832 (or (caadr (member (list cur) allowed))
14833 (error "Allowed effort values are not set")))
14834 (allowed
14835 (message "Select 1-9,0, [RET%s]: %s"
14836 (if cur (concat "=" cur) "")
14837 (mapconcat 'car allowed " "))
14838 (setq rpl (read-char-exclusive))
14839 (if (equal rpl ?\r)
14841 (setq rpl (- rpl ?0))
14842 (if (equal rpl 0) (setq rpl 10))
14843 (if (and (> rpl 0) (<= rpl (length allowed)))
14844 (car (nth (1- rpl) allowed))
14845 (org-completing-read "Effort: " allowed nil))))
14847 (let (org-completion-use-ido org-completion-use-iswitchb)
14848 (org-completing-read
14849 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14850 (concat "[" cur "]") "")
14851 ": ")
14852 existing nil nil "" nil cur))))))
14853 (unless (equal (org-entry-get nil prop) val)
14854 (org-entry-put nil prop val))
14855 (save-excursion
14856 (org-back-to-heading t)
14857 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14858 (when (string= heading org-clock-current-task)
14859 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14860 (org-clock-update-mode-line))
14861 (message "%s is now %s" prop val)))
14863 (defun org-at-property-p ()
14864 "Is cursor inside a property drawer?"
14865 (save-excursion
14866 (beginning-of-line 1)
14867 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14868 (save-match-data ;; Used by calling procedures
14869 (let ((p (point))
14870 (range (unless (org-before-first-heading-p)
14871 (org-get-property-block))))
14872 (and range (<= (car range) p) (< p (cdr range))))))))
14874 (defun org-get-property-block (&optional beg end force)
14875 "Return the (beg . end) range of the body of the property drawer.
14876 BEG and END are the beginning and end of the current subtree, or of
14877 the part before the first headline. If they are not given, they will
14878 be found. If the drawer does not exist and FORCE is non-nil, create
14879 the drawer."
14880 (catch 'exit
14881 (save-excursion
14882 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14883 (progn (org-back-to-heading t) (point))))
14884 (end (or end (and (not (outline-next-heading)) (point-max))
14885 (point))))
14886 (goto-char beg)
14887 (if (re-search-forward org-property-start-re end t)
14888 (setq beg (1+ (match-end 0)))
14889 (if force
14890 (save-excursion
14891 (org-insert-property-drawer)
14892 (setq end (progn (outline-next-heading) (point))))
14893 (throw 'exit nil))
14894 (goto-char beg)
14895 (if (re-search-forward org-property-start-re end t)
14896 (setq beg (1+ (match-end 0)))))
14897 (if (re-search-forward org-property-end-re end t)
14898 (setq end (match-beginning 0))
14899 (or force (throw 'exit nil))
14900 (goto-char beg)
14901 (setq end beg)
14902 (org-indent-line)
14903 (insert ":END:\n"))
14904 (cons beg end)))))
14906 (defun org-entry-properties (&optional pom which specific)
14907 "Get all properties of the entry at point-or-marker POM.
14908 This includes the TODO keyword, the tags, time strings for deadline,
14909 scheduled, and clocking, and any additional properties defined in the
14910 entry. The return value is an alist, keys may occur multiple times
14911 if the property key was used several times.
14912 POM may also be nil, in which case the current entry is used.
14913 If WHICH is nil or `all', get all properties. If WHICH is
14914 `special' or `standard', only get that subclass. If WHICH
14915 is a string only get exactly this property. SPECIFIC can be a string, the
14916 specific property we are interested in. Specifying it can speed
14917 things up because then unnecessary parsing is avoided."
14918 (setq which (or which 'all))
14919 (org-with-point-at pom
14920 (let ((clockstr (substring org-clock-string 0 -1))
14921 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14922 (case-fold-search nil)
14923 beg end range props sum-props key key1 value string clocksum clocksumt)
14924 (save-excursion
14925 (when (condition-case nil
14926 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14927 (error nil))
14928 (setq beg (point))
14929 (setq sum-props (get-text-property (point) 'org-summaries))
14930 (setq clocksum (get-text-property (point) :org-clock-minutes)
14931 clocksumt (get-text-property (point) :org-clock-minutes-today))
14932 (outline-next-heading)
14933 (setq end (point))
14934 (when (memq which '(all special))
14935 ;; Get the special properties, like TODO and tags
14936 (goto-char beg)
14937 (when (and (or (not specific) (string= specific "TODO"))
14938 (looking-at org-todo-line-regexp) (match-end 2))
14939 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14940 (when (and (or (not specific) (string= specific "PRIORITY"))
14941 (looking-at org-priority-regexp))
14942 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14943 (when (or (not specific) (string= specific "FILE"))
14944 (push (cons "FILE" buffer-file-name) props))
14945 (when (and (or (not specific) (string= specific "TAGS"))
14946 (setq value (org-get-tags-string))
14947 (string-match "\\S-" value))
14948 (push (cons "TAGS" value) props))
14949 (when (and (or (not specific) (string= specific "ALLTAGS"))
14950 (setq value (org-get-tags-at)))
14951 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14952 ":"))
14953 props))
14954 (when (or (not specific) (string= specific "BLOCKED"))
14955 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14956 (when (or (not specific)
14957 (member specific
14958 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14959 "TIMESTAMP" "TIMESTAMP_IA")))
14960 (catch 'match
14961 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14962 (setq key (if (match-end 1)
14963 (substring (org-match-string-no-properties 1)
14964 0 -1))
14965 string (if (equal key clockstr)
14966 (org-trim
14967 (buffer-substring-no-properties
14968 (match-beginning 3) (goto-char
14969 (point-at-eol))))
14970 (substring (org-match-string-no-properties 3)
14971 1 -1)))
14972 ;; Get the correct property name from the key. This is
14973 ;; necessary if the user has configured time keywords.
14974 (setq key1 (concat key ":"))
14975 (cond
14976 ((not key)
14977 (setq key
14978 (if (= (char-after (match-beginning 3)) ?\[)
14979 "TIMESTAMP_IA" "TIMESTAMP")))
14980 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14981 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14982 ((equal key1 org-closed-string) (setq key "CLOSED"))
14983 ((equal key1 org-clock-string) (setq key "CLOCK")))
14984 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14985 (progn
14986 (push (cons key string) props)
14987 ;; no need to search further if match is found
14988 (throw 'match t))
14989 (when (or (equal key "CLOCK") (not (assoc key props)))
14990 (push (cons key string) props)))))))
14992 (when (memq which '(all standard))
14993 ;; Get the standard properties, like :PROP: ...
14994 (setq range (org-get-property-block beg end))
14995 (when range
14996 (goto-char (car range))
14997 (while (re-search-forward
14998 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14999 (cdr range) t)
15000 (setq key (org-match-string-no-properties 1)
15001 value (org-trim (or (org-match-string-no-properties 2) "")))
15002 (unless (member key excluded)
15003 (push (cons key (or value "")) props)))))
15004 (if clocksum
15005 (push (cons "CLOCKSUM"
15006 (org-columns-number-to-string (/ (float clocksum) 60.)
15007 'add_times))
15008 props))
15009 (if clocksumt
15010 (push (cons "CLOCKSUM_T"
15011 (org-columns-number-to-string (/ (float clocksumt) 60.)
15012 'add_times))
15013 props))
15014 (unless (assoc "CATEGORY" props)
15015 (push (cons "CATEGORY" (org-get-category)) props))
15016 (append sum-props (nreverse props)))))))
15018 (defun org-entry-get (pom property &optional inherit literal-nil)
15019 "Get value of PROPERTY for entry or content at point-or-marker POM.
15020 If INHERIT is non-nil and the entry does not have the property,
15021 then also check higher levels of the hierarchy.
15022 If INHERIT is the symbol `selective', use inheritance only if the setting
15023 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15024 If the property is present but empty, the return value is the empty string.
15025 If the property is not present at all, nil is returned.
15027 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15028 do not interpret it as the list atom nil. This is used for inheritance
15029 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15030 (org-with-point-at pom
15031 (if (and inherit (if (eq inherit 'selective)
15032 (org-property-inherit-p property)
15034 (org-entry-get-with-inheritance property literal-nil)
15035 (if (member property org-special-properties)
15036 ;; We need a special property. Use `org-entry-properties' to
15037 ;; retrieve it, but specify the wanted property
15038 (cdr (assoc property (org-entry-properties nil 'special property)))
15039 (let ((range (org-get-property-block)))
15040 (when (and range (not (eq (car range) (cdr range))))
15041 (let* ((props (list (or (assoc property org-file-properties)
15042 (assoc property org-global-properties)
15043 (assoc property org-global-properties-fixed))))
15044 (ap (lambda (key)
15045 (when (re-search-forward
15046 (org-re-property key) (cdr range) t)
15047 (setq props
15048 (org-update-property-plist
15050 (if (match-end 1)
15051 (org-match-string-no-properties 1) "")
15052 props)))))
15053 val)
15054 (goto-char (car range))
15055 (funcall ap property)
15056 (goto-char (car range))
15057 (while (funcall ap (concat property "+")))
15058 (setq val (cdr (assoc property props)))
15059 (when val (if literal-nil val (org-not-nil val))))))))))
15061 (defun org-property-or-variable-value (var &optional inherit)
15062 "Check if there is a property fixing the value of VAR.
15063 If yes, return this value. If not, return the current value of the variable."
15064 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15065 (if (and prop (stringp prop) (string-match "\\S-" prop))
15066 (read prop)
15067 (symbol-value var))))
15069 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15070 "Delete the property PROPERTY from entry at point-or-marker POM.
15071 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15072 an empty drawer to delete."
15073 (org-with-point-at pom
15074 (if (member property org-special-properties)
15075 nil ; cannot delete these properties.
15076 (let ((range (org-get-property-block)))
15077 (if (and range
15078 (goto-char (car range))
15079 (re-search-forward
15080 (org-re-property property)
15081 (cdr range) t))
15082 (progn
15083 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15084 (and delete-empty-drawer
15085 (org-remove-empty-drawer-at
15086 delete-empty-drawer (car range)))
15088 nil)))))
15090 ;; Multi-values properties are properties that contain multiple values
15091 ;; These values are assumed to be single words, separated by whitespace.
15092 (defun org-entry-add-to-multivalued-property (pom property value)
15093 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15094 (let* ((old (org-entry-get pom property))
15095 (values (and old (org-split-string old "[ \t]"))))
15096 (setq value (org-entry-protect-space value))
15097 (unless (member value values)
15098 (setq values (cons value values))
15099 (org-entry-put pom property
15100 (mapconcat 'identity values " ")))))
15102 (defun org-entry-remove-from-multivalued-property (pom property value)
15103 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15104 (let* ((old (org-entry-get pom property))
15105 (values (and old (org-split-string old "[ \t]"))))
15106 (setq value (org-entry-protect-space value))
15107 (when (member value values)
15108 (setq values (delete value values))
15109 (org-entry-put pom property
15110 (mapconcat 'identity values " ")))))
15112 (defun org-entry-member-in-multivalued-property (pom property value)
15113 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15114 (let* ((old (org-entry-get pom property))
15115 (values (and old (org-split-string old "[ \t]"))))
15116 (setq value (org-entry-protect-space value))
15117 (member value values)))
15119 (defun org-entry-get-multivalued-property (pom property)
15120 "Return a list of values in a multivalued property."
15121 (let* ((value (org-entry-get pom property))
15122 (values (and value (org-split-string value "[ \t]"))))
15123 (mapcar 'org-entry-restore-space values)))
15125 (defun org-entry-put-multivalued-property (pom property &rest values)
15126 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15127 VALUES should be a list of strings. Spaces will be protected."
15128 (org-entry-put pom property
15129 (mapconcat 'org-entry-protect-space values " "))
15130 (let* ((value (org-entry-get pom property))
15131 (values (and value (org-split-string value "[ \t]"))))
15132 (mapcar 'org-entry-restore-space values)))
15134 (defun org-entry-protect-space (s)
15135 "Protect spaces and newline in string S."
15136 (while (string-match " " s)
15137 (setq s (replace-match "%20" t t s)))
15138 (while (string-match "\n" s)
15139 (setq s (replace-match "%0A" t t s)))
15142 (defun org-entry-restore-space (s)
15143 "Restore spaces and newline in string S."
15144 (while (string-match "%20" s)
15145 (setq s (replace-match " " t t s)))
15146 (while (string-match "%0A" s)
15147 (setq s (replace-match "\n" t t s)))
15150 (defvar org-entry-property-inherited-from (make-marker)
15151 "Marker pointing to the entry from where a property was inherited.
15152 Each call to `org-entry-get-with-inheritance' will set this marker to the
15153 location of the entry where the inheritance search matched. If there was
15154 no match, the marker will point nowhere.
15155 Note that also `org-entry-get' calls this function, if the INHERIT flag
15156 is set.")
15158 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15159 "Get PROPERTY of entry or content at point, search higher levels if needed.
15160 The search will stop at the first ancestor which has the property defined.
15161 If the value found is \"nil\", return nil to show that the property
15162 should be considered as undefined (this is the meaning of nil here).
15163 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15164 (move-marker org-entry-property-inherited-from nil)
15165 (let (tmp)
15166 (save-excursion
15167 (save-restriction
15168 (widen)
15169 (catch 'ex
15170 (while t
15171 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15172 (or (ignore-errors (org-back-to-heading t))
15173 (goto-char (point-min)))
15174 (move-marker org-entry-property-inherited-from (point))
15175 (throw 'ex tmp))
15176 (or (ignore-errors (org-up-heading-safe))
15177 (throw 'ex nil))))))
15178 (setq tmp (or tmp
15179 (cdr (assoc property org-file-properties))
15180 (cdr (assoc property org-global-properties))
15181 (cdr (assoc property org-global-properties-fixed))))
15182 (if literal-nil tmp (org-not-nil tmp))))
15184 (defvar org-property-changed-functions nil
15185 "Hook called when the value of a property has changed.
15186 Each hook function should accept two arguments, the name of the property
15187 and the new value.")
15189 (defun org-entry-put (pom property value)
15190 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15191 (org-with-point-at pom
15192 (org-back-to-heading t)
15193 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15194 range)
15195 (cond
15196 ((equal property "TODO")
15197 (when (and (stringp value) (string-match "\\S-" value)
15198 (not (member value org-todo-keywords-1)))
15199 (error "\"%s\" is not a valid TODO state" value))
15200 (if (or (not value)
15201 (not (string-match "\\S-" value)))
15202 (setq value 'none))
15203 (org-todo value)
15204 (org-set-tags nil 'align))
15205 ((equal property "PRIORITY")
15206 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15207 (string-to-char value) ?\ ))
15208 (org-set-tags nil 'align))
15209 ((equal property "CLOCKSUM")
15210 (if (not (re-search-forward
15211 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15212 (error "Cannot find a clock log")
15213 (goto-char (- (match-end 1) 2))
15214 (cond
15215 ((eq value 'earlier) (org-timestamp-down))
15216 ((eq value 'later) (org-timestamp-up)))
15217 (org-clock-sum-current-item)))
15218 ((equal property "SCHEDULED")
15219 (if (re-search-forward org-scheduled-time-regexp end t)
15220 (cond
15221 ((eq value 'earlier) (org-timestamp-change -1 'day))
15222 ((eq value 'later) (org-timestamp-change 1 'day))
15223 (t (call-interactively 'org-schedule)))
15224 (call-interactively 'org-schedule)))
15225 ((equal property "DEADLINE")
15226 (if (re-search-forward org-deadline-time-regexp end t)
15227 (cond
15228 ((eq value 'earlier) (org-timestamp-change -1 'day))
15229 ((eq value 'later) (org-timestamp-change 1 'day))
15230 (t (call-interactively 'org-deadline)))
15231 (call-interactively 'org-deadline)))
15232 ((member property org-special-properties)
15233 (error "The %s property can not yet be set with `org-entry-put'"
15234 property))
15235 (t ; a non-special property
15236 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15237 (setq range (org-get-property-block beg end 'force))
15238 (goto-char (car range))
15239 (if (re-search-forward
15240 (org-re-property-keyword property) (cdr range) t)
15241 (progn
15242 (delete-region (match-beginning 0) (match-end 0))
15243 (goto-char (match-beginning 0)))
15244 (goto-char (cdr range))
15245 (insert "\n")
15246 (backward-char 1)
15247 (org-indent-line))
15248 (insert ":" property ":")
15249 (and value (insert " " value))
15250 (org-indent-line)))))
15251 (run-hook-with-args 'org-property-changed-functions property value)))
15253 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15254 "Get all property keys in the current buffer.
15255 With INCLUDE-SPECIALS, also list the special properties that reflect things
15256 like tags and TODO state.
15257 With INCLUDE-DEFAULTS, also include properties that has special meaning
15258 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15259 and others.
15260 With INCLUDE-COLUMNS, also include property names given in COLUMN
15261 formats in the current buffer."
15262 (let (rtn range cfmt s p)
15263 (save-excursion
15264 (save-restriction
15265 (widen)
15266 (goto-char (point-min))
15267 (while (re-search-forward org-property-start-re nil t)
15268 (setq range (org-get-property-block))
15269 (goto-char (car range))
15270 (while (re-search-forward
15271 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15272 (cdr range) t)
15273 (add-to-list 'rtn (org-match-string-no-properties 1)))
15274 (outline-next-heading))))
15276 (when include-specials
15277 (setq rtn (append org-special-properties rtn)))
15279 (when include-defaults
15280 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15281 (add-to-list 'rtn org-effort-property))
15283 (when include-columns
15284 (save-excursion
15285 (save-restriction
15286 (widen)
15287 (goto-char (point-min))
15288 (while (re-search-forward
15289 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15290 nil t)
15291 (setq cfmt (match-string 2) s 0)
15292 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15293 cfmt s)
15294 (setq s (match-end 0)
15295 p (match-string 1 cfmt))
15296 (unless (or (equal p "ITEM")
15297 (member p org-special-properties))
15298 (add-to-list 'rtn (match-string 1 cfmt))))))))
15300 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15302 (defun org-property-values (key)
15303 "Return a list of all values of property KEY in the current buffer."
15304 (save-excursion
15305 (save-restriction
15306 (widen)
15307 (goto-char (point-min))
15308 (let ((re (org-re-property key))
15309 values)
15310 (while (re-search-forward re nil t)
15311 (add-to-list 'values (org-trim (match-string 1))))
15312 (delete "" values)))))
15314 (defun org-insert-property-drawer ()
15315 "Insert a property drawer into the current entry."
15316 (org-back-to-heading t)
15317 (looking-at org-outline-regexp)
15318 (let ((indent (if org-adapt-indentation
15319 (- (match-end 0) (match-beginning 0))
15321 (beg (point))
15322 (re (concat "^[ \t]*" org-keyword-time-regexp))
15323 end hiddenp)
15324 (outline-next-heading)
15325 (setq end (point))
15326 (goto-char beg)
15327 (while (re-search-forward re end t))
15328 (setq hiddenp (outline-invisible-p))
15329 (end-of-line 1)
15330 (and (equal (char-after) ?\n) (forward-char 1))
15331 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15332 (if (member (match-string 1) '("CLOCK:" ":END:"))
15333 ;; just skip this line
15334 (beginning-of-line 2)
15335 ;; Drawer start, find the end
15336 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15337 (beginning-of-line 1)))
15338 (org-skip-over-state-notes)
15339 (skip-chars-backward " \t\n\r")
15340 (if (eq (char-before) ?*) (forward-char 1))
15341 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15342 (beginning-of-line 0)
15343 (org-indent-to-column indent)
15344 (beginning-of-line 2)
15345 (org-indent-to-column indent)
15346 (beginning-of-line 0)
15347 (if hiddenp
15348 (save-excursion
15349 (org-back-to-heading t)
15350 (hide-entry))
15351 (org-flag-drawer t))))
15353 (defun org-insert-drawer (&optional arg drawer)
15354 "Insert a drawer at point.
15356 Optional argument DRAWER, when non-nil, is a string representing
15357 drawer's name. Otherwise, the user is prompted for a name.
15359 If a region is active, insert the drawer around that region
15360 instead.
15362 Point is left between drawer's boundaries."
15363 (interactive "P")
15364 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15365 "LOGBOOK"))
15366 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15367 ;; internally by Org. They are meant to be inserted
15368 ;; automatically.
15369 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15370 ;; Remove system drawers from list. Note: For some reason,
15371 ;; `org-completing-read' ignores the predicate while
15372 ;; `completing-read' handles it fine.
15373 (drawer (if arg "PROPERTIES"
15374 (or drawer
15375 (completing-read
15376 "Drawer: " org-drawers
15377 (lambda (d) (not (member d system-drawers))))))))
15378 (cond
15379 ;; With C-u, fall back on `org-insert-property-drawer'
15380 (arg (org-insert-property-drawer))
15381 ;; With an active region, insert a drawer at point.
15382 ((not (org-region-active-p))
15383 (progn
15384 (unless (bolp) (insert "\n"))
15385 (insert (format ":%s:\n\n:END:\n" drawer))
15386 (forward-line -2)))
15387 ;; Otherwise, insert the drawer at point
15389 (let ((rbeg (region-beginning))
15390 (rend (copy-marker (region-end))))
15391 (unwind-protect
15392 (progn
15393 (goto-char rbeg)
15394 (beginning-of-line)
15395 (when (save-excursion
15396 (re-search-forward org-outline-regexp-bol rend t))
15397 (error "Drawers cannot contain headlines"))
15398 ;; Position point at the beginning of the first
15399 ;; non-blank line in region. Insert drawer's opening
15400 ;; there, then indent it.
15401 (org-skip-whitespace)
15402 (beginning-of-line)
15403 (insert ":" drawer ":\n")
15404 (forward-line -1)
15405 (indent-for-tab-command)
15406 ;; Move point to the beginning of the first blank line
15407 ;; after the last non-blank line in region. Insert
15408 ;; drawer's closing, then indent it.
15409 (goto-char rend)
15410 (skip-chars-backward " \r\t\n")
15411 (insert "\n:END:")
15412 (deactivate-mark t)
15413 (indent-for-tab-command)
15414 (unless (eolp) (insert "\n")))
15415 ;; Clear marker, whatever the outcome of insertion is.
15416 (set-marker rend nil)))))))
15418 (defvar org-property-set-functions-alist nil
15419 "Property set function alist.
15420 Each entry should have the following format:
15422 (PROPERTY . READ-FUNCTION)
15424 The read function will be called with the same argument as
15425 `org-completing-read'.")
15427 (defun org-set-property-function (property)
15428 "Get the function that should be used to set PROPERTY.
15429 This is computed according to `org-property-set-functions-alist'."
15430 (or (cdr (assoc property org-property-set-functions-alist))
15431 'org-completing-read))
15433 (defun org-read-property-value (property)
15434 "Read PROPERTY value from user."
15435 (let* ((completion-ignore-case t)
15436 (allowed (org-property-get-allowed-values nil property 'table))
15437 (cur (org-entry-get nil property))
15438 (prompt (concat property " value"
15439 (if (and cur (string-match "\\S-" cur))
15440 (concat " [" cur "]") "") ": "))
15441 (set-function (org-set-property-function property))
15442 (val (if allowed
15443 (funcall set-function prompt allowed nil
15444 (not (get-text-property 0 'org-unrestricted
15445 (caar allowed))))
15446 (let (org-completion-use-ido org-completion-use-iswitchb)
15447 (funcall set-function prompt
15448 (mapcar 'list (org-property-values property))
15449 nil nil "" nil cur)))))
15450 (if (equal val "")
15452 val)))
15454 (defvar org-last-set-property nil)
15455 (defvar org-last-set-property-value nil)
15456 (defun org-read-property-name ()
15457 "Read a property name."
15458 (let* ((completion-ignore-case t)
15459 (keys (org-buffer-property-keys nil t t))
15460 (default-prop (or (save-excursion
15461 (save-match-data
15462 (beginning-of-line)
15463 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15464 (null (string= (match-string 1) "END"))
15465 (match-string 1))))
15466 org-last-set-property))
15467 (property (org-icompleting-read
15468 (concat "Property"
15469 (if default-prop (concat " [" default-prop "]") "")
15470 ": ")
15471 (mapcar 'list keys)
15472 nil nil nil nil
15473 default-prop)))
15474 (if (member property keys)
15475 property
15476 (or (cdr (assoc (downcase property)
15477 (mapcar (lambda (x) (cons (downcase x) x))
15478 keys)))
15479 property))))
15481 (defun org-set-property-and-value (use-last)
15482 "Allow to set [PROPERTY]: [value] direction from prompt.
15483 When use-default, don't even ask, just use the last
15484 \"[PROPERTY]: [value]\" string from the history."
15485 (interactive "P")
15486 (let* ((completion-ignore-case t)
15487 (pv (or (and use-last org-last-set-property-value)
15488 (org-completing-read
15489 "Enter a \"[Property]: [value]\" pair: "
15490 nil nil nil nil nil
15491 org-last-set-property-value)))
15492 prop val)
15493 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15494 (setq prop (match-string 1 pv)
15495 val (match-string 2 pv))
15496 (org-set-property prop val))))
15498 (defun org-set-property (property value)
15499 "In the current entry, set PROPERTY to VALUE.
15500 When called interactively, this will prompt for a property name, offering
15501 completion on existing and default properties. And then it will prompt
15502 for a value, offering completion either on allowed values (via an inherited
15503 xxx_ALL property) or on existing values in other instances of this property
15504 in the current file."
15505 (interactive (list nil nil))
15506 (let* ((property (or property (org-read-property-name)))
15507 (value (or value (org-read-property-value property)))
15508 (fn (cdr (assoc property org-properties-postprocess-alist))))
15509 (setq org-last-set-property property)
15510 (setq org-last-set-property-value (concat property ": " value))
15511 ;; Possibly postprocess the inserted value:
15512 (when fn (setq value (funcall fn value)))
15513 (unless (equal (org-entry-get nil property) value)
15514 (org-entry-put nil property value))))
15516 (defun org-delete-property (property &optional delete-empty-drawer)
15517 "In the current entry, delete PROPERTY.
15518 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15519 an empty drawer to delete."
15520 (interactive
15521 (let* ((completion-ignore-case t)
15522 (prop (org-icompleting-read "Property: "
15523 (org-entry-properties nil 'standard))))
15524 (list prop)))
15525 (message "Property %s %s" property
15526 (if (org-entry-delete nil property delete-empty-drawer)
15527 "deleted"
15528 "was not present in the entry")))
15530 (defun org-delete-property-globally (property)
15531 "Remove PROPERTY globally, from all entries."
15532 (interactive
15533 (let* ((completion-ignore-case t)
15534 (prop (org-icompleting-read
15535 "Globally remove property: "
15536 (mapcar 'list (org-buffer-property-keys)))))
15537 (list prop)))
15538 (save-excursion
15539 (save-restriction
15540 (widen)
15541 (goto-char (point-min))
15542 (let ((cnt 0))
15543 (while (re-search-forward
15544 (org-re-property property)
15545 nil t)
15546 (setq cnt (1+ cnt))
15547 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15548 (message "Property \"%s\" removed from %d entries" property cnt)))))
15550 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15552 (defun org-compute-property-at-point ()
15553 "Compute the property at point.
15554 This looks for an enclosing column format, extracts the operator and
15555 then applies it to the property in the column format's scope."
15556 (interactive)
15557 (unless (org-at-property-p)
15558 (error "Not at a property"))
15559 (let ((prop (org-match-string-no-properties 2)))
15560 (org-columns-get-format-and-top-level)
15561 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15562 (error "No operator defined for property %s" prop))
15563 (org-columns-compute prop)))
15565 (defvar org-property-allowed-value-functions nil
15566 "Hook for functions supplying allowed values for a specific property.
15567 The functions must take a single argument, the name of the property, and
15568 return a flat list of allowed values. If \":ETC\" is one of
15569 the values, this means that these values are intended as defaults for
15570 completion, but that other values should be allowed too.
15571 The functions must return nil if they are not responsible for this
15572 property.")
15574 (defun org-property-get-allowed-values (pom property &optional table)
15575 "Get allowed values for the property PROPERTY.
15576 When TABLE is non-nil, return an alist that can directly be used for
15577 completion."
15578 (let (vals)
15579 (cond
15580 ((equal property "TODO")
15581 (setq vals (org-with-point-at pom
15582 (append org-todo-keywords-1 '("")))))
15583 ((equal property "PRIORITY")
15584 (let ((n org-lowest-priority))
15585 (while (>= n org-highest-priority)
15586 (push (char-to-string n) vals)
15587 (setq n (1- n)))))
15588 ((member property org-special-properties))
15589 ((setq vals (run-hook-with-args-until-success
15590 'org-property-allowed-value-functions property)))
15592 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15593 (when (and vals (string-match "\\S-" vals))
15594 (setq vals (car (read-from-string (concat "(" vals ")"))))
15595 (setq vals (mapcar (lambda (x)
15596 (cond ((stringp x) x)
15597 ((numberp x) (number-to-string x))
15598 ((symbolp x) (symbol-name x))
15599 (t "???")))
15600 vals)))))
15601 (when (member ":ETC" vals)
15602 (setq vals (remove ":ETC" vals))
15603 (org-add-props (car vals) '(org-unrestricted t)))
15604 (if table (mapcar 'list vals) vals)))
15606 (defun org-property-previous-allowed-value (&optional previous)
15607 "Switch to the next allowed value for this property."
15608 (interactive)
15609 (org-property-next-allowed-value t))
15611 (defun org-property-next-allowed-value (&optional previous)
15612 "Switch to the next allowed value for this property."
15613 (interactive)
15614 (unless (org-at-property-p)
15615 (error "Not at a property"))
15616 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15617 (key (match-string 2))
15618 (value (match-string 3))
15619 (allowed (or (org-property-get-allowed-values (point) key)
15620 (and (member value '("[ ]" "[-]" "[X]"))
15621 '("[ ]" "[X]"))))
15622 (heading (save-match-data (nth 4 (org-heading-components))))
15623 nval)
15624 (unless allowed
15625 (error "Allowed values for this property have not been defined"))
15626 (if previous (setq allowed (reverse allowed)))
15627 (if (member value allowed)
15628 (setq nval (car (cdr (member value allowed)))))
15629 (setq nval (or nval (car allowed)))
15630 (if (equal nval value)
15631 (error "Only one allowed value for this property"))
15632 (org-at-property-p)
15633 (replace-match (concat " :" key ": " nval) t t)
15634 (org-indent-line)
15635 (beginning-of-line 1)
15636 (skip-chars-forward " \t")
15637 (when (equal prop org-effort-property)
15638 (save-excursion
15639 (org-back-to-heading t)
15640 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15641 (when (string= org-clock-current-task heading)
15642 (setq org-clock-effort nval)
15643 (org-clock-update-mode-line)))
15644 (run-hook-with-args 'org-property-changed-functions key nval)))
15646 (defun org-find-olp (path &optional this-buffer)
15647 "Return a marker pointing to the entry at outline path OLP.
15648 If anything goes wrong, throw an error.
15649 You can wrap this call to catch the error like this:
15651 (condition-case msg
15652 (org-mobile-locate-entry (match-string 4))
15653 (error (nth 1 msg)))
15655 The return value will then be either a string with the error message,
15656 or a marker if everything is OK.
15658 If THIS-BUFFER is set, the outline path does not contain a file,
15659 only headings."
15660 (let* ((file (if this-buffer buffer-file-name (pop path)))
15661 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15662 (level 1)
15663 (lmin 1)
15664 (lmax 1)
15665 limit re end found pos heading cnt flevel)
15666 (unless buffer (error "File not found :%s" file))
15667 (with-current-buffer buffer
15668 (save-excursion
15669 (save-restriction
15670 (widen)
15671 (setq limit (point-max))
15672 (goto-char (point-min))
15673 (while (setq heading (pop path))
15674 (setq re (format org-complex-heading-regexp-format
15675 (regexp-quote heading)))
15676 (setq cnt 0 pos (point))
15677 (while (re-search-forward re end t)
15678 (setq level (- (match-end 1) (match-beginning 1)))
15679 (if (and (>= level lmin) (<= level lmax))
15680 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15681 (when (= cnt 0) (error "Heading not found on level %d: %s"
15682 lmax heading))
15683 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15684 lmax heading))
15685 (goto-char found)
15686 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15687 (setq end (save-excursion (org-end-of-subtree t t))))
15688 (when (org-at-heading-p)
15689 (point-marker)))))))
15691 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15692 "Find node HEADING in BUFFER.
15693 Return a marker to the heading if it was found, or nil if not.
15694 If POS-ONLY is set, return just the position instead of a marker.
15696 The heading text must match exact, but it may have a TODO keyword,
15697 a priority cookie and tags in the standard locations."
15698 (with-current-buffer (or buffer (current-buffer))
15699 (save-excursion
15700 (save-restriction
15701 (widen)
15702 (goto-char (point-min))
15703 (let (case-fold-search)
15704 (if (re-search-forward
15705 (format org-complex-heading-regexp-format
15706 (regexp-quote heading)) nil t)
15707 (if pos-only
15708 (match-beginning 0)
15709 (move-marker (make-marker) (match-beginning 0)))))))))
15711 (defun org-find-exact-heading-in-directory (heading &optional dir)
15712 "Find Org node headline HEADING in all .org files in directory DIR.
15713 When the target headline is found, return a marker to this location."
15714 (let ((files (directory-files (or dir default-directory)
15715 nil "\\`[^.#].*\\.org\\'"))
15716 file visiting m buffer)
15717 (catch 'found
15718 (while (setq file (pop files))
15719 (message "trying %s" file)
15720 (setq visiting (org-find-base-buffer-visiting file))
15721 (setq buffer (or visiting (find-file-noselect file)))
15722 (setq m (org-find-exact-headline-in-buffer
15723 heading buffer))
15724 (when (and (not m) (not visiting)) (kill-buffer buffer))
15725 (and m (throw 'found m))))))
15727 (defun org-find-entry-with-id (ident)
15728 "Locate the entry that contains the ID property with exact value IDENT.
15729 IDENT can be a string, a symbol or a number, this function will search for
15730 the string representation of it.
15731 Return the position where this entry starts, or nil if there is no such entry."
15732 (interactive "sID: ")
15733 (let ((id (cond
15734 ((stringp ident) ident)
15735 ((symbol-name ident) (symbol-name ident))
15736 ((numberp ident) (number-to-string ident))
15737 (t (error "IDENT %s must be a string, symbol or number" ident))))
15738 (case-fold-search nil))
15739 (save-excursion
15740 (save-restriction
15741 (widen)
15742 (goto-char (point-min))
15743 (when (re-search-forward
15744 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15745 nil t)
15746 (org-back-to-heading t)
15747 (point))))))
15749 ;;;; Timestamps
15751 (defvar org-last-changed-timestamp nil)
15752 (defvar org-last-inserted-timestamp nil
15753 "The last time stamp inserted with `org-insert-time-stamp'.")
15754 (defvar org-time-was-given) ; dynamically scoped parameter
15755 (defvar org-end-time-was-given) ; dynamically scoped parameter
15756 (defvar org-ts-what) ; dynamically scoped parameter
15758 (defun org-time-stamp (arg &optional inactive)
15759 "Prompt for a date/time and insert a time stamp.
15760 If the user specifies a time like HH:MM or if this command is
15761 called with at least one prefix argument, the time stamp contains
15762 the date and the time. Otherwise, only the date is be included.
15764 All parts of a date not specified by the user is filled in from
15765 the current date/time. So if you just press return without
15766 typing anything, the time stamp will represent the current
15767 date/time.
15769 If there is already a timestamp at the cursor, it will be
15770 modified.
15772 With two universal prefix arguments, insert an active timestamp
15773 with the current time without prompting the user."
15774 (interactive "P")
15775 (let* ((ts nil)
15776 (default-time
15777 ;; Default time is either today, or, when entering a range,
15778 ;; the range start.
15779 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15780 (save-excursion
15781 (re-search-backward
15782 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15783 (- (point) 20) t)))
15784 (apply 'encode-time (org-parse-time-string (match-string 1)))
15785 (current-time)))
15786 (default-input (and ts (org-get-compact-tod ts)))
15787 (repeater (save-excursion
15788 (save-match-data
15789 (beginning-of-line)
15790 (when (re-search-forward
15791 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15792 (save-excursion (progn (end-of-line) (point))) t)
15793 (match-string 0)))))
15794 org-time-was-given org-end-time-was-given time)
15795 (cond
15796 ((and (org-at-timestamp-p t)
15797 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15798 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15799 (insert "--")
15800 (setq time (let ((this-command this-command))
15801 (org-read-date arg 'totime nil nil
15802 default-time default-input inactive)))
15803 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15804 ((org-at-timestamp-p t)
15805 (setq time (let ((this-command this-command))
15806 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15807 (when (org-at-timestamp-p t) ; just to get the match data
15808 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15809 (replace-match "")
15810 (setq org-last-changed-timestamp
15811 (org-insert-time-stamp
15812 time (or org-time-was-given arg)
15813 inactive nil nil (list org-end-time-was-given)))
15814 (when repeater (goto-char (1- (point))) (insert " " repeater)
15815 (setq org-last-changed-timestamp
15816 (concat (substring org-last-inserted-timestamp 0 -1)
15817 " " repeater ">"))))
15818 (message "Timestamp updated"))
15819 ((equal arg '(16))
15820 (org-insert-time-stamp (current-time) t))
15822 (setq time (let ((this-command this-command))
15823 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15824 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15825 nil nil (list org-end-time-was-given))))))
15827 ;; FIXME: can we use this for something else, like computing time differences?
15828 (defun org-get-compact-tod (s)
15829 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15830 (let* ((t1 (match-string 1 s))
15831 (h1 (string-to-number (match-string 2 s)))
15832 (m1 (string-to-number (match-string 3 s)))
15833 (t2 (and (match-end 4) (match-string 5 s)))
15834 (h2 (and t2 (string-to-number (match-string 6 s))))
15835 (m2 (and t2 (string-to-number (match-string 7 s))))
15836 dh dm)
15837 (if (not t2)
15839 (setq dh (- h2 h1) dm (- m2 m1))
15840 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15841 (concat t1 "+" (number-to-string dh)
15842 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15844 (defun org-time-stamp-inactive (&optional arg)
15845 "Insert an inactive time stamp.
15846 An inactive time stamp is enclosed in square brackets instead of angle
15847 brackets. It is inactive in the sense that it does not trigger agenda entries,
15848 does not link to the calendar and cannot be changed with the S-cursor keys.
15849 So these are more for recording a certain time/date."
15850 (interactive "P")
15851 (org-time-stamp arg 'inactive))
15853 (defvar org-date-ovl (make-overlay 1 1))
15854 (overlay-put org-date-ovl 'face 'org-date-selected)
15855 (org-detach-overlay org-date-ovl)
15857 (defvar org-ans1) ; dynamically scoped parameter
15858 (defvar org-ans2) ; dynamically scoped parameter
15860 (defvar org-plain-time-of-day-regexp) ; defined below
15862 (defvar org-overriding-default-time nil) ; dynamically scoped
15863 (defvar org-read-date-overlay nil)
15864 (defvar org-dcst nil) ; dynamically scoped
15865 (defvar org-read-date-history nil)
15866 (defvar org-read-date-final-answer nil)
15867 (defvar org-read-date-analyze-futurep nil)
15868 (defvar org-read-date-analyze-forced-year nil)
15869 (defvar org-read-date-inactive)
15871 (defvar org-read-date-minibuffer-local-map
15872 (let ((map (make-sparse-keymap)))
15873 (set-keymap-parent map minibuffer-local-map)
15874 (org-defkey map (kbd ".")
15875 (lambda () (interactive)
15876 (org-eval-in-calendar '(calendar-goto-today))))
15877 (org-defkey map [(meta shift left)]
15878 (lambda () (interactive)
15879 (org-eval-in-calendar '(calendar-backward-month 1))))
15880 (org-defkey map [(meta shift right)]
15881 (lambda () (interactive)
15882 (org-eval-in-calendar '(calendar-forward-month 1))))
15883 (org-defkey map [(meta shift up)]
15884 (lambda () (interactive)
15885 (org-eval-in-calendar '(calendar-backward-year 1))))
15886 (org-defkey map [(meta shift down)]
15887 (lambda () (interactive)
15888 (org-eval-in-calendar '(calendar-forward-year 1))))
15889 (org-defkey map [?\e (shift left)]
15890 (lambda () (interactive)
15891 (org-eval-in-calendar '(calendar-backward-month 1))))
15892 (org-defkey map [?\e (shift right)]
15893 (lambda () (interactive)
15894 (org-eval-in-calendar '(calendar-forward-month 1))))
15895 (org-defkey map [?\e (shift up)]
15896 (lambda () (interactive)
15897 (org-eval-in-calendar '(calendar-backward-year 1))))
15898 (org-defkey map [?\e (shift down)]
15899 (lambda () (interactive)
15900 (org-eval-in-calendar '(calendar-forward-year 1))))
15901 (org-defkey map [(shift up)]
15902 (lambda () (interactive)
15903 (org-eval-in-calendar '(calendar-backward-week 1))))
15904 (org-defkey map [(shift down)]
15905 (lambda () (interactive)
15906 (org-eval-in-calendar '(calendar-forward-week 1))))
15907 (org-defkey map [(shift left)]
15908 (lambda () (interactive)
15909 (org-eval-in-calendar '(calendar-backward-day 1))))
15910 (org-defkey map [(shift right)]
15911 (lambda () (interactive)
15912 (org-eval-in-calendar '(calendar-forward-day 1))))
15913 (org-defkey map "!"
15914 (lambda () (interactive)
15915 (org-eval-in-calendar '(diary-view-entries))
15916 (message "")))
15917 (org-defkey map ">"
15918 (lambda () (interactive)
15919 (org-eval-in-calendar '(scroll-calendar-left 1))))
15920 (org-defkey map "<"
15921 (lambda () (interactive)
15922 (org-eval-in-calendar '(scroll-calendar-right 1))))
15923 (org-defkey map "\C-v"
15924 (lambda () (interactive)
15925 (org-eval-in-calendar
15926 '(calendar-scroll-left-three-months 1))))
15927 (org-defkey map "\M-v"
15928 (lambda () (interactive)
15929 (org-eval-in-calendar
15930 '(calendar-scroll-right-three-months 1))))
15931 map)
15932 "Keymap for minibuffer commands when using `org-read-date'.")
15934 (defun org-read-date (&optional org-with-time to-time from-string prompt
15935 default-time default-input inactive)
15936 "Read a date, possibly a time, and make things smooth for the user.
15937 The prompt will suggest to enter an ISO date, but you can also enter anything
15938 which will at least partially be understood by `parse-time-string'.
15939 Unrecognized parts of the date will default to the current day, month, year,
15940 hour and minute. If this command is called to replace a timestamp at point,
15941 or to enter the second timestamp of a range, the default time is taken
15942 from the existing stamp. Furthermore, the command prefers the future,
15943 so if you are giving a date where the year is not given, and the day-month
15944 combination is already past in the current year, it will assume you
15945 mean next year. For details, see the manual. A few examples:
15947 3-2-5 --> 2003-02-05
15948 feb 15 --> currentyear-02-15
15949 2/15 --> currentyear-02-15
15950 sep 12 9 --> 2009-09-12
15951 12:45 --> today 12:45
15952 22 sept 0:34 --> currentyear-09-22 0:34
15953 12 --> currentyear-currentmonth-12
15954 Fri --> nearest Friday (today or later)
15955 etc.
15957 Furthermore you can specify a relative date by giving, as the *first* thing
15958 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15959 change in days weeks, months, years.
15960 With a single plus or minus, the date is relative to today. With a double
15961 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15962 +4d --> four days from today
15963 +4 --> same as above
15964 +2w --> two weeks from today
15965 ++5 --> five days from default date
15967 The function understands only English month and weekday abbreviations.
15969 While prompting, a calendar is popped up - you can also select the
15970 date with the mouse (button 1). The calendar shows a period of three
15971 months. To scroll it to other months, use the keys `>' and `<'.
15972 If you don't like the calendar, turn it off with
15973 \(setq org-read-date-popup-calendar nil)
15975 With optional argument TO-TIME, the date will immediately be converted
15976 to an internal time.
15977 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15978 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15979 still enter a time, and this function will inform the calling routine
15980 about this change. The calling routine may then choose to change the
15981 format used to insert the time stamp into the buffer to include the time.
15982 With optional argument FROM-STRING, read from this string instead from
15983 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15984 the time/date that is used for everything that is not specified by the
15985 user."
15986 (require 'parse-time)
15987 (let* ((org-time-stamp-rounding-minutes
15988 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15989 (org-dcst org-display-custom-times)
15990 (ct (org-current-time))
15991 (org-def (or org-overriding-default-time default-time ct))
15992 (org-defdecode (decode-time org-def))
15993 (dummy (progn
15994 (when (< (nth 2 org-defdecode) org-extend-today-until)
15995 (setcar (nthcdr 2 org-defdecode) -1)
15996 (setcar (nthcdr 1 org-defdecode) 59)
15997 (setq org-def (apply 'encode-time org-defdecode)
15998 org-defdecode (decode-time org-def)))))
15999 (mouse-autoselect-window nil) ; Don't let the mouse jump
16000 (calendar-frame-setup nil)
16001 (calendar-setup nil)
16002 (calendar-move-hook nil)
16003 (calendar-view-diary-initially-flag nil)
16004 (calendar-view-holidays-initially-flag nil)
16005 (timestr (format-time-string
16006 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16007 (prompt (concat (if prompt (concat prompt " ") "")
16008 (format "Date+time [%s]: " timestr)))
16009 ans (org-ans0 "") org-ans1 org-ans2 final)
16011 (cond
16012 (from-string (setq ans from-string))
16013 (org-read-date-popup-calendar
16014 (save-excursion
16015 (save-window-excursion
16016 (calendar)
16017 (org-eval-in-calendar '(setq cursor-type nil) t)
16018 (unwind-protect
16019 (progn
16020 (calendar-forward-day (- (time-to-days org-def)
16021 (calendar-absolute-from-gregorian
16022 (calendar-current-date))))
16023 (org-eval-in-calendar nil t)
16024 (let* ((old-map (current-local-map))
16025 (map (copy-keymap calendar-mode-map))
16026 (minibuffer-local-map
16027 (copy-keymap org-read-date-minibuffer-local-map)))
16028 (org-defkey map (kbd "RET") 'org-calendar-select)
16029 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16030 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16031 (unwind-protect
16032 (progn
16033 (use-local-map map)
16034 (setq org-read-date-inactive inactive)
16035 (add-hook 'post-command-hook 'org-read-date-display)
16036 (setq org-ans0 (read-string prompt default-input
16037 'org-read-date-history nil))
16038 ;; org-ans0: from prompt
16039 ;; org-ans1: from mouse click
16040 ;; org-ans2: from calendar motion
16041 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16042 (remove-hook 'post-command-hook 'org-read-date-display)
16043 (use-local-map old-map)
16044 (when org-read-date-overlay
16045 (delete-overlay org-read-date-overlay)
16046 (setq org-read-date-overlay nil)))))
16047 (bury-buffer "*Calendar*")))))
16049 (t ; Naked prompt only
16050 (unwind-protect
16051 (setq ans (read-string prompt default-input
16052 'org-read-date-history timestr))
16053 (when org-read-date-overlay
16054 (delete-overlay org-read-date-overlay)
16055 (setq org-read-date-overlay nil)))))
16057 (setq final (org-read-date-analyze ans org-def org-defdecode))
16059 (when org-read-date-analyze-forced-year
16060 (message "Year was forced into %s"
16061 (if org-read-date-force-compatible-dates
16062 "compatible range (1970-2037)"
16063 "range representable on this machine"))
16064 (ding))
16066 ;; One round trip to get rid of 34th of August and stuff like that....
16067 (setq final (decode-time (apply 'encode-time final)))
16069 (setq org-read-date-final-answer ans)
16071 (if to-time
16072 (apply 'encode-time final)
16073 (if (and (boundp 'org-time-was-given) org-time-was-given)
16074 (format "%04d-%02d-%02d %02d:%02d"
16075 (nth 5 final) (nth 4 final) (nth 3 final)
16076 (nth 2 final) (nth 1 final))
16077 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16079 (defvar org-def)
16080 (defvar org-defdecode)
16081 (defvar org-with-time)
16082 (defun org-read-date-display ()
16083 "Display the current date prompt interpretation in the minibuffer."
16084 (when org-read-date-display-live
16085 (when org-read-date-overlay
16086 (delete-overlay org-read-date-overlay))
16087 (when (minibufferp (current-buffer))
16088 (save-excursion
16089 (end-of-line 1)
16090 (while (not (equal (buffer-substring
16091 (max (point-min) (- (point) 4)) (point))
16092 " "))
16093 (insert " ")))
16094 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16095 " " (or org-ans1 org-ans2)))
16096 (org-end-time-was-given nil)
16097 (f (org-read-date-analyze ans org-def org-defdecode))
16098 (fmts (if org-dcst
16099 org-time-stamp-custom-formats
16100 org-time-stamp-formats))
16101 (fmt (if (or org-with-time
16102 (and (boundp 'org-time-was-given) org-time-was-given))
16103 (cdr fmts)
16104 (car fmts)))
16105 (txt (format-time-string fmt (apply 'encode-time f)))
16106 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16107 (txt (concat "=> " txt)))
16108 (when (and org-end-time-was-given
16109 (string-match org-plain-time-of-day-regexp txt))
16110 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16111 org-end-time-was-given
16112 (substring txt (match-end 0)))))
16113 (when org-read-date-analyze-futurep
16114 (setq txt (concat txt " (=>F)")))
16115 (setq org-read-date-overlay
16116 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16117 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16119 (defun org-read-date-analyze (ans org-def org-defdecode)
16120 "Analyze the combined answer of the date prompt."
16121 ;; FIXME: cleanup and comment
16122 (let ((nowdecode (decode-time (current-time)))
16123 delta deltan deltaw deltadef year month day
16124 hour minute second wday pm h2 m2 tl wday1
16125 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16126 (setq org-read-date-analyze-futurep nil
16127 org-read-date-analyze-forced-year nil)
16128 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16129 (setq ans "+0"))
16131 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16132 (setq ans (replace-match "" t t ans)
16133 deltan (car delta)
16134 deltaw (nth 1 delta)
16135 deltadef (nth 2 delta)))
16137 ;; Check if there is an iso week date in there. If yes, store the
16138 ;; info and postpone interpreting it until the rest of the parsing
16139 ;; is done.
16140 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16141 (setq iso-year (if (match-end 1)
16142 (org-small-year-to-year
16143 (string-to-number (match-string 1 ans))))
16144 iso-weekday (if (match-end 3)
16145 (string-to-number (match-string 3 ans)))
16146 iso-week (string-to-number (match-string 2 ans)))
16147 (setq ans (replace-match "" t t ans)))
16149 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16150 (when (string-match
16151 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16152 (setq year (if (match-end 2)
16153 (string-to-number (match-string 2 ans))
16154 (progn (setq kill-year t)
16155 (string-to-number (format-time-string "%Y"))))
16156 month (string-to-number (match-string 3 ans))
16157 day (string-to-number (match-string 4 ans)))
16158 (if (< year 100) (setq year (+ 2000 year)))
16159 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16160 t nil ans)))
16162 ;; Help matching dotted european dates
16163 (when (string-match
16164 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16165 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16166 (setq kill-year t)
16167 (string-to-number (format-time-string "%Y")))
16168 day (string-to-number (match-string 1 ans))
16169 month (string-to-number (match-string 2 ans))
16170 ans (replace-match (format "%04d-%02d-%02d" year month day)
16171 t nil ans)))
16173 ;; Help matching american dates, like 5/30 or 5/30/7
16174 (when (string-match
16175 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16176 (setq year (if (match-end 4)
16177 (string-to-number (match-string 4 ans))
16178 (progn (setq kill-year t)
16179 (string-to-number (format-time-string "%Y"))))
16180 month (string-to-number (match-string 1 ans))
16181 day (string-to-number (match-string 2 ans)))
16182 (if (< year 100) (setq year (+ 2000 year)))
16183 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16184 t nil ans)))
16185 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16186 ;; If there is a time with am/pm, and *no* time without it, we convert
16187 ;; so that matching will be successful.
16188 (loop for i from 1 to 2 do ; twice, for end time as well
16189 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16190 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16191 (setq hour (string-to-number (match-string 1 ans))
16192 minute (if (match-end 3)
16193 (string-to-number (match-string 3 ans))
16195 pm (equal ?p
16196 (string-to-char (downcase (match-string 4 ans)))))
16197 (if (and (= hour 12) (not pm))
16198 (setq hour 0)
16199 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16200 (setq ans (replace-match (format "%02d:%02d" hour minute)
16201 t t ans))))
16203 ;; Check if a time range is given as a duration
16204 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16205 (setq hour (string-to-number (match-string 1 ans))
16206 h2 (+ hour (string-to-number (match-string 3 ans)))
16207 minute (string-to-number (match-string 2 ans))
16208 m2 (+ minute (if (match-end 5) (string-to-number
16209 (match-string 5 ans))0)))
16210 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16211 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16212 t t ans)))
16214 ;; Check if there is a time range
16215 (when (boundp 'org-end-time-was-given)
16216 (setq org-time-was-given nil)
16217 (when (and (string-match org-plain-time-of-day-regexp ans)
16218 (match-end 8))
16219 (setq org-end-time-was-given (match-string 8 ans))
16220 (setq ans (concat (substring ans 0 (match-beginning 7))
16221 (substring ans (match-end 7))))))
16223 (setq tl (parse-time-string ans)
16224 day (or (nth 3 tl) (nth 3 org-defdecode))
16225 month (or (nth 4 tl)
16226 (if (and org-read-date-prefer-future
16227 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16228 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16229 (nth 4 org-defdecode)))
16230 year (or (and (not kill-year) (nth 5 tl))
16231 (if (and org-read-date-prefer-future
16232 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16233 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16234 (nth 5 org-defdecode)))
16235 hour (or (nth 2 tl) (nth 2 org-defdecode))
16236 minute (or (nth 1 tl) (nth 1 org-defdecode))
16237 second (or (nth 0 tl) 0)
16238 wday (nth 6 tl))
16240 (when (and (eq org-read-date-prefer-future 'time)
16241 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16242 (equal day (nth 3 nowdecode))
16243 (equal month (nth 4 nowdecode))
16244 (equal year (nth 5 nowdecode))
16245 (nth 2 tl)
16246 (or (< (nth 2 tl) (nth 2 nowdecode))
16247 (and (= (nth 2 tl) (nth 2 nowdecode))
16248 (nth 1 tl)
16249 (< (nth 1 tl) (nth 1 nowdecode)))))
16250 (setq day (1+ day)
16251 futurep t))
16253 ;; Special date definitions below
16254 (cond
16255 (iso-week
16256 ;; There was an iso week
16257 (require 'cal-iso)
16258 (setq futurep nil)
16259 (setq year (or iso-year year)
16260 day (or iso-weekday wday 1)
16261 wday nil ; to make sure that the trigger below does not match
16262 iso-date (calendar-gregorian-from-absolute
16263 (calendar-absolute-from-iso
16264 (list iso-week day year))))
16265 ; FIXME: Should we also push ISO weeks into the future?
16266 ; (when (and org-read-date-prefer-future
16267 ; (not iso-year)
16268 ; (< (calendar-absolute-from-gregorian iso-date)
16269 ; (time-to-days (current-time))))
16270 ; (setq year (1+ year)
16271 ; iso-date (calendar-gregorian-from-absolute
16272 ; (calendar-absolute-from-iso
16273 ; (list iso-week day year)))))
16274 (setq month (car iso-date)
16275 year (nth 2 iso-date)
16276 day (nth 1 iso-date)))
16277 (deltan
16278 (setq futurep nil)
16279 (unless deltadef
16280 (let ((now (decode-time (current-time))))
16281 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16282 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16283 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16284 ((equal deltaw "m") (setq month (+ month deltan)))
16285 ((equal deltaw "y") (setq year (+ year deltan)))))
16286 ((and wday (not (nth 3 tl)))
16287 ;; Weekday was given, but no day, so pick that day in the week
16288 ;; on or after the derived date.
16289 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16290 (unless (equal wday wday1)
16291 (setq day (+ day (% (- wday wday1 -7) 7))))))
16292 (if (and (boundp 'org-time-was-given)
16293 (nth 2 tl))
16294 (setq org-time-was-given t))
16295 (if (< year 100) (setq year (+ 2000 year)))
16296 ;; Check of the date is representable
16297 (if org-read-date-force-compatible-dates
16298 (progn
16299 (if (< year 1970)
16300 (setq year 1970 org-read-date-analyze-forced-year t))
16301 (if (> year 2037)
16302 (setq year 2037 org-read-date-analyze-forced-year t)))
16303 (condition-case nil
16304 (ignore (encode-time second minute hour day month year))
16305 (error
16306 (setq year (nth 5 org-defdecode))
16307 (setq org-read-date-analyze-forced-year t))))
16308 (setq org-read-date-analyze-futurep futurep)
16309 (list second minute hour day month year)))
16311 (defvar parse-time-weekdays)
16312 (defun org-read-date-get-relative (s today default)
16313 "Check string S for special relative date string.
16314 TODAY and DEFAULT are internal times, for today and for a default.
16315 Return shift list (N what def-flag)
16316 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16317 N is the number of WHATs to shift.
16318 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16319 the DEFAULT date rather than TODAY."
16320 (require 'parse-time)
16321 (when (and
16322 (string-match
16323 (concat
16324 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16325 "\\([0-9]+\\)?"
16326 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16327 "\\([ \t]\\|$\\)") s)
16328 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16329 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16330 (string-to-char (substring (match-string 1 s) -1))
16331 ?+))
16332 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16333 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16334 (what (if (match-end 3) (match-string 3 s) "d"))
16335 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16336 (date (if rel default today))
16337 (wday (nth 6 (decode-time date)))
16338 delta)
16339 (if wday1
16340 (progn
16341 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16342 (if (= dir ?-) (setq delta (- delta 7)))
16343 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16344 (list delta "d" rel))
16345 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16347 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16348 "Turn a user-specified date into the internal representation.
16349 The internal representation needed by the calendar is (month day year).
16350 This is a wrapper to handle the brain-dead convention in calendar that
16351 user function argument order change dependent on argument order."
16352 (if (boundp 'calendar-date-style)
16353 (cond
16354 ((eq calendar-date-style 'american)
16355 (list arg1 arg2 arg3))
16356 ((eq calendar-date-style 'european)
16357 (list arg2 arg1 arg3))
16358 ((eq calendar-date-style 'iso)
16359 (list arg2 arg3 arg1)))
16360 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16361 (if (org-bound-and-true-p european-calendar-style)
16362 (list arg2 arg1 arg3)
16363 (list arg1 arg2 arg3)))))
16365 (defun org-eval-in-calendar (form &optional keepdate)
16366 "Eval FORM in the calendar window and return to current window.
16367 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16368 otherwise stick to the current value of `org-ans2'."
16369 (let ((sf (selected-frame))
16370 (sw (selected-window)))
16371 (select-window (get-buffer-window "*Calendar*" t))
16372 (eval form)
16373 (when (and (not keepdate) (calendar-cursor-to-date))
16374 (let* ((date (calendar-cursor-to-date))
16375 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16376 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16377 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16378 (select-window sw)
16379 (org-select-frame-set-input-focus sf)))
16381 (defun org-calendar-select ()
16382 "Return to `org-read-date' with the date currently selected.
16383 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16384 (interactive)
16385 (when (calendar-cursor-to-date)
16386 (let* ((date (calendar-cursor-to-date))
16387 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16388 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16389 (if (active-minibuffer-window) (exit-minibuffer))))
16391 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16392 "Insert a date stamp for the date given by the internal TIME.
16393 WITH-HM means use the stamp format that includes the time of the day.
16394 INACTIVE means use square brackets instead of angular ones, so that the
16395 stamp will not contribute to the agenda.
16396 PRE and POST are optional strings to be inserted before and after the
16397 stamp.
16398 The command returns the inserted time stamp."
16399 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16400 stamp)
16401 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16402 (insert-before-markers (or pre ""))
16403 (when (listp extra)
16404 (setq extra (car extra))
16405 (if (and (stringp extra)
16406 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16407 (setq extra (format "-%02d:%02d"
16408 (string-to-number (match-string 1 extra))
16409 (string-to-number (match-string 2 extra))))
16410 (setq extra nil)))
16411 (when extra
16412 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16413 (insert-before-markers (setq stamp (format-time-string fmt time)))
16414 (insert-before-markers (or post ""))
16415 (setq org-last-inserted-timestamp stamp)))
16417 (defun org-toggle-time-stamp-overlays ()
16418 "Toggle the use of custom time stamp formats."
16419 (interactive)
16420 (setq org-display-custom-times (not org-display-custom-times))
16421 (unless org-display-custom-times
16422 (let ((p (point-min)) (bmp (buffer-modified-p)))
16423 (while (setq p (next-single-property-change p 'display))
16424 (if (and (get-text-property p 'display)
16425 (eq (get-text-property p 'face) 'org-date))
16426 (remove-text-properties
16427 p (setq p (next-single-property-change p 'display))
16428 '(display t))))
16429 (set-buffer-modified-p bmp)))
16430 (if (featurep 'xemacs)
16431 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16432 (org-restart-font-lock)
16433 (setq org-table-may-need-update t)
16434 (if org-display-custom-times
16435 (message "Time stamps are overlaid with custom format")
16436 (message "Time stamp overlays removed")))
16438 (defun org-display-custom-time (beg end)
16439 "Overlay modified time stamp format over timestamp between BEG and END."
16440 (let* ((ts (buffer-substring beg end))
16441 t1 w1 with-hm tf time str w2 (off 0))
16442 (save-match-data
16443 (setq t1 (org-parse-time-string ts t))
16444 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16445 (setq off (- (match-end 0) (match-beginning 0)))))
16446 (setq end (- end off))
16447 (setq w1 (- end beg)
16448 with-hm (and (nth 1 t1) (nth 2 t1))
16449 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16450 time (org-fix-decoded-time t1)
16451 str (org-add-props
16452 (format-time-string
16453 (substring tf 1 -1) (apply 'encode-time time))
16454 nil 'mouse-face 'highlight)
16455 w2 (length str))
16456 (if (not (= w2 w1))
16457 (add-text-properties (1+ beg) (+ 2 beg)
16458 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16459 (if (featurep 'xemacs)
16460 (progn
16461 (put-text-property beg end 'invisible t)
16462 (put-text-property beg end 'end-glyph (make-glyph str)))
16463 (put-text-property beg end 'display str))))
16465 (defun org-translate-time (string)
16466 "Translate all timestamps in STRING to custom format.
16467 But do this only if the variable `org-display-custom-times' is set."
16468 (when org-display-custom-times
16469 (save-match-data
16470 (let* ((start 0)
16471 (re org-ts-regexp-both)
16472 t1 with-hm inactive tf time str beg end)
16473 (while (setq start (string-match re string start))
16474 (setq beg (match-beginning 0)
16475 end (match-end 0)
16476 t1 (save-match-data
16477 (org-parse-time-string (substring string beg end) t))
16478 with-hm (and (nth 1 t1) (nth 2 t1))
16479 inactive (equal (substring string beg (1+ beg)) "[")
16480 tf (funcall (if with-hm 'cdr 'car)
16481 org-time-stamp-custom-formats)
16482 time (org-fix-decoded-time t1)
16483 str (format-time-string
16484 (concat
16485 (if inactive "[" "<") (substring tf 1 -1)
16486 (if inactive "]" ">"))
16487 (apply 'encode-time time))
16488 string (replace-match str t t string)
16489 start (+ start (length str)))))))
16490 string)
16492 (defun org-fix-decoded-time (time)
16493 "Set 0 instead of nil for the first 6 elements of time.
16494 Don't touch the rest."
16495 (let ((n 0))
16496 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16498 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16500 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16501 "Difference between TIMESTAMP-STRING and now in days.
16502 If SECONDS is non-nil, return the difference in seconds."
16503 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16504 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16505 (funcall fdiff (current-time)))))
16507 (defun org-deadline-close (timestamp-string &optional ndays)
16508 "Is the time in TIMESTAMP-STRING close to the current date?"
16509 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16510 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16511 (not (org-entry-is-done-p))))
16513 (defun org-get-wdays (ts &optional delay zero-delay)
16514 "Get the deadline lead time appropriate for timestring TS.
16515 When DELAY is non-nil, get the delay time for scheduled items
16516 instead of the deadline lead time. When ZERO-DELAY is non-nil
16517 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16518 don't try to find the delay cookie in the scheduled timestamp."
16519 (let ((tv (if delay org-scheduled-delay-days
16520 org-deadline-warning-days)))
16521 (cond
16522 ((or (and delay (< tv 0))
16523 (and delay zero-delay (<= tv 0))
16524 (and (not delay) (<= tv 0)))
16525 ;; Enforce this value no matter what
16526 (- tv))
16527 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16528 ;; lead time is specified.
16529 (floor (* (string-to-number (match-string 1 ts))
16530 (cdr (assoc (match-string 2 ts)
16531 '(("d" . 1) ("w" . 7)
16532 ("m" . 30.4) ("y" . 365.25)
16533 ("h" . 0.041667)))))))
16534 ;; go for the default.
16535 (t tv))))
16537 (defun org-calendar-select-mouse (ev)
16538 "Return to `org-read-date' with the date currently selected.
16539 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16540 (interactive "e")
16541 (mouse-set-point ev)
16542 (when (calendar-cursor-to-date)
16543 (let* ((date (calendar-cursor-to-date))
16544 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16545 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16546 (if (active-minibuffer-window) (exit-minibuffer))))
16548 (defun org-check-deadlines (ndays)
16549 "Check if there are any deadlines due or past due.
16550 A deadline is considered due if it happens within `org-deadline-warning-days'
16551 days from today's date. If the deadline appears in an entry marked DONE,
16552 it is not shown. The prefix arg NDAYS can be used to test that many
16553 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16554 (interactive "P")
16555 (let* ((org-warn-days
16556 (cond
16557 ((equal ndays '(4)) 100000)
16558 (ndays (prefix-numeric-value ndays))
16559 (t (abs org-deadline-warning-days))))
16560 (case-fold-search nil)
16561 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16562 (callback
16563 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16565 (message "%d deadlines past-due or due within %d days"
16566 (org-occur regexp nil callback)
16567 org-warn-days)))
16569 (defsubst org-re-timestamp (type)
16570 "Return a regexp for timestamp TYPE.
16571 Allowed values for TYPE are:
16573 all: all timestamps
16574 active: only active timestamps (<...>)
16575 inactive: only inactive timestamps ([...])
16576 scheduled: only scheduled timestamps
16577 deadline: only deadline timestamps
16579 When TYPE is nil, fall back on returning a regexp that matches
16580 both scheduled and deadline timestamps."
16581 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16582 ((eq type 'active) org-ts-regexp)
16583 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16584 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16585 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16586 ((eq type 'scheduled-or-deadline)
16587 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16589 (defun org-check-before-date (date)
16590 "Check if there are deadlines or scheduled entries before DATE."
16591 (interactive (list (org-read-date)))
16592 (let ((case-fold-search nil)
16593 (regexp (org-re-timestamp org-ts-type))
16594 (callback
16595 (lambda () (time-less-p
16596 (org-time-string-to-time (match-string 1))
16597 (org-time-string-to-time date)))))
16598 (message "%d entries before %s"
16599 (org-occur regexp nil callback) date)))
16601 (defun org-check-after-date (date)
16602 "Check if there are deadlines or scheduled entries after DATE."
16603 (interactive (list (org-read-date)))
16604 (let ((case-fold-search nil)
16605 (regexp (org-re-timestamp org-ts-type))
16606 (callback
16607 (lambda () (not
16608 (time-less-p
16609 (org-time-string-to-time (match-string 1))
16610 (org-time-string-to-time date))))))
16611 (message "%d entries after %s"
16612 (org-occur regexp nil callback) date)))
16614 (defun org-check-dates-range (start-date end-date)
16615 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16616 (interactive (list (org-read-date nil nil nil "Range starts")
16617 (org-read-date nil nil nil "Range end")))
16618 (let ((case-fold-search nil)
16619 (regexp (org-re-timestamp org-ts-type))
16620 (callback
16621 (lambda ()
16622 (let ((match (match-string 1)))
16623 (and
16624 (not (time-less-p
16625 (org-time-string-to-time match)
16626 (org-time-string-to-time start-date)))
16627 (time-less-p
16628 (org-time-string-to-time match)
16629 (org-time-string-to-time end-date)))))))
16630 (message "%d entries between %s and %s"
16631 (org-occur regexp nil callback) start-date end-date)))
16633 (defun org-evaluate-time-range (&optional to-buffer)
16634 "Evaluate a time range by computing the difference between start and end.
16635 Normally the result is just printed in the echo area, but with prefix arg
16636 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16637 If the time range is actually in a table, the result is inserted into the
16638 next column.
16639 For time difference computation, a year is assumed to be exactly 365
16640 days in order to avoid rounding problems."
16641 (interactive "P")
16643 (org-clock-update-time-maybe)
16644 (save-excursion
16645 (unless (org-at-date-range-p t)
16646 (goto-char (point-at-bol))
16647 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16648 (if (not (org-at-date-range-p t))
16649 (error "Not at a time-stamp range, and none found in current line")))
16650 (let* ((ts1 (match-string 1))
16651 (ts2 (match-string 2))
16652 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16653 (match-end (match-end 0))
16654 (time1 (org-time-string-to-time ts1))
16655 (time2 (org-time-string-to-time ts2))
16656 (t1 (org-float-time time1))
16657 (t2 (org-float-time time2))
16658 (diff (abs (- t2 t1)))
16659 (negative (< (- t2 t1) 0))
16660 ;; (ys (floor (* 365 24 60 60)))
16661 (ds (* 24 60 60))
16662 (hs (* 60 60))
16663 (fy "%dy %dd %02d:%02d")
16664 (fy1 "%dy %dd")
16665 (fd "%dd %02d:%02d")
16666 (fd1 "%dd")
16667 (fh "%02d:%02d")
16668 y d h m align)
16669 (if havetime
16670 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16672 d (floor (/ diff ds)) diff (mod diff ds)
16673 h (floor (/ diff hs)) diff (mod diff hs)
16674 m (floor (/ diff 60)))
16675 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16677 d (floor (+ (/ diff ds) 0.5))
16678 h 0 m 0))
16679 (if (not to-buffer)
16680 (message "%s" (org-make-tdiff-string y d h m))
16681 (if (org-at-table-p)
16682 (progn
16683 (goto-char match-end)
16684 (setq align t)
16685 (and (looking-at " *|") (goto-char (match-end 0))))
16686 (goto-char match-end))
16687 (if (looking-at
16688 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16689 (replace-match ""))
16690 (if negative (insert " -"))
16691 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16692 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16693 (insert " " (format fh h m))))
16694 (if align (org-table-align))
16695 (message "Time difference inserted")))))
16697 (defun org-make-tdiff-string (y d h m)
16698 (let ((fmt "")
16699 (l nil))
16700 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16701 l (push y l)))
16702 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16703 l (push d l)))
16704 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16705 l (push h l)))
16706 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16707 l (push m l)))
16708 (apply 'format fmt (nreverse l))))
16710 (defun org-time-string-to-time (s &optional buffer pos)
16711 "Convert a timestamp string into internal time."
16712 (condition-case errdata
16713 (apply 'encode-time (org-parse-time-string s))
16714 (error (error "Bad timestamp `%s'%s\nError was: %s"
16715 s (if (not (and buffer pos))
16717 (format " at %d in buffer `%s'" pos buffer))
16718 (cdr errdata)))))
16720 (defun org-time-string-to-seconds (s)
16721 "Convert a timestamp string to a number of seconds."
16722 (org-float-time (org-time-string-to-time s)))
16724 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16725 "Convert a time stamp to an absolute day number.
16726 If there is a specifier for a cyclic time stamp, get the closest
16727 date to DAYNR.
16728 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16729 The variable `date' is bound by the calendar when this is called."
16730 (cond
16731 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16732 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16733 daynr
16734 (+ daynr 1000)))
16735 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16736 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16737 (time-to-days (current-time))) (match-string 0 s)
16738 prefer show-all))
16739 (t (time-to-days
16740 (condition-case errdata
16741 (apply 'encode-time (org-parse-time-string s))
16742 (error (error "Bad timestamp `%s'%s\nError was: %s"
16743 s (if (not (and buffer pos))
16745 (format " at %d in buffer `%s'" pos buffer))
16746 (cdr errdata))))))))
16748 (defun org-days-to-iso-week (days)
16749 "Return the iso week number."
16750 (require 'cal-iso)
16751 (car (calendar-iso-from-absolute days)))
16753 (defun org-small-year-to-year (year)
16754 "Convert 2-digit years into 4-digit years.
16755 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16756 The year 2000 cannot be abbreviated. Any year larger than 99
16757 is returned unchanged."
16758 (if (< year 38)
16759 (setq year (+ 2000 year))
16760 (if (< year 100)
16761 (setq year (+ 1900 year))))
16762 year)
16764 (defun org-time-from-absolute (d)
16765 "Return the time corresponding to date D.
16766 D may be an absolute day number, or a calendar-type list (month day year)."
16767 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16768 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16770 (defun org-calendar-holiday ()
16771 "List of holidays, for Diary display in Org-mode."
16772 (require 'holidays)
16773 (let ((hl (funcall
16774 (if (fboundp 'calendar-check-holidays)
16775 'calendar-check-holidays 'check-calendar-holidays) date)))
16776 (if hl (mapconcat 'identity hl "; "))))
16778 (defun org-diary-sexp-entry (sexp entry date)
16779 "Process a SEXP diary ENTRY for DATE."
16780 (require 'diary-lib)
16781 (let ((result (if calendar-debug-sexp
16782 (let ((stack-trace-on-error t))
16783 (eval (car (read-from-string sexp))))
16784 (condition-case nil
16785 (eval (car (read-from-string sexp)))
16786 (error
16787 (beep)
16788 (message "Bad sexp at line %d in %s: %s"
16789 (org-current-line)
16790 (buffer-file-name) sexp)
16791 (sleep-for 2))))))
16792 (cond ((stringp result) (split-string result "; "))
16793 ((and (consp result)
16794 (not (consp (cdr result)))
16795 (stringp (cdr result))) (cdr result))
16796 ((and (consp result)
16797 (stringp (car result))) result)
16798 (result entry))))
16800 (defun org-diary-to-ical-string (frombuf)
16801 "Get iCalendar entries from diary entries in buffer FROMBUF.
16802 This uses the icalendar.el library."
16803 (let* ((tmpdir (if (featurep 'xemacs)
16804 (temp-directory)
16805 temporary-file-directory))
16806 (tmpfile (make-temp-name
16807 (expand-file-name "orgics" tmpdir)))
16808 buf rtn b e)
16809 (with-current-buffer frombuf
16810 (icalendar-export-region (point-min) (point-max) tmpfile)
16811 (setq buf (find-buffer-visiting tmpfile))
16812 (set-buffer buf)
16813 (goto-char (point-min))
16814 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16815 (setq b (match-beginning 0)))
16816 (goto-char (point-max))
16817 (if (re-search-backward "^END:VEVENT" nil t)
16818 (setq e (match-end 0)))
16819 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16820 (kill-buffer buf)
16821 (delete-file tmpfile)
16822 rtn))
16824 (defun org-closest-date (start current change prefer show-all)
16825 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16826 When PREFER is `past', return a date that is either CURRENT or past.
16827 When PREFER is `future', return a date that is either CURRENT or future.
16828 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16829 ;; Make the proper lists from the dates
16830 (catch 'exit
16831 (let ((a1 '(("h" . hour)
16832 ("d" . day)
16833 ("w" . week)
16834 ("m" . month)
16835 ("y" . year)))
16836 (shour (nth 2 (org-parse-time-string start)))
16837 dn dw sday cday n1 n2 n0
16838 d m y y1 y2 date1 date2 nmonths nm ny m2)
16840 (setq start (org-date-to-gregorian start)
16841 current (org-date-to-gregorian
16842 (if show-all
16843 current
16844 (time-to-days (current-time))))
16845 sday (calendar-absolute-from-gregorian start)
16846 cday (calendar-absolute-from-gregorian current))
16848 (if (<= cday sday) (throw 'exit sday))
16850 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16851 (setq dn (string-to-number (match-string 1 change))
16852 dw (cdr (assoc (match-string 2 change) a1)))
16853 (error "Invalid change specifier: %s" change))
16854 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16855 (cond
16856 ((eq dw 'hour)
16857 (let ((missing-hours
16858 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16859 dn)))
16860 (setq n1 (if (zerop missing-hours) cday
16861 (- cday (1+ (floor (/ missing-hours 24)))))
16862 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16863 ((eq dw 'day)
16864 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16865 n2 (+ n1 dn)))
16866 ((eq dw 'year)
16867 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16868 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16869 (setq date1 (list m d y1)
16870 n1 (calendar-absolute-from-gregorian date1)
16871 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16872 n2 (calendar-absolute-from-gregorian date2)))
16873 ((eq dw 'month)
16874 ;; approx number of month between the two dates
16875 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16876 ;; How often does dn fit in there?
16877 (setq d (nth 1 start) m (car start) y (nth 2 start)
16878 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16879 m (+ m nm)
16880 ny (floor (/ m 12))
16881 y (+ y ny)
16882 m (- m (* ny 12)))
16883 (while (> m 12) (setq m (- m 12) y (1+ y)))
16884 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16885 (setq m2 (+ m dn) y2 y)
16886 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16887 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16888 (while (<= n2 cday)
16889 (setq n1 n2 m m2 y y2)
16890 (setq m2 (+ m dn) y2 y)
16891 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16892 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16893 ;; Make sure n1 is the earlier date
16894 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16895 (if show-all
16896 (cond
16897 ((eq prefer 'past) (if (= cday n2) n2 n1))
16898 ((eq prefer 'future) (if (= cday n1) n1 n2))
16899 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16900 (cond
16901 ((eq prefer 'past) (if (= cday n2) n2 n1))
16902 ((eq prefer 'future) (if (= cday n1) n1 n2))
16903 (t (if (= cday n1) n1 n2)))))))
16905 (defun org-date-to-gregorian (date)
16906 "Turn any specification of DATE into a Gregorian date for the calendar."
16907 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16908 ((and (listp date) (= (length date) 3)) date)
16909 ((stringp date)
16910 (setq date (org-parse-time-string date))
16911 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16912 ((listp date)
16913 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16915 (defun org-parse-time-string (s &optional nodefault)
16916 "Parse the standard Org-mode time string.
16917 This should be a lot faster than the normal `parse-time-string'.
16918 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16919 hour and minute fields will be nil if not given."
16920 (cond ((string-match org-ts-regexp0 s)
16921 (list 0
16922 (if (or (match-beginning 8) (not nodefault))
16923 (string-to-number (or (match-string 8 s) "0")))
16924 (if (or (match-beginning 7) (not nodefault))
16925 (string-to-number (or (match-string 7 s) "0")))
16926 (string-to-number (match-string 4 s))
16927 (string-to-number (match-string 3 s))
16928 (string-to-number (match-string 2 s))
16929 nil nil nil))
16930 ((string-match "^<[^>]+>$" s)
16931 (decode-time (seconds-to-time (org-matcher-time s))))
16932 (t (error "Not a standard Org-mode time string: %s" s))))
16934 (defun org-timestamp-up (&optional arg)
16935 "Increase the date item at the cursor by one.
16936 If the cursor is on the year, change the year. If it is on the month,
16937 the day or the time, change that.
16938 With prefix ARG, change by that many units."
16939 (interactive "p")
16940 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16942 (defun org-timestamp-down (&optional arg)
16943 "Decrease the date item at the cursor by one.
16944 If the cursor is on the year, change the year. If it is on the month,
16945 the day or the time, change that.
16946 With prefix ARG, change by that many units."
16947 (interactive "p")
16948 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16950 (defun org-timestamp-up-day (&optional arg)
16951 "Increase the date in the time stamp by one day.
16952 With prefix ARG, change that many days."
16953 (interactive "p")
16954 (if (and (not (org-at-timestamp-p t))
16955 (org-at-heading-p))
16956 (org-todo 'up)
16957 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16959 (defun org-timestamp-down-day (&optional arg)
16960 "Decrease the date in the time stamp by one day.
16961 With prefix ARG, change that many days."
16962 (interactive "p")
16963 (if (and (not (org-at-timestamp-p t))
16964 (org-at-heading-p))
16965 (org-todo 'down)
16966 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16968 (defun org-at-timestamp-p (&optional inactive-ok)
16969 "Determine if the cursor is in or at a timestamp."
16970 (interactive)
16971 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16972 (pos (point))
16973 (ans (or (looking-at tsr)
16974 (save-excursion
16975 (skip-chars-backward "^[<\n\r\t")
16976 (if (> (point) (point-min)) (backward-char 1))
16977 (and (looking-at tsr)
16978 (> (- (match-end 0) pos) -1))))))
16979 (and ans
16980 (boundp 'org-ts-what)
16981 (setq org-ts-what
16982 (cond
16983 ((= pos (match-beginning 0)) 'bracket)
16984 ;; Point is considered to be "on the bracket" whether
16985 ;; it's really on it or right after it.
16986 ((= pos (1- (match-end 0))) 'bracket)
16987 ((= pos (match-end 0)) 'after)
16988 ((org-pos-in-match-range pos 2) 'year)
16989 ((org-pos-in-match-range pos 3) 'month)
16990 ((org-pos-in-match-range pos 7) 'hour)
16991 ((org-pos-in-match-range pos 8) 'minute)
16992 ((or (org-pos-in-match-range pos 4)
16993 (org-pos-in-match-range pos 5)) 'day)
16994 ((and (> pos (or (match-end 8) (match-end 5)))
16995 (< pos (match-end 0)))
16996 (- pos (or (match-end 8) (match-end 5))))
16997 (t 'day))))
16998 ans))
17000 (defun org-toggle-timestamp-type ()
17001 "Toggle the type (<active> or [inactive]) of a time stamp."
17002 (interactive)
17003 (when (org-at-timestamp-p t)
17004 (let ((beg (match-beginning 0)) (end (match-end 0))
17005 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17006 (save-excursion
17007 (goto-char beg)
17008 (while (re-search-forward "[][<>]" end t)
17009 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17010 t t)))
17011 (message "Timestamp is now %sactive"
17012 (if (equal (char-after beg) ?<) "" "in")))))
17014 (defun org-at-clock-log-p nil
17015 "Is the cursor on the clock log line?"
17016 (save-excursion
17017 (move-beginning-of-line 1)
17018 (looking-at "^[ \t]*CLOCK:")))
17020 (defvar org-clock-history) ; defined in org-clock.el
17021 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17022 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17023 "Change the date in the time stamp at point.
17024 The date will be changed by N times WHAT. WHAT can be `day', `month',
17025 `year', `minute', `second'. If WHAT is not given, the cursor position
17026 in the timestamp determines what will be changed.
17027 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17028 (let ((origin (point)) origin-cat
17029 with-hm inactive
17030 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17031 org-ts-what
17032 extra rem
17033 ts time time0 fixnext clrgx)
17034 (if (not (org-at-timestamp-p t))
17035 (error "Not at a timestamp"))
17036 (if (and (not what) (eq org-ts-what 'bracket))
17037 (org-toggle-timestamp-type)
17038 ;; Point isn't on brackets. Remember the part of the time-stamp
17039 ;; the point was in. Indeed, size of time-stamps may change,
17040 ;; but point must be kept in the same category nonetheless.
17041 (setq origin-cat org-ts-what)
17042 (if (and (not what) (not (eq org-ts-what 'day))
17043 org-display-custom-times
17044 (get-text-property (point) 'display)
17045 (not (get-text-property (1- (point)) 'display)))
17046 (setq org-ts-what 'day))
17047 (setq org-ts-what (or what org-ts-what)
17048 inactive (= (char-after (match-beginning 0)) ?\[)
17049 ts (match-string 0))
17050 (replace-match "")
17051 (when (string-match
17052 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17054 (setq extra (match-string 1 ts))
17055 (if suppress-tmp-delay
17056 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17057 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17058 (setq with-hm t))
17059 (setq time0 (org-parse-time-string ts))
17060 (when (and updown
17061 (eq org-ts-what 'minute)
17062 (not current-prefix-arg))
17063 ;; This looks like s-up and s-down. Change by one rounding step.
17064 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17065 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17066 (setcar (cdr time0) (+ (nth 1 time0)
17067 (if (> n 0) (- rem) (- dm rem))))))
17068 (setq time
17069 (encode-time (or (car time0) 0)
17070 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17071 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17072 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17073 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17074 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17075 (nthcdr 6 time0)))
17076 (when (and (member org-ts-what '(hour minute))
17077 extra
17078 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17079 (setq extra (org-modify-ts-extra
17080 extra
17081 (if (eq org-ts-what 'hour) 2 5)
17082 n dm)))
17083 (when (integerp org-ts-what)
17084 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17085 (if (eq what 'calendar)
17086 (let ((cal-date (org-get-date-from-calendar)))
17087 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17088 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17089 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17090 (setcar time0 (or (car time0) 0))
17091 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17092 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17093 (setq time (apply 'encode-time time0))))
17094 ;; Insert the new time-stamp, and ensure point stays in the same
17095 ;; category as before (i.e. not after the last position in that
17096 ;; category).
17097 (let ((pos (point)))
17098 ;; Stay before inserted string. `save-excursion' is of no use.
17099 (setq org-last-changed-timestamp
17100 (org-insert-time-stamp time with-hm inactive nil nil extra))
17101 (goto-char pos))
17102 (save-match-data
17103 (looking-at org-ts-regexp3)
17104 (goto-char (cond
17105 ;; `day' category ends before `hour' if any, or at
17106 ;; the end of the day name.
17107 ((eq origin-cat 'day)
17108 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17109 ((eq origin-cat 'hour) (min (match-end 7) origin))
17110 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17111 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17112 ;; `year' and `month' have both fixed size: point
17113 ;; couldn't have moved into another part.
17114 (t origin))))
17115 ;; Update clock if on a CLOCK line.
17116 (org-clock-update-time-maybe)
17117 ;; Maybe adjust the closest clock in `org-clock-history'
17118 (when org-clock-adjust-closest
17119 (if (not (and (org-at-clock-log-p)
17120 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17121 org-clock-history))))))
17122 (message "No clock to adjust")
17123 (cond ((save-excursion ; fix previous clock?
17124 (re-search-backward org-ts-regexp0 nil t)
17125 (org-looking-back (concat org-clock-string " \\[")))
17126 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17127 ((save-excursion ; fix next clock?
17128 (re-search-backward org-ts-regexp0 nil t)
17129 (looking-at (concat org-ts-regexp0 "\\] =>")))
17130 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17131 (save-window-excursion
17132 ;; Find closest clock to point, adjust the previous/next one in history
17133 (let* ((p (save-excursion (org-back-to-heading t)))
17134 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17135 (clfixnth
17136 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17137 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17138 (if (not clfixpos)
17139 (message "No clock to adjust")
17140 (save-excursion
17141 (org-goto-marker-or-bmk clfixpos)
17142 (org-show-subtree)
17143 (when (re-search-forward clrgx nil t)
17144 (goto-char (match-beginning 1))
17145 (let (org-clock-adjust-closest)
17146 (org-timestamp-change n org-ts-what updown))
17147 (message "Clock adjusted in %s for heading: %s"
17148 (file-name-nondirectory (buffer-file-name))
17149 (org-get-heading t t)))))))))
17150 ;; Try to recenter the calendar window, if any.
17151 (if (and org-calendar-follow-timestamp-change
17152 (get-buffer-window "*Calendar*" t)
17153 (memq org-ts-what '(day month year)))
17154 (org-recenter-calendar (time-to-days time))))))
17156 (defun org-modify-ts-extra (s pos n dm)
17157 "Change the different parts of the lead-time and repeat fields in timestamp."
17158 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17159 ng h m new rem)
17160 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17161 (cond
17162 ((or (org-pos-in-match-range pos 2)
17163 (org-pos-in-match-range pos 3))
17164 (setq m (string-to-number (match-string 3 s))
17165 h (string-to-number (match-string 2 s)))
17166 (if (org-pos-in-match-range pos 2)
17167 (setq h (+ h n))
17168 (setq n (* dm (org-no-warnings (signum n))))
17169 (when (not (= 0 (setq rem (% m dm))))
17170 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17171 (setq m (+ m n)))
17172 (if (< m 0) (setq m (+ m 60) h (1- h)))
17173 (if (> m 59) (setq m (- m 60) h (1+ h)))
17174 (setq h (min 24 (max 0 h)))
17175 (setq ng 1 new (format "-%02d:%02d" h m)))
17176 ((org-pos-in-match-range pos 6)
17177 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17178 ((org-pos-in-match-range pos 5)
17179 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17181 ((org-pos-in-match-range pos 9)
17182 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17183 ((org-pos-in-match-range pos 8)
17184 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17186 (when ng
17187 (setq s (concat
17188 (substring s 0 (match-beginning ng))
17190 (substring s (match-end ng))))))
17193 (defun org-recenter-calendar (date)
17194 "If the calendar is visible, recenter it to DATE."
17195 (let ((cwin (get-buffer-window "*Calendar*" t)))
17196 (when cwin
17197 (let ((calendar-move-hook nil))
17198 (with-selected-window cwin
17199 (calendar-goto-date (if (listp date) date
17200 (calendar-gregorian-from-absolute date))))))))
17202 (defun org-goto-calendar (&optional arg)
17203 "Go to the Emacs calendar at the current date.
17204 If there is a time stamp in the current line, go to that date.
17205 A prefix ARG can be used to force the current date."
17206 (interactive "P")
17207 (let ((tsr org-ts-regexp) diff
17208 (calendar-move-hook nil)
17209 (calendar-view-holidays-initially-flag nil)
17210 (calendar-view-diary-initially-flag nil))
17211 (if (or (org-at-timestamp-p)
17212 (save-excursion
17213 (beginning-of-line 1)
17214 (looking-at (concat ".*" tsr))))
17215 (let ((d1 (time-to-days (current-time)))
17216 (d2 (time-to-days
17217 (org-time-string-to-time (match-string 1)))))
17218 (setq diff (- d2 d1))))
17219 (calendar)
17220 (calendar-goto-today)
17221 (if (and diff (not arg)) (calendar-forward-day diff))))
17223 (defun org-get-date-from-calendar ()
17224 "Return a list (month day year) of date at point in calendar."
17225 (with-current-buffer "*Calendar*"
17226 (save-match-data
17227 (calendar-cursor-to-date))))
17229 (defun org-date-from-calendar ()
17230 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17231 If there is already a time stamp at the cursor position, update it."
17232 (interactive)
17233 (if (org-at-timestamp-p t)
17234 (org-timestamp-change 0 'calendar)
17235 (let ((cal-date (org-get-date-from-calendar)))
17236 (org-insert-time-stamp
17237 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17239 (defcustom org-effort-durations
17240 `(("h" . 60)
17241 ("d" . ,(* 60 8))
17242 ("w" . ,(* 60 8 5))
17243 ("m" . ,(* 60 8 5 4))
17244 ("y" . ,(* 60 8 5 40)))
17245 "Conversion factor to minutes for an effort modifier.
17247 Each entry has the form (MODIFIER . MINUTES).
17249 In an effort string, a number followed by MODIFIER is multiplied
17250 by the specified number of MINUTES to obtain an effort in
17251 minutes.
17253 For example, if the value of this variable is ((\"hours\" . 60)), then an
17254 effort string \"2hours\" is equivalent to 120 minutes."
17255 :group 'org-agenda
17256 :version "24.1"
17257 :type '(alist :key-type (string :tag "Modifier")
17258 :value-type (number :tag "Minutes")))
17260 (defun org-minutes-to-clocksum-string (m)
17261 "Format number of minutes as a clocksum string.
17262 The format is determined by `org-time-clocksum-format',
17263 `org-time-clocksum-use-fractional' and
17264 `org-time-clocksum-fractional-format' and
17265 `org-time-clocksum-use-effort-durations'."
17266 (let ((clocksum "") h d w mo y fmt n)
17267 (setq h (if org-time-clocksum-use-effort-durations
17268 (cdr (assoc "h" org-effort-durations)) 60)
17269 d (if org-time-clocksum-use-effort-durations
17270 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17271 w (if org-time-clocksum-use-effort-durations
17272 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17273 mo (if org-time-clocksum-use-effort-durations
17274 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17275 y (if org-time-clocksum-use-effort-durations
17276 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17277 ;; fractional format
17278 (if org-time-clocksum-use-fractional
17279 (cond
17280 ;; single format string
17281 ((stringp org-time-clocksum-fractional-format)
17282 (format org-time-clocksum-fractional-format (/ m (float h))))
17283 ;; choice of fractional formats for different time units
17284 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17285 (> (/ (truncate m) (* y d h)) 0))
17286 (format fmt (/ m (* y d (float h)))))
17287 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17288 (> (/ (truncate m) (* mo d h)) 0))
17289 (format fmt (/ m (* mo d (float h)))))
17290 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17291 (> (/ (truncate m) (* w d h)) 0))
17292 (format fmt (/ m (* w d (float h)))))
17293 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17294 (> (/ (truncate m) (* d h)) 0))
17295 (format fmt (/ m (* d (float h)))))
17296 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17297 (> (/ (truncate m) h) 0))
17298 (format fmt (/ m (float h))))
17299 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17300 (format fmt m))
17301 ;; fall back to smallest time unit with a format
17302 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17303 (format fmt (/ m (float h))))
17304 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17305 (format fmt (/ m (* d (float h)))))
17306 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17307 (format fmt (/ m (* w d (float h)))))
17308 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17309 (format fmt (/ m (* mo d (float h)))))
17310 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17311 (format fmt (/ m (* y d (float h))))))
17312 ;; standard (non-fractional) format, with single format string
17313 (if (stringp org-time-clocksum-format)
17314 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17315 ;; separate formats components
17316 (and (setq fmt (plist-get org-time-clocksum-format :years))
17317 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17318 (plist-get org-time-clocksum-format :require-years))
17319 (setq clocksum (concat clocksum (format fmt n))
17320 m (- m (* n y d h))))
17321 (and (setq fmt (plist-get org-time-clocksum-format :months))
17322 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17323 (plist-get org-time-clocksum-format :require-months))
17324 (setq clocksum (concat clocksum (format fmt n))
17325 m (- m (* n mo d h))))
17326 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17327 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17328 (plist-get org-time-clocksum-format :require-weeks))
17329 (setq clocksum (concat clocksum (format fmt n))
17330 m (- m (* n w d h))))
17331 (and (setq fmt (plist-get org-time-clocksum-format :days))
17332 (or (> (setq n (/ (truncate m) (* d h))) 0)
17333 (plist-get org-time-clocksum-format :require-days))
17334 (setq clocksum (concat clocksum (format fmt n))
17335 m (- m (* n d h))))
17336 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17337 (or (> (setq n (/ (truncate m) h)) 0)
17338 (plist-get org-time-clocksum-format :require-hours))
17339 (setq clocksum (concat clocksum (format fmt n))
17340 m (- m (* n h))))
17341 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17342 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17343 (setq clocksum (concat clocksum (format fmt m))))
17344 ;; return formatted time duration
17345 clocksum))))
17347 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17348 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17349 "Org mode version 8.0")
17351 (defun org-hours-to-clocksum-string (n)
17352 (org-minutes-to-clocksum-string (* n 60)))
17354 (defun org-hh:mm-string-to-minutes (s)
17355 "Convert a string H:MM to a number of minutes.
17356 If the string is just a number, interpret it as minutes.
17357 In fact, the first hh:mm or number in the string will be taken,
17358 there can be extra stuff in the string.
17359 If no number is found, the return value is 0."
17360 (cond
17361 ((integerp s) s)
17362 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17363 (+ (* (string-to-number (match-string 1 s)) 60)
17364 (string-to-number (match-string 2 s))))
17365 ((string-match "\\([0-9]+\\)" s)
17366 (string-to-number (match-string 1 s)))
17367 (t 0)))
17369 (defcustom org-image-actual-width t
17370 "Should we use the actual width of images when inlining them?
17372 When set to `t', always use the image width.
17374 When set to a number, use imagemagick (when available) to set
17375 the image's width to this value.
17377 When set to a number in a list, try to get the width from the
17378 #+ATTR.* keyword if it matches a width specification like
17379 width=\"[0-9]+\", and fall back on that number if none is found.
17381 When set to nil, try to get the width from an #+ATTR.* keyword
17382 and fall back on the original width if none is found.
17384 This requires Emacs >= 24.1, build with imagemagick support."
17385 :group 'org-appearance
17386 :version "24.4"
17387 :package-version '(Org . "8.0")
17388 :type '(choice
17389 (const :tag "Use the image width" t)
17390 (integer :tag "Use a number of pixels")
17391 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17392 (const :tag "Use #+ATTR* or don't resize" nil)))
17394 (defcustom org-agenda-inhibit-startup nil
17395 "Inhibit startup when preparing agenda buffers.
17396 When this variable is `t' (the default), the initialization of
17397 the Org agenda buffers is inhibited: e.g. the visibility state
17398 is not set, the tables are not re-aligned, etc."
17399 :type 'boolean
17400 :version "24.3"
17401 :group 'org-agenda)
17403 (defun org-duration-string-to-minutes (s &optional output-to-string)
17404 "Convert a duration string S to minutes.
17406 A bare number is interpreted as minutes, modifiers can be set by
17407 customizing `org-effort-durations' (which see).
17409 Entries containing a colon are interpreted as H:MM by
17410 `org-hh:mm-string-to-minutes'."
17411 (let ((result 0)
17412 (re (concat "\\([0-9.]+\\) *\\("
17413 (regexp-opt (mapcar 'car org-effort-durations))
17414 "\\)")))
17415 (while (string-match re s)
17416 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17417 (string-to-number (match-string 1 s))))
17418 (setq s (replace-match "" nil t s)))
17419 (setq result (floor result))
17420 (incf result (org-hh:mm-string-to-minutes s))
17421 (if output-to-string (number-to-string result) result)))
17423 ;;;; Files
17425 (defun org-save-all-org-buffers ()
17426 "Save all Org-mode buffers without user confirmation."
17427 (interactive)
17428 (message "Saving all Org-mode buffers...")
17429 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17430 (when (featurep 'org-id) (org-id-locations-save))
17431 (message "Saving all Org-mode buffers... done"))
17433 (defun org-revert-all-org-buffers ()
17434 "Revert all Org-mode buffers.
17435 Prompt for confirmation when there are unsaved changes.
17436 Be sure you know what you are doing before letting this function
17437 overwrite your changes.
17439 This function is useful in a setup where one tracks org files
17440 with a version control system, to revert on one machine after pulling
17441 changes from another. I believe the procedure must be like this:
17443 1. M-x org-save-all-org-buffers
17444 2. Pull changes from the other machine, resolve conflicts
17445 3. M-x org-revert-all-org-buffers"
17446 (interactive)
17447 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17448 (error "Abort"))
17449 (save-excursion
17450 (save-window-excursion
17451 (mapc
17452 (lambda (b)
17453 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17454 (with-current-buffer b buffer-file-name))
17455 (org-pop-to-buffer-same-window b)
17456 (revert-buffer t 'no-confirm)))
17457 (buffer-list))
17458 (when (and (featurep 'org-id) org-id-track-globally)
17459 (org-id-locations-load)))))
17461 ;;;; Agenda files
17463 ;;;###autoload
17464 (defun org-switchb (&optional arg)
17465 "Switch between Org buffers.
17466 With one prefix argument, restrict available buffers to files.
17467 With two prefix arguments, restrict available buffers to agenda files.
17469 Defaults to `iswitchb' for buffer name completion.
17470 Set `org-completion-use-ido' to make it use ido instead."
17471 (interactive "P")
17472 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17473 ((equal arg '(16)) (org-buffer-list 'agenda))
17474 (t (org-buffer-list))))
17475 (org-completion-use-iswitchb org-completion-use-iswitchb)
17476 (org-completion-use-ido org-completion-use-ido))
17477 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17478 (setq org-completion-use-iswitchb t))
17479 (org-pop-to-buffer-same-window
17480 (org-icompleting-read "Org buffer: "
17481 (mapcar 'list (mapcar 'buffer-name blist))
17482 nil t))))
17484 ;;; Define some older names previously used for this functionality
17485 ;;;###autoload
17486 (defalias 'org-ido-switchb 'org-switchb)
17487 ;;;###autoload
17488 (defalias 'org-iswitchb 'org-switchb)
17490 (defun org-buffer-list (&optional predicate exclude-tmp)
17491 "Return a list of Org buffers.
17492 PREDICATE can be `export', `files' or `agenda'.
17494 export restrict the list to Export buffers.
17495 files restrict the list to buffers visiting Org files.
17496 agenda restrict the list to buffers visiting agenda files.
17498 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17499 (let* ((bfn nil)
17500 (agenda-files (and (eq predicate 'agenda)
17501 (mapcar 'file-truename (org-agenda-files t))))
17502 (filter
17503 (cond
17504 ((eq predicate 'files)
17505 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17506 ((eq predicate 'export)
17507 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17508 ((eq predicate 'agenda)
17509 (lambda (b)
17510 (with-current-buffer b
17511 (and (derived-mode-p 'org-mode)
17512 (setq bfn (buffer-file-name b))
17513 (member (file-truename bfn) agenda-files)))))
17514 (t (lambda (b) (with-current-buffer b
17515 (or (derived-mode-p 'org-mode)
17516 (string-match "\*Org .*Export"
17517 (buffer-name b)))))))))
17518 (delq nil
17519 (mapcar
17520 (lambda(b)
17521 (if (and (funcall filter b)
17522 (or (not exclude-tmp)
17523 (not (string-match "tmp" (buffer-name b)))))
17525 nil))
17526 (buffer-list)))))
17528 (defun org-agenda-files (&optional unrestricted archives)
17529 "Get the list of agenda files.
17530 Optional UNRESTRICTED means return the full list even if a restriction
17531 is currently in place.
17532 When ARCHIVES is t, include all archive files that are really being
17533 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17534 `org-agenda-archives-mode' is t."
17535 (let ((files
17536 (cond
17537 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17538 ((stringp org-agenda-files) (org-read-agenda-file-list))
17539 ((listp org-agenda-files) org-agenda-files)
17540 (t (error "Invalid value of `org-agenda-files'")))))
17541 (setq files (apply 'append
17542 (mapcar (lambda (f)
17543 (if (file-directory-p f)
17544 (directory-files
17545 f t org-agenda-file-regexp)
17546 (list f)))
17547 files)))
17548 (when org-agenda-skip-unavailable-files
17549 (setq files (delq nil
17550 (mapcar (function
17551 (lambda (file)
17552 (and (file-readable-p file) file)))
17553 files))))
17554 (when (or (eq archives t)
17555 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17556 (setq files (org-add-archive-files files)))
17557 files))
17559 (defun org-agenda-file-p (&optional file)
17560 "Return non-nil, if FILE is an agenda file.
17561 If FILE is omitted, use the file associated with the current
17562 buffer."
17563 (member (or file (buffer-file-name))
17564 (org-agenda-files t)))
17566 (defun org-edit-agenda-file-list ()
17567 "Edit the list of agenda files.
17568 Depending on setup, this either uses customize to edit the variable
17569 `org-agenda-files', or it visits the file that is holding the list. In the
17570 latter case, the buffer is set up in a way that saving it automatically kills
17571 the buffer and restores the previous window configuration."
17572 (interactive)
17573 (if (stringp org-agenda-files)
17574 (let ((cw (current-window-configuration)))
17575 (find-file org-agenda-files)
17576 (org-set-local 'org-window-configuration cw)
17577 (org-add-hook 'after-save-hook
17578 (lambda ()
17579 (set-window-configuration
17580 (prog1 org-window-configuration
17581 (kill-buffer (current-buffer))))
17582 (org-install-agenda-files-menu)
17583 (message "New agenda file list installed"))
17584 nil 'local)
17585 (message "%s" (substitute-command-keys
17586 "Edit list and finish with \\[save-buffer]")))
17587 (customize-variable 'org-agenda-files)))
17589 (defun org-store-new-agenda-file-list (list)
17590 "Set new value for the agenda file list and save it correctly."
17591 (if (stringp org-agenda-files)
17592 (let ((fe (org-read-agenda-file-list t)) b u)
17593 (while (setq b (find-buffer-visiting org-agenda-files))
17594 (kill-buffer b))
17595 (with-temp-file org-agenda-files
17596 (insert
17597 (mapconcat
17598 (lambda (f) ;; Keep un-expanded entries.
17599 (if (setq u (assoc f fe))
17600 (cdr u)
17602 list "\n")
17603 "\n")))
17604 (let ((org-mode-hook nil) (org-inhibit-startup t)
17605 (org-insert-mode-line-in-empty-file nil))
17606 (setq org-agenda-files list)
17607 (customize-save-variable 'org-agenda-files org-agenda-files))))
17609 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17610 "Read the list of agenda files from a file.
17611 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17612 filenames, used by `org-store-new-agenda-file-list' to write back
17613 un-expanded file names."
17614 (when (file-directory-p org-agenda-files)
17615 (error "`org-agenda-files' cannot be a single directory"))
17616 (when (stringp org-agenda-files)
17617 (with-temp-buffer
17618 (insert-file-contents org-agenda-files)
17619 (mapcar
17620 (lambda (f)
17621 (let ((e (expand-file-name (substitute-in-file-name f)
17622 org-directory)))
17623 (if pair-with-expansion
17624 (cons e f)
17625 e)))
17626 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17628 ;;;###autoload
17629 (defun org-cycle-agenda-files ()
17630 "Cycle through the files in `org-agenda-files'.
17631 If the current buffer visits an agenda file, find the next one in the list.
17632 If the current buffer does not, find the first agenda file."
17633 (interactive)
17634 (let* ((fs (org-agenda-files t))
17635 (files (append fs (list (car fs))))
17636 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17637 file)
17638 (unless files (error "No agenda files"))
17639 (catch 'exit
17640 (while (setq file (pop files))
17641 (if (equal (file-truename file) tcf)
17642 (when (car files)
17643 (find-file (car files))
17644 (throw 'exit t))))
17645 (find-file (car fs)))
17646 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17648 (defun org-agenda-file-to-front (&optional to-end)
17649 "Move/add the current file to the top of the agenda file list.
17650 If the file is not present in the list, it is added to the front. If it is
17651 present, it is moved there. With optional argument TO-END, add/move to the
17652 end of the list."
17653 (interactive "P")
17654 (let ((org-agenda-skip-unavailable-files nil)
17655 (file-alist (mapcar (lambda (x)
17656 (cons (file-truename x) x))
17657 (org-agenda-files t)))
17658 (ctf (file-truename
17659 (or buffer-file-name
17660 (error "Please save the current buffer to a file"))))
17661 x had)
17662 (setq x (assoc ctf file-alist) had x)
17664 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17665 (if to-end
17666 (setq file-alist (append (delq x file-alist) (list x)))
17667 (setq file-alist (cons x (delq x file-alist))))
17668 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17669 (org-install-agenda-files-menu)
17670 (message "File %s to %s of agenda file list"
17671 (if had "moved" "added") (if to-end "end" "front"))))
17673 (defun org-remove-file (&optional file)
17674 "Remove current file from the list of files in variable `org-agenda-files'.
17675 These are the files which are being checked for agenda entries.
17676 Optional argument FILE means use this file instead of the current."
17677 (interactive)
17678 (let* ((org-agenda-skip-unavailable-files nil)
17679 (file (or file buffer-file-name
17680 (error "Current buffer does not visit a file")))
17681 (true-file (file-truename file))
17682 (afile (abbreviate-file-name file))
17683 (files (delq nil (mapcar
17684 (lambda (x)
17685 (if (equal true-file
17686 (file-truename x))
17687 nil x))
17688 (org-agenda-files t)))))
17689 (if (not (= (length files) (length (org-agenda-files t))))
17690 (progn
17691 (org-store-new-agenda-file-list files)
17692 (org-install-agenda-files-menu)
17693 (message "Removed file: %s" afile))
17694 (message "File was not in list: %s (not removed)" afile))))
17696 (defun org-file-menu-entry (file)
17697 (vector file (list 'find-file file) t))
17699 (defun org-check-agenda-file (file)
17700 "Make sure FILE exists. If not, ask user what to do."
17701 (when (not (file-exists-p file))
17702 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17703 (abbreviate-file-name file))
17704 (let ((r (downcase (read-char-exclusive))))
17705 (cond
17706 ((equal r ?r)
17707 (org-remove-file file)
17708 (throw 'nextfile t))
17709 (t (error "Abort"))))))
17711 (defun org-get-agenda-file-buffer (file)
17712 "Get a buffer visiting FILE. If the buffer needs to be created, add
17713 it to the list of buffers which might be released later."
17714 (let ((buf (org-find-base-buffer-visiting file)))
17715 (if buf
17716 buf ; just return it
17717 ;; Make a new buffer and remember it
17718 (setq buf (find-file-noselect file))
17719 (if buf (push buf org-agenda-new-buffers))
17720 buf)))
17722 (defun org-release-buffers (blist)
17723 "Release all buffers in list, asking the user for confirmation when needed.
17724 When a buffer is unmodified, it is just killed. When modified, it is saved
17725 \(if the user agrees) and then killed."
17726 (let (buf file)
17727 (while (setq buf (pop blist))
17728 (setq file (buffer-file-name buf))
17729 (when (and (buffer-modified-p buf)
17730 file
17731 (y-or-n-p (format "Save file %s? " file)))
17732 (with-current-buffer buf (save-buffer)))
17733 (kill-buffer buf))))
17735 (defun org-agenda-prepare-buffers (files)
17736 "Create buffers for all agenda files, protect archived trees and comments."
17737 (interactive)
17738 (let ((pa '(:org-archived t))
17739 (pc '(:org-comment t))
17740 (pall '(:org-archived t :org-comment t))
17741 (inhibit-read-only t)
17742 (org-inhibit-startup org-agenda-inhibit-startup)
17743 (rea (concat ":" org-archive-tag ":"))
17744 file re)
17745 (save-excursion
17746 (save-restriction
17747 (while (setq file (pop files))
17748 (catch 'nextfile
17749 (if (bufferp file)
17750 (set-buffer file)
17751 (org-check-agenda-file file)
17752 (set-buffer (org-get-agenda-file-buffer file)))
17753 (widen)
17754 (org-refresh-category-properties)
17755 (org-refresh-properties org-effort-property 'org-effort)
17756 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17757 (setq org-todo-keywords-for-agenda
17758 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17759 (setq org-done-keywords-for-agenda
17760 (append org-done-keywords-for-agenda org-done-keywords))
17761 (setq org-todo-keyword-alist-for-agenda
17762 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17763 (setq org-drawers-for-agenda
17764 (append org-drawers-for-agenda org-drawers))
17765 (setq org-tag-alist-for-agenda
17766 (append org-tag-alist-for-agenda org-tag-alist))
17767 (org-with-silent-modifications
17768 (save-excursion
17769 (remove-text-properties (point-min) (point-max) pall)
17770 (when org-agenda-skip-archived-trees
17771 (goto-char (point-min))
17772 (while (re-search-forward rea nil t)
17773 (if (org-at-heading-p t)
17774 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17775 (goto-char (point-min))
17776 (setq re (format org-heading-keyword-regexp-format
17777 org-comment-string))
17778 (while (re-search-forward re nil t)
17779 (add-text-properties
17780 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17781 (setq org-todo-keywords-for-agenda
17782 (org-uniquify org-todo-keywords-for-agenda))
17783 (setq org-todo-keyword-alist-for-agenda
17784 (org-uniquify org-todo-keyword-alist-for-agenda)
17785 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17788 ;;;; CDLaTeX minor mode
17790 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17791 "Keymap for the minor `org-cdlatex-mode'.")
17793 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17794 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17795 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17796 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17797 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17799 (defvar org-cdlatex-texmathp-advice-is-done nil
17800 "Flag remembering if we have applied the advice to texmathp already.")
17802 (define-minor-mode org-cdlatex-mode
17803 "Toggle the minor `org-cdlatex-mode'.
17804 This mode supports entering LaTeX environment and math in LaTeX fragments
17805 in Org-mode.
17806 \\{org-cdlatex-mode-map}"
17807 nil " OCDL" nil
17808 (when org-cdlatex-mode
17809 (require 'cdlatex)
17810 (run-hooks 'cdlatex-mode-hook)
17811 (cdlatex-compute-tables))
17812 (unless org-cdlatex-texmathp-advice-is-done
17813 (setq org-cdlatex-texmathp-advice-is-done t)
17814 (defadvice texmathp (around org-math-always-on activate)
17815 "Always return t in org-mode buffers.
17816 This is because we want to insert math symbols without dollars even outside
17817 the LaTeX math segments. If Orgmode thinks that point is actually inside
17818 an embedded LaTeX fragment, let texmathp do its job.
17819 \\[org-cdlatex-mode-map]"
17820 (interactive)
17821 (let (p)
17822 (cond
17823 ((not (derived-mode-p 'org-mode)) ad-do-it)
17824 ((eq this-command 'cdlatex-math-symbol)
17825 (setq ad-return-value t
17826 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17828 (let ((p (org-inside-LaTeX-fragment-p)))
17829 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17830 (setq ad-return-value t
17831 texmathp-why '("Org-mode embedded math" . 0))
17832 (if p ad-do-it)))))))))
17834 (defun turn-on-org-cdlatex ()
17835 "Unconditionally turn on `org-cdlatex-mode'."
17836 (org-cdlatex-mode 1))
17838 (defun org-try-cdlatex-tab ()
17839 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17840 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17841 - inside a LaTeX fragment, or
17842 - after the first word in a line, where an abbreviation expansion could
17843 insert a LaTeX environment."
17844 (when org-cdlatex-mode
17845 (cond
17846 ;; Before any word on the line: No expansion possible.
17847 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17848 ;; Just after first word on the line: Expand it. Make sure it
17849 ;; cannot happen on headlines, though.
17850 ((save-excursion
17851 (skip-chars-backward "a-zA-Z0-9*")
17852 (skip-chars-backward " \t")
17853 (and (bolp) (not (org-at-heading-p))))
17854 (cdlatex-tab) t)
17855 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17857 (defun org-cdlatex-underscore-caret (&optional arg)
17858 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17859 Revert to the normal definition outside of these fragments."
17860 (interactive "P")
17861 (if (org-inside-LaTeX-fragment-p)
17862 (call-interactively 'cdlatex-sub-superscript)
17863 (let (org-cdlatex-mode)
17864 (call-interactively (key-binding (vector last-input-event))))))
17866 (defun org-cdlatex-math-modify (&optional arg)
17867 "Execute `cdlatex-math-modify' in LaTeX fragments.
17868 Revert to the normal definition outside of these fragments."
17869 (interactive "P")
17870 (if (org-inside-LaTeX-fragment-p)
17871 (call-interactively 'cdlatex-math-modify)
17872 (let (org-cdlatex-mode)
17873 (call-interactively (key-binding (vector last-input-event))))))
17877 ;;;; LaTeX fragments
17879 (defvar org-latex-regexps
17880 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17881 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17882 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17883 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17884 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17885 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17886 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17887 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17888 "Regular expressions for matching embedded LaTeX.")
17890 (defun org-inside-LaTeX-fragment-p ()
17891 "Test if point is inside a LaTeX fragment.
17892 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17893 sequence appearing also before point.
17894 Even though the matchers for math are configurable, this function assumes
17895 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17896 delimiters are skipped when they have been removed by customization.
17897 The return value is nil, or a cons cell with the delimiter and the
17898 position of this delimiter.
17900 This function does a reasonably good job, but can locally be fooled by
17901 for example currency specifications. For example it will assume being in
17902 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17903 fragments that are properly closed, but during editing, we have to live
17904 with the uncertainty caused by missing closing delimiters. This function
17905 looks only before point, not after."
17906 (catch 'exit
17907 (let ((pos (point))
17908 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17909 (lim (progn
17910 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17911 (point)))
17912 dd-on str (start 0) m re)
17913 (goto-char pos)
17914 (when dodollar
17915 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17916 re (nth 1 (assoc "$" org-latex-regexps)))
17917 (while (string-match re str start)
17918 (cond
17919 ((= (match-end 0) (length str))
17920 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17921 ((= (match-end 0) (- (length str) 5))
17922 (throw 'exit nil))
17923 (t (setq start (match-end 0))))))
17924 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17925 (goto-char pos)
17926 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17927 (and (match-beginning 2) (throw 'exit nil))
17928 ;; count $$
17929 (while (re-search-backward "\\$\\$" lim t)
17930 (setq dd-on (not dd-on)))
17931 (goto-char pos)
17932 (if dd-on (cons "$$" m))))))
17934 (defun org-inside-latex-macro-p ()
17935 "Is point inside a LaTeX macro or its arguments?"
17936 (save-match-data
17937 (org-in-regexp
17938 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17940 (defvar org-latex-fragment-image-overlays nil
17941 "List of overlays carrying the images of latex fragments.")
17942 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17944 (defun org-remove-latex-fragment-image-overlays ()
17945 "Remove all overlays with LaTeX fragment images in current buffer."
17946 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17947 (setq org-latex-fragment-image-overlays nil))
17949 (defun org-preview-latex-fragment (&optional subtree)
17950 "Preview the LaTeX fragment at point, or all locally or globally.
17951 If the cursor is in a LaTeX fragment, create the image and overlay
17952 it over the source code. If there is no fragment at point, display
17953 all fragments in the current text, from one headline to the next. With
17954 prefix SUBTREE, display all fragments in the current subtree. With a
17955 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17956 the cursor is before the first headline,
17957 display all fragments in the buffer.
17958 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17959 (interactive "P")
17960 (unless buffer-file-name
17961 (error "Can't preview LaTeX fragment in a non-file buffer"))
17962 (org-remove-latex-fragment-image-overlays)
17963 (save-excursion
17964 (save-restriction
17965 (let (beg end at msg)
17966 (cond
17967 ((or (equal subtree '(16))
17968 (not (save-excursion
17969 (re-search-backward org-outline-regexp-bol nil t))))
17970 (setq beg (point-min) end (point-max)
17971 msg "Creating images for buffer...%s"))
17972 ((equal subtree '(4))
17973 (org-back-to-heading)
17974 (setq beg (point) end (org-end-of-subtree t)
17975 msg "Creating images for subtree...%s"))
17977 (if (setq at (org-inside-LaTeX-fragment-p))
17978 (goto-char (max (point-min) (- (cdr at) 2)))
17979 (org-back-to-heading))
17980 (setq beg (point) end (progn (outline-next-heading) (point))
17981 msg (if at "Creating image...%s"
17982 "Creating images for entry...%s"))))
17983 (message msg "")
17984 (narrow-to-region beg end)
17985 (goto-char beg)
17986 (org-format-latex
17987 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17988 (file-name-nondirectory
17989 buffer-file-name)))
17990 default-directory 'overlays msg at 'forbuffer
17991 org-latex-create-formula-image-program)
17992 (message msg "done. Use `C-c C-c' to remove images.")))))
17994 (defun org-format-latex (prefix &optional dir overlays msg at
17995 forbuffer processing-type)
17996 "Replace LaTeX fragments with links to an image, and produce images.
17997 Some of the options can be changed using the variable
17998 `org-format-latex-options'."
17999 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18000 (let* ((prefixnodir (file-name-nondirectory prefix))
18001 (absprefix (expand-file-name prefix dir))
18002 (todir (file-name-directory absprefix))
18003 (opt org-format-latex-options)
18004 (optnew org-format-latex-options)
18005 (matchers (plist-get opt :matchers))
18006 (re-list org-latex-regexps)
18007 (cnt 0) txt hash link beg end re e checkdir
18008 string
18009 m n block-type block linkfile movefile ov)
18010 ;; Check the different regular expressions
18011 (while (setq e (pop re-list))
18012 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18013 block (if block-type "\n\n" ""))
18014 (when (member m matchers)
18015 (goto-char (point-min))
18016 (while (re-search-forward re nil t)
18017 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18018 (or (not overlays)
18019 (not (eq (get-char-property (match-beginning n)
18020 'org-overlay-type)
18021 'org-latex-overlay))))
18022 (cond
18023 ((eq processing-type 'verbatim))
18024 ((eq processing-type 'mathjax)
18025 ;; Prepare for MathJax processing.
18026 (setq string (match-string n))
18027 (when (member m '("$" "$1"))
18028 (save-excursion
18029 (delete-region (match-beginning n) (match-end n))
18030 (goto-char (match-beginning n))
18031 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18032 ((or (eq processing-type 'dvipng)
18033 (eq processing-type 'imagemagick))
18034 ;; Process to an image.
18035 (setq txt (match-string n)
18036 beg (match-beginning n) end (match-end n)
18037 cnt (1+ cnt))
18038 (let ((face (face-at-point))
18039 (fg (plist-get opt :foreground))
18040 (bg (plist-get opt :background))
18041 ;; Ensure full list is printed.
18042 print-length print-level)
18043 (when forbuffer
18044 ;; Get the colors from the face at point.
18045 (goto-char beg)
18046 (when (eq fg 'auto)
18047 (setq fg (face-attribute face :foreground nil 'default)))
18048 (when (eq bg 'auto)
18049 (setq bg (face-attribute face :background nil 'default)))
18050 (setq optnew (copy-sequence opt))
18051 (plist-put optnew :foreground fg)
18052 (plist-put optnew :background bg))
18053 (setq hash (sha1 (prin1-to-string
18054 (list org-format-latex-header
18055 org-latex-default-packages-alist
18056 org-latex-packages-alist
18057 org-format-latex-options
18058 forbuffer txt fg bg)))
18059 linkfile (format "%s_%s.png" prefix hash)
18060 movefile (format "%s_%s.png" absprefix hash)))
18061 (setq link (concat block "[[file:" linkfile "]]" block))
18062 (if msg (message msg cnt))
18063 (goto-char beg)
18064 (unless checkdir ; Ensure the directory exists.
18065 (setq checkdir t)
18066 (or (file-directory-p todir) (make-directory todir t)))
18067 (unless (file-exists-p movefile)
18068 (org-create-formula-image
18069 txt movefile optnew forbuffer processing-type))
18070 (if overlays
18071 (progn
18072 (mapc (lambda (o)
18073 (if (eq (overlay-get o 'org-overlay-type)
18074 'org-latex-overlay)
18075 (delete-overlay o)))
18076 (overlays-in beg end))
18077 (setq ov (make-overlay beg end))
18078 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18079 (if (featurep 'xemacs)
18080 (progn
18081 (overlay-put ov 'invisible t)
18082 (overlay-put
18083 ov 'end-glyph
18084 (make-glyph (vector 'png :file movefile))))
18085 (overlay-put
18086 ov 'display
18087 (list 'image :type 'png :file movefile :ascent 'center)))
18088 (push ov org-latex-fragment-image-overlays)
18089 (goto-char end))
18090 (delete-region beg end)
18091 (insert (org-add-props link
18092 (list 'org-latex-src
18093 (replace-regexp-in-string
18094 "\"" "" txt)
18095 'org-latex-src-embed-type
18096 (if block-type 'paragraph 'character))))))
18097 ((eq processing-type 'mathml)
18098 ;; Process to MathML
18099 (unless (save-match-data (org-format-latex-mathml-available-p))
18100 (error "LaTeX to MathML converter not configured"))
18101 (setq txt (match-string n)
18102 beg (match-beginning n) end (match-end n)
18103 cnt (1+ cnt))
18104 (if msg (message msg cnt))
18105 (goto-char beg)
18106 (delete-region beg end)
18107 (insert (org-format-latex-as-mathml
18108 txt block-type prefix dir)))
18110 (error "Unknown conversion type %s for latex fragments"
18111 processing-type)))))))))
18113 (defun org-create-math-formula (latex-frag &optional mathml-file)
18114 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18115 Use `org-latex-to-mathml-convert-command'. If the conversion is
18116 sucessful, return the portion between \"<math...> </math>\"
18117 elements otherwise return nil. When MATHML-FILE is specified,
18118 write the results in to that file. When invoked as an
18119 interactive command, prompt for LATEX-FRAG, with initial value
18120 set to the current active region and echo the results for user
18121 inspection."
18122 (interactive (list (let ((frag (when (org-region-active-p)
18123 (buffer-substring-no-properties
18124 (region-beginning) (region-end)))))
18125 (read-string "LaTeX Fragment: " frag nil frag))))
18126 (unless latex-frag (error "Invalid latex-frag"))
18127 (let* ((tmp-in-file (file-relative-name
18128 (make-temp-name (expand-file-name "ltxmathml-in"))))
18129 (ignore (write-region latex-frag nil tmp-in-file))
18130 (tmp-out-file (file-relative-name
18131 (make-temp-name (expand-file-name "ltxmathml-out"))))
18132 (cmd (format-spec
18133 org-latex-to-mathml-convert-command
18134 `((?j . ,(shell-quote-argument
18135 (expand-file-name org-latex-to-mathml-jar-file)))
18136 (?I . ,(shell-quote-argument tmp-in-file))
18137 (?o . ,(shell-quote-argument tmp-out-file)))))
18138 mathml shell-command-output)
18139 (when (org-called-interactively-p 'any)
18140 (unless (org-format-latex-mathml-available-p)
18141 (error "LaTeX to MathML converter not configured")))
18142 (message "Running %s" cmd)
18143 (setq shell-command-output (shell-command-to-string cmd))
18144 (setq mathml
18145 (when (file-readable-p tmp-out-file)
18146 (with-current-buffer (find-file-noselect tmp-out-file t)
18147 (goto-char (point-min))
18148 (when (re-search-forward
18149 (concat
18150 (regexp-quote
18151 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18152 "\\(.\\|\n\\)*"
18153 (regexp-quote "</math>")) nil t)
18154 (prog1 (match-string 0) (kill-buffer))))))
18155 (cond
18156 (mathml
18157 (setq mathml
18158 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18159 (when mathml-file
18160 (write-region mathml nil mathml-file))
18161 (when (org-called-interactively-p 'any)
18162 (message mathml)))
18163 ((message "LaTeX to MathML conversion failed")
18164 (message shell-command-output)))
18165 (delete-file tmp-in-file)
18166 (when (file-exists-p tmp-out-file)
18167 (delete-file tmp-out-file))
18168 mathml))
18170 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18171 prefix &optional dir)
18172 "Use `org-create-math-formula' but check local cache first."
18173 (let* ((absprefix (expand-file-name prefix dir))
18174 (print-length nil) (print-level nil)
18175 (formula-id (concat
18176 "formula-"
18177 (sha1
18178 (prin1-to-string
18179 (list latex-frag
18180 org-latex-to-mathml-convert-command)))))
18181 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18182 (formula-cache-dir (file-name-directory formula-cache)))
18184 (unless (file-directory-p formula-cache-dir)
18185 (make-directory formula-cache-dir t))
18187 (unless (file-exists-p formula-cache)
18188 (org-create-math-formula latex-frag formula-cache))
18190 (if (file-exists-p formula-cache)
18191 ;; Successful conversion. Return the link to MathML file.
18192 (org-add-props
18193 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18194 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18195 'org-latex-src-embed-type (if latex-frag-type
18196 'paragraph 'character)))
18197 ;; Failed conversion. Return the LaTeX fragment verbatim
18198 latex-frag)))
18200 (defun org-create-formula-image (string tofile options buffer &optional type)
18201 "Create an image from LaTeX source using dvipng or convert.
18202 This function calls either `org-create-formula-image-with-dvipng'
18203 or `org-create-formula-image-with-imagemagick' depending on the
18204 value of `org-latex-create-formula-image-program' or on the value
18205 of the optional TYPE variable.
18207 Note: ultimately these two function should be combined as they
18208 share a good deal of logic."
18209 (org-check-external-command
18210 "latex" "needed to convert LaTeX fragments to images")
18211 (funcall
18212 (case (or type org-latex-create-formula-image-program)
18213 ('dvipng
18214 (org-check-external-command
18215 "dvipng" "needed to convert LaTeX fragments to images")
18216 #'org-create-formula-image-with-dvipng)
18217 ('imagemagick
18218 (org-check-external-command
18219 "convert" "you need to install imagemagick")
18220 #'org-create-formula-image-with-imagemagick)
18221 (t (error
18222 "invalid value of `org-latex-create-formula-image-program'")))
18223 string tofile options buffer))
18225 (declare-function org-export--get-global-options "ox" (&optional backend))
18226 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18227 (defun org-create-formula--latex-header ()
18228 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18229 (org-latex-guess-inputenc
18230 (org-splice-latex-header
18231 org-format-latex-header
18232 org-latex-default-packages-alist
18233 org-latex-packages-alist t
18234 (plist-get
18235 (org-combine-plists
18236 (org-export--get-global-options 'latex)
18237 (org-export--get-inbuffer-options 'latex))
18238 :latex-header))))
18240 ;; This function borrows from Ganesh Swami's latex2png.el
18241 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18242 "This calls dvipng."
18243 (require 'ox-latex)
18244 (let* ((tmpdir (if (featurep 'xemacs)
18245 (temp-directory)
18246 temporary-file-directory))
18247 (texfilebase (make-temp-name
18248 (expand-file-name "orgtex" tmpdir)))
18249 (texfile (concat texfilebase ".tex"))
18250 (dvifile (concat texfilebase ".dvi"))
18251 (pngfile (concat texfilebase ".png"))
18252 (fnh (if (featurep 'xemacs)
18253 (font-height (face-font 'default))
18254 (face-attribute 'default :height nil)))
18255 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18256 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18257 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18258 "Black"))
18259 (bg (or (plist-get options (if buffer :background :html-background))
18260 "Transparent")))
18261 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18262 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18263 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18264 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18265 (let ((latex-header (org-create-formula--latex-header)))
18266 (with-temp-file texfile
18267 (insert latex-header)
18268 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18269 (let ((dir default-directory))
18270 (condition-case nil
18271 (progn
18272 (cd tmpdir)
18273 (call-process "latex" nil nil nil texfile))
18274 (error nil))
18275 (cd dir))
18276 (if (not (file-exists-p dvifile))
18277 (progn (message "Failed to create dvi file from %s" texfile) nil)
18278 (condition-case nil
18279 (if (featurep 'xemacs)
18280 (call-process "dvipng" nil nil nil
18281 "-fg" fg "-bg" bg
18282 "-T" "tight"
18283 "-o" pngfile
18284 dvifile)
18285 (call-process "dvipng" nil nil nil
18286 "-fg" fg "-bg" bg
18287 "-D" dpi
18288 ;;"-x" scale "-y" scale
18289 "-T" "tight"
18290 "-o" pngfile
18291 dvifile))
18292 (error nil))
18293 (if (not (file-exists-p pngfile))
18294 (if org-format-latex-signal-error
18295 (error "Failed to create png file from %s" texfile)
18296 (message "Failed to create png file from %s" texfile)
18297 nil)
18298 ;; Use the requested file name and clean up
18299 (copy-file pngfile tofile 'replace)
18300 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18301 (if (file-exists-p (concat texfilebase e))
18302 (delete-file (concat texfilebase e))))
18303 pngfile))))
18305 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18306 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18307 "This calls convert, which is included into imagemagick."
18308 (require 'ox-latex)
18309 (let* ((tmpdir (if (featurep 'xemacs)
18310 (temp-directory)
18311 temporary-file-directory))
18312 (texfilebase (make-temp-name
18313 (expand-file-name "orgtex" tmpdir)))
18314 (texfile (concat texfilebase ".tex"))
18315 (pdffile (concat texfilebase ".pdf"))
18316 (pngfile (concat texfilebase ".png"))
18317 (fnh (if (featurep 'xemacs)
18318 (font-height (face-font 'default))
18319 (face-attribute 'default :height nil)))
18320 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18321 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18322 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18323 "black"))
18324 (bg (or (plist-get options (if buffer :background :html-background))
18325 "white")))
18326 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18327 (setq fg (org-latex-color-format fg)))
18328 (if (eq bg 'default) (setq bg (org-latex-color :background))
18329 (setq bg (org-latex-color-format
18330 (if (string= bg "Transparent") "white" bg))))
18331 (let ((latex-header (org-create-formula--latex-header)))
18332 (with-temp-file texfile
18333 (insert latex-header)
18334 (insert "\n\\begin{document}\n"
18335 "\\definecolor{fg}{rgb}{" fg "}\n"
18336 "\\definecolor{bg}{rgb}{" bg "}\n"
18337 "\n\\pagecolor{bg}\n"
18338 "\n{\\color{fg}\n"
18339 string
18340 "\n}\n"
18341 "\n\\end{document}\n")))
18342 (org-latex-compile texfile t)
18343 (if (not (file-exists-p pdffile))
18344 (progn (message "Failed to create pdf file from %s" texfile) nil)
18345 (condition-case nil
18346 (if (featurep 'xemacs)
18347 (call-process "convert" nil nil nil
18348 "-density" "96"
18349 "-trim"
18350 "-antialias"
18351 pdffile
18352 "-quality" "100"
18353 ;; "-sharpen" "0x1.0"
18354 pngfile)
18355 (call-process "convert" nil nil nil
18356 "-density" dpi
18357 "-trim"
18358 "-antialias"
18359 pdffile
18360 "-quality" "100"
18361 ;; "-sharpen" "0x1.0"
18362 pngfile))
18363 (error nil))
18364 (if (not (file-exists-p pngfile))
18365 (if org-format-latex-signal-error
18366 (error "Failed to create png file from %s" texfile)
18367 (message "Failed to create png file from %s" texfile)
18368 nil)
18369 ;; Use the requested file name and clean up
18370 (copy-file pngfile tofile 'replace)
18371 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18372 (if (file-exists-p (concat texfilebase e))
18373 (delete-file (concat texfilebase e))))
18374 pngfile))))
18376 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18377 "Fill a LaTeX header template TPL.
18378 In the template, the following place holders will be recognized:
18380 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18381 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18382 [PACKAGES] \\usepackage statements for PKG
18383 [NO-PACKAGES] do not include PKG
18384 [EXTRA] the string EXTRA
18385 [NO-EXTRA] do not include EXTRA
18387 For backward compatibility, if both the positive and the negative place
18388 holder is missing, the positive one (without the \"NO-\") will be
18389 assumed to be present at the end of the template.
18390 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18391 EXTRA is a string.
18392 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18393 (let (rpl (end ""))
18394 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18395 (setq rpl (if (or (match-end 1) (not def-pkg))
18396 "" (org-latex-packages-to-string def-pkg snippets-p t))
18397 tpl (replace-match rpl t t tpl))
18398 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18400 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18401 (setq rpl (if (or (match-end 1) (not pkg))
18402 "" (org-latex-packages-to-string pkg snippets-p t))
18403 tpl (replace-match rpl t t tpl))
18404 (if pkg (setq end
18405 (concat end "\n"
18406 (org-latex-packages-to-string pkg snippets-p)))))
18408 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18409 (setq rpl (if (or (match-end 1) (not extra))
18410 "" (concat extra "\n"))
18411 tpl (replace-match rpl t t tpl))
18412 (if (and extra (string-match "\\S-" extra))
18413 (setq end (concat end "\n" extra))))
18415 (if (string-match "\\S-" end)
18416 (concat tpl "\n" end)
18417 tpl)))
18419 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18420 "Turn an alist of packages into a string with the \\usepackage macros."
18421 (setq pkg (mapconcat (lambda(p)
18422 (cond
18423 ((stringp p) p)
18424 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18425 (format "%% Package %s omitted" (cadr p)))
18426 ((equal "" (car p))
18427 (format "\\usepackage{%s}" (cadr p)))
18429 (format "\\usepackage[%s]{%s}"
18430 (car p) (cadr p)))))
18432 "\n"))
18433 (if newline (concat pkg "\n") pkg))
18435 (defun org-dvipng-color (attr)
18436 "Return a RGB color specification for dvipng."
18437 (apply 'format "rgb %s %s %s"
18438 (mapcar 'org-normalize-color
18439 (if (featurep 'xemacs)
18440 (color-rgb-components
18441 (face-property 'default
18442 (cond ((eq attr :foreground) 'foreground)
18443 ((eq attr :background) 'background))))
18444 (color-values (face-attribute 'default attr nil))))))
18446 (defun org-dvipng-color-format (color-name)
18447 "Convert COLOR-NAME to a RGB color value for dvipng."
18448 (apply 'format "rgb %s %s %s"
18449 (mapcar 'org-normalize-color
18450 (color-values color-name))))
18452 (defun org-latex-color (attr)
18453 "Return a RGB color for the LaTeX color package."
18454 (apply 'format "%s,%s,%s"
18455 (mapcar 'org-normalize-color
18456 (if (featurep 'xemacs)
18457 (color-rgb-components
18458 (face-property 'default
18459 (cond ((eq attr :foreground) 'foreground)
18460 ((eq attr :background) 'background))))
18461 (color-values (face-attribute 'default attr nil))))))
18463 (defun org-latex-color-format (color-name)
18464 "Convert COLOR-NAME to a RGB color value."
18465 (apply 'format "%s,%s,%s"
18466 (mapcar 'org-normalize-color
18467 (color-values color-name))))
18469 (defun org-normalize-color (value)
18470 "Return string to be used as color value for an RGB component."
18471 (format "%g" (/ value 65535.0)))
18475 ;; Image display
18477 (defvar org-inline-image-overlays nil)
18478 (make-variable-buffer-local 'org-inline-image-overlays)
18480 (defun org-toggle-inline-images (&optional include-linked)
18481 "Toggle the display of inline images.
18482 INCLUDE-LINKED is passed to `org-display-inline-images'."
18483 (interactive "P")
18484 (if org-inline-image-overlays
18485 (progn
18486 (org-remove-inline-images)
18487 (message "Inline image display turned off"))
18488 (org-display-inline-images include-linked)
18489 (if (and (org-called-interactively-p)
18490 org-inline-image-overlays)
18491 (message "%d images displayed inline"
18492 (length org-inline-image-overlays))
18493 (message "No images to display inline"))))
18495 (defun org-redisplay-inline-images ()
18496 "Refresh the display of inline images."
18497 (interactive)
18498 (if (not org-inline-image-overlays)
18499 (org-toggle-inline-images)
18500 (org-toggle-inline-images)
18501 (org-toggle-inline-images)))
18503 (defun org-display-inline-images (&optional include-linked refresh beg end)
18504 "Display inline images.
18505 Normally only links without a description part are inlined, because this
18506 is how it will work for export. When INCLUDE-LINKED is set, also links
18507 with a description part will be inlined. This can be nice for a quick
18508 look at those images, but it does not reflect what exported files will look
18509 like.
18510 When REFRESH is set, refresh existing images between BEG and END.
18511 This will create new image displays only if necessary.
18512 BEG and END default to the buffer boundaries."
18513 (interactive "P")
18514 (unless refresh
18515 (org-remove-inline-images)
18516 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18517 (save-excursion
18518 (save-restriction
18519 (widen)
18520 (setq beg (or beg (point-min)) end (or end (point-max)))
18521 (goto-char beg)
18522 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18523 (substring (org-image-file-name-regexp) 0 -2)
18524 "\\)\\]" (if include-linked "" "\\]")))
18525 old file ov img type attrwidth width)
18526 (while (re-search-forward re end t)
18527 (setq old (get-char-property-and-overlay (match-beginning 1)
18528 'org-image-overlay)
18529 file (expand-file-name
18530 (concat (or (match-string 3) "") (match-string 4))))
18531 (when (image-type-available-p 'imagemagick)
18532 (setq attrwidth (if (or (listp org-image-actual-width)
18533 (null org-image-actual-width))
18534 (save-excursion
18535 (save-match-data
18536 (when (re-search-backward
18537 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18538 (save-excursion
18539 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18540 (string-to-number (match-string 1))))))
18541 width (cond ((eq org-image-actual-width t) nil)
18542 ((null org-image-actual-width) attrwidth)
18543 ((numberp org-image-actual-width)
18544 org-image-actual-width)
18545 ((listp org-image-actual-width)
18546 (or attrwidth (car org-image-actual-width))))
18547 type (if width 'imagemagick)))
18548 (when (file-exists-p file)
18549 (if (and (car-safe old) refresh)
18550 (image-refresh (overlay-get (cdr old) 'display))
18551 (setq img (save-match-data (create-image file type nil :width width)))
18552 (when img
18553 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18554 (overlay-put ov 'display img)
18555 (overlay-put ov 'face 'default)
18556 (overlay-put ov 'org-image-overlay t)
18557 (overlay-put ov 'modification-hooks
18558 (list 'org-display-inline-remove-overlay))
18559 (push ov org-inline-image-overlays)))))))))
18561 (define-obsolete-function-alias
18562 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18564 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18565 "Remove inline-display overlay if a corresponding region is modified."
18566 (let ((inhibit-modification-hooks t))
18567 (when (and ov after)
18568 (delete ov org-inline-image-overlays)
18569 (delete-overlay ov))))
18571 (defun org-remove-inline-images ()
18572 "Remove inline display of images."
18573 (interactive)
18574 (mapc 'delete-overlay org-inline-image-overlays)
18575 (setq org-inline-image-overlays nil))
18577 ;;;; Key bindings
18579 ;; Outline functions from `outline-mode-prefix-map'
18580 ;; that can be remapped in Org:
18581 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18582 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18583 (define-key org-mode-map [remap outline-forward-same-level]
18584 'org-forward-heading-same-level)
18585 (define-key org-mode-map [remap outline-backward-same-level]
18586 'org-backward-heading-same-level)
18587 (define-key org-mode-map [remap show-branches]
18588 'org-kill-note-or-show-branches)
18589 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18590 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18591 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18593 ;; Outline functions from `outline-mode-prefix-map' that can not
18594 ;; be remapped in Org:
18596 ;; - the column "key binding" shows whether the Outline function is still
18597 ;; available in Org mode on the same key that it has been bound to in
18598 ;; Outline mode:
18599 ;; - "overridden": key used for a different functionality in Org mode
18600 ;; - else: key still bound to the same Outline function in Org mode
18602 ;; | Outline function | key binding | Org replacement |
18603 ;; |------------------------------------+-------------+-----------------------|
18604 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18605 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18606 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18607 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18608 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18609 ;; | `show-entry' | overridden | no replacement |
18610 ;; | `show-children' | `C-c C-i' | visibility cycling |
18611 ;; | `show-branches' | `C-c C-k' | still same function |
18612 ;; | `show-subtree' | overridden | visibility cycling |
18613 ;; | `show-all' | overridden | no replacement |
18614 ;; | `hide-subtree' | overridden | visibility cycling |
18615 ;; | `hide-body' | overridden | no replacement |
18616 ;; | `hide-entry' | overridden | visibility cycling |
18617 ;; | `hide-leaves' | overridden | no replacement |
18618 ;; | `hide-sublevels' | overridden | no replacement |
18619 ;; | `hide-other' | overridden | no replacement |
18621 ;; Make `C-c C-x' a prefix key
18622 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18624 ;; TAB key with modifiers
18625 (org-defkey org-mode-map "\C-i" 'org-cycle)
18626 (org-defkey org-mode-map [(tab)] 'org-cycle)
18627 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18628 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18629 ;; The following line is necessary under Suse GNU/Linux
18630 (unless (featurep 'xemacs)
18631 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18632 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18633 (define-key org-mode-map [backtab] 'org-shifttab)
18635 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18636 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18637 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18639 ;; Cursor keys with modifiers
18640 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18641 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18642 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18643 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18645 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18646 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18647 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18648 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18650 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18651 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18652 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18653 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18655 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18656 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18657 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18658 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18660 ;; Babel keys
18661 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18662 (mapc (lambda (pair)
18663 (define-key org-babel-map (car pair) (cdr pair)))
18664 org-babel-key-bindings)
18666 ;;; Extra keys for tty access.
18667 ;; We only set them when really needed because otherwise the
18668 ;; menus don't show the simple keys
18670 (when (or org-use-extra-keys
18671 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18672 (not window-system))
18673 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18674 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18675 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18676 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18677 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18678 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18679 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18680 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18681 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18682 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18683 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18684 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18685 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18686 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18687 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18688 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18689 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18690 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18691 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18692 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18693 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18694 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18695 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18696 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18697 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18698 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18699 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18700 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18702 ;; All the other keys
18704 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18705 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18706 (if (boundp 'narrow-map)
18707 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18708 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18709 (if (boundp 'narrow-map)
18710 (org-defkey narrow-map "b" 'org-narrow-to-block)
18711 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18712 (if (boundp 'narrow-map)
18713 (org-defkey narrow-map "e" 'org-narrow-to-element)
18714 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18715 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18716 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18717 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18718 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18719 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18720 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18721 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18722 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18723 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18724 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18725 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18726 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18727 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18728 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18729 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18730 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18731 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18732 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18733 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18734 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18735 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18736 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18737 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18738 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18739 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18740 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18741 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18742 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18743 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18744 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18745 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18746 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18747 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18748 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18749 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18750 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18751 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18752 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18753 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18754 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18755 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18756 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18757 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18758 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18759 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18760 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18761 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18762 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18763 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18764 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18765 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18766 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18767 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18768 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18769 (org-defkey org-mode-map "\C-c^" 'org-sort)
18770 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18771 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18772 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18773 (org-defkey org-mode-map "\C-m" 'org-return)
18774 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18775 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18776 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18777 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18778 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18779 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18780 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18781 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18782 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18783 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18784 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18785 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18786 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18787 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18788 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18789 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18790 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18791 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18792 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18793 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18794 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18795 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18796 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18798 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18799 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18800 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18802 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18803 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18804 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18805 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18806 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18807 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18808 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18809 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18810 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18811 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18812 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18813 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18814 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18815 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18816 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18817 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18818 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18819 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18820 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18821 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18822 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18823 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18824 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18826 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18827 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18828 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18829 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18830 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18832 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18834 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18836 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18837 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18839 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18842 (when (featurep 'xemacs)
18843 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18846 (defconst org-speed-commands-default
18848 ("Outline Navigation")
18849 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18850 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18851 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18852 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18853 ("F" . org-next-block)
18854 ("B" . org-previous-block)
18855 ("u" . (org-speed-move-safe 'outline-up-heading))
18856 ("j" . org-goto)
18857 ("g" . (org-refile t))
18858 ("Outline Visibility")
18859 ("c" . org-cycle)
18860 ("C" . org-shifttab)
18861 (" " . org-display-outline-path)
18862 ("=" . org-columns)
18863 ("Outline Structure Editing")
18864 ("U" . org-shiftmetaup)
18865 ("D" . org-shiftmetadown)
18866 ("r" . org-metaright)
18867 ("l" . org-metaleft)
18868 ("R" . org-shiftmetaright)
18869 ("L" . org-shiftmetaleft)
18870 ("i" . (progn (forward-char 1) (call-interactively
18871 'org-insert-heading-respect-content)))
18872 ("^" . org-sort)
18873 ("w" . org-refile)
18874 ("a" . org-archive-subtree-default-with-confirmation)
18875 ("@" . org-mark-subtree)
18876 ("#" . org-toggle-comment)
18877 ("Clock Commands")
18878 ("I" . org-clock-in)
18879 ("O" . org-clock-out)
18880 ("Meta Data Editing")
18881 ("t" . org-todo)
18882 ("," . (org-priority))
18883 ("0" . (org-priority ?\ ))
18884 ("1" . (org-priority ?A))
18885 ("2" . (org-priority ?B))
18886 ("3" . (org-priority ?C))
18887 (":" . org-set-tags-command)
18888 ("e" . org-set-effort)
18889 ("E" . org-inc-effort)
18890 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18891 (org-entry-put (point) "APPT_WARNTIME" m)))
18892 ("Agenda Views etc")
18893 ("v" . org-agenda)
18894 ("/" . org-sparse-tree)
18895 ("Misc")
18896 ("o" . org-open-at-point)
18897 ("?" . org-speed-command-help)
18898 ("<" . (org-agenda-set-restriction-lock 'subtree))
18899 (">" . (org-agenda-remove-restriction-lock))
18901 "The default speed commands.")
18903 (defun org-print-speed-command (e)
18904 (if (> (length (car e)) 1)
18905 (progn
18906 (princ "\n")
18907 (princ (car e))
18908 (princ "\n")
18909 (princ (make-string (length (car e)) ?-))
18910 (princ "\n"))
18911 (princ (car e))
18912 (princ " ")
18913 (if (symbolp (cdr e))
18914 (princ (symbol-name (cdr e)))
18915 (prin1 (cdr e)))
18916 (princ "\n")))
18918 (defun org-speed-command-help ()
18919 "Show the available speed commands."
18920 (interactive)
18921 (if (not org-use-speed-commands)
18922 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18923 (with-output-to-temp-buffer "*Help*"
18924 (princ "User-defined Speed commands\n===========================\n")
18925 (mapc 'org-print-speed-command org-speed-commands-user)
18926 (princ "\n")
18927 (princ "Built-in Speed commands\n=======================\n")
18928 (mapc 'org-print-speed-command org-speed-commands-default))
18929 (with-current-buffer "*Help*"
18930 (setq truncate-lines t))))
18932 (defun org-speed-move-safe (cmd)
18933 "Execute CMD, but make sure that the cursor always ends up in a headline.
18934 If not, return to the original position and throw an error."
18935 (interactive)
18936 (let ((pos (point)))
18937 (call-interactively cmd)
18938 (unless (and (bolp) (org-at-heading-p))
18939 (goto-char pos)
18940 (error "Boundary reached while executing %s" cmd))))
18942 (defvar org-self-insert-command-undo-counter 0)
18944 (defvar org-table-auto-blank-field) ; defined in org-table.el
18945 (defvar org-speed-command nil)
18947 (define-obsolete-function-alias
18948 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18950 (defun org-speed-command-activate (keys)
18951 "Hook for activating single-letter speed commands.
18952 `org-speed-commands-default' specifies a minimal command set.
18953 Use `org-speed-commands-user' for further customization."
18954 (when (or (and (bolp) (looking-at org-outline-regexp))
18955 (and (functionp org-use-speed-commands)
18956 (funcall org-use-speed-commands)))
18957 (cdr (assoc keys (append org-speed-commands-user
18958 org-speed-commands-default)))))
18960 (define-obsolete-function-alias
18961 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18963 (defun org-babel-speed-command-activate (keys)
18964 "Hook for activating single-letter code block commands."
18965 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18966 (cdr (assoc keys org-babel-key-bindings))))
18968 (defcustom org-speed-command-hook
18969 '(org-speed-command-default-hook org-babel-speed-command-hook)
18970 "Hook for activating speed commands at strategic locations.
18971 Hook functions are called in sequence until a valid handler is
18972 found.
18974 Each hook takes a single argument, a user-pressed command key
18975 which is also a `self-insert-command' from the global map.
18977 Within the hook, examine the cursor position and the command key
18978 and return nil or a valid handler as appropriate. Handler could
18979 be one of an interactive command, a function, or a form.
18981 Set `org-use-speed-commands' to non-nil value to enable this
18982 hook. The default setting is `org-speed-command-activate'."
18983 :group 'org-structure
18984 :version "24.1"
18985 :type 'hook)
18987 (defun org-self-insert-command (N)
18988 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18989 If the cursor is in a table looking at whitespace, the whitespace is
18990 overwritten, and the table is not marked as requiring realignment."
18991 (interactive "p")
18992 (org-check-before-invisible-edit 'insert)
18993 (cond
18994 ((and org-use-speed-commands
18995 (setq org-speed-command
18996 (run-hook-with-args-until-success
18997 'org-speed-command-hook (this-command-keys))))
18998 (cond
18999 ((commandp org-speed-command)
19000 (setq this-command org-speed-command)
19001 (call-interactively org-speed-command))
19002 ((functionp org-speed-command)
19003 (funcall org-speed-command))
19004 ((and org-speed-command (listp org-speed-command))
19005 (eval org-speed-command))
19006 (t (let (org-use-speed-commands)
19007 (call-interactively 'org-self-insert-command)))))
19008 ((and
19009 (org-table-p)
19010 (progn
19011 ;; check if we blank the field, and if that triggers align
19012 (and (featurep 'org-table) org-table-auto-blank-field
19013 (member last-command
19014 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19015 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19016 ;; got extra space, this field does not determine column width
19017 (let (org-table-may-need-update) (org-table-blank-field))
19018 ;; no extra space, this field may determine column width
19019 (org-table-blank-field)))
19021 (eq N 1)
19022 (looking-at "[^|\n]* |"))
19023 (let (org-table-may-need-update)
19024 (goto-char (1- (match-end 0)))
19025 (backward-delete-char 1)
19026 (goto-char (match-beginning 0))
19027 (self-insert-command N)))
19029 (setq org-table-may-need-update t)
19030 (self-insert-command N)
19031 (org-fix-tags-on-the-fly)
19032 (if org-self-insert-cluster-for-undo
19033 (if (not (eq last-command 'org-self-insert-command))
19034 (setq org-self-insert-command-undo-counter 1)
19035 (if (>= org-self-insert-command-undo-counter 20)
19036 (setq org-self-insert-command-undo-counter 1)
19037 (and (> org-self-insert-command-undo-counter 0)
19038 buffer-undo-list (listp buffer-undo-list)
19039 (not (cadr buffer-undo-list)) ; remove nil entry
19040 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19041 (setq org-self-insert-command-undo-counter
19042 (1+ org-self-insert-command-undo-counter))))))))
19044 (defun org-check-before-invisible-edit (kind)
19045 "Check is editing if kind KIND would be dangerous with invisible text around.
19046 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19047 ;; First, try to get out of here as quickly as possible, to reduce overhead
19048 (if (and org-catch-invisible-edits
19049 (or (not (boundp 'visible-mode)) (not visible-mode))
19050 (or (get-char-property (point) 'invisible)
19051 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19052 ;; OK, we need to take a closer look
19053 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19054 (invisible-before-point (if (bobp) nil (get-char-property
19055 (1- (point)) 'invisible)))
19056 (border-and-ok-direction
19058 ;; Check if we are acting predictably before invisible text
19059 (and invisible-at-point (not invisible-before-point)
19060 (memq kind '(insert delete-backward)))
19061 ;; Check if we are acting predictably after invisible text
19062 ;; This works not well, and I have turned it off. It seems
19063 ;; better to always show and stop after invisible text.
19064 ;; (and (not invisible-at-point) invisible-before-point
19065 ;; (memq kind '(insert delete)))
19067 (when (or (memq invisible-at-point '(outline org-hide-block t))
19068 (memq invisible-before-point '(outline org-hide-block t)))
19069 (if (eq org-catch-invisible-edits 'error)
19070 (error "Editing in invisible areas is prohibited - make visible first"))
19071 (if (and org-custom-properties-overlays
19072 (y-or-n-p "Display invisible properties in this buffer? "))
19073 (org-toggle-custom-properties-visibility)
19074 ;; Make the area visible
19075 (save-excursion
19076 (if invisible-before-point
19077 (goto-char (previous-single-char-property-change
19078 (point) 'invisible)))
19079 (org-cycle))
19080 (cond
19081 ((eq org-catch-invisible-edits 'show)
19082 ;; That's it, we do the edit after showing
19083 (message
19084 "Unfolding invisible region around point before editing")
19085 (sit-for 1))
19086 ((and (eq org-catch-invisible-edits 'smart)
19087 border-and-ok-direction)
19088 (message "Unfolding invisible region around point before editing"))
19090 ;; Don't do the edit, make the user repeat it in full visibility
19091 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19093 (defun org-fix-tags-on-the-fly ()
19094 (when (and (equal (char-after (point-at-bol)) ?*)
19095 (org-at-heading-p))
19096 (org-align-tags-here org-tags-column)))
19098 (defun org-delete-backward-char (N)
19099 "Like `delete-backward-char', insert whitespace at field end in tables.
19100 When deleting backwards, in tables this function will insert whitespace in
19101 front of the next \"|\" separator, to keep the table aligned. The table will
19102 still be marked for re-alignment if the field did fill the entire column,
19103 because, in this case the deletion might narrow the column."
19104 (interactive "p")
19105 (save-match-data
19106 (org-check-before-invisible-edit 'delete-backward)
19107 (if (and (org-table-p)
19108 (eq N 1)
19109 (string-match "|" (buffer-substring (point-at-bol) (point)))
19110 (looking-at ".*?|"))
19111 (let ((pos (point))
19112 (noalign (looking-at "[^|\n\r]* |"))
19113 (c org-table-may-need-update))
19114 (backward-delete-char N)
19115 (if (not overwrite-mode)
19116 (progn
19117 (skip-chars-forward "^|")
19118 (insert " ")
19119 (goto-char (1- pos))))
19120 ;; noalign: if there were two spaces at the end, this field
19121 ;; does not determine the width of the column.
19122 (if noalign (setq org-table-may-need-update c)))
19123 (backward-delete-char N)
19124 (org-fix-tags-on-the-fly))))
19126 (defun org-delete-char (N)
19127 "Like `delete-char', but insert whitespace at field end in tables.
19128 When deleting characters, in tables this function will insert whitespace in
19129 front of the next \"|\" separator, to keep the table aligned. The table will
19130 still be marked for re-alignment if the field did fill the entire column,
19131 because, in this case the deletion might narrow the column."
19132 (interactive "p")
19133 (save-match-data
19134 (org-check-before-invisible-edit 'delete)
19135 (if (and (org-table-p)
19136 (not (bolp))
19137 (not (= (char-after) ?|))
19138 (eq N 1))
19139 (if (looking-at ".*?|")
19140 (let ((pos (point))
19141 (noalign (looking-at "[^|\n\r]* |"))
19142 (c org-table-may-need-update))
19143 (replace-match
19144 (concat (substring (match-string 0) 1 -1) " |") nil t)
19145 (goto-char pos)
19146 ;; noalign: if there were two spaces at the end, this field
19147 ;; does not determine the width of the column.
19148 (if noalign (setq org-table-may-need-update c)))
19149 (delete-char N))
19150 (delete-char N)
19151 (org-fix-tags-on-the-fly))))
19153 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19154 (put 'org-self-insert-command 'delete-selection t)
19155 (put 'orgtbl-self-insert-command 'delete-selection t)
19156 (put 'org-delete-char 'delete-selection 'supersede)
19157 (put 'org-delete-backward-char 'delete-selection 'supersede)
19158 (put 'org-yank 'delete-selection 'yank)
19160 ;; Make `flyspell-mode' delay after some commands
19161 (put 'org-self-insert-command 'flyspell-delayed t)
19162 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19163 (put 'org-delete-char 'flyspell-delayed t)
19164 (put 'org-delete-backward-char 'flyspell-delayed t)
19166 ;; Make pabbrev-mode expand after org-mode commands
19167 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19168 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19170 ;; How to do this: Measure non-white length of current string
19171 ;; If equal to column width, we should realign.
19173 (defun org-remap (map &rest commands)
19174 "In MAP, remap the functions given in COMMANDS.
19175 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19176 (let (new old)
19177 (while commands
19178 (setq old (pop commands) new (pop commands))
19179 (if (fboundp 'command-remapping)
19180 (org-defkey map (vector 'remap old) new)
19181 (substitute-key-definition old new map global-map)))))
19183 (defun org-transpose-words ()
19184 "Transpose words for Org.
19185 This uses the `org-mode-transpose-word-syntax-table' syntax
19186 table, which interprets characters in `org-emphasis-alist' as
19187 word constituants."
19188 (interactive)
19189 (with-syntax-table org-mode-transpose-word-syntax-table
19190 (call-interactively 'transpose-words)))
19191 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19193 (when (eq org-enable-table-editor 'optimized)
19194 ;; If the user wants maximum table support, we need to hijack
19195 ;; some standard editing functions
19196 (org-remap org-mode-map
19197 'self-insert-command 'org-self-insert-command
19198 'delete-char 'org-delete-char
19199 'delete-backward-char 'org-delete-backward-char)
19200 (org-defkey org-mode-map "|" 'org-force-self-insert))
19202 (defvar org-ctrl-c-ctrl-c-hook nil
19203 "Hook for functions attaching themselves to `C-c C-c'.
19205 This can be used to add additional functionality to the C-c C-c
19206 key which executes context-dependent commands. This hook is run
19207 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19208 run after the last test.
19210 Each function will be called with no arguments. The function
19211 must check if the context is appropriate for it to act. If yes,
19212 it should do its thing and then return a non-nil value. If the
19213 context is wrong, just do nothing and return nil.")
19215 (defvar org-ctrl-c-ctrl-c-final-hook nil
19216 "Hook for functions attaching themselves to `C-c C-c'.
19218 This can be used to add additional functionality to the C-c C-c
19219 key which executes context-dependent commands. This hook is run
19220 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19221 before the first test.
19223 Each function will be called with no arguments. The function
19224 must check if the context is appropriate for it to act. If yes,
19225 it should do its thing and then return a non-nil value. If the
19226 context is wrong, just do nothing and return nil.")
19228 (defvar org-tab-first-hook nil
19229 "Hook for functions to attach themselves to TAB.
19230 See `org-ctrl-c-ctrl-c-hook' for more information.
19231 This hook runs as the first action when TAB is pressed, even before
19232 `org-cycle' messes around with the `outline-regexp' to cater for
19233 inline tasks and plain list item folding.
19234 If any function in this hook returns t, any other actions that
19235 would have been caused by TAB (such as table field motion or visibility
19236 cycling) will not occur.")
19238 (defvar org-tab-after-check-for-table-hook nil
19239 "Hook for functions to attach themselves to TAB.
19240 See `org-ctrl-c-ctrl-c-hook' for more information.
19241 This hook runs after it has been established that the cursor is not in a
19242 table, but before checking if the cursor is in a headline or if global cycling
19243 should be done.
19244 If any function in this hook returns t, not other actions like visibility
19245 cycling will be done.")
19247 (defvar org-tab-after-check-for-cycling-hook nil
19248 "Hook for functions to attach themselves to TAB.
19249 See `org-ctrl-c-ctrl-c-hook' for more information.
19250 This hook runs after it has been established that not table field motion and
19251 not visibility should be done because of current context. This is probably
19252 the place where a package like yasnippets can hook in.")
19254 (defvar org-tab-before-tab-emulation-hook nil
19255 "Hook for functions to attach themselves to TAB.
19256 See `org-ctrl-c-ctrl-c-hook' for more information.
19257 This hook runs after every other options for TAB have been exhausted, but
19258 before indentation and \t insertion takes place.")
19260 (defvar org-metaleft-hook nil
19261 "Hook for functions attaching themselves to `M-left'.
19262 See `org-ctrl-c-ctrl-c-hook' for more information.")
19263 (defvar org-metaright-hook nil
19264 "Hook for functions attaching themselves to `M-right'.
19265 See `org-ctrl-c-ctrl-c-hook' for more information.")
19266 (defvar org-metaup-hook nil
19267 "Hook for functions attaching themselves to `M-up'.
19268 See `org-ctrl-c-ctrl-c-hook' for more information.")
19269 (defvar org-metadown-hook nil
19270 "Hook for functions attaching themselves to `M-down'.
19271 See `org-ctrl-c-ctrl-c-hook' for more information.")
19272 (defvar org-shiftmetaleft-hook nil
19273 "Hook for functions attaching themselves to `M-S-left'.
19274 See `org-ctrl-c-ctrl-c-hook' for more information.")
19275 (defvar org-shiftmetaright-hook nil
19276 "Hook for functions attaching themselves to `M-S-right'.
19277 See `org-ctrl-c-ctrl-c-hook' for more information.")
19278 (defvar org-shiftmetaup-hook nil
19279 "Hook for functions attaching themselves to `M-S-up'.
19280 See `org-ctrl-c-ctrl-c-hook' for more information.")
19281 (defvar org-shiftmetadown-hook nil
19282 "Hook for functions attaching themselves to `M-S-down'.
19283 See `org-ctrl-c-ctrl-c-hook' for more information.")
19284 (defvar org-metareturn-hook nil
19285 "Hook for functions attaching themselves to `M-RET'.
19286 See `org-ctrl-c-ctrl-c-hook' for more information.")
19287 (defvar org-shiftup-hook nil
19288 "Hook for functions attaching themselves to `S-up'.
19289 See `org-ctrl-c-ctrl-c-hook' for more information.")
19290 (defvar org-shiftup-final-hook nil
19291 "Hook for functions attaching themselves to `S-up'.
19292 This one runs after all other options except shift-select have been excluded.
19293 See `org-ctrl-c-ctrl-c-hook' for more information.")
19294 (defvar org-shiftdown-hook nil
19295 "Hook for functions attaching themselves to `S-down'.
19296 See `org-ctrl-c-ctrl-c-hook' for more information.")
19297 (defvar org-shiftdown-final-hook nil
19298 "Hook for functions attaching themselves to `S-down'.
19299 This one runs after all other options except shift-select have been excluded.
19300 See `org-ctrl-c-ctrl-c-hook' for more information.")
19301 (defvar org-shiftleft-hook nil
19302 "Hook for functions attaching themselves to `S-left'.
19303 See `org-ctrl-c-ctrl-c-hook' for more information.")
19304 (defvar org-shiftleft-final-hook nil
19305 "Hook for functions attaching themselves to `S-left'.
19306 This one runs after all other options except shift-select have been excluded.
19307 See `org-ctrl-c-ctrl-c-hook' for more information.")
19308 (defvar org-shiftright-hook nil
19309 "Hook for functions attaching themselves to `S-right'.
19310 See `org-ctrl-c-ctrl-c-hook' for more information.")
19311 (defvar org-shiftright-final-hook nil
19312 "Hook for functions attaching themselves to `S-right'.
19313 This one runs after all other options except shift-select have been excluded.
19314 See `org-ctrl-c-ctrl-c-hook' for more information.")
19316 (defun org-modifier-cursor-error ()
19317 "Throw an error, a modified cursor command was applied in wrong context."
19318 (error "This command is active in special context like tables, headlines or items"))
19320 (defun org-shiftselect-error ()
19321 "Throw an error because Shift-Cursor command was applied in wrong context."
19322 (if (and (boundp 'shift-select-mode) shift-select-mode)
19323 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19324 (error "This command works only in special context like headlines or timestamps")))
19326 (defun org-call-for-shift-select (cmd)
19327 (let ((this-command-keys-shift-translated t))
19328 (call-interactively cmd)))
19330 (defun org-shifttab (&optional arg)
19331 "Global visibility cycling or move to previous table field.
19332 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19333 on context.
19334 See the individual commands for more information."
19335 (interactive "P")
19336 (cond
19337 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19338 ((integerp arg)
19339 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19340 (message "Content view to level: %d" arg)
19341 (org-content (prefix-numeric-value arg2))
19342 (setq org-cycle-global-status 'overview)))
19343 (t (call-interactively 'org-global-cycle))))
19345 (defun org-shiftmetaleft ()
19346 "Promote subtree or delete table column.
19347 Calls `org-promote-subtree', `org-outdent-item-tree', or
19348 `org-table-delete-column', depending on context. See the
19349 individual commands for more information."
19350 (interactive)
19351 (cond
19352 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19353 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19354 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19355 ((if (not (org-region-active-p)) (org-at-item-p)
19356 (save-excursion (goto-char (region-beginning))
19357 (org-at-item-p)))
19358 (call-interactively 'org-outdent-item-tree))
19359 (t (org-modifier-cursor-error))))
19361 (defun org-shiftmetaright ()
19362 "Demote subtree or insert table column.
19363 Calls `org-demote-subtree', `org-indent-item-tree', or
19364 `org-table-insert-column', depending on context. See the
19365 individual commands for more information."
19366 (interactive)
19367 (cond
19368 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19369 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19370 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19371 ((if (not (org-region-active-p)) (org-at-item-p)
19372 (save-excursion (goto-char (region-beginning))
19373 (org-at-item-p)))
19374 (call-interactively 'org-indent-item-tree))
19375 (t (org-modifier-cursor-error))))
19377 (defun org-shiftmetaup (&optional arg)
19378 "Move subtree up or kill table row.
19379 Calls `org-move-subtree-up' or `org-table-kill-row' or
19380 `org-move-item-up' or `org-timestamp-up', depending on context.
19381 See the individual commands for more information."
19382 (interactive "P")
19383 (cond
19384 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19385 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19386 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19387 ((org-at-item-p) (call-interactively 'org-move-item-up))
19388 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19389 (call-interactively 'org-timestamp-up)))
19390 (t (call-interactively 'org-drag-line-backward))))
19392 (defun org-shiftmetadown (&optional arg)
19393 "Move subtree down or insert table row.
19394 Calls `org-move-subtree-down' or `org-table-insert-row' or
19395 `org-move-item-down' or `org-timestamp-up', depending on context.
19396 See the individual commands for more information."
19397 (interactive "P")
19398 (cond
19399 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19400 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19401 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19402 ((org-at-item-p) (call-interactively 'org-move-item-down))
19403 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19404 (call-interactively 'org-timestamp-down)))
19405 (t (call-interactively 'org-drag-line-forward))))
19407 (defsubst org-hidden-tree-error ()
19408 (error
19409 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19411 (defun org-metaleft (&optional arg)
19412 "Promote heading or move table column to left.
19413 Calls `org-do-promote' or `org-table-move-column', depending on context.
19414 With no specific context, calls the Emacs default `backward-word'.
19415 See the individual commands for more information."
19416 (interactive "P")
19417 (cond
19418 ((run-hook-with-args-until-success 'org-metaleft-hook))
19419 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19420 ((org-with-limited-levels
19421 (or (org-at-heading-p)
19422 (and (org-region-active-p)
19423 (save-excursion
19424 (goto-char (region-beginning))
19425 (org-at-heading-p)))))
19426 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19427 (call-interactively 'org-do-promote))
19428 ;; At an inline task.
19429 ((org-at-heading-p)
19430 (call-interactively 'org-inlinetask-promote))
19431 ((or (org-at-item-p)
19432 (and (org-region-active-p)
19433 (save-excursion
19434 (goto-char (region-beginning))
19435 (org-at-item-p))))
19436 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19437 (call-interactively 'org-outdent-item))
19438 (t (call-interactively 'backward-word))))
19440 (defun org-metaright (&optional arg)
19441 "Demote a subtree, a list item or move table column to right.
19442 In front of a drawer or a block keyword, indent it correctly.
19443 With no specific context, calls the Emacs default `forward-word'.
19444 See the individual commands for more information."
19445 (interactive "P")
19446 (cond
19447 ((run-hook-with-args-until-success 'org-metaright-hook))
19448 ((org-at-table-p) (call-interactively 'org-table-move-column))
19449 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19450 ((org-at-block-p) (call-interactively 'org-indent-block))
19451 ((org-with-limited-levels
19452 (or (org-at-heading-p)
19453 (and (org-region-active-p)
19454 (save-excursion
19455 (goto-char (region-beginning))
19456 (org-at-heading-p)))))
19457 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19458 (call-interactively 'org-do-demote))
19459 ;; At an inline task.
19460 ((org-at-heading-p)
19461 (call-interactively 'org-inlinetask-demote))
19462 ((or (org-at-item-p)
19463 (and (org-region-active-p)
19464 (save-excursion
19465 (goto-char (region-beginning))
19466 (org-at-item-p))))
19467 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19468 (call-interactively 'org-indent-item))
19469 (t (call-interactively 'forward-word))))
19471 (defun org-check-for-hidden (what)
19472 "Check if there are hidden headlines/items in the current visual line.
19473 WHAT can be either `headlines' or `items'. If the current line is
19474 an outline or item heading and it has a folded subtree below it,
19475 this function returns t, nil otherwise."
19476 (let ((re (cond
19477 ((eq what 'headlines) org-outline-regexp-bol)
19478 ((eq what 'items) (org-item-beginning-re))
19479 (t (error "This should not happen"))))
19480 beg end)
19481 (save-excursion
19482 (catch 'exit
19483 (unless (org-region-active-p)
19484 (setq beg (point-at-bol))
19485 (beginning-of-line 2)
19486 (while (and (not (eobp)) ;; this is like `next-line'
19487 (get-char-property (1- (point)) 'invisible))
19488 (beginning-of-line 2))
19489 (setq end (point))
19490 (goto-char beg)
19491 (goto-char (point-at-eol))
19492 (setq end (max end (point)))
19493 (while (re-search-forward re end t)
19494 (if (get-char-property (match-beginning 0) 'invisible)
19495 (throw 'exit t))))
19496 nil))))
19498 (defun org-metaup (&optional arg)
19499 "Move subtree up or move table row up.
19500 Calls `org-move-subtree-up' or `org-table-move-row' or
19501 `org-move-item-up', depending on context. See the individual commands
19502 for more information."
19503 (interactive "P")
19504 (cond
19505 ((run-hook-with-args-until-success 'org-metaup-hook))
19506 ((org-region-active-p)
19507 (let* ((a (min (region-beginning) (region-end)))
19508 (b (1- (max (region-beginning) (region-end))))
19509 (c (save-excursion (goto-char a)
19510 (move-beginning-of-line 0)))
19511 (d (save-excursion (goto-char a)
19512 (move-end-of-line 0) (point))))
19513 (transpose-regions a b c d)
19514 (goto-char c)))
19515 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19516 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19517 ((org-at-item-p) (call-interactively 'org-move-item-up))
19518 (t (org-drag-element-backward))))
19520 (defun org-metadown (&optional arg)
19521 "Move subtree down or move table row down.
19522 Calls `org-move-subtree-down' or `org-table-move-row' or
19523 `org-move-item-down', depending on context. See the individual
19524 commands for more information."
19525 (interactive "P")
19526 (cond
19527 ((run-hook-with-args-until-success 'org-metadown-hook))
19528 ((org-region-active-p)
19529 (let* ((a (min (region-beginning) (region-end)))
19530 (b (max (region-beginning) (region-end)))
19531 (c (save-excursion (goto-char b)
19532 (move-beginning-of-line 1)))
19533 (d (save-excursion (goto-char b)
19534 (move-end-of-line 1) (1+ (point)))))
19535 (transpose-regions a b c d)
19536 (goto-char d)))
19537 ((org-at-table-p) (call-interactively 'org-table-move-row))
19538 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19539 ((org-at-item-p) (call-interactively 'org-move-item-down))
19540 (t (org-drag-element-forward))))
19542 (defun org-shiftup (&optional arg)
19543 "Increase item in timestamp or increase priority of current headline.
19544 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19545 depending on context. See the individual commands for more information."
19546 (interactive "P")
19547 (cond
19548 ((run-hook-with-args-until-success 'org-shiftup-hook))
19549 ((and org-support-shift-select (org-region-active-p))
19550 (org-call-for-shift-select 'previous-line))
19551 ((org-at-timestamp-p t)
19552 (call-interactively (if org-edit-timestamp-down-means-later
19553 'org-timestamp-down 'org-timestamp-up)))
19554 ((and (not (eq org-support-shift-select 'always))
19555 org-enable-priority-commands
19556 (org-at-heading-p))
19557 (call-interactively 'org-priority-up))
19558 ((and (not org-support-shift-select) (org-at-item-p))
19559 (call-interactively 'org-previous-item))
19560 ((org-clocktable-try-shift 'up arg))
19561 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19562 (org-support-shift-select
19563 (org-call-for-shift-select 'previous-line))
19564 (t (org-shiftselect-error))))
19566 (defun org-shiftdown (&optional arg)
19567 "Decrease item in timestamp or decrease priority of current headline.
19568 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19569 depending on context. See the individual commands for more information."
19570 (interactive "P")
19571 (cond
19572 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19573 ((and org-support-shift-select (org-region-active-p))
19574 (org-call-for-shift-select 'next-line))
19575 ((org-at-timestamp-p t)
19576 (call-interactively (if org-edit-timestamp-down-means-later
19577 'org-timestamp-up 'org-timestamp-down)))
19578 ((and (not (eq org-support-shift-select 'always))
19579 org-enable-priority-commands
19580 (org-at-heading-p))
19581 (call-interactively 'org-priority-down))
19582 ((and (not org-support-shift-select) (org-at-item-p))
19583 (call-interactively 'org-next-item))
19584 ((org-clocktable-try-shift 'down arg))
19585 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19586 (org-support-shift-select
19587 (org-call-for-shift-select 'next-line))
19588 (t (org-shiftselect-error))))
19590 (defun org-shiftright (&optional arg)
19591 "Cycle the thing at point or in the current line, depending on context.
19592 Depending on context, this does one of the following:
19594 - switch a timestamp at point one day into the future
19595 - on a headline, switch to the next TODO keyword.
19596 - on an item, switch entire list to the next bullet type
19597 - on a property line, switch to the next allowed value
19598 - on a clocktable definition line, move time block into the future"
19599 (interactive "P")
19600 (cond
19601 ((run-hook-with-args-until-success 'org-shiftright-hook))
19602 ((and org-support-shift-select (org-region-active-p))
19603 (org-call-for-shift-select 'forward-char))
19604 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19605 ((and (not (eq org-support-shift-select 'always))
19606 (org-at-heading-p))
19607 (let ((org-inhibit-logging
19608 (not org-treat-S-cursor-todo-selection-as-state-change))
19609 (org-inhibit-blocking
19610 (not org-treat-S-cursor-todo-selection-as-state-change)))
19611 (org-call-with-arg 'org-todo 'right)))
19612 ((or (and org-support-shift-select
19613 (not (eq org-support-shift-select 'always))
19614 (org-at-item-bullet-p))
19615 (and (not org-support-shift-select) (org-at-item-p)))
19616 (org-call-with-arg 'org-cycle-list-bullet nil))
19617 ((and (not (eq org-support-shift-select 'always))
19618 (org-at-property-p))
19619 (call-interactively 'org-property-next-allowed-value))
19620 ((org-clocktable-try-shift 'right arg))
19621 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19622 (org-support-shift-select
19623 (org-call-for-shift-select 'forward-char))
19624 (t (org-shiftselect-error))))
19626 (defun org-shiftleft (&optional arg)
19627 "Cycle the thing at point or in the current line, depending on context.
19628 Depending on context, this does one of the following:
19630 - switch a timestamp at point one day into the past
19631 - on a headline, switch to the previous TODO keyword.
19632 - on an item, switch entire list to the previous bullet type
19633 - on a property line, switch to the previous allowed value
19634 - on a clocktable definition line, move time block into the past"
19635 (interactive "P")
19636 (cond
19637 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19638 ((and org-support-shift-select (org-region-active-p))
19639 (org-call-for-shift-select 'backward-char))
19640 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19641 ((and (not (eq org-support-shift-select 'always))
19642 (org-at-heading-p))
19643 (let ((org-inhibit-logging
19644 (not org-treat-S-cursor-todo-selection-as-state-change))
19645 (org-inhibit-blocking
19646 (not org-treat-S-cursor-todo-selection-as-state-change)))
19647 (org-call-with-arg 'org-todo 'left)))
19648 ((or (and org-support-shift-select
19649 (not (eq org-support-shift-select 'always))
19650 (org-at-item-bullet-p))
19651 (and (not org-support-shift-select) (org-at-item-p)))
19652 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19653 ((and (not (eq org-support-shift-select 'always))
19654 (org-at-property-p))
19655 (call-interactively 'org-property-previous-allowed-value))
19656 ((org-clocktable-try-shift 'left arg))
19657 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19658 (org-support-shift-select
19659 (org-call-for-shift-select 'backward-char))
19660 (t (org-shiftselect-error))))
19662 (defun org-shiftcontrolright ()
19663 "Switch to next TODO set."
19664 (interactive)
19665 (cond
19666 ((and org-support-shift-select (org-region-active-p))
19667 (org-call-for-shift-select 'forward-word))
19668 ((and (not (eq org-support-shift-select 'always))
19669 (org-at-heading-p))
19670 (org-call-with-arg 'org-todo 'nextset))
19671 (org-support-shift-select
19672 (org-call-for-shift-select 'forward-word))
19673 (t (org-shiftselect-error))))
19675 (defun org-shiftcontrolleft ()
19676 "Switch to previous TODO set."
19677 (interactive)
19678 (cond
19679 ((and org-support-shift-select (org-region-active-p))
19680 (org-call-for-shift-select 'backward-word))
19681 ((and (not (eq org-support-shift-select 'always))
19682 (org-at-heading-p))
19683 (org-call-with-arg 'org-todo 'previousset))
19684 (org-support-shift-select
19685 (org-call-for-shift-select 'backward-word))
19686 (t (org-shiftselect-error))))
19688 (defun org-shiftcontrolup (&optional n)
19689 "Change timestamps synchronously up in CLOCK log lines.
19690 Optional argument N tells to change by that many units."
19691 (interactive "P")
19692 (cond ((and (not org-support-shift-select)
19693 (org-at-clock-log-p)
19694 (org-at-timestamp-p t))
19695 (org-clock-timestamps-up n))
19696 (t (org-shiftselect-error))))
19698 (defun org-shiftcontroldown (&optional n)
19699 "Change timestamps synchronously down in CLOCK log lines.
19700 Optional argument N tells to change by that many units."
19701 (interactive "P")
19702 (cond ((and (not org-support-shift-select)
19703 (org-at-clock-log-p)
19704 (org-at-timestamp-p t))
19705 (org-clock-timestamps-down n))
19706 (t (org-shiftselect-error))))
19708 (defun org-ctrl-c-ret ()
19709 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19710 (interactive)
19711 (cond
19712 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19713 (t (call-interactively 'org-insert-heading))))
19715 (defun org-find-visible ()
19716 (let ((s (point)))
19717 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19718 (get-char-property s 'invisible)))
19720 (defun org-find-invisible ()
19721 (let ((s (point)))
19722 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19723 (not (get-char-property s 'invisible))))
19726 (defun org-copy-visible (beg end)
19727 "Copy the visible parts of the region."
19728 (interactive "r")
19729 (let (snippets s)
19730 (save-excursion
19731 (save-restriction
19732 (narrow-to-region beg end)
19733 (setq s (goto-char (point-min)))
19734 (while (not (= (point) (point-max)))
19735 (goto-char (org-find-invisible))
19736 (push (buffer-substring s (point)) snippets)
19737 (setq s (goto-char (org-find-visible))))))
19738 (kill-new (apply 'concat (nreverse snippets)))))
19740 (defun org-copy-special ()
19741 "Copy region in table or copy current subtree.
19742 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19743 See the individual commands for more information."
19744 (interactive)
19745 (call-interactively
19746 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19748 (defun org-cut-special ()
19749 "Cut region in table or cut current subtree.
19750 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19751 See the individual commands for more information."
19752 (interactive)
19753 (call-interactively
19754 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19756 (defun org-paste-special (arg)
19757 "Paste rectangular region into table, or past subtree relative to level.
19758 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19759 See the individual commands for more information."
19760 (interactive "P")
19761 (if (org-at-table-p)
19762 (org-table-paste-rectangle)
19763 (org-paste-subtree arg)))
19765 (defsubst org-in-fixed-width-region-p ()
19766 "Is point in a fixed-width region?"
19767 (save-match-data
19768 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19770 (defun org-edit-special (&optional arg)
19771 "Call a special editor for the element at point.
19772 When at a table, call the formula editor with `org-table-edit-formulas'.
19773 When in a source code block, call `org-edit-src-code'.
19774 When in a fixed-width region, call `org-edit-fixed-width-region'.
19775 When at an #+INCLUDE keyword, visit the included file.
19776 On a link, call `ffap' to visit the link at point.
19777 Otherwise, return a user error."
19778 (interactive)
19779 (let ((element (org-element-at-point)))
19780 (assert (not buffer-read-only) nil
19781 "Buffer is read-only: %s" (buffer-name))
19782 (case (org-element-type element)
19783 (src-block
19784 (if (not arg) (org-edit-src-code)
19785 (let* ((info (org-babel-get-src-block-info))
19786 (lang (nth 0 info))
19787 (params (nth 2 info))
19788 (session (cdr (assq :session params))))
19789 (if (not session) (org-edit-src-code)
19790 ;; At a src-block with a session and function called with
19791 ;; an ARG: switch to the buffer related to the inferior
19792 ;; process.
19793 (funcall (intern (concat "org-babel-prep-session:" lang))
19794 session params)))))
19795 (keyword
19796 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19797 (find-file
19798 (org-remove-double-quotes
19799 (car (org-split-string (org-element-property :value element)))))
19800 (user-error "No special environment to edit here")))
19801 (table
19802 (if (eq (org-element-property :type element) 'table.el)
19803 (org-edit-src-code)
19804 (call-interactively 'org-table-edit-formulas)))
19805 ;; Only Org tables contain `table-row' type elements.
19806 (table-row (call-interactively 'org-table-edit-formulas))
19807 ((example-block export-block) (org-edit-src-code))
19808 (fixed-width (org-edit-fixed-width-region))
19809 (otherwise
19810 ;; No notable element at point. Though, we may be at a link,
19811 ;; which is an object. Thus, scan deeper.
19812 (if (eq (org-element-type (org-element-context element)) 'link)
19813 (call-interactively 'ffap)
19814 (user-error "No special environment to edit here"))))))
19816 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19817 (defun org-ctrl-c-ctrl-c (&optional arg)
19818 "Set tags in headline, or update according to changed information at point.
19820 This command does many different things, depending on context:
19822 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19823 this is what we do.
19825 - If the cursor is on a statistics cookie, update it.
19827 - If the cursor is in a headline, prompt for tags and insert them
19828 into the current line, aligned to `org-tags-column'. When called
19829 with prefix arg, realign all tags in the current buffer.
19831 - If the cursor is in one of the special #+KEYWORD lines, this
19832 triggers scanning the buffer for these lines and updating the
19833 information.
19835 - If the cursor is inside a table, realign the table. This command
19836 works even if the automatic table editor has been turned off.
19838 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19839 the entire table.
19841 - If the cursor is at a footnote reference or definition, jump to
19842 the corresponding definition or references, respectively.
19844 - If the cursor is a the beginning of a dynamic block, update it.
19846 - If the current buffer is a capture buffer, close note and file it.
19848 - If the cursor is on a <<<target>>>, update radio targets and
19849 corresponding links in this buffer.
19851 - If the cursor is on a numbered item in a plain list, renumber the
19852 ordered list.
19854 - If the cursor is on a checkbox, toggle it.
19856 - If the cursor is on a code block, evaluate it. The variable
19857 `org-confirm-babel-evaluate' can be used to control prompting
19858 before code block evaluation, by default every code block
19859 evaluation requires confirmation. Code block evaluation can be
19860 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19861 (interactive "P")
19862 (cond
19863 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19864 org-occur-highlights
19865 org-latex-fragment-image-overlays)
19866 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19867 (org-remove-occur-highlights)
19868 (org-remove-latex-fragment-image-overlays)
19869 (message "Temporary highlights/overlays removed from current buffer"))
19870 ((and (local-variable-p 'org-finish-function (current-buffer))
19871 (fboundp org-finish-function))
19872 (funcall org-finish-function))
19873 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19875 (let* ((context (org-element-context)) (type (org-element-type context)))
19876 ;; Test if point is within a blank line.
19877 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19878 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19879 (user-error "C-c C-c can do nothing useful at this location"))
19880 ;; For convenience: at the first line of a paragraph on the
19881 ;; same line as an item, apply function on that item instead.
19882 (when (eq type 'paragraph)
19883 (let ((parent (org-element-property :parent context)))
19884 (when (and (eq (org-element-type parent) 'item)
19885 (= (point-at-bol) (org-element-property :begin parent)))
19886 (setq context parent type 'item))))
19887 ;; Act according to type of element or object at point.
19888 (case type
19889 (clock (org-clock-update-time-maybe))
19890 (dynamic-block
19891 (save-excursion
19892 (goto-char (org-element-property :post-affiliated context))
19893 (org-update-dblock)))
19894 (footnote-definition
19895 (goto-char (org-element-property :post-affiliated context))
19896 (call-interactively 'org-footnote-action))
19897 (footnote-reference (call-interactively 'org-footnote-action))
19898 ((headline inlinetask)
19899 (save-excursion (goto-char (org-element-property :begin context))
19900 (call-interactively 'org-set-tags)))
19901 (item
19902 ;; At an item: a double C-u set checkbox to "[-]"
19903 ;; unconditionally, whereas a single one will toggle its
19904 ;; presence. Without an universal argument, if the item
19905 ;; has a checkbox, toggle it. Otherwise repair the list.
19906 (let* ((box (org-element-property :checkbox context))
19907 (struct (org-element-property :structure context))
19908 (old-struct (copy-tree struct))
19909 (parents (org-list-parents-alist struct))
19910 (prevs (org-list-prevs-alist struct))
19911 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19912 (org-list-set-checkbox
19913 (org-element-property :begin context) struct
19914 (cond ((equal arg '(16)) "[-]")
19915 ((and (not box) (equal arg '(4))) "[ ]")
19916 ((or (not box) (equal arg '(4))) nil)
19917 ((eq box 'on) "[ ]")
19918 (t "[X]")))
19919 ;; Mimic `org-list-write-struct' but with grabbing
19920 ;; a return value from `org-list-struct-fix-box'.
19921 (org-list-struct-fix-ind struct parents 2)
19922 (org-list-struct-fix-item-end struct)
19923 (org-list-struct-fix-bul struct prevs)
19924 (org-list-struct-fix-ind struct parents)
19925 (let ((block-item
19926 (org-list-struct-fix-box struct parents prevs orderedp)))
19927 (if (and box (equal struct old-struct))
19928 (if (equal arg '(16))
19929 (message "Checkboxes already reset")
19930 (user-error "Cannot toggle this checkbox: %s"
19931 (if (eq box 'on)
19932 "all subitems checked"
19933 "unchecked subitems")))
19934 (org-list-struct-apply-struct struct old-struct)
19935 (org-update-checkbox-count-maybe))
19936 (when block-item
19937 (message "Checkboxes were removed due to empty box at line %d"
19938 (org-current-line block-item))))))
19939 (keyword
19940 (let ((org-inhibit-startup-visibility-stuff t)
19941 (org-startup-align-all-tables nil))
19942 (when (boundp 'org-table-coordinate-overlays)
19943 (mapc 'delete-overlay org-table-coordinate-overlays)
19944 (setq org-table-coordinate-overlays nil))
19945 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19946 (message "Local setup has been refreshed"))
19947 (plain-list
19948 ;; At a plain list, with a double C-u argument, set
19949 ;; checkboxes of each item to "[-]", whereas a single one
19950 ;; will toggle their presence according to the state of the
19951 ;; first item in the list. Without an argument, repair the
19952 ;; list.
19953 (let* ((begin (org-element-property :contents-begin context))
19954 (struct (org-element-property :structure context))
19955 (old-struct (copy-tree struct))
19956 (first-box (save-excursion
19957 (goto-char begin)
19958 (looking-at org-list-full-item-re)
19959 (match-string-no-properties 3)))
19960 (new-box (cond ((equal arg '(16)) "[-]")
19961 ((equal arg '(4)) (unless first-box "[ ]"))
19962 ((equal first-box "[X]") "[ ]")
19963 (t "[X]"))))
19964 (cond
19965 (arg
19966 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19967 (org-list-get-all-items
19968 begin struct (org-list-prevs-alist struct))))
19969 ((and first-box (eq (point) begin))
19970 ;; For convenience, when point is at bol on the first
19971 ;; item of the list and no argument is provided, simply
19972 ;; toggle checkbox of that item, if any.
19973 (org-list-set-checkbox begin struct new-box)))
19974 (org-list-write-struct
19975 struct (org-list-parents-alist struct) old-struct)
19976 (org-update-checkbox-count-maybe)
19977 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19978 ((property-drawer node-property)
19979 (call-interactively 'org-property-action))
19980 ((radio-target target)
19981 (call-interactively 'org-update-radio-target-regexp))
19982 (statistics-cookie
19983 (call-interactively 'org-update-statistics-cookies))
19984 ((table table-cell table-row)
19985 ;; At a table, recalculate every field and align it. Also
19986 ;; send the table if necessary. If the table has
19987 ;; a `table.el' type, just give up. At a table row or
19988 ;; cell, maybe recalculate line but always align table.
19989 (if (eq (org-element-property :type context) 'table.el)
19990 (message "Use C-c ' to edit table.el tables")
19991 (let ((org-enable-table-editor t))
19992 (if (or (eq type 'table)
19993 ;; Check if point is at a TBLFM line.
19994 (and (eq type 'table-row)
19995 (= (point) (org-element-property :end context))))
19996 (save-excursion
19997 (goto-char (org-element-property :contents-begin context))
19998 (org-call-with-arg 'org-table-recalculate (or arg t))
19999 (orgtbl-send-table 'maybe))
20000 (org-table-maybe-eval-formula)
20001 (cond (arg (call-interactively 'org-table-recalculate))
20002 ((org-table-maybe-recalculate-line))
20003 (t (org-table-align)))))))
20004 (timestamp (org-timestamp-change 0 'day))
20005 (otherwise
20006 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20007 (user-error
20008 "C-c C-c can do nothing useful at this location")))))))))
20010 (defun org-mode-restart ()
20011 "Restart Org-mode, to scan again for special lines.
20012 Also updates the keyword regular expressions."
20013 (interactive)
20014 (org-mode)
20015 (message "Org-mode restarted"))
20017 (defun org-kill-note-or-show-branches ()
20018 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20019 (interactive)
20020 (if (not org-finish-function)
20021 (progn
20022 (hide-subtree)
20023 (call-interactively 'show-branches))
20024 (let ((org-note-abort t))
20025 (funcall org-finish-function))))
20027 (defun org-return (&optional indent)
20028 "Goto next table row or insert a newline.
20029 Calls `org-table-next-row' or `newline', depending on context.
20030 See the individual commands for more information."
20031 (interactive)
20032 (let (org-ts-what)
20033 (cond
20034 ((or (bobp) (org-in-src-block-p))
20035 (if indent (newline-and-indent) (newline)))
20036 ((org-at-table-p)
20037 (org-table-justify-field-maybe)
20038 (call-interactively 'org-table-next-row))
20039 ;; when `newline-and-indent' is called within a list, make sure
20040 ;; text moved stays inside the item.
20041 ((and (org-in-item-p) indent)
20042 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20043 (progn
20044 (save-match-data (newline))
20045 (org-indent-line-to (length (match-string 0))))
20046 (let ((ind (org-get-indentation)))
20047 (newline)
20048 (if (org-looking-back org-list-end-re)
20049 (org-indent-line)
20050 (org-indent-line-to ind)))))
20051 ((and org-return-follows-link
20052 (org-at-timestamp-p t)
20053 (not (eq org-ts-what 'after)))
20054 (org-follow-timestamp-link))
20055 ((and org-return-follows-link
20056 (let ((tprop (get-text-property (point) 'face)))
20057 (or (eq tprop 'org-link)
20058 (and (listp tprop) (memq 'org-link tprop)))))
20059 (call-interactively 'org-open-at-point))
20060 ((and (org-at-heading-p)
20061 (looking-at
20062 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20063 (org-show-entry)
20064 (end-of-line 1)
20065 (newline))
20066 (t (if indent (newline-and-indent) (newline))))))
20068 (defun org-return-indent ()
20069 "Goto next table row or insert a newline and indent.
20070 Calls `org-table-next-row' or `newline-and-indent', depending on
20071 context. See the individual commands for more information."
20072 (interactive)
20073 (org-return t))
20075 (defun org-ctrl-c-star ()
20076 "Compute table, or change heading status of lines.
20077 Calls `org-table-recalculate' or `org-toggle-heading',
20078 depending on context."
20079 (interactive)
20080 (cond
20081 ((org-at-table-p)
20082 (call-interactively 'org-table-recalculate))
20084 ;; Convert all lines in region to list items
20085 (call-interactively 'org-toggle-heading))))
20087 (defun org-ctrl-c-minus ()
20088 "Insert separator line in table or modify bullet status of line.
20089 Also turns a plain line or a region of lines into list items.
20090 Calls `org-table-insert-hline', `org-toggle-item', or
20091 `org-cycle-list-bullet', depending on context."
20092 (interactive)
20093 (cond
20094 ((org-at-table-p)
20095 (call-interactively 'org-table-insert-hline))
20096 ((org-region-active-p)
20097 (call-interactively 'org-toggle-item))
20098 ((org-in-item-p)
20099 (call-interactively 'org-cycle-list-bullet))
20101 (call-interactively 'org-toggle-item))))
20103 (defun org-toggle-item (arg)
20104 "Convert headings or normal lines to items, items to normal lines.
20105 If there is no active region, only the current line is considered.
20107 If the first non blank line in the region is a headline, convert
20108 all headlines to items, shifting text accordingly.
20110 If it is an item, convert all items to normal lines.
20112 If it is normal text, change region into a list of items.
20113 With a prefix argument ARG, change the region in a single item."
20114 (interactive "P")
20115 (let ((shift-text
20116 (function
20117 ;; Shift text in current section to IND, from point to END.
20118 ;; The function leaves point to END line.
20119 (lambda (ind end)
20120 (let ((min-i 1000) (end (copy-marker end)))
20121 ;; First determine the minimum indentation (MIN-I) of
20122 ;; the text.
20123 (save-excursion
20124 (catch 'exit
20125 (while (< (point) end)
20126 (let ((i (org-get-indentation)))
20127 (cond
20128 ;; Skip blank lines and inline tasks.
20129 ((looking-at "^[ \t]*$"))
20130 ((looking-at org-outline-regexp-bol))
20131 ;; We can't find less than 0 indentation.
20132 ((zerop i) (throw 'exit (setq min-i 0)))
20133 ((< i min-i) (setq min-i i))))
20134 (forward-line))))
20135 ;; Then indent each line so that a line indented to
20136 ;; MIN-I becomes indented to IND. Ignore blank lines
20137 ;; and inline tasks in the process.
20138 (let ((delta (- ind min-i)))
20139 (while (< (point) end)
20140 (unless (or (looking-at "^[ \t]*$")
20141 (looking-at org-outline-regexp-bol))
20142 (org-indent-line-to (+ (org-get-indentation) delta)))
20143 (forward-line)))))))
20144 (skip-blanks
20145 (function
20146 ;; Return beginning of first non-blank line, starting from
20147 ;; line at POS.
20148 (lambda (pos)
20149 (save-excursion
20150 (goto-char pos)
20151 (skip-chars-forward " \r\t\n")
20152 (point-at-bol)))))
20153 beg end)
20154 ;; Determine boundaries of changes.
20155 (if (org-region-active-p)
20156 (setq beg (funcall skip-blanks (region-beginning))
20157 end (copy-marker (region-end)))
20158 (setq beg (funcall skip-blanks (point-at-bol))
20159 end (copy-marker (point-at-eol))))
20160 ;; Depending on the starting line, choose an action on the text
20161 ;; between BEG and END.
20162 (org-with-limited-levels
20163 (save-excursion
20164 (goto-char beg)
20165 (cond
20166 ;; Case 1. Start at an item: de-itemize. Note that it only
20167 ;; happens when a region is active: `org-ctrl-c-minus'
20168 ;; would call `org-cycle-list-bullet' otherwise.
20169 ((org-at-item-p)
20170 (while (< (point) end)
20171 (when (org-at-item-p)
20172 (skip-chars-forward " \t")
20173 (delete-region (point) (match-end 0)))
20174 (forward-line)))
20175 ;; Case 2. Start at an heading: convert to items.
20176 ((org-at-heading-p)
20177 (let* ((bul (org-list-bullet-string "-"))
20178 (bul-len (length bul))
20179 ;; Indentation of the first heading. It should be
20180 ;; relative to the indentation of its parent, if any.
20181 (start-ind (save-excursion
20182 (cond
20183 ((not org-adapt-indentation) 0)
20184 ((not (outline-previous-heading)) 0)
20185 (t (length (match-string 0))))))
20186 ;; Level of first heading. Further headings will be
20187 ;; compared to it to determine hierarchy in the list.
20188 (ref-level (org-reduced-level (org-outline-level))))
20189 (while (< (point) end)
20190 (let* ((level (org-reduced-level (org-outline-level)))
20191 (delta (max 0 (- level ref-level))))
20192 ;; If current headline is less indented than the first
20193 ;; one, set it as reference, in order to preserve
20194 ;; subtrees.
20195 (when (< level ref-level) (setq ref-level level))
20196 (replace-match bul t t)
20197 (org-indent-line-to (+ start-ind (* delta bul-len)))
20198 ;; Ensure all text down to END (or SECTION-END) belongs
20199 ;; to the newly created item.
20200 (let ((section-end (save-excursion
20201 (or (outline-next-heading) (point)))))
20202 (forward-line)
20203 (funcall shift-text
20204 (+ start-ind (* (1+ delta) bul-len))
20205 (min end section-end)))))))
20206 ;; Case 3. Normal line with ARG: make the first line of region
20207 ;; an item, and shift indentation of others lines to
20208 ;; set them as item's body.
20209 (arg (let* ((bul (org-list-bullet-string "-"))
20210 (bul-len (length bul))
20211 (ref-ind (org-get-indentation)))
20212 (skip-chars-forward " \t")
20213 (insert bul)
20214 (forward-line)
20215 (while (< (point) end)
20216 ;; Ensure that lines less indented than first one
20217 ;; still get included in item body.
20218 (funcall shift-text
20219 (+ ref-ind bul-len)
20220 (min end (save-excursion (or (outline-next-heading)
20221 (point)))))
20222 (forward-line))))
20223 ;; Case 4. Normal line without ARG: turn each non-item line
20224 ;; into an item.
20226 (while (< (point) end)
20227 (unless (or (org-at-heading-p) (org-at-item-p))
20228 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20229 (replace-match
20230 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20231 (forward-line))))))))
20233 (defun org-toggle-heading (&optional nstars)
20234 "Convert headings to normal text, or items or text to headings.
20235 If there is no active region, only convert the current line.
20237 With a \\[universal-argument] prefix, convert the whole list at
20238 point into heading.
20240 In a region:
20242 - If the first non blank line is a headline, remove the stars
20243 from all headlines in the region.
20245 - If it is a normal line, turn each and every normal line (i.e.,
20246 not an heading or an item) in the region into headings. If you
20247 want to convert only the first line of this region, use one
20248 universal prefix argument.
20250 - If it is a plain list item, turn all plain list items into headings.
20252 When converting a line into a heading, the number of stars is chosen
20253 such that the lines become children of the current entry. However,
20254 when a numeric prefix argument is given, its value determines the
20255 number of stars to add."
20256 (interactive "P")
20257 (let ((skip-blanks
20258 (function
20259 ;; Return beginning of first non-blank line, starting from
20260 ;; line at POS.
20261 (lambda (pos)
20262 (save-excursion
20263 (goto-char pos)
20264 (while (org-at-comment-p) (forward-line))
20265 (skip-chars-forward " \r\t\n")
20266 (point-at-bol)))))
20267 beg end toggled)
20268 ;; Determine boundaries of changes. If a universal prefix has
20269 ;; been given, put the list in a region. If region ends at a bol,
20270 ;; do not consider the last line to be in the region.
20272 (when (and current-prefix-arg (org-at-item-p))
20273 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20274 (org-mark-element))
20276 (if (org-region-active-p)
20277 (setq beg (funcall skip-blanks (region-beginning))
20278 end (copy-marker (save-excursion
20279 (goto-char (region-end))
20280 (if (bolp) (point) (point-at-eol)))))
20281 (setq beg (funcall skip-blanks (point-at-bol))
20282 end (copy-marker (point-at-eol))))
20283 ;; Ensure inline tasks don't count as headings.
20284 (org-with-limited-levels
20285 (save-excursion
20286 (goto-char beg)
20287 (cond
20288 ;; Case 1. Started at an heading: de-star headings.
20289 ((org-at-heading-p)
20290 (while (< (point) end)
20291 (when (org-at-heading-p t)
20292 (looking-at org-outline-regexp) (replace-match "")
20293 (setq toggled t))
20294 (forward-line)))
20295 ;; Case 2. Started at an item: change items into headlines.
20296 ;; One star will be added by `org-list-to-subtree'.
20297 ((org-at-item-p)
20298 (let* ((stars (make-string
20299 ;; subtract the star that will be added again by
20300 ;; `org-list-to-subtree'
20301 (if (numberp nstars) (1- nstars)
20302 (or (org-current-level) 0))
20303 ?*))
20304 (add-stars
20305 (cond (nstars "") ; stars from prefix only
20306 ((equal stars "") "") ; before first heading
20307 (org-odd-levels-only "*") ; inside heading, odd
20308 (t "")))) ; inside heading, oddeven
20309 (while (< (point) end)
20310 (when (org-at-item-p)
20311 ;; Pay attention to cases when region ends before list.
20312 (let* ((struct (org-list-struct))
20313 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20314 (save-restriction
20315 (narrow-to-region (point) list-end)
20316 (insert
20317 (org-list-to-subtree
20318 (org-list-parse-list t)
20319 '(:istart (concat stars add-stars (funcall get-stars depth))
20320 :icount (concat stars add-stars (funcall get-stars depth)))))))
20321 (setq toggled t))
20322 (forward-line))))
20323 ;; Case 3. Started at normal text: make every line an heading,
20324 ;; skipping headlines and items.
20325 (t (let* ((stars
20326 (make-string
20327 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20328 (add-stars
20329 (cond (nstars "") ; stars from prefix only
20330 ((equal stars "") "*") ; before first heading
20331 (org-odd-levels-only "**") ; inside heading, odd
20332 (t "*"))) ; inside heading, oddeven
20333 (rpl (concat stars add-stars " "))
20334 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20335 (while (< (point) (if (equal nstars '(4)) lend end))
20336 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20337 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20338 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20339 (forward-line)))))))
20340 (unless toggled (message "Cannot toggle heading from here"))))
20342 (defun org-meta-return (&optional arg)
20343 "Insert a new heading or wrap a region in a table.
20344 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20345 See the individual commands for more information."
20346 (interactive "P")
20347 (cond
20348 ((run-hook-with-args-until-success 'org-metareturn-hook))
20349 ((or (org-at-drawer-p) (org-at-property-p))
20350 (newline-and-indent))
20351 ((org-at-table-p)
20352 (call-interactively 'org-table-wrap-region))
20353 (t (call-interactively 'org-insert-heading))))
20355 ;;; Menu entries
20357 (defsubst org-in-subtree-not-table-p ()
20358 "Are we in a subtree and not in a table?"
20359 (and (not (org-before-first-heading-p))
20360 (not (org-at-table-p))))
20362 ;; Define the Org-mode menus
20363 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20364 '("Tbl"
20365 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20366 ["Next Field" org-cycle (org-at-table-p)]
20367 ["Previous Field" org-shifttab (org-at-table-p)]
20368 ["Next Row" org-return (org-at-table-p)]
20369 "--"
20370 ["Blank Field" org-table-blank-field (org-at-table-p)]
20371 ["Edit Field" org-table-edit-field (org-at-table-p)]
20372 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20373 "--"
20374 ("Column"
20375 ["Move Column Left" org-metaleft (org-at-table-p)]
20376 ["Move Column Right" org-metaright (org-at-table-p)]
20377 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20378 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20379 ("Row"
20380 ["Move Row Up" org-metaup (org-at-table-p)]
20381 ["Move Row Down" org-metadown (org-at-table-p)]
20382 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20383 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20384 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20385 "--"
20386 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20387 ("Rectangle"
20388 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20389 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20390 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20391 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20392 "--"
20393 ("Calculate"
20394 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20395 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20396 ["Edit Formulas" org-edit-special (org-at-table-p)]
20397 "--"
20398 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20399 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20400 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20401 "--"
20402 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20403 "--"
20404 ["Sum Column/Rectangle" org-table-sum
20405 (or (org-at-table-p) (org-region-active-p))]
20406 ["Which Column?" org-table-current-column (org-at-table-p)])
20407 ["Debug Formulas"
20408 org-table-toggle-formula-debugger
20409 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20410 ["Show Col/Row Numbers"
20411 org-table-toggle-coordinate-overlays
20412 :style toggle
20413 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20414 "--"
20415 ["Create" org-table-create (and (not (org-at-table-p))
20416 org-enable-table-editor)]
20417 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20418 ["Import from File" org-table-import (not (org-at-table-p))]
20419 ["Export to File" org-table-export (org-at-table-p)]
20420 "--"
20421 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20423 (easy-menu-define org-org-menu org-mode-map "Org menu"
20424 '("Org"
20425 ("Show/Hide"
20426 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20427 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20428 ["Sparse Tree..." org-sparse-tree t]
20429 ["Reveal Context" org-reveal t]
20430 ["Show All" show-all t]
20431 "--"
20432 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20433 "--"
20434 ["New Heading" org-insert-heading t]
20435 ("Navigate Headings"
20436 ["Up" outline-up-heading t]
20437 ["Next" outline-next-visible-heading t]
20438 ["Previous" outline-previous-visible-heading t]
20439 ["Next Same Level" outline-forward-same-level t]
20440 ["Previous Same Level" outline-backward-same-level t]
20441 "--"
20442 ["Jump" org-goto t])
20443 ("Edit Structure"
20444 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20445 "--"
20446 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20447 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20448 "--"
20449 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20450 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20451 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20452 "--"
20453 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20454 "--"
20455 ["Copy visible text" org-copy-visible t]
20456 "--"
20457 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20458 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20459 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20460 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20461 "--"
20462 ["Sort Region/Children" org-sort t]
20463 "--"
20464 ["Convert to odd levels" org-convert-to-odd-levels t]
20465 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20466 ("Editing"
20467 ["Emphasis..." org-emphasize t]
20468 ["Edit Source Example" org-edit-special t]
20469 "--"
20470 ["Footnote new/jump" org-footnote-action t]
20471 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20472 ("Archive"
20473 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20474 "--"
20475 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20476 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20477 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20479 "--"
20480 ("Hyperlinks"
20481 ["Store Link (Global)" org-store-link t]
20482 ["Find existing link to here" org-occur-link-in-agenda-files t]
20483 ["Insert Link" org-insert-link t]
20484 ["Follow Link" org-open-at-point t]
20485 "--"
20486 ["Next link" org-next-link t]
20487 ["Previous link" org-previous-link t]
20488 "--"
20489 ["Descriptive Links"
20490 org-toggle-link-display
20491 :style radio
20492 :selected org-descriptive-links
20494 ["Literal Links"
20495 org-toggle-link-display
20496 :style radio
20497 :selected (not org-descriptive-links)])
20498 "--"
20499 ("TODO Lists"
20500 ["TODO/DONE/-" org-todo t]
20501 ("Select keyword"
20502 ["Next keyword" org-shiftright (org-at-heading-p)]
20503 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20504 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20505 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20506 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20507 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20508 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20509 "--"
20510 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20511 :selected org-enforce-todo-dependencies :style toggle :active t]
20512 "Settings for tree at point"
20513 ["Do Children sequentially" org-toggle-ordered-property :style radio
20514 :selected (org-entry-get nil "ORDERED")
20515 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20516 ["Do Children parallel" org-toggle-ordered-property :style radio
20517 :selected (not (org-entry-get nil "ORDERED"))
20518 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20519 "--"
20520 ["Set Priority" org-priority t]
20521 ["Priority Up" org-shiftup t]
20522 ["Priority Down" org-shiftdown t]
20523 "--"
20524 ["Get news from all feeds" org-feed-update-all t]
20525 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20526 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20527 ("TAGS and Properties"
20528 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20529 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20530 "--"
20531 ["Set property" org-set-property (not (org-before-first-heading-p))]
20532 ["Column view of properties" org-columns t]
20533 ["Insert Column View DBlock" org-insert-columns-dblock t])
20534 ("Dates and Scheduling"
20535 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20536 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20537 ("Change Date"
20538 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20539 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20540 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20541 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20542 ["Compute Time Range" org-evaluate-time-range t]
20543 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20544 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20545 "--"
20546 ["Custom time format" org-toggle-time-stamp-overlays
20547 :style radio :selected org-display-custom-times]
20548 "--"
20549 ["Goto Calendar" org-goto-calendar t]
20550 ["Date from Calendar" org-date-from-calendar t]
20551 "--"
20552 ["Start/Restart Timer" org-timer-start t]
20553 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20554 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20555 ["Insert Timer String" org-timer t]
20556 ["Insert Timer Item" org-timer-item t])
20557 ("Logging work"
20558 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20559 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20560 ["Clock out" org-clock-out t]
20561 ["Clock cancel" org-clock-cancel t]
20562 "--"
20563 ["Mark as default task" org-clock-mark-default-task t]
20564 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20565 ["Goto running clock" org-clock-goto t]
20566 "--"
20567 ["Display times" org-clock-display t]
20568 ["Create clock table" org-clock-report t]
20569 "--"
20570 ["Record DONE time"
20571 (progn (setq org-log-done (not org-log-done))
20572 (message "Switching to %s will %s record a timestamp"
20573 (car org-done-keywords)
20574 (if org-log-done "automatically" "not")))
20575 :style toggle :selected org-log-done])
20576 "--"
20577 ["Agenda Command..." org-agenda t]
20578 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20579 ("File List for Agenda")
20580 ("Special views current file"
20581 ["TODO Tree" org-show-todo-tree t]
20582 ["Check Deadlines" org-check-deadlines t]
20583 ["Timeline" org-timeline t]
20584 ["Tags/Property tree" org-match-sparse-tree t])
20585 "--"
20586 ["Export/Publish..." org-export-dispatch t]
20587 ("LaTeX"
20588 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20589 :selected org-cdlatex-mode]
20590 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20591 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20592 ["Modify math symbol" org-cdlatex-math-modify
20593 (org-inside-LaTeX-fragment-p)]
20594 ["Insert citation" org-reftex-citation t]
20595 "--"
20596 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20597 "--"
20598 ("MobileOrg"
20599 ["Push Files and Views" org-mobile-push t]
20600 ["Get Captured and Flagged" org-mobile-pull t]
20601 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20602 "--"
20603 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20604 "--"
20605 ("Documentation"
20606 ["Show Version" org-version t]
20607 ["Info Documentation" org-info t])
20608 ("Customize"
20609 ["Browse Org Group" org-customize t]
20610 "--"
20611 ["Expand This Menu" org-create-customize-menu
20612 (fboundp 'customize-menu-create)])
20613 ["Send bug report" org-submit-bug-report t]
20614 "--"
20615 ("Refresh/Reload"
20616 ["Refresh setup current buffer" org-mode-restart t]
20617 ["Reload Org (after update)" org-reload t]
20618 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20621 (defun org-info (&optional node)
20622 "Read documentation for Org-mode in the info system.
20623 With optional NODE, go directly to that node."
20624 (interactive)
20625 (info (format "(org)%s" (or node ""))))
20627 ;;;###autoload
20628 (defun org-submit-bug-report ()
20629 "Submit a bug report on Org-mode via mail.
20631 Don't hesitate to report any problems or inaccurate documentation.
20633 If you don't have setup sending mail from (X)Emacs, please copy the
20634 output buffer into your mail program, as it gives us important
20635 information about your Org-mode version and configuration."
20636 (interactive)
20637 (require 'reporter)
20638 (org-load-modules-maybe)
20639 (org-require-autoloaded-modules)
20640 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20641 (reporter-submit-bug-report
20642 "emacs-orgmode@gnu.org"
20643 (org-version nil 'full)
20644 (let (list)
20645 (save-window-excursion
20646 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20647 (delete-other-windows)
20648 (erase-buffer)
20649 (insert "You are about to submit a bug report to the Org-mode mailing list.
20651 We would like to add your full Org-mode and Outline configuration to the
20652 bug report. This greatly simplifies the work of the maintainer and
20653 other experts on the mailing list.
20655 HOWEVER, some variables you have customized may contain private
20656 information. The names of customers, colleagues, or friends, might
20657 appear in the form of file names, tags, todo states, or search strings.
20658 If you answer yes to the prompt, you might want to check and remove
20659 such private information before sending the email.")
20660 (add-text-properties (point-min) (point-max) '(face org-warning))
20661 (when (yes-or-no-p "Include your Org-mode configuration ")
20662 (mapatoms
20663 (lambda (v)
20664 (and (boundp v)
20665 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20666 (or (and (symbol-value v)
20667 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20668 (and
20669 (get v 'custom-type) (get v 'standard-value)
20670 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20671 (push v list)))))
20672 (kill-buffer (get-buffer "*Warn about privacy*"))
20673 list))
20674 nil nil
20675 "Remember to cover the basics, that is, what you expected to happen and
20676 what in fact did happen. You don't know how to make a good report? See
20678 http://orgmode.org/manual/Feedback.html#Feedback
20680 Your bug report will be posted to the Org-mode mailing list.
20681 ------------------------------------------------------------------------")
20682 (save-excursion
20683 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20684 (replace-match "\\1Bug: \\3 [\\2]")))))
20687 (defun org-install-agenda-files-menu ()
20688 (let ((bl (buffer-list)))
20689 (save-excursion
20690 (while bl
20691 (set-buffer (pop bl))
20692 (if (derived-mode-p 'org-mode) (setq bl nil)))
20693 (when (derived-mode-p 'org-mode)
20694 (easy-menu-change
20695 '("Org") "File List for Agenda"
20696 (append
20697 (list
20698 ["Edit File List" (org-edit-agenda-file-list) t]
20699 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20700 ["Remove Current File from List" org-remove-file t]
20701 ["Cycle through agenda files" org-cycle-agenda-files t]
20702 ["Occur in all agenda files" org-occur-in-agenda-files t]
20703 "--")
20704 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20706 ;;;; Documentation
20708 (defun org-require-autoloaded-modules ()
20709 (interactive)
20710 (mapc 'require
20711 '(org-agenda org-archive org-attach org-clock org-colview org-id
20712 org-remember org-table org-timer)))
20714 ;;;###autoload
20715 (defun org-reload (&optional uncompiled)
20716 "Reload all org lisp files.
20717 With prefix arg UNCOMPILED, load the uncompiled versions."
20718 (interactive "P")
20719 (require 'loadhist)
20720 (let* ((org-dir (org-find-library-dir "org"))
20721 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20722 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20723 (remove-re (mapconcat 'identity
20724 (mapcar (lambda (f) (concat "^" f "$"))
20725 (list (if (featurep 'xemacs)
20726 "org-colview"
20727 "org-colview-xemacs")
20728 "org" "org-loaddefs" "org-version"))
20729 "\\|"))
20730 (feats (delete-dups
20731 (mapcar 'file-name-sans-extension
20732 (mapcar 'file-name-nondirectory
20733 (delq nil
20734 (mapcar 'feature-file
20735 features))))))
20736 (lfeat (append
20737 (sort
20738 (setq feats
20739 (delq nil (mapcar
20740 (lambda (f)
20741 (if (and (string-match feature-re f)
20742 (not (string-match remove-re f)))
20743 f nil))
20744 feats)))
20745 'string-lessp)
20746 (list "org-version" "org")))
20747 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20748 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20749 load-uncore load-misses)
20750 (setq load-misses
20751 (delq 't
20752 (mapcar (lambda (f)
20753 (or (org-load-noerror-mustsuffix (concat org-dir f))
20754 (and (string= org-dir contrib-dir)
20755 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20756 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20757 (add-to-list 'load-uncore f 'append)
20760 lfeat)))
20761 (if load-uncore
20762 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20763 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20764 (if load-misses
20765 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20766 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20767 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20769 ;;;###autoload
20770 (defun org-customize ()
20771 "Call the customize function with org as argument."
20772 (interactive)
20773 (org-load-modules-maybe)
20774 (org-require-autoloaded-modules)
20775 (customize-browse 'org))
20777 (defun org-create-customize-menu ()
20778 "Create a full customization menu for Org-mode, insert it into the menu."
20779 (interactive)
20780 (org-load-modules-maybe)
20781 (org-require-autoloaded-modules)
20782 (if (fboundp 'customize-menu-create)
20783 (progn
20784 (easy-menu-change
20785 '("Org") "Customize"
20786 `(["Browse Org group" org-customize t]
20787 "--"
20788 ,(customize-menu-create 'org)
20789 ["Set" Custom-set t]
20790 ["Save" Custom-save t]
20791 ["Reset to Current" Custom-reset-current t]
20792 ["Reset to Saved" Custom-reset-saved t]
20793 ["Reset to Standard Settings" Custom-reset-standard t]))
20794 (message "\"Org\"-menu now contains full customization menu"))
20795 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20797 ;;;; Miscellaneous stuff
20799 ;;; Generally useful functions
20801 (defun org-get-at-bol (property)
20802 "Get text property PROPERTY at beginning of line."
20803 (get-text-property (point-at-bol) property))
20805 (defun org-find-text-property-in-string (prop s)
20806 "Return the first non-nil value of property PROP in string S."
20807 (or (get-text-property 0 prop s)
20808 (get-text-property (or (next-single-property-change 0 prop s) 0)
20809 prop s)))
20811 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20812 "Display the given MESSAGE as a warning."
20813 (if (fboundp 'display-warning)
20814 (display-warning 'org message
20815 (if (featurep 'xemacs) 'warning :warning))
20816 (let ((buf (get-buffer-create "*Org warnings*")))
20817 (with-current-buffer buf
20818 (goto-char (point-max))
20819 (insert "Warning (Org): " message)
20820 (unless (bolp)
20821 (newline)))
20822 (display-buffer buf)
20823 (sit-for 0))))
20825 (defun org-eval (form)
20826 "Eval FORM and return result."
20827 (condition-case error
20828 (eval form)
20829 (error (format "%%![Error: %s]" error))))
20831 (defun org-in-clocktable-p ()
20832 "Check if the cursor is in a clocktable."
20833 (let ((pos (point)) start)
20834 (save-excursion
20835 (end-of-line 1)
20836 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20837 (setq start (match-beginning 0))
20838 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20839 (>= (match-end 0) pos)
20840 start))))
20842 (defun org-in-commented-line ()
20843 "Is point in a line starting with `#'?"
20844 (equal (char-after (point-at-bol)) ?#))
20846 (defun org-in-indented-comment-line ()
20847 "Is point in a line starting with `#' after some white space?"
20848 (save-excursion
20849 (save-match-data
20850 (goto-char (point-at-bol))
20851 (looking-at "[ \t]*#"))))
20853 (defun org-in-verbatim-emphasis ()
20854 (save-match-data
20855 (and (org-in-regexp org-emph-re 2)
20856 (>= (point) (match-beginning 3))
20857 (<= (point) (match-end 4))
20858 (member (match-string 3) '("=" "~")))))
20860 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20861 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20862 (if (and marker (marker-buffer marker)
20863 (buffer-live-p (marker-buffer marker)))
20864 (progn
20865 (org-pop-to-buffer-same-window (marker-buffer marker))
20866 (if (or (> marker (point-max)) (< marker (point-min)))
20867 (widen))
20868 (goto-char marker)
20869 (org-show-context 'org-goto))
20870 (if bookmark
20871 (bookmark-jump bookmark)
20872 (error "Cannot find location"))))
20874 (defun org-quote-csv-field (s)
20875 "Quote field for inclusion in CSV material."
20876 (if (string-match "[\",]" s)
20877 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20880 (defun org-force-self-insert (N)
20881 "Needed to enforce self-insert under remapping."
20882 (interactive "p")
20883 (self-insert-command N))
20885 (defun org-string-width (s)
20886 "Compute width of string, ignoring invisible characters.
20887 This ignores character with invisibility property `org-link', and also
20888 characters with property `org-cwidth', because these will become invisible
20889 upon the next fontification round."
20890 (let (b l)
20891 (when (or (eq t buffer-invisibility-spec)
20892 (assq 'org-link buffer-invisibility-spec))
20893 (while (setq b (text-property-any 0 (length s)
20894 'invisible 'org-link s))
20895 (setq s (concat (substring s 0 b)
20896 (substring s (or (next-single-property-change
20897 b 'invisible s) (length s)))))))
20898 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20899 (setq s (concat (substring s 0 b)
20900 (substring s (or (next-single-property-change
20901 b 'org-cwidth s) (length s))))))
20902 (setq l (string-width s) b -1)
20903 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20904 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20907 (defun org-shorten-string (s maxlength)
20908 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20909 If the string is shorter or has length MAXLENGTH, just return the
20910 original string. If it is longer, the functions finds a space in the
20911 string, breaks this string off at that locations and adds three dots
20912 as ellipsis. Including the ellipsis, the string will not be longer
20913 than MAXLENGTH. If finding a good breaking point in the string does
20914 not work, the string is just chopped off in the middle of a word
20915 if necessary."
20916 (if (<= (length s) maxlength)
20918 (let* ((n (max (- maxlength 4) 1))
20919 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20920 (if (string-match re s)
20921 (concat (match-string 1 s) "...")
20922 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20924 (defun org-get-indentation (&optional line)
20925 "Get the indentation of the current line, interpreting tabs.
20926 When LINE is given, assume it represents a line and compute its indentation."
20927 (if line
20928 (if (string-match "^ *" (org-remove-tabs line))
20929 (match-end 0))
20930 (save-excursion
20931 (beginning-of-line 1)
20932 (skip-chars-forward " \t")
20933 (current-column))))
20935 (defun org-get-string-indentation (s)
20936 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20937 (let ((n -1) (i 0) (w tab-width) c)
20938 (catch 'exit
20939 (while (< (setq n (1+ n)) (length s))
20940 (setq c (aref s n))
20941 (cond ((= c ?\ ) (setq i (1+ i)))
20942 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20943 (t (throw 'exit t)))))
20946 (defun org-remove-tabs (s &optional width)
20947 "Replace tabulators in S with spaces.
20948 Assumes that s is a single line, starting in column 0."
20949 (setq width (or width tab-width))
20950 (while (string-match "\t" s)
20951 (setq s (replace-match
20952 (make-string
20953 (- (* width (/ (+ (match-beginning 0) width) width))
20954 (match-beginning 0)) ?\ )
20955 t t s)))
20958 (defun org-fix-indentation (line ind)
20959 "Fix indentation in LINE.
20960 IND is a cons cell with target and minimum indentation.
20961 If the current indentation in LINE is smaller than the minimum,
20962 leave it alone. If it is larger than ind, set it to the target."
20963 (let* ((l (org-remove-tabs line))
20964 (i (org-get-indentation l))
20965 (i1 (car ind)) (i2 (cdr ind)))
20966 (if (>= i i2) (setq l (substring line i2)))
20967 (if (> i1 0)
20968 (concat (make-string i1 ?\ ) l)
20969 l)))
20971 (defun org-remove-indentation (code &optional n)
20972 "Remove the maximum common indentation from the lines in CODE.
20973 N may optionally be the number of spaces to remove."
20974 (with-temp-buffer
20975 (insert code)
20976 (org-do-remove-indentation n)
20977 (buffer-string)))
20979 (defun org-do-remove-indentation (&optional n)
20980 "Remove the maximum common indentation from the buffer."
20981 (untabify (point-min) (point-max))
20982 (let ((min 10000) re)
20983 (if n
20984 (setq min n)
20985 (goto-char (point-min))
20986 (while (re-search-forward "^ *[^ \n]" nil t)
20987 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20988 (unless (or (= min 0) (= min 10000))
20989 (setq re (format "^ \\{%d\\}" min))
20990 (goto-char (point-min))
20991 (while (re-search-forward re nil t)
20992 (replace-match "")
20993 (end-of-line 1))
20994 min)))
20996 (defun org-fill-template (template alist)
20997 "Find each %key of ALIST in TEMPLATE and replace it."
20998 (let ((case-fold-search nil)
20999 entry key value)
21000 (setq alist (sort (copy-sequence alist)
21001 (lambda (a b) (< (length (car a)) (length (car b))))))
21002 (while (setq entry (pop alist))
21003 (setq template
21004 (replace-regexp-in-string
21005 (concat "%" (regexp-quote (car entry)))
21006 (or (cdr entry) "") template t t)))
21007 template))
21009 (defun org-base-buffer (buffer)
21010 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21011 (if (not buffer)
21012 buffer
21013 (or (buffer-base-buffer buffer)
21014 buffer)))
21016 (defun org-trim (s)
21017 "Remove whitespace at beginning and end of string."
21018 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21019 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21022 (defun org-wrap (string &optional width lines)
21023 "Wrap string to either a number of lines, or a width in characters.
21024 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21025 that costs. If there is a word longer than WIDTH, the text is actually
21026 wrapped to the length of that word.
21027 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21028 many lines, whatever width that takes.
21029 The return value is a list of lines, without newlines at the end."
21030 (let* ((words (org-split-string string "[ \t\n]+"))
21031 (maxword (apply 'max (mapcar 'org-string-width words)))
21032 w ll)
21033 (cond (width
21034 (org-do-wrap words (max maxword width)))
21035 (lines
21036 (setq w maxword)
21037 (setq ll (org-do-wrap words maxword))
21038 (if (<= (length ll) lines)
21040 (setq ll words)
21041 (while (> (length ll) lines)
21042 (setq w (1+ w))
21043 (setq ll (org-do-wrap words w)))
21044 ll))
21045 (t (error "Cannot wrap this")))))
21047 (defun org-do-wrap (words width)
21048 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21049 (let (lines line)
21050 (while words
21051 (setq line (pop words))
21052 (while (and words (< (+ (length line) (length (car words))) width))
21053 (setq line (concat line " " (pop words))))
21054 (setq lines (push line lines)))
21055 (nreverse lines)))
21057 (defun org-split-string (string &optional separators)
21058 "Splits STRING into substrings at SEPARATORS.
21059 No empty strings are returned if there are matches at the beginning
21060 and end of string."
21061 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21062 (start 0)
21063 notfirst
21064 (list nil))
21065 (while (and (string-match rexp string
21066 (if (and notfirst
21067 (= start (match-beginning 0))
21068 (< start (length string)))
21069 (1+ start) start))
21070 (< (match-beginning 0) (length string)))
21071 (setq notfirst t)
21072 (or (eq (match-beginning 0) 0)
21073 (and (eq (match-beginning 0) (match-end 0))
21074 (eq (match-beginning 0) start))
21075 (setq list
21076 (cons (substring string start (match-beginning 0))
21077 list)))
21078 (setq start (match-end 0)))
21079 (or (eq start (length string))
21080 (setq list
21081 (cons (substring string start)
21082 list)))
21083 (nreverse list)))
21085 (defun org-quote-vert (s)
21086 "Replace \"|\" with \"\\vert\"."
21087 (while (string-match "|" s)
21088 (setq s (replace-match "\\vert" t t s)))
21091 (defun org-uuidgen-p (s)
21092 "Is S an ID created by UUIDGEN?"
21093 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21095 (defun org-in-src-block-p (&optional inside)
21096 "Whether point is in a code source block.
21097 When INSIDE is non-nil, don't consider we are within a src block
21098 when point is at #+BEGIN_SRC or #+END_SRC."
21099 (let ((case-fold-search t) ov)
21100 (or (and (setq ov (overlays-at (point)))
21101 (memq 'org-block-background
21102 (overlay-properties (car ov))))
21103 (and (not inside)
21104 (save-match-data
21105 (save-excursion
21106 (beginning-of-line)
21107 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21109 (defun org-context ()
21110 "Return a list of contexts of the current cursor position.
21111 If several contexts apply, all are returned.
21112 Each context entry is a list with a symbol naming the context, and
21113 two positions indicating start and end of the context. Possible
21114 contexts are:
21116 :headline anywhere in a headline
21117 :headline-stars on the leading stars in a headline
21118 :todo-keyword on a TODO keyword (including DONE) in a headline
21119 :tags on the TAGS in a headline
21120 :priority on the priority cookie in a headline
21121 :item on the first line of a plain list item
21122 :item-bullet on the bullet/number of a plain list item
21123 :checkbox on the checkbox in a plain list item
21124 :table in an org-mode table
21125 :table-special on a special filed in a table
21126 :table-table in a table.el table
21127 :clocktable in a clocktable
21128 :src-block in a source block
21129 :link on a hyperlink
21130 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21131 :target on a <<target>>
21132 :radio-target on a <<<radio-target>>>
21133 :latex-fragment on a LaTeX fragment
21134 :latex-preview on a LaTeX fragment with overlaid preview image
21136 This function expects the position to be visible because it uses font-lock
21137 faces as a help to recognize the following contexts: :table-special, :link,
21138 and :keyword."
21139 (let* ((f (get-text-property (point) 'face))
21140 (faces (if (listp f) f (list f)))
21141 (case-fold-search t)
21142 (p (point)) clist o)
21143 ;; First the large context
21144 (cond
21145 ((org-at-heading-p t)
21146 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21147 (when (progn
21148 (beginning-of-line 1)
21149 (looking-at org-todo-line-tags-regexp))
21150 (push (org-point-in-group p 1 :headline-stars) clist)
21151 (push (org-point-in-group p 2 :todo-keyword) clist)
21152 (push (org-point-in-group p 4 :tags) clist))
21153 (goto-char p)
21154 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21155 (if (looking-at "\\[#[A-Z0-9]\\]")
21156 (push (org-point-in-group p 0 :priority) clist)))
21158 ((org-at-item-p)
21159 (push (org-point-in-group p 2 :item-bullet) clist)
21160 (push (list :item (point-at-bol)
21161 (save-excursion (org-end-of-item) (point)))
21162 clist)
21163 (and (org-at-item-checkbox-p)
21164 (push (org-point-in-group p 0 :checkbox) clist)))
21166 ((org-at-table-p)
21167 (push (list :table (org-table-begin) (org-table-end)) clist)
21168 (if (memq 'org-formula faces)
21169 (push (list :table-special
21170 (previous-single-property-change p 'face)
21171 (next-single-property-change p 'face)) clist)))
21172 ((org-at-table-p 'any)
21173 (push (list :table-table) clist)))
21174 (goto-char p)
21176 (let ((case-fold-search t))
21177 ;; New the "medium" contexts: clocktables, source blocks
21178 (cond ((org-in-clocktable-p)
21179 (push (list :clocktable
21180 (and (or (looking-at "#\\+BEGIN: clocktable")
21181 (search-backward "#+BEGIN: clocktable" nil t))
21182 (match-beginning 0))
21183 (and (re-search-forward "#\\+END:?" nil t)
21184 (match-end 0))) clist))
21185 ((org-in-src-block-p)
21186 (push (list :src-block
21187 (and (or (looking-at "#\\+BEGIN_SRC")
21188 (search-backward "#+BEGIN_SRC" nil t))
21189 (match-beginning 0))
21190 (and (search-forward "#+END_SRC" nil t)
21191 (match-beginning 0))) clist))))
21192 (goto-char p)
21194 ;; Now the small context
21195 (cond
21196 ((org-at-timestamp-p)
21197 (push (org-point-in-group p 0 :timestamp) clist))
21198 ((memq 'org-link faces)
21199 (push (list :link
21200 (previous-single-property-change p 'face)
21201 (next-single-property-change p 'face)) clist))
21202 ((memq 'org-special-keyword faces)
21203 (push (list :keyword
21204 (previous-single-property-change p 'face)
21205 (next-single-property-change p 'face)) clist))
21206 ((org-at-target-p)
21207 (push (org-point-in-group p 0 :target) clist)
21208 (goto-char (1- (match-beginning 0)))
21209 (if (looking-at org-radio-target-regexp)
21210 (push (org-point-in-group p 0 :radio-target) clist))
21211 (goto-char p))
21212 ((setq o (car (delq nil
21213 (mapcar
21214 (lambda (x)
21215 (if (memq x org-latex-fragment-image-overlays) x))
21216 (overlays-at (point))))))
21217 (push (list :latex-fragment
21218 (overlay-start o) (overlay-end o)) clist)
21219 (push (list :latex-preview
21220 (overlay-start o) (overlay-end o)) clist))
21221 ((org-inside-LaTeX-fragment-p)
21222 ;; FIXME: positions wrong.
21223 (push (list :latex-fragment (point) (point)) clist)))
21225 (setq clist (nreverse (delq nil clist)))
21226 clist))
21228 ;; FIXME: Compare with at-regexp-p Do we need both?
21229 (defun org-in-regexp (re &optional nlines visually)
21230 "Check if point is inside a match of regexp.
21231 Normally only the current line is checked, but you can include NLINES extra
21232 lines both before and after point into the search.
21233 If VISUALLY is set, require that the cursor is not after the match but
21234 really on, so that the block visually is on the match."
21235 (catch 'exit
21236 (let ((pos (point))
21237 (eol (point-at-eol (+ 1 (or nlines 0))))
21238 (inc (if visually 1 0)))
21239 (save-excursion
21240 (beginning-of-line (- 1 (or nlines 0)))
21241 (while (re-search-forward re eol t)
21242 (if (and (<= (match-beginning 0) pos)
21243 (>= (+ inc (match-end 0)) pos))
21244 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21246 (defun org-at-regexp-p (regexp)
21247 "Is point inside a match of REGEXP in the current line?"
21248 (catch 'exit
21249 (save-excursion
21250 (let ((pos (point)) (end (point-at-eol)))
21251 (beginning-of-line 1)
21252 (while (re-search-forward regexp end t)
21253 (if (and (<= (match-beginning 0) pos)
21254 (>= (match-end 0) pos))
21255 (throw 'exit t)))
21256 nil))))
21258 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21259 "Non-nil when point is between matches of START-RE and END-RE.
21261 Also return a non-nil value when point is on one of the matches.
21263 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21264 buffer positions. Default values are the positions of headlines
21265 surrounding the point.
21267 The functions returns a cons cell whose car (resp. cdr) is the
21268 position before START-RE (resp. after END-RE)."
21269 (save-match-data
21270 (let ((pos (point))
21271 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21272 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21273 beg end)
21274 (save-excursion
21275 ;; Point is on a block when on START-RE or if START-RE can be
21276 ;; found before it...
21277 (and (or (org-at-regexp-p start-re)
21278 (re-search-backward start-re limit-up t))
21279 (setq beg (match-beginning 0))
21280 ;; ... and END-RE after it...
21281 (goto-char (match-end 0))
21282 (re-search-forward end-re limit-down t)
21283 (> (setq end (match-end 0)) pos)
21284 ;; ... without another START-RE in-between.
21285 (goto-char (match-beginning 0))
21286 (not (re-search-backward start-re (1+ beg) t))
21287 ;; Return value.
21288 (cons beg end))))))
21290 (defun org-in-block-p (names)
21291 "Non-nil when point belongs to a block whose name belongs to NAMES.
21293 NAMES is a list of strings containing names of blocks.
21295 Return first block name matched, or nil. Beware that in case of
21296 nested blocks, the returned name may not belong to the closest
21297 block from point."
21298 (save-match-data
21299 (catch 'exit
21300 (let ((case-fold-search t)
21301 (lim-up (save-excursion (outline-previous-heading)))
21302 (lim-down (save-excursion (outline-next-heading))))
21303 (mapc (lambda (name)
21304 (let ((n (regexp-quote name)))
21305 (when (org-between-regexps-p
21306 (concat "^[ \t]*#\\+begin_" n)
21307 (concat "^[ \t]*#\\+end_" n)
21308 lim-up lim-down)
21309 (throw 'exit n))))
21310 names))
21311 nil)))
21313 (defun org-occur-in-agenda-files (regexp &optional nlines)
21314 "Call `multi-occur' with buffers for all agenda files."
21315 (interactive "sOrg-files matching: \np")
21316 (let* ((files (org-agenda-files))
21317 (tnames (mapcar 'file-truename files))
21318 (extra org-agenda-text-search-extra-files)
21320 (when (eq (car extra) 'agenda-archives)
21321 (setq extra (cdr extra))
21322 (setq files (org-add-archive-files files)))
21323 (while (setq f (pop extra))
21324 (unless (member (file-truename f) tnames)
21325 (add-to-list 'files f 'append)
21326 (add-to-list 'tnames (file-truename f) 'append)))
21327 (multi-occur
21328 (mapcar (lambda (x)
21329 (with-current-buffer
21330 (or (get-file-buffer x) (find-file-noselect x))
21331 (widen)
21332 (current-buffer)))
21333 files)
21334 regexp)))
21336 (if (boundp 'occur-mode-find-occurrence-hook)
21337 ;; Emacs 23
21338 (add-hook 'occur-mode-find-occurrence-hook
21339 (lambda ()
21340 (when (derived-mode-p 'org-mode)
21341 (org-reveal))))
21342 ;; Emacs 22
21343 (defadvice occur-mode-goto-occurrence
21344 (after org-occur-reveal activate)
21345 (and (derived-mode-p 'org-mode) (org-reveal)))
21346 (defadvice occur-mode-goto-occurrence-other-window
21347 (after org-occur-reveal activate)
21348 (and (derived-mode-p 'org-mode) (org-reveal)))
21349 (defadvice occur-mode-display-occurrence
21350 (after org-occur-reveal activate)
21351 (when (derived-mode-p 'org-mode)
21352 (let ((pos (occur-mode-find-occurrence)))
21353 (with-current-buffer (marker-buffer pos)
21354 (save-excursion
21355 (goto-char pos)
21356 (org-reveal)))))))
21358 (defun org-occur-link-in-agenda-files ()
21359 "Create a link and search for it in the agendas.
21360 The link is not stored in `org-stored-links', it is just created
21361 for the search purpose."
21362 (interactive)
21363 (let ((link (condition-case nil
21364 (org-store-link nil)
21365 (error "Unable to create a link to here"))))
21366 (org-occur-in-agenda-files (regexp-quote link))))
21368 (defun org-reverse-string (string)
21369 "Return the reverse of STRING."
21370 (apply 'string (reverse (string-to-list string))))
21372 (defun org-uniquify (list)
21373 "Remove duplicate elements from LIST."
21374 (let (res)
21375 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21376 res))
21378 (defun org-delete-all (elts list)
21379 "Remove all elements in ELTS from LIST."
21380 (while elts
21381 (setq list (delete (pop elts) list)))
21382 list)
21384 (defun org-count (cl-item cl-seq)
21385 "Count the number of occurrences of ITEM in SEQ.
21386 Taken from `count' in cl-seq.el with all keyword arguments removed."
21387 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21388 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21389 (while (< cl-start cl-end)
21390 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21391 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21392 (setq cl-start (1+ cl-start)))
21393 cl-count))
21395 (defun org-remove-if (predicate seq)
21396 "Remove everything from SEQ that fulfills PREDICATE."
21397 (let (res e)
21398 (while seq
21399 (setq e (pop seq))
21400 (if (not (funcall predicate e)) (push e res)))
21401 (nreverse res)))
21403 (defun org-remove-if-not (predicate seq)
21404 "Remove everything from SEQ that does not fulfill PREDICATE."
21405 (let (res e)
21406 (while seq
21407 (setq e (pop seq))
21408 (if (funcall predicate e) (push e res)))
21409 (nreverse res)))
21411 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21412 "Reduce two-argument FUNCTION across SEQ.
21413 Taken from `reduce' in cl-seq.el with all keyword arguments but
21414 \":initial-value\" removed."
21415 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21416 (cadr (memq :initial-value cl-keys)))
21417 (cl-seq (pop cl-seq))
21418 (t (funcall cl-func)))))
21419 (while cl-seq
21420 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21421 cl-accum))
21423 (defun org-back-over-empty-lines ()
21424 "Move backwards over whitespace, to the beginning of the first empty line.
21425 Returns the number of empty lines passed."
21426 (let ((pos (point)))
21427 (if (cdr (assoc 'heading org-blank-before-new-entry))
21428 (skip-chars-backward " \t\n\r")
21429 (unless (eobp)
21430 (forward-line -1)))
21431 (beginning-of-line 2)
21432 (goto-char (min (point) pos))
21433 (count-lines (point) pos)))
21435 (defun org-skip-whitespace ()
21436 (skip-chars-forward " \t\n\r"))
21438 (defun org-point-in-group (point group &optional context)
21439 "Check if POINT is in match-group GROUP.
21440 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21441 match. If the match group does not exist or point is not inside it,
21442 return nil."
21443 (and (match-beginning group)
21444 (>= point (match-beginning group))
21445 (<= point (match-end group))
21446 (if context
21447 (list context (match-beginning group) (match-end group))
21448 t)))
21450 (defun org-switch-to-buffer-other-window (&rest args)
21451 "Switch to buffer in a second window on the current frame.
21452 In particular, do not allow pop-up frames.
21453 Returns the newly created buffer."
21454 (org-no-popups
21455 (apply 'switch-to-buffer-other-window args)))
21457 (defun org-combine-plists (&rest plists)
21458 "Create a single property list from all plists in PLISTS.
21459 The process starts by copying the first list, and then setting properties
21460 from the other lists. Settings in the last list are the most significant
21461 ones and overrule settings in the other lists."
21462 (let ((rtn (copy-sequence (pop plists)))
21463 p v ls)
21464 (while plists
21465 (setq ls (pop plists))
21466 (while ls
21467 (setq p (pop ls) v (pop ls))
21468 (setq rtn (plist-put rtn p v))))
21469 rtn))
21471 (defun org-replace-escapes (string table)
21472 "Replace %-escapes in STRING with values in TABLE.
21473 TABLE is an association list with keys like \"%a\" and string values.
21474 The sequences in STRING may contain normal field width and padding information,
21475 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21476 so values can contain further %-escapes if they are define later in TABLE."
21477 (let ((tbl (copy-alist table))
21478 (case-fold-search nil)
21479 (pchg 0)
21480 e re rpl)
21481 (while (setq e (pop tbl))
21482 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21483 (when (and (cdr e) (string-match re (cdr e)))
21484 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21485 (safe "SREF"))
21486 (add-text-properties 0 3 (list 'sref sref) safe)
21487 (setcdr e (replace-match safe t t (cdr e)))))
21488 (while (string-match re string)
21489 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21490 (cdr e)))
21491 (setq string (replace-match rpl t t string))))
21492 (while (setq pchg (next-property-change pchg string))
21493 (let ((sref (get-text-property pchg 'sref string)))
21494 (when (and sref (string-match "SREF" string pchg))
21495 (setq string (replace-match sref t t string)))))
21496 string))
21498 (defun org-sublist (list start end)
21499 "Return a section of LIST, from START to END.
21500 Counting starts at 1."
21501 (let (rtn (c start))
21502 (setq list (nthcdr (1- start) list))
21503 (while (and list (<= c end))
21504 (push (pop list) rtn)
21505 (setq c (1+ c)))
21506 (nreverse rtn)))
21508 (defun org-find-base-buffer-visiting (file)
21509 "Like `find-buffer-visiting' but always return the base buffer and
21510 not an indirect buffer."
21511 (let ((buf (or (get-file-buffer file)
21512 (find-buffer-visiting file))))
21513 (if buf
21514 (or (buffer-base-buffer buf) buf)
21515 nil)))
21517 (defun org-image-file-name-regexp (&optional extensions)
21518 "Return regexp matching the file names of images.
21519 If EXTENSIONS is given, only match these."
21520 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21521 (image-file-name-regexp)
21522 (let ((image-file-name-extensions
21523 (or extensions
21524 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21525 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21526 (concat "\\."
21527 (regexp-opt (nconc (mapcar 'upcase
21528 image-file-name-extensions)
21529 image-file-name-extensions)
21531 "\\'"))))
21533 (defun org-file-image-p (file &optional extensions)
21534 "Return non-nil if FILE is an image."
21535 (save-match-data
21536 (string-match (org-image-file-name-regexp extensions) file)))
21538 (defun org-get-cursor-date (&optional with-time)
21539 "Return the date at cursor in as a time.
21540 This works in the calendar and in the agenda, anywhere else it just
21541 returns the current time.
21542 If WITH-TIME is non-nil, returns the time of the event at point (in
21543 the agenda) or the current time of the day."
21544 (let (date day defd tp tm hod mod)
21545 (when with-time
21546 (setq tp (get-text-property (point) 'time))
21547 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21548 (setq hod (string-to-number (match-string 1 tp))
21549 mod (string-to-number (match-string 2 tp))))
21550 (or tp (setq hod (nth 2 (decode-time (current-time)))
21551 mod (nth 1 (decode-time (current-time))))))
21552 (cond
21553 ((eq major-mode 'calendar-mode)
21554 (setq date (calendar-cursor-to-date)
21555 defd (encode-time 0 (or mod 0) (or hod 0)
21556 (nth 1 date) (nth 0 date) (nth 2 date))))
21557 ((eq major-mode 'org-agenda-mode)
21558 (setq day (get-text-property (point) 'day))
21559 (if day
21560 (setq date (calendar-gregorian-from-absolute day)
21561 defd (encode-time 0 (or mod 0) (or hod 0)
21562 (nth 1 date) (nth 0 date) (nth 2 date))))))
21563 (or defd (current-time))))
21565 (defun org-mark-subtree (&optional up)
21566 "Mark the current subtree.
21567 This puts point at the start of the current subtree, and mark at
21568 the end. If a numeric prefix UP is given, move up into the
21569 hierarchy of headlines by UP levels before marking the subtree."
21570 (interactive "P")
21571 (org-with-limited-levels
21572 (cond ((org-at-heading-p) (beginning-of-line))
21573 ((org-before-first-heading-p) (error "Not in a subtree"))
21574 (t (outline-previous-visible-heading 1))))
21575 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21576 (if (org-called-interactively-p 'any)
21577 (call-interactively 'org-mark-element)
21578 (org-mark-element)))
21581 ;;; Indentation
21583 (defun org-indent-line ()
21584 "Indent line depending on context."
21585 (interactive)
21586 (let* ((pos (point))
21587 (itemp (org-at-item-p))
21588 (case-fold-search t)
21589 (org-drawer-regexp (or org-drawer-regexp "\000"))
21590 (inline-task-p (and (featurep 'org-inlinetask)
21591 (org-inlinetask-in-task-p)))
21592 (inline-re (and inline-task-p
21593 (org-inlinetask-outline-regexp)))
21594 column)
21595 (if (and orgstruct-is-++ (eq pos (point)))
21596 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21597 (indent-according-to-mode))
21598 (beginning-of-line 1)
21599 (cond
21600 ;; Headings
21601 ((looking-at org-outline-regexp) (setq column 0))
21602 ;; Footnote definition
21603 ((looking-at org-footnote-definition-re) (setq column 0))
21604 ;; Literal examples
21605 ((looking-at "[ \t]*:\\( \\|$\\)")
21606 (setq column (org-get-indentation))) ; do nothing
21607 ;; Lists
21608 ((ignore-errors (goto-char (org-in-item-p)))
21609 (setq column (if itemp
21610 (org-get-indentation)
21611 (org-list-item-body-column (point))))
21612 (goto-char pos))
21613 ;; Drawers
21614 ((and (looking-at "[ \t]*:END:")
21615 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21616 (save-excursion
21617 (goto-char (1- (match-beginning 1)))
21618 (setq column (current-column))))
21619 ;; Special blocks
21620 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21621 (save-excursion
21622 (re-search-backward
21623 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21624 (setq column (org-get-indentation (match-string 0))))
21625 ((and (not (looking-at "[ \t]*#\\+begin_"))
21626 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21627 (save-excursion
21628 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21629 (setq column
21630 (cond ((equal (downcase (match-string 1)) "src")
21631 ;; src blocks: let `org-edit-src-exit' handle them
21632 (org-get-indentation))
21633 ((equal (downcase (match-string 1)) "example")
21634 (max (org-get-indentation)
21635 (org-get-indentation (match-string 0))))
21637 (org-get-indentation (match-string 0))))))
21638 ;; This line has nothing special, look at the previous relevant
21639 ;; line to compute indentation
21641 (beginning-of-line 0)
21642 (while (and (not (bobp))
21643 (not (looking-at org-table-line-regexp))
21644 (not (looking-at org-drawer-regexp))
21645 ;; When point started in an inline task, do not move
21646 ;; above task starting line.
21647 (not (and inline-task-p (looking-at inline-re)))
21648 ;; Skip drawers, blocks, empty lines, verbatim,
21649 ;; comments, tables, footnotes definitions, lists,
21650 ;; inline tasks.
21651 (or (and (looking-at "[ \t]*:END:")
21652 (re-search-backward org-drawer-regexp nil t))
21653 (and (looking-at "[ \t]*#\\+end_")
21654 (re-search-backward "[ \t]*#\\+begin_"nil t))
21655 (looking-at "[ \t]*[\n:#|]")
21656 (looking-at org-footnote-definition-re)
21657 (and (ignore-errors (goto-char (org-in-item-p)))
21658 (goto-char
21659 (org-list-get-top-point (org-list-struct))))
21660 (and (not inline-task-p)
21661 (featurep 'org-inlinetask)
21662 (org-inlinetask-in-task-p)
21663 (or (org-inlinetask-goto-beginning) t))))
21664 (beginning-of-line 0))
21665 (cond
21666 ;; There was an heading above.
21667 ((looking-at "\\*+[ \t]+")
21668 (if (not org-adapt-indentation)
21669 (setq column 0)
21670 (goto-char (match-end 0))
21671 (setq column (current-column))))
21672 ;; A drawer had started and is unfinished
21673 ((looking-at org-drawer-regexp)
21674 (goto-char (1- (match-beginning 1)))
21675 (setq column (current-column)))
21676 ;; Else, nothing noticeable found: get indentation and go on.
21677 (t (setq column (org-get-indentation))))))
21678 ;; Now apply indentation and move cursor accordingly
21679 (goto-char pos)
21680 (if (<= (current-column) (current-indentation))
21681 (org-indent-line-to column)
21682 (save-excursion (org-indent-line-to column)))
21683 ;; Special polishing for properties, see `org-property-format'
21684 (setq column (current-column))
21685 (beginning-of-line 1)
21686 (if (looking-at
21687 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21688 (replace-match (concat (match-string 1)
21689 (format org-property-format
21690 (match-string 2) (match-string 3)))
21691 t t))
21692 (org-move-to-column column))))
21694 (defun org-indent-drawer ()
21695 "Indent the drawer at point."
21696 (interactive)
21697 (let ((p (point))
21698 (e (and (save-excursion (re-search-forward ":END:" nil t))
21699 (match-end 0)))
21700 (folded
21701 (save-excursion
21702 (end-of-line)
21703 (when (overlays-at (point))
21704 (member 'invisible (overlay-properties
21705 (car (overlays-at (point)))))))))
21706 (when folded (org-cycle))
21707 (indent-for-tab-command)
21708 (while (and (move-beginning-of-line 2) (< (point) e))
21709 (indent-for-tab-command))
21710 (goto-char p)
21711 (when folded (org-cycle)))
21712 (message "Drawer at point indented"))
21714 (defun org-indent-block ()
21715 "Indent the block at point."
21716 (interactive)
21717 (let ((p (point))
21718 (case-fold-search t)
21719 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21720 (match-end 0)))
21721 (folded
21722 (save-excursion
21723 (end-of-line)
21724 (when (overlays-at (point))
21725 (member 'invisible (overlay-properties
21726 (car (overlays-at (point)))))))))
21727 (when folded (org-cycle))
21728 (indent-for-tab-command)
21729 (while (and (move-beginning-of-line 2) (< (point) e))
21730 (indent-for-tab-command))
21731 (goto-char p)
21732 (when folded (org-cycle)))
21733 (message "Block at point indented"))
21735 (defun org-indent-region (start end)
21736 "Indent region."
21737 (interactive "r")
21738 (save-excursion
21739 (let ((line-end (org-current-line end)))
21740 (goto-char start)
21741 (while (< (org-current-line) line-end)
21742 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21743 (t (call-interactively 'org-indent-line)))
21744 (move-beginning-of-line 2)))))
21747 ;;; Filling
21749 ;; We use our own fill-paragraph and auto-fill functions.
21751 ;; `org-fill-paragraph' relies on adaptive filling and context
21752 ;; checking. Appropriate `fill-prefix' is computed with
21753 ;; `org-adaptive-fill-function'.
21755 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21756 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21757 ;; `org-adaptive-fill-function' value. Internally,
21758 ;; `org-comment-line-break-function' breaks the line.
21760 ;; `org-setup-filling' installs filling and auto-filling related
21761 ;; variables during `org-mode' initialization.
21763 (defun org-setup-filling ()
21764 (interactive)
21765 ;; Prevent auto-fill from inserting unwanted new items.
21766 (when (boundp 'fill-nobreak-predicate)
21767 (org-set-local
21768 'fill-nobreak-predicate
21769 (org-uniquify
21770 (append fill-nobreak-predicate
21771 '(org-fill-paragraph-separate-nobreak-p
21772 org-fill-line-break-nobreak-p
21773 org-fill-paragraph-with-timestamp-nobreak-p)))))
21774 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21775 (org-set-local 'auto-fill-inhibit-regexp nil)
21776 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21777 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21778 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21780 (defvar org-element-paragraph-separate) ; org-element.el
21781 (defun org-fill-paragraph-separate-nobreak-p ()
21782 "Non-nil when a line break at point would insert a new item."
21783 (looking-at (substring org-element-paragraph-separate 1)))
21785 (defun org-fill-line-break-nobreak-p ()
21786 "Non-nil when a line break at point would create an Org line break."
21787 (save-excursion
21788 (skip-chars-backward "[ \t]")
21789 (skip-chars-backward "\\\\")
21790 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21792 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21793 "Non-nil when a line break at point would insert a new item."
21794 (and (org-at-timestamp-p t)
21795 (not (looking-at org-ts-regexp-both))))
21797 (declare-function message-in-body-p "message" ())
21798 (defvar orgtbl-line-start-regexp) ; From org-table.el
21799 (defun org-adaptive-fill-function ()
21800 "Compute a fill prefix for the current line.
21801 Return fill prefix, as a string, or nil if current line isn't
21802 meant to be filled."
21803 (let (prefix)
21804 (catch 'exit
21805 (when (derived-mode-p 'message-mode)
21806 (save-excursion
21807 (beginning-of-line)
21808 (cond ((or (not (message-in-body-p))
21809 (looking-at orgtbl-line-start-regexp))
21810 (throw 'exit nil))
21811 ((looking-at message-cite-prefix-regexp)
21812 (throw 'exit (match-string-no-properties 0)))
21813 ((looking-at org-outline-regexp)
21814 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21815 (org-with-wide-buffer
21816 (let* ((p (line-beginning-position))
21817 (element (save-excursion (beginning-of-line)
21818 (org-element-at-point)))
21819 (type (org-element-type element))
21820 (post-affiliated (org-element-property :post-affiliated element)))
21821 (unless (and post-affiliated (< p post-affiliated))
21822 (case type
21823 (comment (looking-at "[ \t]*# ?") (match-string 0))
21824 (footnote-definition "")
21825 ((item plain-list)
21826 (make-string (org-list-item-body-column
21827 (or post-affiliated
21828 (org-element-property :begin element)))
21829 ? ))
21830 (paragraph
21831 ;; Fill prefix is usually the same as the current line,
21832 ;; except if the paragraph is at the beginning of an item.
21833 (let ((parent (org-element-property :parent element)))
21834 (cond ((eq (org-element-type parent) 'item)
21835 (make-string (org-list-item-body-column
21836 (org-element-property :begin parent))
21837 ? ))
21838 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21839 (match-string 0))
21840 (t ""))))
21841 (comment-block
21842 ;; Only fill contents if P is within block boundaries.
21843 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21844 (forward-line)
21845 (point)))
21846 (cend (save-excursion
21847 (goto-char (org-element-property :end element))
21848 (skip-chars-backward " \r\t\n")
21849 (line-beginning-position))))
21850 (when (and (>= p cbeg) (< p cend))
21851 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21852 (match-string 0)
21853 "")))))))))))
21855 (declare-function message-goto-body "message" ())
21856 (defvar message-cite-prefix-regexp) ; From message.el
21857 (defun org-fill-paragraph (&optional justify)
21858 "Fill element at point, when applicable.
21860 This function only applies to comment blocks, comments, example
21861 blocks and paragraphs. Also, as a special case, re-align table
21862 when point is at one.
21864 If JUSTIFY is non-nil (interactively, with prefix argument),
21865 justify as well. If `sentence-end-double-space' is non-nil, then
21866 period followed by one space does not end a sentence, so don't
21867 break a line there. The variable `fill-column' controls the
21868 width for filling.
21870 For convenience, when point is at a plain list, an item or
21871 a footnote definition, try to fill the first paragraph within."
21872 (interactive)
21873 (if (and (derived-mode-p 'message-mode)
21874 (or (not (message-in-body-p))
21875 (save-excursion (move-beginning-of-line 1)
21876 (looking-at message-cite-prefix-regexp))))
21877 ;; First ensure filling is correct in message-mode.
21878 (let ((fill-paragraph-function
21879 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21880 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21881 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21882 (paragraph-separate
21883 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21884 (fill-paragraph nil))
21885 (with-syntax-table org-mode-transpose-word-syntax-table
21886 ;; Move to end of line in order to get the first paragraph
21887 ;; within a plain list or a footnote definition.
21888 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21889 ;; First check if point is in a blank line at the beginning of
21890 ;; the buffer. In that case, ignore filling.
21891 (case (org-element-type element)
21892 ;; Use major mode filling function is src blocks.
21893 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21894 ;; Align Org tables, leave table.el tables as-is.
21895 (table-row (org-table-align) t)
21896 (table
21897 (when (eq (org-element-property :type element) 'org)
21898 (org-table-align))
21900 (paragraph
21901 ;; Paragraphs may contain `line-break' type objects.
21902 (let ((beg (max (point-min)
21903 (org-element-property :contents-begin element)))
21904 (end (min (point-max)
21905 (org-element-property :contents-end element))))
21906 ;; Do nothing if point is at an affiliated keyword.
21907 (if (< (line-end-position) beg) t
21908 (when (derived-mode-p 'message-mode)
21909 ;; In `message-mode', do not fill following citation
21910 ;; in current paragraph nor text before message body.
21911 (let ((body-start (save-excursion (message-goto-body))))
21912 (when body-start (setq beg (max body-start beg))))
21913 (when (save-excursion
21914 (re-search-forward
21915 (concat "^" message-cite-prefix-regexp) end t))
21916 (setq end (match-beginning 0))))
21917 ;; Fill paragraph, taking line breaks into account.
21918 ;; For that, slice the paragraph using line breaks as
21919 ;; separators, and fill the parts in reverse order to
21920 ;; avoid messing with markers.
21921 (save-excursion
21922 (goto-char end)
21923 (mapc
21924 (lambda (pos)
21925 (fill-region-as-paragraph pos (point) justify)
21926 (goto-char pos))
21927 ;; Find the list of ending positions for line breaks
21928 ;; in the current paragraph. Add paragraph
21929 ;; beginning to include first slice.
21930 (nreverse
21931 (cons beg
21932 (org-element-map
21933 (org-element--parse-objects
21934 beg end nil (org-element-restriction 'paragraph))
21935 'line-break
21936 (lambda (lb) (org-element-property :end lb)))))))
21937 t)))
21938 ;; Contents of `comment-block' type elements should be
21939 ;; filled as plain text, but only if point is within block
21940 ;; markers.
21941 (comment-block
21942 (let* ((case-fold-search t)
21943 (beg (save-excursion
21944 (goto-char (org-element-property :begin element))
21945 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21946 (forward-line)
21947 (point)))
21948 (end (save-excursion
21949 (goto-char (org-element-property :end element))
21950 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21951 (line-beginning-position))))
21952 (when (and (>= (point) beg) (< (point) end))
21953 (fill-region-as-paragraph
21954 (save-excursion
21955 (end-of-line)
21956 (re-search-backward "^[ \t]*$" beg 'move)
21957 (line-beginning-position))
21958 (save-excursion
21959 (beginning-of-line)
21960 (re-search-forward "^[ \t]*$" end 'move)
21961 (line-beginning-position))
21962 justify)))
21964 ;; Fill comments.
21965 (comment (fill-comment-paragraph justify))
21966 ;; Ignore every other element.
21967 (otherwise t))))))
21969 (defun org-auto-fill-function ()
21970 "Auto-fill function."
21971 ;; Check if auto-filling is meaningful.
21972 (let ((fc (current-fill-column)))
21973 (when (and fc (> (current-column) fc))
21974 (let* ((fill-prefix (org-adaptive-fill-function))
21975 ;; Enforce empty fill prefix, if required. Otherwise, it
21976 ;; will be computed again.
21977 (adaptive-fill-mode (not (equal fill-prefix ""))))
21978 (when fill-prefix (do-auto-fill))))))
21980 (defun org-comment-line-break-function (&optional soft)
21981 "Break line at point and indent, continuing comment if within one.
21982 The inserted newline is marked hard if variable
21983 `use-hard-newlines' is true, unless optional argument SOFT is
21984 non-nil."
21985 (if soft (insert-and-inherit ?\n) (newline 1))
21986 (save-excursion (forward-char -1) (delete-horizontal-space))
21987 (delete-horizontal-space)
21988 (indent-to-left-margin)
21989 (insert-before-markers-and-inherit fill-prefix))
21992 ;;; Comments
21994 ;; Org comments syntax is quite complex. It requires the entire line
21995 ;; to be just a comment. Also, even with the right syntax at the
21996 ;; beginning of line, some some elements (i.e. verse-block or
21997 ;; example-block) don't accept comments. Usual Emacs comment commands
21998 ;; cannot cope with those requirements. Therefore, Org replaces them.
22000 ;; Org still relies on `comment-dwim', but cannot trust
22001 ;; `comment-only-p'. So, `comment-region-function' and
22002 ;; `uncomment-region-function' both point
22003 ;; to`org-comment-or-uncomment-region'. Eventually,
22004 ;; `org-insert-comment' takes care of insertion of comments at the
22005 ;; beginning of line.
22007 ;; `org-setup-comments-handling' install comments related variables
22008 ;; during `org-mode' initialization.
22010 (defun org-setup-comments-handling ()
22011 (interactive)
22012 (org-set-local 'comment-use-syntax nil)
22013 (org-set-local 'comment-start "# ")
22014 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22015 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22016 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22017 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22019 (defun org-insert-comment ()
22020 "Insert an empty comment above current line.
22021 If the line is empty, insert comment at its beginning."
22022 (beginning-of-line)
22023 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22024 (org-indent-line)
22025 (insert "# "))
22027 (defvar comment-empty-lines) ; From newcomment.el.
22028 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22029 "Comment or uncomment each non-blank line in the region.
22030 Uncomment each non-blank line between BEG and END if it only
22031 contains commented lines. Otherwise, comment them."
22032 (save-restriction
22033 ;; Restrict region
22034 (narrow-to-region (save-excursion (goto-char beg)
22035 (skip-chars-forward " \r\t\n" end)
22036 (line-beginning-position))
22037 (save-excursion (goto-char end)
22038 (skip-chars-backward " \r\t\n" beg)
22039 (line-end-position)))
22040 (let ((uncommentp
22041 ;; UNCOMMENTP is non-nil when every non blank line between
22042 ;; BEG and END is a comment.
22043 (save-excursion
22044 (goto-char (point-min))
22045 (while (and (not (eobp))
22046 (let ((element (org-element-at-point)))
22047 (and (eq (org-element-type element) 'comment)
22048 (goto-char (min (point-max)
22049 (org-element-property
22050 :end element)))))))
22051 (eobp))))
22052 (if uncommentp
22053 ;; Only blank lines and comments in region: uncomment it.
22054 (save-excursion
22055 (goto-char (point-min))
22056 (while (not (eobp))
22057 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22058 (replace-match "" nil nil nil 1))
22059 (forward-line)))
22060 ;; Comment each line in region.
22061 (let ((min-indent (point-max)))
22062 ;; First find the minimum indentation across all lines.
22063 (save-excursion
22064 (goto-char (point-min))
22065 (while (and (not (eobp)) (not (zerop min-indent)))
22066 (unless (looking-at "[ \t]*$")
22067 (setq min-indent (min min-indent (current-indentation))))
22068 (forward-line)))
22069 ;; Then loop over all lines.
22070 (save-excursion
22071 (goto-char (point-min))
22072 (while (not (eobp))
22073 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22074 ;; Don't get fooled by invisible text (e.g. link path)
22075 ;; when moving to column MIN-INDENT.
22076 (let ((buffer-invisibility-spec nil))
22077 (org-move-to-column min-indent t))
22078 (insert comment-start))
22079 (forward-line))))))))
22082 ;;; Planning
22084 ;; This section contains tools to operate on timestamp objects, as
22085 ;; returned by, e.g. `org-element-context'.
22087 (defun org-timestamp-has-time-p (timestamp)
22088 "Non-nil when TIMESTAMP has a time specified."
22089 (org-element-property :hour-start timestamp))
22091 (defun org-timestamp-format (timestamp format &optional end utc)
22092 "Format a TIMESTAMP element into a string.
22094 FORMAT is a format specifier to be passed to
22095 `format-time-string'.
22097 When optional argument END is non-nil, use end of date-range or
22098 time-range, if possible.
22100 When optional argument UTC is non-nil, time will be expressed as
22101 Universal Time."
22102 (format-time-string
22103 format
22104 (apply 'encode-time
22105 (cons 0
22106 (mapcar
22107 (lambda (prop) (or (org-element-property prop timestamp) 0))
22108 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22109 '(:minute-start :hour-start :day-start :month-start
22110 :year-start)))))
22111 utc))
22113 (defun org-timestamp-split-range (timestamp &optional end)
22114 "Extract a timestamp object from a date or time range.
22116 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22117 the end of the range. Otherwise, extract its start.
22119 Return a new timestamp object sharing the same parent as
22120 TIMESTAMP."
22121 (let ((type (org-element-property :type timestamp)))
22122 (if (memq type '(active inactive diary)) timestamp
22123 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22124 ;; Set new type.
22125 (org-element-put-property
22126 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22127 ;; Copy start properties over end properties if END is
22128 ;; non-nil. Otherwise, copy end properties over `start' ones.
22129 (let ((p-alist '((:minute-start . :minute-end)
22130 (:hour-start . :hour-end)
22131 (:day-start . :day-end)
22132 (:month-start . :month-end)
22133 (:year-start . :year-end))))
22134 (dolist (p-cell p-alist)
22135 (org-element-put-property
22136 split-ts
22137 (funcall (if end 'car 'cdr) p-cell)
22138 (org-element-property
22139 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22140 ;; Eventually refresh `:raw-value'.
22141 (org-element-put-property split-ts :raw-value nil)
22142 (org-element-put-property
22143 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22145 (defun org-timestamp-translate (timestamp &optional boundary)
22146 "Apply `org-translate-time' on a TIMESTAMP object.
22147 When optional argument BOUNDARY is non-nil, it is either the
22148 symbol `start' or `end'. In this case, only translate the
22149 starting or ending part of TIMESTAMP if it is a date or time
22150 range. Otherwise, translate both parts."
22151 (if (and (not boundary)
22152 (memq (org-element-property :type timestamp)
22153 '(active-range inactive-range)))
22154 (concat
22155 (org-translate-time
22156 (org-element-property :raw-value
22157 (org-timestamp-split-range timestamp)))
22158 "--"
22159 (org-translate-time
22160 (org-element-property :raw-value
22161 (org-timestamp-split-range timestamp t))))
22162 (org-translate-time
22163 (org-element-property
22164 :raw-value
22165 (if (not boundary) timestamp
22166 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22170 ;;; Other stuff.
22172 (defun org-toggle-fixed-width-section (arg)
22173 "Toggle the fixed-width export.
22174 If there is no active region, the QUOTE keyword at the current headline is
22175 inserted or removed. When present, it causes the text between this headline
22176 and the next to be exported as fixed-width text, and unmodified.
22177 If there is an active region, this command adds or removes a colon as the
22178 first character of this line. If the first character of a line is a colon,
22179 this line is also exported in fixed-width font."
22180 (interactive "P")
22181 (let* ((cc 0)
22182 (regionp (org-region-active-p))
22183 (beg (if regionp (region-beginning) (point)))
22184 (end (if regionp (region-end)))
22185 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22186 (case-fold-search nil)
22187 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22188 off)
22189 (if regionp
22190 (save-excursion
22191 (goto-char beg)
22192 (setq cc (current-column))
22193 (beginning-of-line 1)
22194 (setq off (looking-at re))
22195 (while (> nlines 0)
22196 (setq nlines (1- nlines))
22197 (beginning-of-line 1)
22198 (cond
22199 (arg
22200 (org-move-to-column cc t)
22201 (insert ": \n")
22202 (forward-line -1))
22203 ((and off (looking-at re))
22204 (replace-match "" t t nil 1))
22205 ((not off) (org-move-to-column cc t) (insert ": ")))
22206 (forward-line 1)))
22207 (save-excursion
22208 (org-back-to-heading)
22209 (cond
22210 ((looking-at (format org-heading-keyword-regexp-format
22211 org-quote-string))
22212 (goto-char (match-end 1))
22213 (looking-at (concat " +" org-quote-string))
22214 (replace-match "" t t)
22215 (when (eolp) (insert " ")))
22216 ((looking-at org-outline-regexp)
22217 (goto-char (match-end 0))
22218 (insert org-quote-string " ")))))))
22220 (defun org-reftex-citation ()
22221 "Use reftex-citation to insert a citation into the buffer.
22222 This looks for a line like
22224 #+BIBLIOGRAPHY: foo plain option:-d
22226 and derives from it that foo.bib is the bibliography file relevant
22227 for this document. It then installs the necessary environment for RefTeX
22228 to work in this buffer and calls `reftex-citation' to insert a citation
22229 into the buffer.
22231 Export of such citations to both LaTeX and HTML is handled by the contributed
22232 package org-exp-bibtex by Taru Karttunen."
22233 (interactive)
22234 (let ((reftex-docstruct-symbol 'rds)
22235 (reftex-cite-format "\\cite{%l}")
22236 rds bib)
22237 (save-excursion
22238 (save-restriction
22239 (widen)
22240 (let ((case-fold-search t)
22241 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22242 (if (not (save-excursion
22243 (or (re-search-forward re nil t)
22244 (re-search-backward re nil t))))
22245 (error "No bibliography defined in file")
22246 (setq bib (concat (match-string 1) ".bib")
22247 rds (list (list 'bib bib)))))))
22248 (call-interactively 'reftex-citation)))
22250 ;;;; Functions extending outline functionality
22252 (defun org-beginning-of-line (&optional arg)
22253 "Go to the beginning of the current line. If that is invisible, continue
22254 to a visible line beginning. This makes the function of C-a more intuitive.
22255 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22256 first attempt, and only move to after the tags when the cursor is already
22257 beyond the end of the headline."
22258 (interactive "P")
22259 (let ((pos (point))
22260 (special (if (consp org-special-ctrl-a/e)
22261 (car org-special-ctrl-a/e)
22262 org-special-ctrl-a/e))
22263 refpos)
22264 (if (org-bound-and-true-p visual-line-mode)
22265 (beginning-of-visual-line 1)
22266 (beginning-of-line 1))
22267 (if (and arg (fboundp 'move-beginning-of-line))
22268 (call-interactively 'move-beginning-of-line)
22269 (if (bobp)
22271 (backward-char 1)
22272 (if (org-truely-invisible-p)
22273 (while (and (not (bobp)) (org-truely-invisible-p))
22274 (backward-char 1)
22275 (beginning-of-line 1))
22276 (forward-char 1))))
22277 (when special
22278 (cond
22279 ((and (looking-at org-complex-heading-regexp)
22280 (= (char-after (match-end 1)) ?\ ))
22281 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22282 (point-at-eol)))
22283 (goto-char
22284 (if (eq special t)
22285 (cond ((> pos refpos) refpos)
22286 ((= pos (point)) refpos)
22287 (t (point)))
22288 (cond ((> pos (point)) (point))
22289 ((not (eq last-command this-command)) (point))
22290 (t refpos)))))
22291 ((org-at-item-p)
22292 ;; Being at an item and not looking at an the item means point
22293 ;; was previously moved to beginning of a visual line, which
22294 ;; doesn't contain the item. Therefore, do nothing special,
22295 ;; just stay here.
22296 (when (looking-at org-list-full-item-re)
22297 ;; Set special position at first white space character after
22298 ;; bullet, and check-box, if any.
22299 (let ((after-bullet
22300 (let ((box (match-end 3)))
22301 (if (not box) (match-end 1)
22302 (let ((after (char-after box)))
22303 (if (and after (= after ? )) (1+ box) box))))))
22304 ;; Special case: Move point to special position when
22305 ;; currently after it or at beginning of line.
22306 (if (eq special t)
22307 (when (or (> pos after-bullet) (= (point) pos))
22308 (goto-char after-bullet))
22309 ;; Reversed case: Move point to special position when
22310 ;; point was already at beginning of line and command is
22311 ;; repeated.
22312 (when (and (= (point) pos) (eq last-command this-command))
22313 (goto-char after-bullet))))))))
22314 (org-no-warnings
22315 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22317 (defun org-end-of-line (&optional arg)
22318 "Go to the end of the line.
22319 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22320 tags on the first attempt, and only move to after the tags when
22321 the cursor is already beyond the end of the headline."
22322 (interactive "P")
22323 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22324 org-special-ctrl-a/e))
22325 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22326 'end-of-visual-line)
22327 ((fboundp 'move-end-of-line) 'move-end-of-line)
22328 (t 'end-of-line))))
22329 (if (or (not special) arg) (call-interactively move-fun)
22330 (let* ((element (save-excursion (beginning-of-line)
22331 (org-element-at-point)))
22332 (type (org-element-type element)))
22333 (cond
22334 ((memq type '(headline inlinetask))
22335 (let ((pos (point)))
22336 (beginning-of-line 1)
22337 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22338 (if (eq special t)
22339 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22340 (goto-char (match-beginning 1))
22341 (goto-char (match-end 0)))
22342 (if (or (< pos (match-end 0))
22343 (not (eq this-command last-command)))
22344 (goto-char (match-end 0))
22345 (goto-char (match-beginning 1))))
22346 (call-interactively move-fun))))
22347 ((org-element-property :hiddenp element)
22348 ;; If element is hidden, `move-end-of-line' would put point
22349 ;; after it. Use `end-of-line' to stay on current line.
22350 (call-interactively 'end-of-line))
22351 (t (call-interactively move-fun)))))
22352 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22354 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22355 (define-key org-mode-map "\C-e" 'org-end-of-line)
22357 (defun org-backward-sentence (&optional arg)
22358 "Go to beginning of sentence, or beginning of table field.
22359 This will call `backward-sentence' or `org-table-beginning-of-field',
22360 depending on context."
22361 (interactive "P")
22362 (cond
22363 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22364 (t (call-interactively 'backward-sentence))))
22366 (defun org-forward-sentence (&optional arg)
22367 "Go to end of sentence, or end of table field.
22368 This will call `forward-sentence' or `org-table-end-of-field',
22369 depending on context."
22370 (interactive "P")
22371 (cond
22372 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22373 (t (call-interactively 'forward-sentence))))
22375 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22376 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22378 (defun org-kill-line (&optional arg)
22379 "Kill line, to tags or end of line."
22380 (interactive "P")
22381 (cond
22382 ((or (not org-special-ctrl-k)
22383 (bolp)
22384 (not (org-at-heading-p)))
22385 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22386 org-ctrl-k-protect-subtree)
22387 (if (or (eq org-ctrl-k-protect-subtree 'error)
22388 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22389 (error "C-k aborted - would kill hidden subtree")))
22390 (call-interactively
22391 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22392 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22393 (kill-region (point) (match-beginning 1))
22394 (org-set-tags nil t))
22395 (t (kill-region (point) (point-at-eol)))))
22397 (define-key org-mode-map "\C-k" 'org-kill-line)
22399 (defun org-yank (&optional arg)
22400 "Yank. If the kill is a subtree, treat it specially.
22401 This command will look at the current kill and check if is a single
22402 subtree, or a series of subtrees[1]. If it passes the test, and if the
22403 cursor is at the beginning of a line or after the stars of a currently
22404 empty headline, then the yank is handled specially. How exactly depends
22405 on the value of the following variables, both set by default.
22407 org-yank-folded-subtrees
22408 When set, the subtree(s) will be folded after insertion, but only
22409 if doing so would now swallow text after the yanked text.
22411 org-yank-adjusted-subtrees
22412 When set, the subtree will be promoted or demoted in order to
22413 fit into the local outline tree structure, which means that the level
22414 will be adjusted so that it becomes the smaller one of the two
22415 *visible* surrounding headings.
22417 Any prefix to this command will cause `yank' to be called directly with
22418 no special treatment. In particular, a simple \\[universal-argument] prefix \
22419 will just
22420 plainly yank the text as it is.
22422 \[1] The test checks if the first non-white line is a heading
22423 and if there are no other headings with fewer stars."
22424 (interactive "P")
22425 (org-yank-generic 'yank arg))
22427 (defun org-yank-generic (command arg)
22428 "Perform some yank-like command.
22430 This function implements the behavior described in the `org-yank'
22431 documentation. However, it has been generalized to work for any
22432 interactive command with similar behavior."
22434 ;; pretend to be command COMMAND
22435 (setq this-command command)
22437 (if arg
22438 (call-interactively command)
22440 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22441 (and (org-kill-is-subtree-p)
22442 (or (bolp)
22443 (and (looking-at "[ \t]*$")
22444 (string-match
22445 "\\`\\*+\\'"
22446 (buffer-substring (point-at-bol) (point)))))))
22447 swallowp)
22448 (cond
22449 ((and subtreep org-yank-folded-subtrees)
22450 (let ((beg (point))
22451 end)
22452 (if (and subtreep org-yank-adjusted-subtrees)
22453 (org-paste-subtree nil nil 'for-yank)
22454 (call-interactively command))
22456 (setq end (point))
22457 (goto-char beg)
22458 (when (and (bolp) subtreep
22459 (not (setq swallowp
22460 (org-yank-folding-would-swallow-text beg end))))
22461 (org-with-limited-levels
22462 (or (looking-at org-outline-regexp)
22463 (re-search-forward org-outline-regexp-bol end t))
22464 (while (and (< (point) end) (looking-at org-outline-regexp))
22465 (hide-subtree)
22466 (org-cycle-show-empty-lines 'folded)
22467 (condition-case nil
22468 (outline-forward-same-level 1)
22469 (error (goto-char end))))))
22470 (when swallowp
22471 (message
22472 "Inserted text not folded because that would swallow text"))
22474 (goto-char end)
22475 (skip-chars-forward " \t\n\r")
22476 (beginning-of-line 1)
22477 (push-mark beg 'nomsg)))
22478 ((and subtreep org-yank-adjusted-subtrees)
22479 (let ((beg (point-at-bol)))
22480 (org-paste-subtree nil nil 'for-yank)
22481 (push-mark beg 'nomsg)))
22483 (call-interactively command))))))
22485 (defun org-yank-folding-would-swallow-text (beg end)
22486 "Would hide-subtree at BEG swallow any text after END?"
22487 (let (level)
22488 (org-with-limited-levels
22489 (save-excursion
22490 (goto-char beg)
22491 (when (or (looking-at org-outline-regexp)
22492 (re-search-forward org-outline-regexp-bol end t))
22493 (setq level (org-outline-level)))
22494 (goto-char end)
22495 (skip-chars-forward " \t\r\n\v\f")
22496 (if (or (eobp)
22497 (and (bolp) (looking-at org-outline-regexp)
22498 (<= (org-outline-level) level)))
22499 nil ; Nothing would be swallowed
22500 t))))) ; something would swallow
22502 (define-key org-mode-map "\C-y" 'org-yank)
22504 (defun org-truely-invisible-p ()
22505 "Check if point is at a character currently not visible.
22506 This version does not only check the character property, but also
22507 `visible-mode'."
22508 ;; Early versions of noutline don't have `outline-invisible-p'.
22509 (if (org-bound-and-true-p visible-mode)
22511 (outline-invisible-p)))
22513 (defun org-invisible-p2 ()
22514 "Check if point is at a character currently not visible."
22515 (save-excursion
22516 (if (and (eolp) (not (bobp))) (backward-char 1))
22517 ;; Early versions of noutline don't have `outline-invisible-p'.
22518 (outline-invisible-p)))
22520 (defun org-back-to-heading (&optional invisible-ok)
22521 "Call `outline-back-to-heading', but provide a better error message."
22522 (condition-case nil
22523 (outline-back-to-heading invisible-ok)
22524 (error (error "Before first headline at position %d in buffer %s"
22525 (point) (current-buffer)))))
22527 (defun org-before-first-heading-p ()
22528 "Before first heading?"
22529 (save-excursion
22530 (end-of-line)
22531 (null (re-search-backward org-outline-regexp-bol nil t))))
22533 (defun org-at-heading-p (&optional ignored)
22534 (outline-on-heading-p t))
22535 ;; Compatibility alias with Org versions < 7.8.03
22536 (defalias 'org-on-heading-p 'org-at-heading-p)
22538 (defun org-at-comment-p nil
22539 "Is cursor in a line starting with a # character?"
22540 (save-excursion
22541 (beginning-of-line)
22542 (looking-at "^#")))
22544 (defun org-at-drawer-p nil
22545 "Is cursor at a drawer keyword?"
22546 (save-excursion
22547 (move-beginning-of-line 1)
22548 (looking-at org-drawer-regexp)))
22550 (defun org-at-block-p nil
22551 "Is cursor at a block keyword?"
22552 (save-excursion
22553 (move-beginning-of-line 1)
22554 (looking-at org-block-regexp)))
22556 (defun org-point-at-end-of-empty-headline ()
22557 "If point is at the end of an empty headline, return t, else nil.
22558 If the heading only contains a TODO keyword, it is still still considered
22559 empty."
22560 (and (looking-at "[ \t]*$")
22561 (when org-todo-line-regexp
22562 (save-excursion
22563 (beginning-of-line 1)
22564 (let ((case-fold-search nil))
22565 (looking-at org-todo-line-regexp)
22566 (string= (match-string 3) ""))))))
22568 (defun org-at-heading-or-item-p ()
22569 (or (org-at-heading-p) (org-at-item-p)))
22571 (defun org-at-target-p ()
22572 (or (org-in-regexp org-radio-target-regexp)
22573 (org-in-regexp org-target-regexp)))
22574 ;; Compatibility alias with Org versions < 7.8.03
22575 (defalias 'org-on-target-p 'org-at-target-p)
22577 (defun org-up-heading-all (arg)
22578 "Move to the heading line of which the present line is a subheading.
22579 This function considers both visible and invisible heading lines.
22580 With argument, move up ARG levels."
22581 (if (fboundp 'outline-up-heading-all)
22582 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22583 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22585 (defun org-up-heading-safe ()
22586 "Move to the heading line of which the present line is a subheading.
22587 This version will not throw an error. It will return the level of the
22588 headline found, or nil if no higher level is found.
22590 Also, this function will be a lot faster than `outline-up-heading',
22591 because it relies on stars being the outline starters. This can really
22592 make a significant difference in outlines with very many siblings."
22593 (let (start-level re)
22594 (org-back-to-heading t)
22595 (setq start-level (funcall outline-level))
22596 (if (equal start-level 1)
22598 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22599 (if (re-search-backward re nil t)
22600 (funcall outline-level)))))
22602 (defun org-first-sibling-p ()
22603 "Is this heading the first child of its parents?"
22604 (interactive)
22605 (let ((re org-outline-regexp-bol)
22606 level l)
22607 (unless (org-at-heading-p t)
22608 (error "Not at a heading"))
22609 (setq level (funcall outline-level))
22610 (save-excursion
22611 (if (not (re-search-backward re nil t))
22613 (setq l (funcall outline-level))
22614 (< l level)))))
22616 (defun org-goto-sibling (&optional previous)
22617 "Goto the next sibling, even if it is invisible.
22618 When PREVIOUS is set, go to the previous sibling instead. Returns t
22619 when a sibling was found. When none is found, return nil and don't
22620 move point."
22621 (let ((fun (if previous 're-search-backward 're-search-forward))
22622 (pos (point))
22623 (re org-outline-regexp-bol)
22624 level l)
22625 (when (condition-case nil (org-back-to-heading t) (error nil))
22626 (setq level (funcall outline-level))
22627 (catch 'exit
22628 (or previous (forward-char 1))
22629 (while (funcall fun re nil t)
22630 (setq l (funcall outline-level))
22631 (when (< l level) (goto-char pos) (throw 'exit nil))
22632 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22633 (goto-char pos)
22634 nil))))
22636 (defun org-show-siblings ()
22637 "Show all siblings of the current headline."
22638 (save-excursion
22639 (while (org-goto-sibling) (org-flag-heading nil)))
22640 (save-excursion
22641 (while (org-goto-sibling 'previous)
22642 (org-flag-heading nil))))
22644 (defun org-goto-first-child ()
22645 "Goto the first child, even if it is invisible.
22646 Return t when a child was found. Otherwise don't move point and
22647 return nil."
22648 (let (level (pos (point)) (re org-outline-regexp-bol))
22649 (when (condition-case nil (org-back-to-heading t) (error nil))
22650 (setq level (outline-level))
22651 (forward-char 1)
22652 (if (and (re-search-forward re nil t) (> (outline-level) level))
22653 (progn (goto-char (match-beginning 0)) t)
22654 (goto-char pos) nil))))
22656 (defun org-show-hidden-entry ()
22657 "Show an entry where even the heading is hidden."
22658 (save-excursion
22659 (org-show-entry)))
22661 (defun org-flag-heading (flag &optional entry)
22662 "Flag the current heading. FLAG non-nil means make invisible.
22663 When ENTRY is non-nil, show the entire entry."
22664 (save-excursion
22665 (org-back-to-heading t)
22666 ;; Check if we should show the entire entry
22667 (if entry
22668 (progn
22669 (org-show-entry)
22670 (save-excursion
22671 (and (outline-next-heading)
22672 (org-flag-heading nil))))
22673 (outline-flag-region (max (point-min) (1- (point)))
22674 (save-excursion (outline-end-of-heading) (point))
22675 flag))))
22677 (defun org-get-next-sibling ()
22678 "Move to next heading of the same level, and return point.
22679 If there is no such heading, return nil.
22680 This is like outline-next-sibling, but invisible headings are ok."
22681 (let ((level (funcall outline-level)))
22682 (outline-next-heading)
22683 (while (and (not (eobp)) (> (funcall outline-level) level))
22684 (outline-next-heading))
22685 (if (or (eobp) (< (funcall outline-level) level))
22687 (point))))
22689 (defun org-get-last-sibling ()
22690 "Move to previous heading of the same level, and return point.
22691 If there is no such heading, return nil."
22692 (let ((opoint (point))
22693 (level (funcall outline-level)))
22694 (outline-previous-heading)
22695 (when (and (/= (point) opoint) (outline-on-heading-p t))
22696 (while (and (> (funcall outline-level) level)
22697 (not (bobp)))
22698 (outline-previous-heading))
22699 (if (< (funcall outline-level) level)
22701 (point)))))
22703 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22704 "Goto to the end of a subtree."
22705 ;; This contains an exact copy of the original function, but it uses
22706 ;; `org-back-to-heading', to make it work also in invisible
22707 ;; trees. And is uses an invisible-ok argument.
22708 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22709 ;; Furthermore, when used inside Org, finding the end of a large subtree
22710 ;; with many children and grandchildren etc, this can be much faster
22711 ;; than the outline version.
22712 (org-back-to-heading invisible-ok)
22713 (let ((first t)
22714 (level (funcall outline-level)))
22715 (if (and (derived-mode-p 'org-mode) (< level 1000))
22716 ;; A true heading (not a plain list item), in Org-mode
22717 ;; This means we can easily find the end by looking
22718 ;; only for the right number of stars. Using a regexp to do
22719 ;; this is so much faster than using a Lisp loop.
22720 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22721 (forward-char 1)
22722 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22723 ;; something else, do it the slow way
22724 (while (and (not (eobp))
22725 (or first (> (funcall outline-level) level)))
22726 (setq first nil)
22727 (outline-next-heading)))
22728 (unless to-heading
22729 (if (memq (preceding-char) '(?\n ?\^M))
22730 (progn
22731 ;; Go to end of line before heading
22732 (forward-char -1)
22733 (if (memq (preceding-char) '(?\n ?\^M))
22734 ;; leave blank line before heading
22735 (forward-char -1))))))
22736 (point))
22738 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22739 "Use Org version in org-mode, for dramatic speed-up."
22740 (if (derived-mode-p 'org-mode)
22741 (progn
22742 (org-end-of-subtree nil t)
22743 (unless (eobp) (backward-char 1)))
22744 ad-do-it))
22746 (defun org-end-of-meta-data-and-drawers ()
22747 "Jump to the first text after meta data and drawers in the current entry.
22748 This will move over empty lines, lines with planning time stamps,
22749 clocking lines, and drawers."
22750 (org-back-to-heading t)
22751 (let ((end (save-excursion (outline-next-heading) (point)))
22752 (re (concat "\\(" org-drawer-regexp "\\)"
22753 "\\|" "[ \t]*" org-keyword-time-regexp)))
22754 (forward-line 1)
22755 (while (re-search-forward re end t)
22756 (if (not (match-end 1))
22757 ;; empty or planning line
22758 (forward-line 1)
22759 ;; a drawer, find the end
22760 (re-search-forward "^[ \t]*:END:" end 'move)
22761 (forward-line 1)))
22762 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22763 (point)))
22765 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22766 "Move forward to the ARG'th subheading at same level as this one.
22767 Stop at the first and last subheadings of a superior heading.
22768 Normally this only looks at visible headings, but when INVISIBLE-OK is
22769 non-nil it will also look at invisible ones."
22770 (interactive "p")
22771 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22772 (if (and arg (< arg 0))
22773 (goto-char (point-min))
22774 (outline-next-heading))
22775 (org-at-heading-p)
22776 (let ((level (- (match-end 0) (match-beginning 0) 1))
22777 (f (if (and arg (< arg 0))
22778 're-search-backward
22779 're-search-forward))
22780 (count (if arg (abs arg) 1))
22781 (result (point)))
22782 (forward-char (if (and arg (< arg 0)) -1 1))
22783 (while (and (> count 0)
22784 (funcall f org-outline-regexp-bol nil 'move))
22785 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22786 (cond ((< l level) (setq count 0))
22787 ((and (= l level)
22788 (or invisible-ok
22789 (progn
22790 (goto-char (line-beginning-position))
22791 (not (outline-invisible-p)))))
22792 (setq count (1- count))
22793 (when (eq l level)
22794 (setq result (point)))))))
22795 (goto-char result))
22796 (beginning-of-line 1)))
22798 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22799 "Move backward to the ARG'th subheading at same level as this one.
22800 Stop at the first and last subheadings of a superior heading."
22801 (interactive "p")
22802 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22804 (defun org-next-block (arg &optional backward block-regexp)
22805 "Jump to the next block.
22806 With a prefix argument ARG, jump forward ARG many source blocks.
22807 When BACKWARD is non-nil, jump to the previous block.
22808 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22809 (interactive "p")
22810 (let ((re (or block-regexp org-block-regexp))
22811 (re-search-fn (or (and backward 're-search-backward)
22812 're-search-forward)))
22813 (if (looking-at re) (forward-char 1))
22814 (condition-case nil
22815 (funcall re-search-fn re nil nil arg)
22816 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22817 (goto-char (match-beginning 0)) (org-show-context)))
22819 (defun org-previous-block (arg &optional block-regexp)
22820 "Jump to the previous block.
22821 With a prefix argument ARG, jump backward ARG many source blocks.
22822 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22823 (interactive "p")
22824 (org-next-block arg t block-regexp))
22826 (defun org-forward-element ()
22827 "Move forward by one element.
22828 Move to the next element at the same level, when possible."
22829 (interactive)
22830 (cond ((eobp) (user-error "Cannot move further down"))
22831 ((org-with-limited-levels (org-at-heading-p))
22832 (let ((origin (point)))
22833 (goto-char (org-end-of-subtree nil t))
22834 (unless (org-with-limited-levels (org-at-heading-p))
22835 (goto-char origin)
22836 (user-error "Cannot move further down"))))
22838 (let* ((elem (org-element-at-point))
22839 (end (org-element-property :end elem))
22840 (parent (org-element-property :parent elem)))
22841 (if (and parent (= (org-element-property :contents-end parent) end))
22842 (goto-char (org-element-property :end parent))
22843 (goto-char end))))))
22845 (defun org-backward-element ()
22846 "Move backward by one element.
22847 Move to the previous element at the same level, when possible."
22848 (interactive)
22849 (cond ((bobp) (user-error "Cannot move further up"))
22850 ((org-with-limited-levels (org-at-heading-p))
22851 ;; At a headline, move to the previous one, if any, or stay
22852 ;; here.
22853 (let ((origin (point)))
22854 (org-with-limited-levels (org-backward-heading-same-level 1))
22855 ;; When current headline has no sibling above, move to its
22856 ;; parent.
22857 (when (= (point) origin)
22858 (or (org-with-limited-levels (org-up-heading-safe))
22859 (progn (goto-char origin)
22860 (user-error "Cannot move further up"))))))
22862 (let* ((trail (org-element-at-point 'keep-trail))
22863 (elem (car trail))
22864 (prev-elem (nth 1 trail))
22865 (beg (org-element-property :begin elem)))
22866 (cond
22867 ;; Move to beginning of current element if point isn't
22868 ;; there already.
22869 ((/= (point) beg) (goto-char beg))
22870 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22871 ((org-before-first-heading-p) (goto-char (point-min)))
22872 (t (org-back-to-heading)))))))
22874 (defun org-up-element ()
22875 "Move to upper element."
22876 (interactive)
22877 (if (org-with-limited-levels (org-at-heading-p))
22878 (unless (org-up-heading-safe) (error "No surrounding element"))
22879 (let* ((elem (org-element-at-point))
22880 (parent (org-element-property :parent elem)))
22881 (if parent (goto-char (org-element-property :begin parent))
22882 (if (org-with-limited-levels (org-before-first-heading-p))
22883 (error "No surrounding element")
22884 (org-with-limited-levels (org-back-to-heading)))))))
22886 (defvar org-element-greater-elements)
22887 (defun org-down-element ()
22888 "Move to inner element."
22889 (interactive)
22890 (let ((element (org-element-at-point)))
22891 (cond
22892 ((memq (org-element-type element) '(plain-list table))
22893 (goto-char (org-element-property :contents-begin element))
22894 (forward-char))
22895 ((memq (org-element-type element) org-element-greater-elements)
22896 ;; If contents are hidden, first disclose them.
22897 (when (org-element-property :hiddenp element) (org-cycle))
22898 (goto-char (or (org-element-property :contents-begin element)
22899 (error "No content for this element"))))
22900 (t (error "No inner element")))))
22902 (defun org-drag-element-backward ()
22903 "Move backward element at point."
22904 (interactive)
22905 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22906 (let* ((trail (org-element-at-point 'keep-trail))
22907 (elem (car trail))
22908 (prev-elem (nth 1 trail)))
22909 ;; Error out if no previous element or previous element is
22910 ;; a parent of the current one.
22911 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22912 (error "Cannot drag element backward")
22913 (let ((pos (point)))
22914 (org-element-swap-A-B prev-elem elem)
22915 (goto-char (+ (org-element-property :begin prev-elem)
22916 (- pos (org-element-property :begin elem)))))))))
22918 (defun org-drag-element-forward ()
22919 "Move forward element at point."
22920 (interactive)
22921 (let* ((pos (point))
22922 (elem (org-element-at-point)))
22923 (when (= (point-max) (org-element-property :end elem))
22924 (error "Cannot drag element forward"))
22925 (goto-char (org-element-property :end elem))
22926 (let ((next-elem (org-element-at-point)))
22927 (when (or (org-element-nested-p elem next-elem)
22928 (and (eq (org-element-type next-elem) 'headline)
22929 (not (eq (org-element-type elem) 'headline))))
22930 (goto-char pos)
22931 (error "Cannot drag element forward"))
22932 ;; Compute new position of point: it's shifted by NEXT-ELEM
22933 ;; body's length (without final blanks) and by the length of
22934 ;; blanks between ELEM and NEXT-ELEM.
22935 (let ((size-next (- (save-excursion
22936 (goto-char (org-element-property :end next-elem))
22937 (skip-chars-backward " \r\t\n")
22938 (forward-line)
22939 ;; Small correction if buffer doesn't end
22940 ;; with a newline character.
22941 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22942 (org-element-property :begin next-elem)))
22943 (size-blank (- (org-element-property :end elem)
22944 (save-excursion
22945 (goto-char (org-element-property :end elem))
22946 (skip-chars-backward " \r\t\n")
22947 (forward-line)
22948 (point)))))
22949 (org-element-swap-A-B elem next-elem)
22950 (goto-char (+ pos size-next size-blank))))))
22952 (defun org-drag-line-forward (arg)
22953 "Drag the line at point ARG lines forward."
22954 (interactive "p")
22955 (dotimes (n (abs arg))
22956 (let ((c (current-column)))
22957 (if (< 0 arg)
22958 (progn
22959 (beginning-of-line 2)
22960 (transpose-lines 1)
22961 (beginning-of-line 0))
22962 (transpose-lines 1)
22963 (beginning-of-line -1))
22964 (org-move-to-column c))))
22966 (defun org-drag-line-backward (arg)
22967 "Drag the line at point ARG lines backward."
22968 (interactive "p")
22969 (org-drag-line-forward (- arg)))
22971 (defun org-mark-element ()
22972 "Put point at beginning of this element, mark at end.
22974 Interactively, if this command is repeated or (in Transient Mark
22975 mode) if the mark is active, it marks the next element after the
22976 ones already marked."
22977 (interactive)
22978 (let (deactivate-mark)
22979 (if (and (org-called-interactively-p 'any)
22980 (or (and (eq last-command this-command) (mark t))
22981 (and transient-mark-mode mark-active)))
22982 (set-mark
22983 (save-excursion
22984 (goto-char (mark))
22985 (goto-char (org-element-property :end (org-element-at-point)))))
22986 (let ((element (org-element-at-point)))
22987 (end-of-line)
22988 (push-mark (org-element-property :end element) t t)
22989 (goto-char (org-element-property :begin element))))))
22991 (defun org-narrow-to-element ()
22992 "Narrow buffer to current element."
22993 (interactive)
22994 (let ((elem (org-element-at-point)))
22995 (cond
22996 ((eq (car elem) 'headline)
22997 (narrow-to-region
22998 (org-element-property :begin elem)
22999 (org-element-property :end elem)))
23000 ((memq (car elem) org-element-greater-elements)
23001 (narrow-to-region
23002 (org-element-property :contents-begin elem)
23003 (org-element-property :contents-end elem)))
23005 (narrow-to-region
23006 (org-element-property :begin elem)
23007 (org-element-property :end elem))))))
23009 (defun org-transpose-element ()
23010 "Transpose current and previous elements, keeping blank lines between.
23011 Point is moved after both elements."
23012 (interactive)
23013 (org-skip-whitespace)
23014 (let ((end (org-element-property :end (org-element-at-point))))
23015 (org-drag-element-backward)
23016 (goto-char end)))
23018 (defun org-unindent-buffer ()
23019 "Un-indent the visible part of the buffer.
23020 Relative indentation (between items, inside blocks, etc.) isn't
23021 modified."
23022 (interactive)
23023 (unless (eq major-mode 'org-mode)
23024 (error "Cannot un-indent a buffer not in Org mode"))
23025 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23026 unindent-tree ; For byte-compiler.
23027 (unindent-tree
23028 (function
23029 (lambda (contents)
23030 (mapc
23031 (lambda (element)
23032 (if (memq (org-element-type element) '(headline section))
23033 (funcall unindent-tree (org-element-contents element))
23034 (save-excursion
23035 (save-restriction
23036 (narrow-to-region
23037 (org-element-property :begin element)
23038 (org-element-property :end element))
23039 (org-do-remove-indentation)))))
23040 (reverse contents))))))
23041 (funcall unindent-tree (org-element-contents parse-tree))))
23043 (defun org-show-subtree ()
23044 "Show everything after this heading at deeper levels."
23045 (interactive)
23046 (outline-flag-region
23047 (point)
23048 (save-excursion
23049 (org-end-of-subtree t t))
23050 nil))
23052 (defun org-show-entry ()
23053 "Show the body directly following this heading.
23054 Show the heading too, if it is currently invisible."
23055 (interactive)
23056 (save-excursion
23057 (condition-case nil
23058 (progn
23059 (org-back-to-heading t)
23060 (outline-flag-region
23061 (max (point-min) (1- (point)))
23062 (save-excursion
23063 (if (re-search-forward
23064 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23065 (match-beginning 1)
23066 (point-max)))
23067 nil)
23068 (org-cycle-hide-drawers 'children))
23069 (error nil))))
23071 (defun org-make-options-regexp (kwds &optional extra)
23072 "Make a regular expression for keyword lines."
23073 (concat
23074 "^#\\+\\("
23075 (mapconcat 'regexp-quote kwds "\\|")
23076 (if extra (concat "\\|" extra))
23077 "\\):[ \t]*\\(.*\\)"))
23079 ;; Make isearch reveal the necessary context
23080 (defun org-isearch-end ()
23081 "Reveal context after isearch exits."
23082 (when isearch-success ; only if search was successful
23083 (if (featurep 'xemacs)
23084 ;; Under XEmacs, the hook is run in the correct place,
23085 ;; we directly show the context.
23086 (org-show-context 'isearch)
23087 ;; In Emacs the hook runs *before* restoring the overlays.
23088 ;; So we have to use a one-time post-command-hook to do this.
23089 ;; (Emacs 22 has a special variable, see function `org-mode')
23090 (unless (and (boundp 'isearch-mode-end-hook-quit)
23091 isearch-mode-end-hook-quit)
23092 ;; Only when the isearch was not quitted.
23093 (org-add-hook 'post-command-hook 'org-isearch-post-command
23094 'append 'local)))
23095 (org-fix-ellipsis-at-bol)))
23097 (defun org-isearch-post-command ()
23098 "Remove self from hook, and show context."
23099 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23100 (org-show-context 'isearch))
23103 ;;;; Integration with and fixes for other packages
23105 ;;; Imenu support
23107 (defvar org-imenu-markers nil
23108 "All markers currently used by Imenu.")
23109 (make-variable-buffer-local 'org-imenu-markers)
23111 (defun org-imenu-new-marker (&optional pos)
23112 "Return a new marker for use by Imenu, and remember the marker."
23113 (let ((m (make-marker)))
23114 (move-marker m (or pos (point)))
23115 (push m org-imenu-markers)
23118 (defun org-imenu-get-tree ()
23119 "Produce the index for Imenu."
23120 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23121 (setq org-imenu-markers nil)
23122 (let* ((n org-imenu-depth)
23123 (re (concat "^" (org-get-limited-outline-regexp)))
23124 (subs (make-vector (1+ n) nil))
23125 (last-level 0)
23126 m level head0 head)
23127 (save-excursion
23128 (save-restriction
23129 (widen)
23130 (goto-char (point-max))
23131 (while (re-search-backward re nil t)
23132 (setq level (org-reduced-level (funcall outline-level)))
23133 (when (and (<= level n)
23134 (looking-at org-complex-heading-regexp)
23135 (setq head0 (org-match-string-no-properties 4)))
23136 (setq head (org-link-display-format head0)
23137 m (org-imenu-new-marker))
23138 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23139 (if (>= level last-level)
23140 (push (cons head m) (aref subs level))
23141 (push (cons head (aref subs (1+ level))) (aref subs level))
23142 (loop for i from (1+ level) to n do (aset subs i nil)))
23143 (setq last-level level)))))
23144 (aref subs 1)))
23146 (eval-after-load "imenu"
23147 '(progn
23148 (add-hook 'imenu-after-jump-hook
23149 (lambda ()
23150 (if (derived-mode-p 'org-mode)
23151 (org-show-context 'org-goto))))))
23153 (defun org-link-display-format (link)
23154 "Replace a link with either the description, or the link target
23155 if no description is present"
23156 (save-match-data
23157 (if (string-match org-bracket-link-analytic-regexp link)
23158 (replace-match (if (match-end 5)
23159 (match-string 5 link)
23160 (concat (match-string 1 link)
23161 (match-string 3 link)))
23162 nil t link)
23163 link)))
23165 (defun org-toggle-link-display ()
23166 "Toggle the literal or descriptive display of links."
23167 (interactive)
23168 (if org-descriptive-links
23169 (progn (org-remove-from-invisibility-spec '(org-link))
23170 (org-restart-font-lock)
23171 (setq org-descriptive-links nil))
23172 (progn (add-to-invisibility-spec '(org-link))
23173 (org-restart-font-lock)
23174 (setq org-descriptive-links t))))
23176 ;; Speedbar support
23178 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23179 "Overlay marking the agenda restriction line in speedbar.")
23180 (overlay-put org-speedbar-restriction-lock-overlay
23181 'face 'org-agenda-restriction-lock)
23182 (overlay-put org-speedbar-restriction-lock-overlay
23183 'help-echo "Agendas are currently limited to this item.")
23184 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23186 (defun org-speedbar-set-agenda-restriction ()
23187 "Restrict future agenda commands to the location at point in speedbar.
23188 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23189 (interactive)
23190 (require 'org-agenda)
23191 (let (p m tp np dir txt)
23192 (cond
23193 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23194 'org-imenu t))
23195 (setq m (get-text-property p 'org-imenu-marker))
23196 (with-current-buffer (marker-buffer m)
23197 (goto-char m)
23198 (org-agenda-set-restriction-lock 'subtree)))
23199 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23200 'speedbar-function 'speedbar-find-file))
23201 (setq tp (previous-single-property-change
23202 (1+ p) 'speedbar-function)
23203 np (next-single-property-change
23204 tp 'speedbar-function)
23205 dir (speedbar-line-directory)
23206 txt (buffer-substring-no-properties (or tp (point-min))
23207 (or np (point-max))))
23208 (with-current-buffer (find-file-noselect
23209 (let ((default-directory dir))
23210 (expand-file-name txt)))
23211 (unless (derived-mode-p 'org-mode)
23212 (error "Cannot restrict to non-Org-mode file"))
23213 (org-agenda-set-restriction-lock 'file)))
23214 (t (error "Don't know how to restrict Org-mode's agenda")))
23215 (move-overlay org-speedbar-restriction-lock-overlay
23216 (point-at-bol) (point-at-eol))
23217 (setq current-prefix-arg nil)
23218 (org-agenda-maybe-redo)))
23220 (eval-after-load "speedbar"
23221 '(progn
23222 (speedbar-add-supported-extension ".org")
23223 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23224 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23225 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23226 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23227 (add-hook 'speedbar-visiting-tag-hook
23228 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23230 ;;; Fixes and Hacks for problems with other packages
23232 ;; Make flyspell not check words in links, to not mess up our keymap
23233 (defvar org-element-affiliated-keywords) ; From org-element.el
23234 (defvar org-element-block-name-alist) ; From org-element.el
23235 (defun org-mode-flyspell-verify ()
23236 "Don't let flyspell put overlays at active buttons, or on
23237 {todo,all-time,additional-option-like}-keywords."
23238 (let ((pos (max (1- (point)) (point-min)))
23239 (word (thing-at-point 'word)))
23240 (and (not (get-text-property pos 'keymap))
23241 (not (get-text-property pos 'org-no-flyspell))
23242 (not (member word org-todo-keywords-1))
23243 (not (member word org-all-time-keywords))
23244 (not (member word org-options-keywords))
23245 (not (member word (mapcar 'car org-startup-options)))
23246 (not (member-ignore-case word org-element-affiliated-keywords))
23247 (not (member-ignore-case word (org-get-export-keywords)))
23248 (not (member-ignore-case
23249 word (mapcar 'car org-element-block-name-alist)))
23250 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23252 (defun org-remove-flyspell-overlays-in (beg end)
23253 "Remove flyspell overlays in region."
23254 (and (org-bound-and-true-p flyspell-mode)
23255 (fboundp 'flyspell-delete-region-overlays)
23256 (flyspell-delete-region-overlays beg end))
23257 (add-text-properties beg end '(org-no-flyspell t)))
23259 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23260 (eval-after-load "bookmark"
23261 '(if (boundp 'bookmark-after-jump-hook)
23262 ;; We can use the hook
23263 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23264 ;; Hook not available, use advice
23265 (defadvice bookmark-jump (after org-make-visible activate)
23266 "Make the position visible."
23267 (org-bookmark-jump-unhide))))
23269 ;; Make sure saveplace shows the location if it was hidden
23270 (eval-after-load "saveplace"
23271 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23272 "Make the position visible."
23273 (org-bookmark-jump-unhide)))
23275 ;; Make sure ecb shows the location if it was hidden
23276 (eval-after-load "ecb"
23277 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23278 "Make hierarchy visible when jumping into location from ECB tree buffer."
23279 (if (derived-mode-p 'org-mode)
23280 (org-show-context))))
23282 (defun org-bookmark-jump-unhide ()
23283 "Unhide the current position, to show the bookmark location."
23284 (and (derived-mode-p 'org-mode)
23285 (or (outline-invisible-p)
23286 (save-excursion (goto-char (max (point-min) (1- (point))))
23287 (outline-invisible-p)))
23288 (org-show-context 'bookmark-jump)))
23290 ;; Make session.el ignore our circular variable
23291 (eval-after-load "session"
23292 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23294 ;;;; Experimental code
23296 (defun org-closed-in-range ()
23297 "Sparse tree of items closed in a certain time range.
23298 Still experimental, may disappear in the future."
23299 (interactive)
23300 ;; Get the time interval from the user.
23301 (let* ((time1 (org-float-time
23302 (org-read-date nil 'to-time nil "Starting date: ")))
23303 (time2 (org-float-time
23304 (org-read-date nil 'to-time nil "End date:")))
23305 ;; callback function
23306 (callback (lambda ()
23307 (let ((time
23308 (org-float-time
23309 (apply 'encode-time
23310 (org-parse-time-string
23311 (match-string 1))))))
23312 ;; check if time in interval
23313 (and (>= time time1) (<= time time2))))))
23314 ;; make tree, check each match with the callback
23315 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23317 ;;;; Finish up
23319 (provide 'org)
23321 (run-hooks 'org-load-hook)
23323 ;;; org.el ends here