org.el (org-modules): Remove deleted libraries, add new ones
[org-mode/org-kjn.git] / lisp / org.el
blob529e81ec6ea8121593e5a3cb58048e83906b31b5
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 bullets: Add overlays to headlines stars" org-bullets)
377 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
378 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
379 (const :tag "C collector: Collect properties into tables" org-collector)
380 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
381 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
382 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
383 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
384 (const :tag "C eval: Include command output as text" org-eval)
385 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
386 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
387 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
388 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
389 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
391 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
393 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
394 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
395 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
396 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
397 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
398 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
399 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
400 (const :tag "C mtags: Support for muse-like tags" org-mtags)
401 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
402 (const :tag "C registry: A registry for Org-mode links" org-registry)
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 (org-table-set-constants))
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)))
4912 ;; Process the tags.
4913 (when tags
4914 (let (e tgs)
4915 (while (setq e (pop tags))
4916 (cond
4917 ((equal e "{") (push '(:startgroup) tgs))
4918 ((equal e "}") (push '(:endgroup) tgs))
4919 ((equal e "\\n") (push '(:newline) tgs))
4920 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4921 (push (cons (match-string 1 e)
4922 (string-to-char (match-string 2 e)))
4923 tgs))
4924 (t (push (list e) tgs))))
4925 (org-set-local 'org-tag-alist nil)
4926 (while (setq e (pop tgs))
4927 (or (and (stringp (car e))
4928 (assoc (car e) org-tag-alist))
4929 (push e org-tag-alist)))))
4931 ;; Compute the regular expressions and other local variables.
4932 ;; Using `org-outline-regexp-bol' would complicate them much,
4933 ;; because of the fixed white space at the end of that string.
4934 (if (not org-done-keywords)
4935 (setq org-done-keywords (and org-todo-keywords-1
4936 (list (org-last org-todo-keywords-1)))))
4937 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4938 (length org-scheduled-string)
4939 (length org-clock-string)
4940 (length org-closed-string)))
4941 org-drawer-regexp
4942 (concat "^[ \t]*:\\("
4943 (mapconcat 'regexp-quote org-drawers "\\|")
4944 "\\):[ \t]*$")
4945 org-not-done-keywords
4946 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4947 org-todo-regexp
4948 (concat "\\("
4949 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4950 "\\)")
4951 org-not-done-regexp
4952 (concat "\\("
4953 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4954 "\\)")
4955 org-not-done-heading-regexp
4956 (format org-heading-keyword-regexp-format org-not-done-regexp)
4957 org-todo-line-regexp
4958 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4959 org-complex-heading-regexp
4960 (concat "^\\(\\*+\\)"
4961 "\\(?: +" org-todo-regexp "\\)?"
4962 "\\(?: +\\(\\[#.\\]\\)\\)?"
4963 "\\(?: +\\(.*?\\)\\)??"
4964 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4965 "[ \t]*$")
4966 org-complex-heading-regexp-format
4967 (concat "^\\(\\*+\\)"
4968 "\\(?: +" org-todo-regexp "\\)?"
4969 "\\(?: +\\(\\[#.\\]\\)\\)?"
4970 "\\(?: +"
4971 ;; Stats cookies can be stuck to body.
4972 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4973 "\\(%s\\)"
4974 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4975 "\\)"
4976 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4977 "[ \t]*$")
4978 org-todo-line-tags-regexp
4979 (concat "^\\(\\*+\\)"
4980 "\\(?: +" org-todo-regexp "\\)?"
4981 "\\(?: +\\(.*?\\)\\)??"
4982 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4983 "[ \t]*$")
4984 org-deadline-regexp (concat "\\<" org-deadline-string)
4985 org-deadline-time-regexp
4986 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4987 org-deadline-time-hour-regexp
4988 (concat "\\<" org-deadline-string
4989 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
4990 org-deadline-line-regexp
4991 (concat "\\<\\(" org-deadline-string "\\).*")
4992 org-scheduled-regexp
4993 (concat "\\<" org-scheduled-string)
4994 org-scheduled-time-regexp
4995 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4996 org-scheduled-time-hour-regexp
4997 (concat "\\<" org-scheduled-string
4998 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
4999 org-closed-time-regexp
5000 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5001 org-keyword-time-regexp
5002 (concat "\\<\\(" org-scheduled-string
5003 "\\|" org-deadline-string
5004 "\\|" org-closed-string
5005 "\\|" org-clock-string "\\)"
5006 " *[[<]\\([^]>]+\\)[]>]")
5007 org-keyword-time-not-clock-regexp
5008 (concat "\\<\\(" org-scheduled-string
5009 "\\|" org-deadline-string
5010 "\\|" org-closed-string
5011 "\\)"
5012 " *[[<]\\([^]>]+\\)[]>]")
5013 org-maybe-keyword-time-regexp
5014 (concat "\\(\\<\\(" org-scheduled-string
5015 "\\|" org-deadline-string
5016 "\\|" org-closed-string
5017 "\\|" org-clock-string "\\)\\)?"
5018 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5019 org-all-time-keywords
5020 (mapcar (lambda (w) (substring w 0 -1))
5021 (list org-scheduled-string org-deadline-string
5022 org-clock-string org-closed-string)))
5023 (org-compute-latex-and-related-regexp)
5024 (org-set-font-lock-defaults))))
5026 (defun org-file-contents (file &optional noerror)
5027 "Return the contents of FILE, as a string."
5028 (if (or (not file)
5029 (not (file-readable-p file)))
5030 (if noerror
5031 (progn
5032 (message "Cannot read file \"%s\"" file)
5033 (ding) (sit-for 2)
5035 (error "Cannot read file \"%s\"" file))
5036 (with-temp-buffer
5037 (insert-file-contents file)
5038 (buffer-string))))
5040 (defun org-extract-log-state-settings (x)
5041 "Extract the log state setting from a TODO keyword string.
5042 This will extract info from a string like \"WAIT(w@/!)\"."
5043 (let (kw key log1 log2)
5044 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5045 (setq kw (match-string 1 x)
5046 key (and (match-end 2) (match-string 2 x))
5047 log1 (and (match-end 3) (match-string 3 x))
5048 log2 (and (match-end 4) (match-string 4 x)))
5049 (and (or log1 log2)
5050 (list kw
5051 (and log1 (if (equal log1 "!") 'time 'note))
5052 (and log2 (if (equal log2 "!") 'time 'note)))))))
5054 (defun org-remove-keyword-keys (list)
5055 "Remove a pair of parenthesis at the end of each string in LIST."
5056 (mapcar (lambda (x)
5057 (if (string-match "(.*)$" x)
5058 (substring x 0 (match-beginning 0))
5060 list))
5062 (defun org-assign-fast-keys (alist)
5063 "Assign fast keys to a keyword-key alist.
5064 Respect keys that are already there."
5065 (let (new e (alt ?0))
5066 (while (setq e (pop alist))
5067 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5068 (cdr e)) ;; Key already assigned.
5069 (push e new)
5070 (let ((clist (string-to-list (downcase (car e))))
5071 (used (append new alist)))
5072 (when (= (car clist) ?@)
5073 (pop clist))
5074 (while (and clist (rassoc (car clist) used))
5075 (pop clist))
5076 (unless clist
5077 (while (rassoc alt used)
5078 (incf alt)))
5079 (push (cons (car e) (or (car clist) alt)) new))))
5080 (nreverse new)))
5082 ;;; Some variables used in various places
5084 (defvar org-window-configuration nil
5085 "Used in various places to store a window configuration.")
5086 (defvar org-selected-window nil
5087 "Used in various places to store a window configuration.")
5088 (defvar org-finish-function nil
5089 "Function to be called when `C-c C-c' is used.
5090 This is for getting out of special buffers like capture.")
5093 ;; FIXME: Occasionally check by commenting these, to make sure
5094 ;; no other functions uses these, forgetting to let-bind them.
5095 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5096 (defvar org-last-state)
5097 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5099 ;; Defined somewhere in this file, but used before definition.
5100 (defvar org-entities) ;; defined in org-entities.el
5101 (defvar org-struct-menu)
5102 (defvar org-org-menu)
5103 (defvar org-tbl-menu)
5105 ;;;; Define the Org-mode
5107 ;; We use a before-change function to check if a table might need
5108 ;; an update.
5109 (defvar org-table-may-need-update t
5110 "Indicates that a table might need an update.
5111 This variable is set by `org-before-change-function'.
5112 `org-table-align' sets it back to nil.")
5113 (defun org-before-change-function (beg end)
5114 "Every change indicates that a table might need an update."
5115 (setq org-table-may-need-update t))
5116 (defvar org-mode-map)
5117 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5118 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5119 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5120 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5121 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5122 (defvar org-table-buffer-is-an nil)
5124 (defvar bidi-paragraph-direction)
5125 (defvar buffer-face-mode-face)
5127 (require 'outline)
5128 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5129 (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"))
5130 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5132 ;; Other stuff we need.
5133 (require 'time-date)
5134 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5135 (require 'easymenu)
5136 (require 'overlay)
5138 ;; (require 'org-macs) moved higher up in the file before it is first used
5139 (require 'org-entities)
5140 ;; (require 'org-compat) moved higher up in the file before it is first used
5141 (require 'org-faces)
5142 (require 'org-list)
5143 (require 'org-pcomplete)
5144 (require 'org-src)
5145 (require 'org-footnote)
5146 (require 'org-macro)
5148 ;; babel
5149 (require 'ob)
5151 ;;;###autoload
5152 (define-derived-mode org-mode outline-mode "Org"
5153 "Outline-based notes management and organizer, alias
5154 \"Carsten's outline-mode for keeping track of everything.\"
5156 Org-mode develops organizational tasks around a NOTES file which
5157 contains information about projects as plain text. Org-mode is
5158 implemented on top of outline-mode, which is ideal to keep the content
5159 of large files well structured. It supports ToDo items, deadlines and
5160 time stamps, which magically appear in the diary listing of the Emacs
5161 calendar. Tables are easily created with a built-in table editor.
5162 Plain text URL-like links connect to websites, emails (VM), Usenet
5163 messages (Gnus), BBDB entries, and any files related to the project.
5164 For printing and sharing of notes, an Org-mode file (or a part of it)
5165 can be exported as a structured ASCII or HTML file.
5167 The following commands are available:
5169 \\{org-mode-map}"
5171 ;; Get rid of Outline menus, they are not needed
5172 ;; Need to do this here because define-derived-mode sets up
5173 ;; the keymap so late. Still, it is a waste to call this each time
5174 ;; we switch another buffer into org-mode.
5175 (if (featurep 'xemacs)
5176 (when (boundp 'outline-mode-menu-heading)
5177 ;; Assume this is Greg's port, it uses easymenu
5178 (easy-menu-remove outline-mode-menu-heading)
5179 (easy-menu-remove outline-mode-menu-show)
5180 (easy-menu-remove outline-mode-menu-hide))
5181 (define-key org-mode-map [menu-bar headings] 'undefined)
5182 (define-key org-mode-map [menu-bar hide] 'undefined)
5183 (define-key org-mode-map [menu-bar show] 'undefined))
5185 (org-load-modules-maybe)
5186 (easy-menu-add org-org-menu)
5187 (easy-menu-add org-tbl-menu)
5188 (org-install-agenda-files-menu)
5189 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5190 (add-to-invisibility-spec '(org-cwidth))
5191 (add-to-invisibility-spec '(org-hide-block . t))
5192 (when (featurep 'xemacs)
5193 (org-set-local 'line-move-ignore-invisible t))
5194 (org-set-local 'outline-regexp org-outline-regexp)
5195 (org-set-local 'outline-level 'org-outline-level)
5196 (setq bidi-paragraph-direction 'left-to-right)
5197 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5198 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5199 (when (and org-ellipsis
5200 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5201 (fboundp 'make-glyph-code))
5202 (unless org-display-table
5203 (setq org-display-table (make-display-table)))
5204 (set-display-table-slot
5205 org-display-table 4
5206 (vconcat (mapcar
5207 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5208 org-ellipsis)))
5209 (if (stringp org-ellipsis) org-ellipsis "..."))))
5210 (setq buffer-display-table org-display-table))
5211 (org-set-regexps-and-options)
5212 (when (and org-tag-faces (not org-tags-special-faces-re))
5213 ;; tag faces set outside customize.... force initialization.
5214 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5215 ;; Calc embedded
5216 (org-set-local 'calc-embedded-open-mode "# ")
5217 ;; Modify a few syntax entries
5218 (modify-syntax-entry ?@ "w")
5219 (modify-syntax-entry ?\" "\"")
5220 (if org-startup-truncated (setq truncate-lines t))
5221 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5222 (org-set-local 'font-lock-unfontify-region-function
5223 'org-unfontify-region)
5224 ;; Activate before-change-function
5225 (org-set-local 'org-table-may-need-update t)
5226 (org-add-hook 'before-change-functions 'org-before-change-function nil
5227 'local)
5228 ;; Check for running clock before killing a buffer
5229 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5230 ;; Initialize macros templates.
5231 (org-macro-initialize-templates)
5232 ;; Initialize radio targets.
5233 (org-update-radio-target-regexp)
5234 ;; Indentation.
5235 (org-set-local 'indent-line-function 'org-indent-line)
5236 (org-set-local 'indent-region-function 'org-indent-region)
5237 ;; Filling and auto-filling.
5238 (org-setup-filling)
5239 ;; Comments.
5240 (org-setup-comments-handling)
5241 ;; Beginning/end of defun
5242 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5243 (org-set-local 'end-of-defun-function 'org-forward-element)
5244 ;; Next error for sparse trees
5245 (org-set-local 'next-error-function 'org-occur-next-match)
5246 ;; Make sure dependence stuff works reliably, even for users who set it
5247 ;; too late :-(
5248 (if org-enforce-todo-dependencies
5249 (add-hook 'org-blocker-hook
5250 'org-block-todo-from-children-or-siblings-or-parent)
5251 (remove-hook 'org-blocker-hook
5252 'org-block-todo-from-children-or-siblings-or-parent))
5253 (if org-enforce-todo-checkbox-dependencies
5254 (add-hook 'org-blocker-hook
5255 'org-block-todo-from-checkboxes)
5256 (remove-hook 'org-blocker-hook
5257 'org-block-todo-from-checkboxes))
5259 ;; Align options lines
5260 (org-set-local
5261 'align-mode-rules-list
5262 '((org-in-buffer-settings
5263 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5264 (modes . '(org-mode)))))
5266 ;; Imenu
5267 (org-set-local 'imenu-create-index-function
5268 'org-imenu-get-tree)
5270 ;; Make isearch reveal context
5271 (if (or (featurep 'xemacs)
5272 (not (boundp 'outline-isearch-open-invisible-function)))
5273 ;; Emacs 21 and XEmacs make use of the hook
5274 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5275 ;; Emacs 22 deals with this through a special variable
5276 (org-set-local 'outline-isearch-open-invisible-function
5277 (lambda (&rest ignore) (org-show-context 'isearch)))
5278 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5280 ;; Setup the pcomplete hooks
5281 (set (make-local-variable 'pcomplete-command-completion-function)
5282 'org-pcomplete-initial)
5283 (set (make-local-variable 'pcomplete-command-name-function)
5284 'org-command-at-point)
5285 (set (make-local-variable 'pcomplete-default-completion-function)
5286 'ignore)
5287 (set (make-local-variable 'pcomplete-parse-arguments-function)
5288 'org-parse-arguments)
5289 (set (make-local-variable 'pcomplete-termination-string) "")
5290 (when (>= emacs-major-version 23)
5291 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5293 ;; If empty file that did not turn on org-mode automatically, make it to.
5294 (if (and org-insert-mode-line-in-empty-file
5295 (org-called-interactively-p 'any)
5296 (= (point-min) (point-max)))
5297 (insert "# -*- mode: org -*-\n\n"))
5298 (unless org-inhibit-startup
5299 (org-unmodified
5300 (and org-startup-with-beamer-mode (org-beamer-mode))
5301 (when org-startup-align-all-tables
5302 (org-table-map-tables 'org-table-align 'quietly))
5303 (when org-startup-with-inline-images
5304 (org-display-inline-images))
5305 (when org-startup-with-latex-preview
5306 (org-preview-latex-fragment))
5307 (unless org-inhibit-startup-visibility-stuff
5308 (org-set-startup-visibility))))
5309 ;; Try to set org-hide correctly
5310 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5312 ;; Update `customize-package-emacs-version-alist'
5313 (add-to-list 'customize-package-emacs-version-alist
5314 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5315 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5316 ("8.0" . "24.4")))
5318 (defvar org-mode-transpose-word-syntax-table
5319 (let ((st (make-syntax-table)))
5320 (mapc (lambda(c) (modify-syntax-entry
5321 (string-to-char (car c)) "w p" st))
5322 org-emphasis-alist)
5323 st))
5325 (when (fboundp 'abbrev-table-put)
5326 (abbrev-table-put org-mode-abbrev-table
5327 :parents (list text-mode-abbrev-table)))
5329 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5331 (defsubst org-fix-ellipsis-at-bol ()
5332 (save-excursion (goto-char (window-start)) (recenter 0)))
5334 (defun org-find-invisible-foreground ()
5335 (let ((candidates (remove
5336 "unspecified-bg"
5337 (nconc
5338 (list (face-background 'default)
5339 (face-background 'org-default))
5340 (mapcar
5341 (lambda (alist)
5342 (when (boundp alist)
5343 (cdr (assoc 'background-color (symbol-value alist)))))
5344 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5345 (list (face-foreground 'org-hide))))))
5346 (car (remove nil candidates))))
5348 (defun org-current-time (&optional rounding-minutes past)
5349 "Current time, possibly rounded to ROUNDING-MINUTES.
5350 When ROUNDING-MINUTES is not an integer, fall back on the car of
5351 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5352 the rounding returns a past time."
5353 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5354 (car org-time-stamp-rounding-minutes)))
5355 (time (decode-time)) res)
5356 (if (< r 1)
5357 (current-time)
5358 (setq res
5359 (apply 'encode-time
5360 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5361 (nthcdr 2 time))))
5362 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5363 (seconds-to-time (- (org-float-time res) (* r 60)))
5364 res))))
5366 (defun org-today ()
5367 "Return today date, considering `org-extend-today-until'."
5368 (time-to-days
5369 (time-subtract (current-time)
5370 (list 0 (* 3600 org-extend-today-until) 0))))
5372 ;;;; Font-Lock stuff, including the activators
5374 (defvar org-mouse-map (make-sparse-keymap))
5375 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5376 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5377 (when org-mouse-1-follows-link
5378 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5379 (when org-tab-follows-link
5380 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5381 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5383 (require 'font-lock)
5385 (defconst org-non-link-chars "]\t\n\r<>")
5386 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5387 "shell" "elisp" "doi" "message"))
5388 (defvar org-link-types-re nil
5389 "Matches a link that has a url-like prefix like \"http:\"")
5390 (defvar org-link-re-with-space nil
5391 "Matches a link with spaces, optional angular brackets around it.")
5392 (defvar org-link-re-with-space2 nil
5393 "Matches a link with spaces, optional angular brackets around it.")
5394 (defvar org-link-re-with-space3 nil
5395 "Matches a link with spaces, only for internal part in bracket links.")
5396 (defvar org-angle-link-re nil
5397 "Matches link with angular brackets, spaces are allowed.")
5398 (defvar org-plain-link-re nil
5399 "Matches plain link, without spaces.")
5400 (defvar org-bracket-link-regexp nil
5401 "Matches a link in double brackets.")
5402 (defvar org-bracket-link-analytic-regexp nil
5403 "Regular expression used to analyze links.
5404 Here is what the match groups contain after a match:
5405 1: http:
5406 2: http
5407 3: path
5408 4: [desc]
5409 5: desc")
5410 (defvar org-bracket-link-analytic-regexp++ nil
5411 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5412 (defvar org-any-link-re nil
5413 "Regular expression matching any link.")
5415 (defconst org-match-sexp-depth 3
5416 "Number of stacked braces for sub/superscript matching.")
5418 (defun org-create-multibrace-regexp (left right n)
5419 "Create a regular expression which will match a balanced sexp.
5420 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5421 as single character strings.
5422 The regexp returned will match the entire expression including the
5423 delimiters. It will also define a single group which contains the
5424 match except for the outermost delimiters. The maximum depth of
5425 stacked delimiters is N. Escaping delimiters is not possible."
5426 (let* ((nothing (concat "[^" left right "]*?"))
5427 (or "\\|")
5428 (re nothing)
5429 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5430 (while (> n 1)
5431 (setq n (1- n)
5432 re (concat re or next)
5433 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5434 (concat left "\\(" re "\\)" right)))
5436 (defvar org-match-substring-regexp
5437 (concat
5438 "\\(\\S-\\)\\([_^]\\)\\("
5439 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5440 "\\|"
5441 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5442 "\\|"
5443 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5444 "The regular expression matching a sub- or superscript.")
5446 (defvar org-match-substring-with-braces-regexp
5447 (concat
5448 "\\(\\S-\\)\\([_^]\\)\\("
5449 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5450 "\\)")
5451 "The regular expression matching a sub- or superscript, forcing braces.")
5453 (defun org-make-link-regexps ()
5454 "Update the link regular expressions.
5455 This should be called after the variable `org-link-types' has changed."
5456 (setq org-link-types-re
5457 (concat
5458 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5459 org-link-re-with-space
5460 (concat
5461 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5462 "\\([^" org-non-link-chars " ]"
5463 "[^" org-non-link-chars "]*"
5464 "[^" org-non-link-chars " ]\\)>?")
5465 org-link-re-with-space2
5466 (concat
5467 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5468 "\\([^" org-non-link-chars " ]"
5469 "[^\t\n\r]*"
5470 "[^" org-non-link-chars " ]\\)>?")
5471 org-link-re-with-space3
5472 (concat
5473 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5474 "\\([^" org-non-link-chars " ]"
5475 "[^\t\n\r]*\\)")
5476 org-angle-link-re
5477 (concat
5478 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5479 "\\([^" org-non-link-chars " ]"
5480 "[^" org-non-link-chars "]*"
5481 "\\)>")
5482 org-plain-link-re
5483 (concat
5484 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5485 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5486 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5487 org-bracket-link-regexp
5488 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5489 org-bracket-link-analytic-regexp
5490 (concat
5491 "\\[\\["
5492 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5493 "\\([^]]+\\)"
5494 "\\]"
5495 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5496 "\\]")
5497 org-bracket-link-analytic-regexp++
5498 (concat
5499 "\\[\\["
5500 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5501 "\\([^]]+\\)"
5502 "\\]"
5503 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5504 "\\]")
5505 org-any-link-re
5506 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5507 org-angle-link-re "\\)\\|\\("
5508 org-plain-link-re "\\)")))
5510 (org-make-link-regexps)
5512 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5513 "Regular expression for fast time stamp matching.")
5514 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5515 "Regular expression for fast time stamp matching.")
5516 (defconst org-ts-regexp0
5517 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5518 "Regular expression matching time strings for analysis.
5519 This one does not require the space after the date, so it can be used
5520 on a string that terminates immediately after the date.")
5521 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5522 "Regular expression matching time strings for analysis.")
5523 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5524 "Regular expression matching time stamps, with groups.")
5525 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5526 "Regular expression matching time stamps (also [..]), with groups.")
5527 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5528 "Regular expression matching a time stamp range.")
5529 (defconst org-tr-regexp-both
5530 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5531 "Regular expression matching a time stamp range.")
5532 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5533 org-ts-regexp "\\)?")
5534 "Regular expression matching a time stamp or time stamp range.")
5535 (defconst org-tsr-regexp-both
5536 (concat org-ts-regexp-both "\\(--?-?"
5537 org-ts-regexp-both "\\)?")
5538 "Regular expression matching a time stamp or time stamp range.
5539 The time stamps may be either active or inactive.")
5541 (defvar org-emph-face nil)
5543 (defun org-do-emphasis-faces (limit)
5544 "Run through the buffer and add overlays to emphasized strings."
5545 (let (rtn a)
5546 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5547 (if (not (= (char-after (match-beginning 3))
5548 (char-after (match-beginning 4))))
5549 (progn
5550 (setq rtn t)
5551 (setq a (assoc (match-string 3) org-emphasis-alist))
5552 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5553 'face
5554 (nth 1 a))
5555 (and (nth 4 a)
5556 (org-remove-flyspell-overlays-in
5557 (match-beginning 0) (match-end 0)))
5558 (add-text-properties (match-beginning 2) (match-end 2)
5559 '(font-lock-multiline t org-emphasis t))
5560 (when org-hide-emphasis-markers
5561 (add-text-properties (match-end 4) (match-beginning 5)
5562 '(invisible org-link))
5563 (add-text-properties (match-beginning 3) (match-end 3)
5564 '(invisible org-link)))))
5565 (backward-char 1))
5566 rtn))
5568 (defun org-emphasize (&optional char)
5569 "Insert or change an emphasis, i.e. a font like bold or italic.
5570 If there is an active region, change that region to a new emphasis.
5571 If there is no region, just insert the marker characters and position
5572 the cursor between them.
5573 CHAR should be either the marker character, or the first character of the
5574 HTML tag associated with that emphasis. If CHAR is a space, the means
5575 to remove the emphasis of the selected region.
5576 If char is not given (for example in an interactive call) it
5577 will be prompted for."
5578 (interactive)
5579 (let ((eal org-emphasis-alist) e det
5580 (erc org-emphasis-regexp-components)
5581 (prompt "")
5582 (string "") beg end move tag c s)
5583 (if (org-region-active-p)
5584 (setq beg (region-beginning) end (region-end)
5585 string (buffer-substring beg end))
5586 (setq move t))
5588 (while (setq e (pop eal))
5589 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5590 c (aref tag 0))
5591 (push (cons c (string-to-char (car e))) det)
5592 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5593 (substring tag 1)))))
5594 (setq det (nreverse det))
5595 (unless char
5596 (message "%s" (concat "Emphasis marker or tag:" prompt))
5597 (setq char (read-char-exclusive)))
5598 (setq char (or (cdr (assoc char det)) char))
5599 (if (equal char ?\ )
5600 (setq s "" move nil)
5601 (unless (assoc (char-to-string char) org-emphasis-alist)
5602 (error "No such emphasis marker: \"%c\"" char))
5603 (setq s (char-to-string char)))
5604 (while (and (> (length string) 1)
5605 (equal (substring string 0 1) (substring string -1))
5606 (assoc (substring string 0 1) org-emphasis-alist))
5607 (setq string (substring string 1 -1)))
5608 (setq string (concat s string s))
5609 (if beg (delete-region beg end))
5610 (unless (or (bolp)
5611 (string-match (concat "[" (nth 0 erc) "\n]")
5612 (char-to-string (char-before (point)))))
5613 (insert " "))
5614 (unless (or (eobp)
5615 (string-match (concat "[" (nth 1 erc) "\n]")
5616 (char-to-string (char-after (point)))))
5617 (insert " ") (backward-char 1))
5618 (insert string)
5619 (and move (backward-char 1))))
5621 (defconst org-nonsticky-props
5622 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5624 (defsubst org-rear-nonsticky-at (pos)
5625 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5627 (defun org-activate-plain-links (limit)
5628 "Run through the buffer and add overlays to links."
5629 (let (f hl)
5630 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5631 (not (org-in-src-block-p)))
5632 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5633 (setq f (get-text-property (match-beginning 0) 'face))
5634 (setq hl (org-match-string-no-properties 0))
5635 (if (or (eq f 'org-tag)
5636 (and (listp f) (memq 'org-tag f)))
5638 (add-text-properties (match-beginning 0) (match-end 0)
5639 (list 'mouse-face 'highlight
5640 'face 'org-link
5641 'htmlize-link `(:uri ,hl)
5642 'keymap org-mouse-map))
5643 (org-rear-nonsticky-at (match-end 0)))
5644 t)))
5646 (defun org-activate-code (limit)
5647 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5648 (progn
5649 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5650 (remove-text-properties (match-beginning 0) (match-end 0)
5651 '(display t invisible t intangible t))
5652 t)))
5654 (defcustom org-src-fontify-natively nil
5655 "When non-nil, fontify code in code blocks."
5656 :type 'boolean
5657 :version "24.1"
5658 :group 'org-appearance
5659 :group 'org-babel)
5661 (defcustom org-allow-promoting-top-level-subtree nil
5662 "When non-nil, allow promoting a top level subtree.
5663 The leading star of the top level headline will be replaced
5664 by a #."
5665 :type 'boolean
5666 :version "24.1"
5667 :group 'org-appearance)
5669 (defun org-fontify-meta-lines-and-blocks (limit)
5670 (condition-case nil
5671 (org-fontify-meta-lines-and-blocks-1 limit)
5672 (error (message "org-mode fontification error"))))
5674 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5675 "Fontify #+ lines and blocks, in the correct ways."
5676 (let ((case-fold-search t))
5677 (if (re-search-forward
5678 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5679 limit t)
5680 (let ((beg (match-beginning 0))
5681 (block-start (match-end 0))
5682 (block-end nil)
5683 (lang (match-string 7))
5684 (beg1 (line-beginning-position 2))
5685 (dc1 (downcase (match-string 2)))
5686 (dc3 (downcase (match-string 3)))
5687 end end1 quoting block-type ovl)
5688 (cond
5689 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5690 ;; a single line of backend-specific content
5691 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5692 (remove-text-properties (match-beginning 0) (match-end 0)
5693 '(display t invisible t intangible t))
5694 (add-text-properties (match-beginning 1) (match-end 3)
5695 '(font-lock-fontified t face org-meta-line))
5696 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5697 '(font-lock-fontified t face org-block))
5698 ; for backend-specific code
5700 ((and (match-end 4) (equal dc3 "+begin"))
5701 ;; Truly a block
5702 (setq block-type (downcase (match-string 5))
5703 quoting (member block-type org-protecting-blocks))
5704 (when (re-search-forward
5705 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5706 nil t) ;; on purpose, we look further than LIMIT
5707 (setq end (min (point-max) (match-end 0))
5708 end1 (min (point-max) (1- (match-beginning 0))))
5709 (setq block-end (match-beginning 0))
5710 (when quoting
5711 (remove-text-properties beg end
5712 '(display t invisible t intangible t)))
5713 (add-text-properties
5714 beg end
5715 '(font-lock-fontified t font-lock-multiline t))
5716 (add-text-properties beg beg1 '(face org-meta-line))
5717 (add-text-properties end1 (min (point-max) (1+ end))
5718 '(face org-meta-line)) ; for end_src
5719 (cond
5720 ((and lang (not (string= lang "")) org-src-fontify-natively)
5721 (org-src-font-lock-fontify-block lang block-start block-end)
5722 ;; remove old background overlays
5723 (mapc (lambda (ov)
5724 (if (eq (overlay-get ov 'face) 'org-block-background)
5725 (delete-overlay ov)))
5726 (overlays-at (/ (+ beg1 block-end) 2)))
5727 ;; add a background overlay
5728 (setq ovl (make-overlay beg1 block-end))
5729 (overlay-put ovl 'face 'org-block-background)
5730 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5731 (quoting
5732 (add-text-properties beg1 (min (point-max) (1+ end1))
5733 '(face org-block))) ; end of source block
5734 ((not org-fontify-quote-and-verse-blocks))
5735 ((string= block-type "quote")
5736 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5737 ((string= block-type "verse")
5738 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5739 (add-text-properties beg beg1 '(face org-block-begin-line))
5740 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5741 '(face org-block-end-line))
5743 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5744 (add-text-properties
5745 beg (match-end 3)
5746 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5747 '(font-lock-fontified t invisible t)
5748 '(font-lock-fontified t face org-document-info-keyword)))
5749 (add-text-properties
5750 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5751 (if (string-equal dc1 "+title:")
5752 '(font-lock-fontified t face org-document-title)
5753 '(font-lock-fontified t face org-document-info))))
5754 ((or (equal dc1 "+results")
5755 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5756 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5757 "+call:" "+header:" "+headers:" "+name:"))
5758 (and (match-end 4) (equal dc3 "+attr")))
5759 (add-text-properties
5760 beg (match-end 0)
5761 '(font-lock-fontified t face org-meta-line))
5763 ((member dc3 '(" " ""))
5764 (add-text-properties
5765 beg (match-end 0)
5766 '(font-lock-fontified t face font-lock-comment-face)))
5767 ((not (member (char-after beg) '(?\ ?\t)))
5768 ;; just any other in-buffer setting, but not indented
5769 (add-text-properties
5770 beg (match-end 0)
5771 '(font-lock-fontified t face org-meta-line))
5773 (t nil))))))
5775 (defun org-activate-angle-links (limit)
5776 "Run through the buffer and add overlays to links."
5777 (if (and (re-search-forward org-angle-link-re limit t)
5778 (not (org-in-src-block-p)))
5779 (progn
5780 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5781 (add-text-properties (match-beginning 0) (match-end 0)
5782 (list 'mouse-face 'highlight
5783 'keymap org-mouse-map))
5784 (org-rear-nonsticky-at (match-end 0))
5785 t)))
5787 (defun org-activate-footnote-links (limit)
5788 "Run through the buffer and add overlays to footnotes."
5789 (let ((fn (org-footnote-next-reference-or-definition limit)))
5790 (when fn
5791 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5792 (org-remove-flyspell-overlays-in beg end)
5793 (add-text-properties beg end
5794 (list 'mouse-face 'highlight
5795 'keymap org-mouse-map
5796 'help-echo
5797 (if (= (point-at-bol) beg)
5798 "Footnote definition"
5799 "Footnote reference")
5800 'font-lock-fontified t
5801 'font-lock-multiline t
5802 'face 'org-footnote))))))
5804 (defun org-activate-bracket-links (limit)
5805 "Run through the buffer and add overlays to bracketed links."
5806 (if (and (re-search-forward org-bracket-link-regexp limit t)
5807 (not (org-in-src-block-p)))
5808 (let* ((hl (org-match-string-no-properties 1))
5809 (help (concat "LINK: " hl))
5810 ;; FIXME: Above we should remove the escapes. But that
5811 ;; requires another match, protecting match data, a lot
5812 ;; of overhead for font-lock.
5813 (ip (org-maybe-intangible
5814 (list 'invisible 'org-link
5815 'keymap org-mouse-map 'mouse-face 'highlight
5816 'font-lock-multiline t 'help-echo help
5817 'htmlize-link `(:uri ,hl))))
5818 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5819 'font-lock-multiline t 'help-echo help
5820 'htmlize-link `(:uri ,hl))))
5821 ;; We need to remove the invisible property here. Table narrowing
5822 ;; may have made some of this invisible.
5823 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5824 (remove-text-properties (match-beginning 0) (match-end 0)
5825 '(invisible nil))
5826 (if (match-end 3)
5827 (progn
5828 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5829 (org-rear-nonsticky-at (match-beginning 3))
5830 (add-text-properties (match-beginning 3) (match-end 3) vp)
5831 (org-rear-nonsticky-at (match-end 3))
5832 (add-text-properties (match-end 3) (match-end 0) ip)
5833 (org-rear-nonsticky-at (match-end 0)))
5834 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5835 (org-rear-nonsticky-at (match-beginning 1))
5836 (add-text-properties (match-beginning 1) (match-end 1) vp)
5837 (org-rear-nonsticky-at (match-end 1))
5838 (add-text-properties (match-end 1) (match-end 0) ip)
5839 (org-rear-nonsticky-at (match-end 0)))
5840 t)))
5842 (defun org-activate-dates (limit)
5843 "Run through the buffer and add overlays to dates."
5844 (if (and (re-search-forward org-tsr-regexp-both limit t)
5845 (not (equal (char-before (match-beginning 0)) 91)))
5846 (progn
5847 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5848 (add-text-properties (match-beginning 0) (match-end 0)
5849 (list 'mouse-face 'highlight
5850 'keymap org-mouse-map))
5851 (org-rear-nonsticky-at (match-end 0))
5852 (when org-display-custom-times
5853 (if (match-end 3)
5854 (org-display-custom-time (match-beginning 3) (match-end 3)))
5855 (org-display-custom-time (match-beginning 1) (match-end 1)))
5856 t)))
5858 (defvar org-target-link-regexp nil
5859 "Regular expression matching radio targets in plain text.")
5860 (make-variable-buffer-local 'org-target-link-regexp)
5861 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5862 "Regular expression matching a link target.")
5863 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5864 "Regular expression matching a radio target.")
5865 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5866 "Regular expression matching any target.")
5868 (defun org-activate-target-links (limit)
5869 "Run through the buffer and add overlays to target matches."
5870 (when org-target-link-regexp
5871 (let ((case-fold-search t))
5872 (if (re-search-forward org-target-link-regexp limit t)
5873 (progn
5874 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5875 (add-text-properties (match-beginning 0) (match-end 0)
5876 (list 'mouse-face 'highlight
5877 'keymap org-mouse-map
5878 'help-echo "Radio target link"
5879 'org-linked-text t))
5880 (org-rear-nonsticky-at (match-end 0))
5881 t)))))
5883 (defun org-update-radio-target-regexp ()
5884 "Find all radio targets in this file and update the regular expression."
5885 (interactive)
5886 (when (memq 'radio org-activate-links)
5887 (setq org-target-link-regexp
5888 (org-make-target-link-regexp (org-all-targets 'radio)))
5889 (org-restart-font-lock)))
5891 (defun org-hide-wide-columns (limit)
5892 (let (s e)
5893 (setq s (text-property-any (point) (or limit (point-max))
5894 'org-cwidth t))
5895 (when s
5896 (setq e (next-single-property-change s 'org-cwidth))
5897 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5898 (goto-char e)
5899 t)))
5901 (defvar org-latex-and-related-regexp nil
5902 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5903 (defvar org-match-substring-regexp)
5904 (defvar org-match-substring-with-braces-regexp)
5906 (defun org-compute-latex-and-related-regexp ()
5907 "Compute regular expression for LaTeX, entities and sub/superscript.
5908 Result depends on variable `org-highlight-latex-and-related'."
5909 (org-set-local
5910 'org-latex-and-related-regexp
5911 (let* ((re-sub
5912 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5913 ((eq org-use-sub-superscripts '{})
5914 (list org-match-substring-with-braces-regexp))
5915 (org-use-sub-superscripts (list org-match-substring-regexp))))
5916 (re-latex
5917 (when (memq 'latex org-highlight-latex-and-related)
5918 (let ((matchers (plist-get org-format-latex-options :matchers)))
5919 (delq nil
5920 (mapcar (lambda (x)
5921 (and (member (car x) matchers) (nth 1 x)))
5922 org-latex-regexps)))))
5923 (re-entities
5924 (when (memq 'entities org-highlight-latex-and-related)
5925 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5926 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5928 (defun org-do-latex-and-related (limit)
5929 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5930 LIMIT bounds the search for syntax to highlight. Stop at first
5931 highlighted object, if any. Return t if some highlighting was
5932 done, nil otherwise."
5933 (when (org-string-nw-p org-latex-and-related-regexp)
5934 (catch 'found
5935 (while (re-search-forward org-latex-and-related-regexp limit t)
5936 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5937 'face))
5938 '(org-code org-verbatim underline))
5939 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5940 '(?_ ?^))
5942 0)))
5943 (font-lock-prepend-text-property
5944 (+ offset (match-beginning 0)) (match-end 0)
5945 'face 'org-latex-and-related)
5946 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5947 '(font-lock-multiline t)))
5948 (throw 'found t)))
5949 nil)))
5951 (defun org-restart-font-lock ()
5952 "Restart `font-lock-mode', to force refontification."
5953 (when (and (boundp 'font-lock-mode) font-lock-mode)
5954 (font-lock-mode -1)
5955 (font-lock-mode 1)))
5957 (defun org-all-targets (&optional radio)
5958 "Return a list of all targets in this file.
5959 When optional argument RADIO is non-nil, only find radio
5960 targets."
5961 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5962 (save-excursion
5963 (goto-char (point-min))
5964 (while (re-search-forward re nil t)
5965 ;; Make sure point is really within the object.
5966 (backward-char)
5967 (let ((obj (org-element-context)))
5968 (when (memq (org-element-type obj) '(radio-target target))
5969 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5970 rtn)))
5972 (defun org-make-target-link-regexp (targets)
5973 "Make regular expression matching all strings in TARGETS.
5974 The regular expression finds the targets also if there is a line break
5975 between words."
5976 (and targets
5977 (concat
5978 "\\<\\("
5979 (mapconcat
5980 (lambda (x)
5981 (setq x (regexp-quote x))
5982 (while (string-match " +" x)
5983 (setq x (replace-match "\\s-+" t t x)))
5985 targets
5986 "\\|")
5987 "\\)\\>")))
5989 (defun org-activate-tags (limit)
5990 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5991 (progn
5992 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5993 (add-text-properties (match-beginning 1) (match-end 1)
5994 (list 'mouse-face 'highlight
5995 'keymap org-mouse-map))
5996 (org-rear-nonsticky-at (match-end 1))
5997 t)))
5999 (defun org-outline-level ()
6000 "Compute the outline level of the heading at point.
6001 If this is called at a normal headline, the level is the number of stars.
6002 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6003 (save-excursion
6004 (if (not (condition-case nil
6005 (org-back-to-heading t)
6006 (error nil)))
6008 (looking-at org-outline-regexp)
6009 (1- (- (match-end 0) (match-beginning 0))))))
6011 (defvar org-font-lock-keywords nil)
6013 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6014 "Regular expression matching a property line.")
6016 (defvar org-font-lock-hook nil
6017 "Functions to be called for special font lock stuff.")
6019 (defvar org-font-lock-set-keywords-hook nil
6020 "Functions that can manipulate `org-font-lock-extra-keywords'.
6021 This is called after `org-font-lock-extra-keywords' is defined, but before
6022 it is installed to be used by font lock. This can be useful if something
6023 needs to be inserted at a specific position in the font-lock sequence.")
6025 (defun org-font-lock-hook (limit)
6026 "Run `org-font-lock-hook' within LIMIT."
6027 (run-hook-with-args 'org-font-lock-hook limit))
6029 (defun org-set-font-lock-defaults ()
6030 "Set font lock defaults for the current buffer."
6031 (let* ((em org-fontify-emphasized-text)
6032 (lk org-activate-links)
6033 (org-font-lock-extra-keywords
6034 (list
6035 ;; Call the hook
6036 '(org-font-lock-hook)
6037 ;; Headlines
6038 `(,(if org-fontify-whole-heading-line
6039 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6040 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6041 (1 (org-get-level-face 1))
6042 (2 (org-get-level-face 2))
6043 (3 (org-get-level-face 3)))
6044 ;; Table lines
6045 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6046 (1 'org-table t))
6047 ;; Table internals
6048 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6049 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6050 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6051 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6052 ;; Drawers
6053 (list org-drawer-regexp '(0 'org-special-keyword t))
6054 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6055 ;; Properties
6056 (list org-property-re
6057 '(1 'org-special-keyword t)
6058 '(3 'org-property-value t))
6059 ;; Links
6060 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6061 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6062 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6063 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6064 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6065 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6066 (if (memq 'footnote lk) '(org-activate-footnote-links))
6067 ;; Targets.
6068 (list org-any-target-regexp '(0 'org-target t))
6069 ;; Diary sexps.
6070 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6071 ;; Macro
6072 '("{{{.+}}}" (0 'org-macro t))
6073 '(org-hide-wide-columns (0 nil append))
6074 ;; TODO keyword
6075 (list (format org-heading-keyword-regexp-format
6076 org-todo-regexp)
6077 '(2 (org-get-todo-face 2) t))
6078 ;; DONE
6079 (if org-fontify-done-headline
6080 (list (format org-heading-keyword-regexp-format
6081 (concat
6082 "\\(?:"
6083 (mapconcat 'regexp-quote org-done-keywords "\\|")
6084 "\\)"))
6085 '(2 'org-headline-done t))
6086 nil)
6087 ;; Priorities
6088 '(org-font-lock-add-priority-faces)
6089 ;; Tags
6090 '(org-font-lock-add-tag-faces)
6091 ;; Special keywords
6092 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6093 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6094 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6095 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6096 ;; Emphasis
6097 (if em
6098 (if (featurep 'xemacs)
6099 '(org-do-emphasis-faces (0 nil append))
6100 '(org-do-emphasis-faces)))
6101 ;; Checkboxes
6102 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6103 1 'org-checkbox prepend)
6104 (if (cdr (assq 'checkbox org-list-automatic-rules))
6105 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6106 (0 (org-get-checkbox-statistics-face) t)))
6107 ;; Description list items
6108 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6109 1 'org-list-dt prepend)
6110 ;; ARCHIVEd headings
6111 (list (concat
6112 org-outline-regexp-bol
6113 "\\(.*:" org-archive-tag ":.*\\)")
6114 '(1 'org-archived prepend))
6115 ;; Specials
6116 '(org-do-latex-and-related)
6117 '(org-fontify-entities)
6118 '(org-raise-scripts)
6119 ;; Code
6120 '(org-activate-code (1 'org-code t))
6121 ;; COMMENT
6122 (list (format org-heading-keyword-regexp-format
6123 (concat "\\("
6124 org-comment-string "\\|" org-quote-string
6125 "\\)"))
6126 '(2 'org-special-keyword t))
6127 ;; Blocks and meta lines
6128 '(org-fontify-meta-lines-and-blocks)
6130 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6131 (run-hooks 'org-font-lock-set-keywords-hook)
6132 ;; Now set the full font-lock-keywords
6133 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6134 (org-set-local 'font-lock-defaults
6135 '(org-font-lock-keywords t nil nil backward-paragraph))
6136 (kill-local-variable 'font-lock-keywords) nil))
6138 (defun org-toggle-pretty-entities ()
6139 "Toggle the composition display of entities as UTF8 characters."
6140 (interactive)
6141 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6142 (org-restart-font-lock)
6143 (if org-pretty-entities
6144 (message "Entities are displayed as UTF8 characters")
6145 (save-restriction
6146 (widen)
6147 (org-decompose-region (point-min) (point-max))
6148 (message "Entities are displayed plain"))))
6150 (defvar org-custom-properties-overlays nil
6151 "List of overlays used for custom properties.")
6152 (make-variable-buffer-local 'org-custom-properties-overlays)
6154 (defun org-toggle-custom-properties-visibility ()
6155 "Display or hide properties in `org-custom-properties'."
6156 (interactive)
6157 (if org-custom-properties-overlays
6158 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6159 (setq org-custom-properties-overlays nil))
6160 (unless (not org-custom-properties)
6161 (save-excursion
6162 (save-restriction
6163 (widen)
6164 (goto-char (point-min))
6165 (while (re-search-forward org-property-re nil t)
6166 (mapc (lambda(p)
6167 (when (equal p (substring (match-string 1) 1 -1))
6168 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6169 (overlay-put o 'invisible t)
6170 (overlay-put o 'org-custom-property t)
6171 (push o org-custom-properties-overlays))))
6172 org-custom-properties)))))))
6174 (defun org-fontify-entities (limit)
6175 "Find an entity to fontify."
6176 (let (ee)
6177 (when org-pretty-entities
6178 (catch 'match
6179 (while (re-search-forward
6180 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6181 limit t)
6182 (if (and (not (org-in-indented-comment-line))
6183 (setq ee (org-entity-get (match-string 1)))
6184 (= (length (nth 6 ee)) 1))
6185 (let*
6186 ((end (if (equal (match-string 2) "{}")
6187 (match-end 2)
6188 (match-end 1))))
6189 (add-text-properties
6190 (match-beginning 0) end
6191 (list 'font-lock-fontified t))
6192 (compose-region (match-beginning 0) end
6193 (nth 6 ee) nil)
6194 (backward-char 1)
6195 (throw 'match t))))
6196 nil))))
6198 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6199 "Fontify string S like in Org-mode."
6200 (with-temp-buffer
6201 (insert s)
6202 (let ((org-odd-levels-only odd-levels))
6203 (org-mode)
6204 (font-lock-fontify-buffer)
6205 (buffer-string))))
6207 (defvar org-m nil)
6208 (defvar org-l nil)
6209 (defvar org-f nil)
6210 (defun org-get-level-face (n)
6211 "Get the right face for match N in font-lock matching of headlines."
6212 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6213 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6214 (if org-cycle-level-faces
6215 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6216 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6217 (cond
6218 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6219 ((eq n 2) org-f)
6220 (t (if org-level-color-stars-only nil org-f))))
6223 (defun org-get-todo-face (kwd)
6224 "Get the right face for a TODO keyword KWD.
6225 If KWD is a number, get the corresponding match group."
6226 (if (numberp kwd) (setq kwd (match-string kwd)))
6227 (or (org-face-from-face-or-color
6228 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6229 (and (member kwd org-done-keywords) 'org-done)
6230 'org-todo))
6232 (defun org-face-from-face-or-color (context inherit face-or-color)
6233 "Create a face list that inherits INHERIT, but sets the foreground color.
6234 When FACE-OR-COLOR is not a string, just return it."
6235 (if (stringp face-or-color)
6236 (list :inherit inherit
6237 (cdr (assoc context org-faces-easy-properties))
6238 face-or-color)
6239 face-or-color))
6241 (defun org-font-lock-add-tag-faces (limit)
6242 "Add the special tag faces."
6243 (when (and org-tag-faces org-tags-special-faces-re)
6244 (while (re-search-forward org-tags-special-faces-re limit t)
6245 (add-text-properties (match-beginning 1) (match-end 1)
6246 (list 'face (org-get-tag-face 1)
6247 'font-lock-fontified t))
6248 (backward-char 1))))
6250 (defun org-font-lock-add-priority-faces (limit)
6251 "Add the special priority faces."
6252 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6253 (when (save-match-data (org-at-heading-p))
6254 (add-text-properties
6255 (match-beginning 0) (match-end 0)
6256 (list 'face (or (org-face-from-face-or-color
6257 'priority 'org-priority
6258 (cdr (assoc (char-after (match-beginning 1))
6259 org-priority-faces)))
6260 'org-priority)
6261 'font-lock-fontified t)))))
6263 (defun org-get-tag-face (kwd)
6264 "Get the right face for a TODO keyword KWD.
6265 If KWD is a number, get the corresponding match group."
6266 (if (numberp kwd) (setq kwd (match-string kwd)))
6267 (or (org-face-from-face-or-color
6268 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6269 'org-tag))
6271 (defun org-unfontify-region (beg end &optional maybe_loudly)
6272 "Remove fontification and activation overlays from links."
6273 (font-lock-default-unfontify-region beg end)
6274 (let* ((buffer-undo-list t)
6275 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6276 (inhibit-modification-hooks t)
6277 deactivate-mark buffer-file-name buffer-file-truename)
6278 (org-decompose-region beg end)
6279 (remove-text-properties beg end
6280 '(mouse-face t keymap t org-linked-text t
6281 invisible t intangible t
6282 org-no-flyspell t org-emphasis t))
6283 (org-remove-font-lock-display-properties beg end)))
6285 (defconst org-script-display '(((raise -0.3) (height 0.7))
6286 ((raise 0.3) (height 0.7))
6287 ((raise -0.5))
6288 ((raise 0.5)))
6289 "Display properties for showing superscripts and subscripts.")
6291 (defun org-remove-font-lock-display-properties (beg end)
6292 "Remove specific display properties that have been added by font lock.
6293 The will remove the raise properties that are used to show superscripts
6294 and subscripts."
6295 (let (next prop)
6296 (while (< beg end)
6297 (setq next (next-single-property-change beg 'display nil end)
6298 prop (get-text-property beg 'display))
6299 (if (member prop org-script-display)
6300 (put-text-property beg next 'display nil))
6301 (setq beg next))))
6303 (defun org-raise-scripts (limit)
6304 "Add raise properties to sub/superscripts."
6305 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6306 (if (re-search-forward
6307 (if (eq org-use-sub-superscripts t)
6308 org-match-substring-regexp
6309 org-match-substring-with-braces-regexp)
6310 limit t)
6311 (let* ((pos (point)) table-p comment-p
6312 (mpos (match-beginning 3))
6313 (emph-p (get-text-property mpos 'org-emphasis))
6314 (link-p (get-text-property mpos 'mouse-face))
6315 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6316 (goto-char (point-at-bol))
6317 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6318 comment-p (org-looking-at-p "[ \t]*#"))
6319 (goto-char pos)
6320 ;; FIXME: Should we go back one character here, for a_b^c
6321 ;; (goto-char (1- pos)) ;????????????????????
6322 (if (or comment-p emph-p link-p keyw-p)
6324 (put-text-property (match-beginning 3) (match-end 0)
6325 'display
6326 (if (equal (char-after (match-beginning 2)) ?^)
6327 (nth (if table-p 3 1) org-script-display)
6328 (nth (if table-p 2 0) org-script-display)))
6329 (add-text-properties (match-beginning 2) (match-end 2)
6330 (list 'invisible t
6331 'org-dwidth t 'org-dwidth-n 1))
6332 (if (and (eq (char-after (match-beginning 3)) ?{)
6333 (eq (char-before (match-end 3)) ?}))
6334 (progn
6335 (add-text-properties
6336 (match-beginning 3) (1+ (match-beginning 3))
6337 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6338 (add-text-properties
6339 (1- (match-end 3)) (match-end 3)
6340 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6341 t)))))
6343 ;;;; Visibility cycling, including org-goto and indirect buffer
6345 ;;; Cycling
6347 (defvar org-cycle-global-status nil)
6348 (make-variable-buffer-local 'org-cycle-global-status)
6349 (put 'org-cycle-global-status 'org-state t)
6350 (defvar org-cycle-subtree-status nil)
6351 (make-variable-buffer-local 'org-cycle-subtree-status)
6352 (put 'org-cycle-subtree-status 'org-state t)
6354 (defvar org-inlinetask-min-level)
6356 ;;;###autoload
6357 (defun org-cycle (&optional arg)
6358 "TAB-action and visibility cycling for Org-mode.
6360 This is the command invoked in Org-mode by the TAB key. Its main purpose
6361 is outline visibility cycling, but it also invokes other actions
6362 in special contexts.
6364 - When this function is called with a prefix argument, rotate the entire
6365 buffer through 3 states (global cycling)
6366 1. OVERVIEW: Show only top-level headlines.
6367 2. CONTENTS: Show all headlines of all levels, but no body text.
6368 3. SHOW ALL: Show everything.
6369 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6370 determined by the variable `org-startup-folded', and by any VISIBILITY
6371 properties in the buffer.
6372 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6373 including any drawers.
6375 - When inside a table, re-align the table and move to the next field.
6377 - When point is at the beginning of a headline, rotate the subtree started
6378 by this line through 3 different states (local cycling)
6379 1. FOLDED: Only the main headline is shown.
6380 2. CHILDREN: The main headline and the direct children are shown.
6381 From this state, you can move to one of the children
6382 and zoom in further.
6383 3. SUBTREE: Show the entire subtree, including body text.
6384 If there is no subtree, switch directly from CHILDREN to FOLDED.
6386 - When point is at the beginning of an empty headline and the variable
6387 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6388 of the headline by demoting and promoting it to likely levels. This
6389 speeds up creation document structure by pressing TAB once or several
6390 times right after creating a new headline.
6392 - When there is a numeric prefix, go up to a heading with level ARG, do
6393 a `show-subtree' and return to the previous cursor position. If ARG
6394 is negative, go up that many levels.
6396 - When point is not at the beginning of a headline, execute the global
6397 binding for TAB, which is re-indenting the line. See the option
6398 `org-cycle-emulate-tab' for details.
6400 - Special case: if point is at the beginning of the buffer and there is
6401 no headline in line 1, this function will act as if called with prefix arg
6402 (C-u TAB, same as S-TAB) also when called without prefix arg.
6403 But only if also the variable `org-cycle-global-at-bob' is t."
6404 (interactive "P")
6405 (org-load-modules-maybe)
6406 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6407 (and org-cycle-level-after-item/entry-creation
6408 (or (org-cycle-level)
6409 (org-cycle-item-indentation))))
6410 (let* (message-log-max ; Don't populate the *Messages* buffer
6411 (limit-level
6412 (or org-cycle-max-level
6413 (and (boundp 'org-inlinetask-min-level)
6414 org-inlinetask-min-level
6415 (1- org-inlinetask-min-level))))
6416 (nstars (and limit-level
6417 (if org-odd-levels-only
6418 (and limit-level (1- (* limit-level 2)))
6419 limit-level)))
6420 (org-outline-regexp
6421 (if (not (derived-mode-p 'org-mode))
6422 outline-regexp
6423 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6424 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6425 (not (looking-at org-outline-regexp))))
6426 (org-cycle-hook
6427 (if bob-special
6428 (delq 'org-optimize-window-after-visibility-change
6429 (copy-sequence org-cycle-hook))
6430 org-cycle-hook))
6431 (pos (point)))
6433 (if (or bob-special (equal arg '(4)))
6434 ;; special case: use global cycling
6435 (setq arg t))
6437 (cond
6439 ((equal arg '(16))
6440 (setq last-command 'dummy)
6441 (org-set-startup-visibility)
6442 (message "Startup visibility, plus VISIBILITY properties"))
6444 ((equal arg '(64))
6445 (show-all)
6446 (message "Entire buffer visible, including drawers"))
6448 ;; Table: enter it or move to the next field.
6449 ((org-at-table-p 'any)
6450 (if (org-at-table.el-p)
6451 (message "Use C-c ' to edit table.el tables")
6452 (if arg (org-table-edit-field t)
6453 (org-table-justify-field-maybe)
6454 (call-interactively 'org-table-next-field))))
6456 ((run-hook-with-args-until-success
6457 'org-tab-after-check-for-table-hook))
6459 ;; Global cycling: delegate to `org-cycle-internal-global'.
6460 ((eq arg t) (org-cycle-internal-global))
6462 ;; Drawers: delegate to `org-flag-drawer'.
6463 ((and org-drawers org-drawer-regexp
6464 (save-excursion
6465 (beginning-of-line 1)
6466 (looking-at org-drawer-regexp)))
6467 (org-flag-drawer ; toggle block visibility
6468 (not (get-char-property (match-end 0) 'invisible))))
6470 ;; Show-subtree, ARG levels up from here.
6471 ((integerp arg)
6472 (save-excursion
6473 (org-back-to-heading)
6474 (outline-up-heading (if (< arg 0) (- arg)
6475 (- (funcall outline-level) arg)))
6476 (org-show-subtree)))
6478 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6479 ((and (featurep 'org-inlinetask)
6480 (org-inlinetask-at-task-p)
6481 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6482 (org-inlinetask-toggle-visibility))
6484 ((org-try-cdlatex-tab))
6486 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6487 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6488 (save-excursion (beginning-of-line 1)
6489 (looking-at org-outline-regexp)))
6490 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6491 (org-cycle-internal-local))
6493 ;; From there: TAB emulation and template completion.
6494 (buffer-read-only (org-back-to-heading))
6496 ((run-hook-with-args-until-success
6497 'org-tab-after-check-for-cycling-hook))
6499 ((org-try-structure-completion))
6501 ((run-hook-with-args-until-success
6502 'org-tab-before-tab-emulation-hook))
6504 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6505 (or (not (bolp))
6506 (not (looking-at org-outline-regexp))))
6507 (call-interactively (global-key-binding "\t")))
6509 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6510 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6511 (or (and (eq org-cycle-emulate-tab 'white)
6512 (= (match-end 0) (point-at-eol)))
6513 (and (eq org-cycle-emulate-tab 'whitestart)
6514 (>= (match-end 0) pos))))
6516 (eq org-cycle-emulate-tab t))
6517 (call-interactively (global-key-binding "\t")))
6519 (t (save-excursion
6520 (org-back-to-heading)
6521 (org-cycle)))))))
6523 (defun org-cycle-internal-global ()
6524 "Do the global cycling action."
6525 ;; Hack to avoid display of messages for .org attachments in Gnus
6526 (let (message-log-max ; Don't populate the *Messages* buffer
6527 (ga (string-match "\\*fontification" (buffer-name))))
6528 (cond
6529 ((and (eq last-command this-command)
6530 (eq org-cycle-global-status 'overview))
6531 ;; We just created the overview - now do table of contents
6532 ;; This can be slow in very large buffers, so indicate action
6533 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6534 (unless ga (message "CONTENTS..."))
6535 (org-content)
6536 (unless ga (message "CONTENTS...done"))
6537 (setq org-cycle-global-status 'contents)
6538 (run-hook-with-args 'org-cycle-hook 'contents))
6540 ((and (eq last-command this-command)
6541 (eq org-cycle-global-status 'contents))
6542 ;; We just showed the table of contents - now show everything
6543 (run-hook-with-args 'org-pre-cycle-hook 'all)
6544 (show-all)
6545 (unless ga (message "SHOW ALL"))
6546 (setq org-cycle-global-status 'all)
6547 (run-hook-with-args 'org-cycle-hook 'all))
6550 ;; Default action: go to overview
6551 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6552 (org-overview)
6553 (unless ga (message "OVERVIEW"))
6554 (setq org-cycle-global-status 'overview)
6555 (run-hook-with-args 'org-cycle-hook 'overview)))))
6557 (defun org-cycle-internal-local ()
6558 "Do the local cycling action."
6559 (let (message-log-max ; Don't populate the *Messages* buffer
6560 (goal-column 0) eoh eol eos has-children children-skipped struct)
6561 ;; First, determine end of headline (EOH), end of subtree or item
6562 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6563 (save-excursion
6564 (if (org-at-item-p)
6565 (progn
6566 (beginning-of-line)
6567 (setq struct (org-list-struct))
6568 (setq eoh (point-at-eol))
6569 (setq eos (org-list-get-item-end-before-blank (point) struct))
6570 (setq has-children (org-list-has-child-p (point) struct)))
6571 (org-back-to-heading)
6572 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6573 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6574 (setq has-children
6575 (or (save-excursion
6576 (let ((level (funcall outline-level)))
6577 (outline-next-heading)
6578 (and (org-at-heading-p t)
6579 (> (funcall outline-level) level))))
6580 (save-excursion
6581 (org-list-search-forward (org-item-beginning-re) eos t)))))
6582 ;; Determine end invisible part of buffer (EOL)
6583 (beginning-of-line 2)
6584 ;; XEmacs doesn't have `next-single-char-property-change'
6585 (if (featurep 'xemacs)
6586 (while (and (not (eobp)) ;; this is like `next-line'
6587 (get-char-property (1- (point)) 'invisible))
6588 (beginning-of-line 2))
6589 (while (and (not (eobp)) ;; this is like `next-line'
6590 (get-char-property (1- (point)) 'invisible))
6591 (goto-char (next-single-char-property-change (point) 'invisible))
6592 (and (eolp) (beginning-of-line 2))))
6593 (setq eol (point)))
6594 ;; Find out what to do next and set `this-command'
6595 (cond
6596 ((= eos eoh)
6597 ;; Nothing is hidden behind this heading
6598 (unless (org-before-first-heading-p)
6599 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6600 (message "EMPTY ENTRY")
6601 (setq org-cycle-subtree-status nil)
6602 (save-excursion
6603 (goto-char eos)
6604 (outline-next-heading)
6605 (if (outline-invisible-p) (org-flag-heading nil))))
6606 ((and (or (>= eol eos)
6607 (not (string-match "\\S-" (buffer-substring eol eos))))
6608 (or has-children
6609 (not (setq children-skipped
6610 org-cycle-skip-children-state-if-no-children))))
6611 ;; Entire subtree is hidden in one line: children view
6612 (unless (org-before-first-heading-p)
6613 (run-hook-with-args 'org-pre-cycle-hook 'children))
6614 (if (org-at-item-p)
6615 (org-list-set-item-visibility (point-at-bol) struct 'children)
6616 (org-show-entry)
6617 (org-with-limited-levels (show-children))
6618 ;; FIXME: This slows down the func way too much.
6619 ;; How keep drawers hidden in subtree anyway?
6620 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6621 ;; (org-cycle-hide-drawers 'subtree))
6623 ;; Fold every list in subtree to top-level items.
6624 (when (eq org-cycle-include-plain-lists 'integrate)
6625 (save-excursion
6626 (org-back-to-heading)
6627 (while (org-list-search-forward (org-item-beginning-re) eos t)
6628 (beginning-of-line 1)
6629 (let* ((struct (org-list-struct))
6630 (prevs (org-list-prevs-alist struct))
6631 (end (org-list-get-bottom-point struct)))
6632 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6633 (org-list-get-all-items (point) struct prevs))
6634 (goto-char end))))))
6635 (message "CHILDREN")
6636 (save-excursion
6637 (goto-char eos)
6638 (outline-next-heading)
6639 (if (outline-invisible-p) (org-flag-heading nil)))
6640 (setq org-cycle-subtree-status 'children)
6641 (unless (org-before-first-heading-p)
6642 (run-hook-with-args 'org-cycle-hook 'children)))
6643 ((or children-skipped
6644 (and (eq last-command this-command)
6645 (eq org-cycle-subtree-status 'children)))
6646 ;; We just showed the children, or no children are there,
6647 ;; now show everything.
6648 (unless (org-before-first-heading-p)
6649 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6650 (outline-flag-region eoh eos nil)
6651 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6652 (setq org-cycle-subtree-status 'subtree)
6653 (unless (org-before-first-heading-p)
6654 (run-hook-with-args 'org-cycle-hook 'subtree)))
6656 ;; Default action: hide the subtree.
6657 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6658 (outline-flag-region eoh eos t)
6659 (message "FOLDED")
6660 (setq org-cycle-subtree-status 'folded)
6661 (unless (org-before-first-heading-p)
6662 (run-hook-with-args 'org-cycle-hook 'folded))))))
6664 ;;;###autoload
6665 (defun org-global-cycle (&optional arg)
6666 "Cycle the global visibility. For details see `org-cycle'.
6667 With \\[universal-argument] prefix arg, switch to startup visibility.
6668 With a numeric prefix, show all headlines up to that level."
6669 (interactive "P")
6670 (let ((org-cycle-include-plain-lists
6671 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6672 (cond
6673 ((integerp arg)
6674 (show-all)
6675 (hide-sublevels arg)
6676 (setq org-cycle-global-status 'contents))
6677 ((equal arg '(4))
6678 (org-set-startup-visibility)
6679 (message "Startup visibility, plus VISIBILITY properties."))
6681 (org-cycle '(4))))))
6683 (defun org-set-startup-visibility ()
6684 "Set the visibility required by startup options and properties."
6685 (cond
6686 ((eq org-startup-folded t)
6687 (org-cycle '(4)))
6688 ((eq org-startup-folded 'content)
6689 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6690 (org-cycle '(4)) (org-cycle '(4)))))
6691 (unless (eq org-startup-folded 'showeverything)
6692 (if org-hide-block-startup (org-hide-block-all))
6693 (org-set-visibility-according-to-property 'no-cleanup)
6694 (org-cycle-hide-archived-subtrees 'all)
6695 (org-cycle-hide-drawers 'all)
6696 (org-cycle-show-empty-lines t)))
6698 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6699 "Switch subtree visibilities according to :VISIBILITY: property."
6700 (interactive)
6701 (let (org-show-entry-below state)
6702 (save-excursion
6703 (goto-char (point-min))
6704 (while (re-search-forward
6705 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6706 nil t)
6707 (setq state (match-string 1))
6708 (save-excursion
6709 (org-back-to-heading t)
6710 (hide-subtree)
6711 (org-reveal)
6712 (cond
6713 ((equal state '("fold" "folded"))
6714 (hide-subtree))
6715 ((equal state "children")
6716 (org-show-hidden-entry)
6717 (show-children))
6718 ((equal state "content")
6719 (save-excursion
6720 (save-restriction
6721 (org-narrow-to-subtree)
6722 (org-content))))
6723 ((member state '("all" "showall"))
6724 (show-subtree)))))
6725 (unless no-cleanup
6726 (org-cycle-hide-archived-subtrees 'all)
6727 (org-cycle-hide-drawers 'all)
6728 (org-cycle-show-empty-lines 'all)))))
6730 ;; This function uses outline-regexp instead of the more fundamental
6731 ;; org-outline-regexp so that org-cycle-global works outside of Org
6732 ;; buffers, where outline-regexp is needed.
6733 (defun org-overview ()
6734 "Switch to overview mode, showing only top-level headlines.
6735 Really, this shows all headlines with level equal or greater than the level
6736 of the first headline in the buffer. This is important, because if the
6737 first headline is not level one, then (hide-sublevels 1) gives confusing
6738 results."
6739 (interactive)
6740 (let ((l (org-current-line))
6741 (level (save-excursion
6742 (goto-char (point-min))
6743 (if (re-search-forward (concat "^" outline-regexp) nil t)
6744 (progn
6745 (goto-char (match-beginning 0))
6746 (funcall outline-level))))))
6747 (and level (hide-sublevels level))
6748 (recenter '(4))
6749 (org-goto-line l)))
6751 (defun org-content (&optional arg)
6752 "Show all headlines in the buffer, like a table of contents.
6753 With numerical argument N, show content up to level N."
6754 (interactive "P")
6755 (save-excursion
6756 ;; Visit all headings and show their offspring
6757 (and (integerp arg) (org-overview))
6758 (goto-char (point-max))
6759 (catch 'exit
6760 (while (and (progn (condition-case nil
6761 (outline-previous-visible-heading 1)
6762 (error (goto-char (point-min))))
6764 (looking-at org-outline-regexp))
6765 (if (integerp arg)
6766 (show-children (1- arg))
6767 (show-branches))
6768 (if (bobp) (throw 'exit nil))))))
6771 (defun org-optimize-window-after-visibility-change (state)
6772 "Adjust the window after a change in outline visibility.
6773 This function is the default value of the hook `org-cycle-hook'."
6774 (when (get-buffer-window (current-buffer))
6775 (cond
6776 ((eq state 'content) nil)
6777 ((eq state 'all) nil)
6778 ((eq state 'folded) nil)
6779 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6780 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6782 (defun org-remove-empty-overlays-at (pos)
6783 "Remove outline overlays that do not contain non-white stuff."
6784 (mapc
6785 (lambda (o)
6786 (and (eq 'outline (overlay-get o 'invisible))
6787 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6788 (overlay-end o))))
6789 (delete-overlay o)))
6790 (overlays-at pos)))
6792 (defun org-clean-visibility-after-subtree-move ()
6793 "Fix visibility issues after moving a subtree."
6794 ;; First, find a reasonable region to look at:
6795 ;; Start two siblings above, end three below
6796 (let* ((beg (save-excursion
6797 (and (org-get-last-sibling)
6798 (org-get-last-sibling))
6799 (point)))
6800 (end (save-excursion
6801 (and (org-get-next-sibling)
6802 (org-get-next-sibling)
6803 (org-get-next-sibling))
6804 (if (org-at-heading-p)
6805 (point-at-eol)
6806 (point))))
6807 (level (looking-at "\\*+"))
6808 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6809 (save-excursion
6810 (save-restriction
6811 (narrow-to-region beg end)
6812 (when re
6813 ;; Properly fold already folded siblings
6814 (goto-char (point-min))
6815 (while (re-search-forward re nil t)
6816 (if (and (not (outline-invisible-p))
6817 (save-excursion
6818 (goto-char (point-at-eol)) (outline-invisible-p)))
6819 (hide-entry))))
6820 (org-cycle-show-empty-lines 'overview)
6821 (org-cycle-hide-drawers 'overview)))))
6823 (defun org-cycle-show-empty-lines (state)
6824 "Show empty lines above all visible headlines.
6825 The region to be covered depends on STATE when called through
6826 `org-cycle-hook'. Lisp program can use t for STATE to get the
6827 entire buffer covered. Note that an empty line is only shown if there
6828 are at least `org-cycle-separator-lines' empty lines before the headline."
6829 (when (not (= org-cycle-separator-lines 0))
6830 (save-excursion
6831 (let* ((n (abs org-cycle-separator-lines))
6832 (re (cond
6833 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6834 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6835 (t (let ((ns (number-to-string (- n 2))))
6836 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6837 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6838 beg end b e)
6839 (cond
6840 ((memq state '(overview contents t))
6841 (setq beg (point-min) end (point-max)))
6842 ((memq state '(children folded))
6843 (setq beg (point) end (progn (org-end-of-subtree t t)
6844 (beginning-of-line 2)
6845 (point)))))
6846 (when beg
6847 (goto-char beg)
6848 (while (re-search-forward re end t)
6849 (unless (get-char-property (match-end 1) 'invisible)
6850 (setq e (match-end 1))
6851 (if (< org-cycle-separator-lines 0)
6852 (setq b (save-excursion
6853 (goto-char (match-beginning 0))
6854 (org-back-over-empty-lines)
6855 (if (save-excursion
6856 (goto-char (max (point-min) (1- (point))))
6857 (org-at-heading-p))
6858 (1- (point))
6859 (point))))
6860 (setq b (match-beginning 1)))
6861 (outline-flag-region b e nil)))))))
6862 ;; Never hide empty lines at the end of the file.
6863 (save-excursion
6864 (goto-char (point-max))
6865 (outline-previous-heading)
6866 (outline-end-of-heading)
6867 (if (and (looking-at "[ \t\n]+")
6868 (= (match-end 0) (point-max)))
6869 (outline-flag-region (point) (match-end 0) nil))))
6871 (defun org-show-empty-lines-in-parent ()
6872 "Move to the parent and re-show empty lines before visible headlines."
6873 (save-excursion
6874 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6875 (org-cycle-show-empty-lines context))))
6877 (defun org-files-list ()
6878 "Return `org-agenda-files' list, plus all open org-mode files.
6879 This is useful for operations that need to scan all of a user's
6880 open and agenda-wise Org files."
6881 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6882 (dolist (buf (buffer-list))
6883 (with-current-buffer buf
6884 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6885 (let ((file (expand-file-name (buffer-file-name))))
6886 (unless (member file files)
6887 (push file files))))))
6888 files))
6890 (defsubst org-entry-beginning-position ()
6891 "Return the beginning position of the current entry."
6892 (save-excursion (outline-back-to-heading t) (point)))
6894 (defsubst org-entry-end-position ()
6895 "Return the end position of the current entry."
6896 (save-excursion (outline-next-heading) (point)))
6898 (defun org-cycle-hide-drawers (state)
6899 "Re-hide all drawers after a visibility state change."
6900 (when (and (derived-mode-p 'org-mode)
6901 (not (memq state '(overview folded contents))))
6902 (save-excursion
6903 (let* ((globalp (memq state '(contents all)))
6904 (beg (if globalp (point-min) (point)))
6905 (end (if globalp (point-max)
6906 (if (eq state 'children)
6907 (save-excursion (outline-next-heading) (point))
6908 (org-end-of-subtree t)))))
6909 (goto-char beg)
6910 (while (re-search-forward org-drawer-regexp end t)
6911 (org-flag-drawer t))))))
6913 (defun org-cycle-hide-inline-tasks (state)
6914 "Re-hide inline task when switching to 'contents visibility state."
6915 (when (and (eq state 'contents)
6916 (boundp 'org-inlinetask-min-level)
6917 org-inlinetask-min-level)
6918 (hide-sublevels (1- org-inlinetask-min-level))))
6920 (defun org-flag-drawer (flag)
6921 "When FLAG is non-nil, hide the drawer we are within.
6922 Otherwise make it visible."
6923 (save-excursion
6924 (beginning-of-line 1)
6925 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6926 (let ((b (match-end 0)))
6927 (if (re-search-forward
6928 "^[ \t]*:END:"
6929 (save-excursion (outline-next-heading) (point)) t)
6930 (outline-flag-region b (point-at-eol) flag)
6931 (error ":END: line missing at position %s" b))))))
6933 (defun org-subtree-end-visible-p ()
6934 "Is the end of the current subtree visible?"
6935 (pos-visible-in-window-p
6936 (save-excursion (org-end-of-subtree t) (point))))
6938 (defun org-first-headline-recenter (&optional N)
6939 "Move cursor to the first headline and recenter the headline.
6940 Optional argument N means put the headline into the Nth line of the window."
6941 (goto-char (point-min))
6942 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6943 (beginning-of-line)
6944 (recenter (prefix-numeric-value N))))
6946 ;;; Saving and restoring visibility
6948 (defun org-outline-overlay-data (&optional use-markers)
6949 "Return a list of the locations of all outline overlays.
6950 These are overlays with the `invisible' property value `outline'.
6951 The return value is a list of cons cells, with start and stop
6952 positions for each overlay.
6953 If USE-MARKERS is set, return the positions as markers."
6954 (let (beg end)
6955 (save-excursion
6956 (save-restriction
6957 (widen)
6958 (delq nil
6959 (mapcar (lambda (o)
6960 (when (eq (overlay-get o 'invisible) 'outline)
6961 (setq beg (overlay-start o)
6962 end (overlay-end o))
6963 (and beg end (> end beg)
6964 (if use-markers
6965 (cons (move-marker (make-marker) beg)
6966 (move-marker (make-marker) end))
6967 (cons beg end)))))
6968 (overlays-in (point-min) (point-max))))))))
6970 (defun org-set-outline-overlay-data (data)
6971 "Create visibility overlays for all positions in DATA.
6972 DATA should have been made by `org-outline-overlay-data'."
6973 (let (o)
6974 (save-excursion
6975 (save-restriction
6976 (widen)
6977 (show-all)
6978 (mapc (lambda (c)
6979 (outline-flag-region (car c) (cdr c) t))
6980 data)))))
6982 ;;; Folding of blocks
6984 (defvar org-hide-block-overlays nil
6985 "Overlays hiding blocks.")
6986 (make-variable-buffer-local 'org-hide-block-overlays)
6988 (defun org-block-map (function &optional start end)
6989 "Call FUNCTION at the head of all source blocks in the current buffer.
6990 Optional arguments START and END can be used to limit the range."
6991 (let ((start (or start (point-min)))
6992 (end (or end (point-max))))
6993 (save-excursion
6994 (goto-char start)
6995 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6996 (save-excursion
6997 (save-match-data
6998 (goto-char (match-beginning 0))
6999 (funcall function)))))))
7001 (defun org-hide-block-toggle-all ()
7002 "Toggle the visibility of all blocks in the current buffer."
7003 (org-block-map #'org-hide-block-toggle))
7005 (defun org-hide-block-all ()
7006 "Fold all blocks in the current buffer."
7007 (interactive)
7008 (org-show-block-all)
7009 (org-block-map #'org-hide-block-toggle-maybe))
7011 (defun org-show-block-all ()
7012 "Unfold all blocks in the current buffer."
7013 (interactive)
7014 (mapc 'delete-overlay org-hide-block-overlays)
7015 (setq org-hide-block-overlays nil))
7017 (defun org-hide-block-toggle-maybe ()
7018 "Toggle visibility of block at point."
7019 (interactive)
7020 (let ((case-fold-search t))
7021 (if (save-excursion
7022 (beginning-of-line 1)
7023 (looking-at org-block-regexp))
7024 (progn (org-hide-block-toggle)
7025 t) ;; to signal that we took action
7026 nil))) ;; to signal that we did not
7028 (defun org-hide-block-toggle (&optional force)
7029 "Toggle the visibility of the current block."
7030 (interactive)
7031 (save-excursion
7032 (beginning-of-line)
7033 (if (re-search-forward org-block-regexp nil t)
7034 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7035 (end (match-end 0)) ;; end of entire body
7037 (if (memq t (mapcar (lambda (overlay)
7038 (eq (overlay-get overlay 'invisible)
7039 'org-hide-block))
7040 (overlays-at start)))
7041 (if (or (not force) (eq force 'off))
7042 (mapc (lambda (ov)
7043 (when (member ov org-hide-block-overlays)
7044 (setq org-hide-block-overlays
7045 (delq ov org-hide-block-overlays)))
7046 (when (eq (overlay-get ov 'invisible)
7047 'org-hide-block)
7048 (delete-overlay ov)))
7049 (overlays-at start)))
7050 (setq ov (make-overlay start end))
7051 (overlay-put ov 'invisible 'org-hide-block)
7052 ;; make the block accessible to isearch
7053 (overlay-put
7054 ov 'isearch-open-invisible
7055 (lambda (ov)
7056 (when (member ov org-hide-block-overlays)
7057 (setq org-hide-block-overlays
7058 (delq ov org-hide-block-overlays)))
7059 (when (eq (overlay-get ov 'invisible)
7060 'org-hide-block)
7061 (delete-overlay ov))))
7062 (push ov org-hide-block-overlays)))
7063 (error "Not looking at a source block"))))
7065 ;; org-tab-after-check-for-cycling-hook
7066 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7067 ;; Remove overlays when changing major mode
7068 (add-hook 'org-mode-hook
7069 (lambda () (org-add-hook 'change-major-mode-hook
7070 'org-show-block-all 'append 'local)))
7072 ;;; Org-goto
7074 (defvar org-goto-window-configuration nil)
7075 (defvar org-goto-marker nil)
7076 (defvar org-goto-map)
7077 (defun org-goto-map ()
7078 "Set the keymap `org-goto'."
7079 (setq org-goto-map
7080 (let ((map (make-sparse-keymap)))
7081 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7082 mouse-drag-region universal-argument org-occur))
7083 cmd)
7084 (while (setq cmd (pop cmds))
7085 (substitute-key-definition cmd cmd map global-map)))
7086 (suppress-keymap map)
7087 (org-defkey map "\C-m" 'org-goto-ret)
7088 (org-defkey map [(return)] 'org-goto-ret)
7089 (org-defkey map [(left)] 'org-goto-left)
7090 (org-defkey map [(right)] 'org-goto-right)
7091 (org-defkey map [(control ?g)] 'org-goto-quit)
7092 (org-defkey map "\C-i" 'org-cycle)
7093 (org-defkey map [(tab)] 'org-cycle)
7094 (org-defkey map [(down)] 'outline-next-visible-heading)
7095 (org-defkey map [(up)] 'outline-previous-visible-heading)
7096 (if org-goto-auto-isearch
7097 (if (fboundp 'define-key-after)
7098 (define-key-after map [t] 'org-goto-local-auto-isearch)
7099 nil)
7100 (org-defkey map "q" 'org-goto-quit)
7101 (org-defkey map "n" 'outline-next-visible-heading)
7102 (org-defkey map "p" 'outline-previous-visible-heading)
7103 (org-defkey map "f" 'outline-forward-same-level)
7104 (org-defkey map "b" 'outline-backward-same-level)
7105 (org-defkey map "u" 'outline-up-heading))
7106 (org-defkey map "/" 'org-occur)
7107 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7108 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7109 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7110 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7111 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7112 map)))
7114 (defconst org-goto-help
7115 "Browse buffer copy, to find location or copy text.%s
7116 RET=jump to location C-g=quit and return to previous location
7117 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7119 (defvar org-goto-start-pos) ; dynamically scoped parameter
7121 (defun org-goto (&optional alternative-interface)
7122 "Look up a different location in the current file, keeping current visibility.
7124 When you want look-up or go to a different location in a
7125 document, the fastest way is often to fold the entire buffer and
7126 then dive into the tree. This method has the disadvantage, that
7127 the previous location will be folded, which may not be what you
7128 want.
7130 This command works around this by showing a copy of the current
7131 buffer in an indirect buffer, in overview mode. You can dive
7132 into the tree in that copy, use org-occur and incremental search
7133 to find a location. When pressing RET or `Q', the command
7134 returns to the original buffer in which the visibility is still
7135 unchanged. After RET it will also jump to the location selected
7136 in the indirect buffer and expose the headline hierarchy above.
7138 With a prefix argument, use the alternative interface: e.g. if
7139 `org-goto-interface' is 'outline use 'outline-path-completion."
7140 (interactive "P")
7141 (org-goto-map)
7142 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7143 (org-refile-use-outline-path t)
7144 (org-refile-target-verify-function nil)
7145 (interface
7146 (if (not alternative-interface)
7147 org-goto-interface
7148 (if (eq org-goto-interface 'outline)
7149 'outline-path-completion
7150 'outline)))
7151 (org-goto-start-pos (point))
7152 (selected-point
7153 (if (eq interface 'outline)
7154 (car (org-get-location (current-buffer) org-goto-help))
7155 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7156 (org-refile-check-position pa)
7157 (nth 3 pa)))))
7158 (if selected-point
7159 (progn
7160 (org-mark-ring-push org-goto-start-pos)
7161 (goto-char selected-point)
7162 (if (or (outline-invisible-p) (org-invisible-p2))
7163 (org-show-context 'org-goto)))
7164 (message "Quit"))))
7166 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7167 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7168 (defvar org-goto-local-auto-isearch-map) ; defined below
7170 (defun org-get-location (buf help)
7171 "Let the user select a location in the Org-mode buffer BUF.
7172 This function uses a recursive edit. It returns the selected position
7173 or nil."
7174 (org-no-popups
7175 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7176 (isearch-hide-immediately nil)
7177 (isearch-search-fun-function
7178 (lambda () 'org-goto-local-search-headings))
7179 (org-goto-selected-point org-goto-exit-command))
7180 (save-excursion
7181 (save-window-excursion
7182 (delete-other-windows)
7183 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7184 (org-pop-to-buffer-same-window
7185 (condition-case nil
7186 (make-indirect-buffer (current-buffer) "*org-goto*")
7187 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7188 (with-output-to-temp-buffer "*Org Help*"
7189 (princ (format help (if org-goto-auto-isearch
7190 " Just type for auto-isearch."
7191 " n/p/f/b/u to navigate, q to quit."))))
7192 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7193 (setq buffer-read-only nil)
7194 (let ((org-startup-truncated t)
7195 (org-startup-folded nil)
7196 (org-startup-align-all-tables nil))
7197 (org-mode)
7198 (org-overview))
7199 (setq buffer-read-only t)
7200 (if (and (boundp 'org-goto-start-pos)
7201 (integer-or-marker-p org-goto-start-pos))
7202 (let ((org-show-hierarchy-above t)
7203 (org-show-siblings t)
7204 (org-show-following-heading t))
7205 (goto-char org-goto-start-pos)
7206 (and (outline-invisible-p) (org-show-context)))
7207 (goto-char (point-min)))
7208 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7209 (message "Select location and press RET")
7210 (use-local-map org-goto-map)
7211 (recursive-edit)))
7212 (kill-buffer "*org-goto*")
7213 (cons org-goto-selected-point org-goto-exit-command))))
7215 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7216 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7217 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7218 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7220 (defun org-goto-local-search-headings (string bound noerror)
7221 "Search and make sure that any matches are in headlines."
7222 (catch 'return
7223 (while (if isearch-forward
7224 (search-forward string bound noerror)
7225 (search-backward string bound noerror))
7226 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7227 (and (member :headline context)
7228 (not (member :tags context))))
7229 (throw 'return (point))))))
7231 (defun org-goto-local-auto-isearch ()
7232 "Start isearch."
7233 (interactive)
7234 (goto-char (point-min))
7235 (let ((keys (this-command-keys)))
7236 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7237 (isearch-mode t)
7238 (isearch-process-search-char (string-to-char keys)))))
7240 (defun org-goto-ret (&optional arg)
7241 "Finish `org-goto' by going to the new location."
7242 (interactive "P")
7243 (setq org-goto-selected-point (point)
7244 org-goto-exit-command 'return)
7245 (throw 'exit nil))
7247 (defun org-goto-left ()
7248 "Finish `org-goto' by going to the new location."
7249 (interactive)
7250 (if (org-at-heading-p)
7251 (progn
7252 (beginning-of-line 1)
7253 (setq org-goto-selected-point (point)
7254 org-goto-exit-command 'left)
7255 (throw 'exit nil))
7256 (error "Not on a heading")))
7258 (defun org-goto-right ()
7259 "Finish `org-goto' by going to the new location."
7260 (interactive)
7261 (if (org-at-heading-p)
7262 (progn
7263 (setq org-goto-selected-point (point)
7264 org-goto-exit-command 'right)
7265 (throw 'exit nil))
7266 (error "Not on a heading")))
7268 (defun org-goto-quit ()
7269 "Finish `org-goto' without cursor motion."
7270 (interactive)
7271 (setq org-goto-selected-point nil)
7272 (setq org-goto-exit-command 'quit)
7273 (throw 'exit nil))
7275 ;;; Indirect buffer display of subtrees
7277 (defvar org-indirect-dedicated-frame nil
7278 "This is the frame being used for indirect tree display.")
7279 (defvar org-last-indirect-buffer nil)
7281 (defun org-tree-to-indirect-buffer (&optional arg)
7282 "Create indirect buffer and narrow it to current subtree.
7283 With a numerical prefix ARG, go up to this level and then take that tree.
7284 If ARG is negative, go up that many levels.
7286 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7287 indirect buffer previously made with this command, to avoid proliferation of
7288 indirect buffers. However, when you call the command with a \
7289 \\[universal-argument] prefix, or
7290 when `org-indirect-buffer-display' is `new-frame', the last buffer
7291 is kept so that you can work with several indirect buffers at the same time.
7292 If `org-indirect-buffer-display' is `dedicated-frame', the \
7293 \\[universal-argument] prefix also
7294 requests that a new frame be made for the new buffer, so that the dedicated
7295 frame is not changed."
7296 (interactive "P")
7297 (let ((cbuf (current-buffer))
7298 (cwin (selected-window))
7299 (pos (point))
7300 beg end level heading ibuf)
7301 (save-excursion
7302 (org-back-to-heading t)
7303 (when (numberp arg)
7304 (setq level (org-outline-level))
7305 (if (< arg 0) (setq arg (+ level arg)))
7306 (while (> (setq level (org-outline-level)) arg)
7307 (org-up-heading-safe)))
7308 (setq beg (point)
7309 heading (org-get-heading))
7310 (org-end-of-subtree t t)
7311 (if (org-at-heading-p) (backward-char 1))
7312 (setq end (point)))
7313 (if (and (buffer-live-p org-last-indirect-buffer)
7314 (not (eq org-indirect-buffer-display 'new-frame))
7315 (not arg))
7316 (kill-buffer org-last-indirect-buffer))
7317 (setq ibuf (org-get-indirect-buffer cbuf)
7318 org-last-indirect-buffer ibuf)
7319 (cond
7320 ((or (eq org-indirect-buffer-display 'new-frame)
7321 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7322 (select-frame (make-frame))
7323 (delete-other-windows)
7324 (org-pop-to-buffer-same-window ibuf)
7325 (org-set-frame-title heading))
7326 ((eq org-indirect-buffer-display 'dedicated-frame)
7327 (raise-frame
7328 (select-frame (or (and org-indirect-dedicated-frame
7329 (frame-live-p org-indirect-dedicated-frame)
7330 org-indirect-dedicated-frame)
7331 (setq org-indirect-dedicated-frame (make-frame)))))
7332 (delete-other-windows)
7333 (org-pop-to-buffer-same-window ibuf)
7334 (org-set-frame-title (concat "Indirect: " heading)))
7335 ((eq org-indirect-buffer-display 'current-window)
7336 (org-pop-to-buffer-same-window ibuf))
7337 ((eq org-indirect-buffer-display 'other-window)
7338 (pop-to-buffer ibuf))
7339 (t (error "Invalid value")))
7340 (if (featurep 'xemacs)
7341 (save-excursion (org-mode) (turn-on-font-lock)))
7342 (narrow-to-region beg end)
7343 (show-all)
7344 (goto-char pos)
7345 (run-hook-with-args 'org-cycle-hook 'all)
7346 (and (window-live-p cwin) (select-window cwin))))
7348 (defun org-get-indirect-buffer (&optional buffer)
7349 (setq buffer (or buffer (current-buffer)))
7350 (let ((n 1) (base (buffer-name buffer)) bname)
7351 (while (buffer-live-p
7352 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7353 (setq n (1+ n)))
7354 (condition-case nil
7355 (make-indirect-buffer buffer bname 'clone)
7356 (error (make-indirect-buffer buffer bname)))))
7358 (defun org-set-frame-title (title)
7359 "Set the title of the current frame to the string TITLE."
7360 ;; FIXME: how to name a single frame in XEmacs???
7361 (unless (featurep 'xemacs)
7362 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7364 ;;;; Structure editing
7366 ;;; Inserting headlines
7368 (defun org-previous-line-empty-p (&optional next)
7369 "Is the previous line a blank line?
7370 When NEXT is non-nil, check the next line instead."
7371 (save-excursion
7372 (and (not (bobp))
7373 (or (beginning-of-line (if next 2 0)) t)
7374 (save-match-data
7375 (looking-at "[ \t]*$")))))
7377 (defun org-insert-heading (&optional arg invisible-ok)
7378 "Insert a new heading or item with same depth at point.
7379 If point is in a plain list and ARG is nil, create a new list item.
7380 With one universal prefix argument, insert a heading even in lists.
7381 With two universal prefix arguments, insert the heading at the end
7382 of the parent subtree.
7384 If point is at the beginning of a headline, insert a sibling before
7385 the current headline. If point is not at the beginning, split the line
7386 and create a new headline with the text in the current line after point
7387 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7389 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7390 This is important for non-interactive uses of the command."
7391 (interactive "P")
7392 (cond
7393 ((or (= (buffer-size) 0)
7394 (and (not (save-excursion
7395 (and (ignore-errors (org-back-to-heading invisible-ok))
7396 (org-at-heading-p))))
7397 (or arg (not (org-in-item-p)))))
7398 (insert
7399 (if (org-previous-line-empty-p) "" "\n")
7400 (if (org-in-src-block-p) ",* " "* "))
7401 (run-hooks 'org-insert-heading-hook))
7402 ((or arg (not (org-insert-item
7403 (save-excursion
7404 (beginning-of-line)
7405 (looking-at org-list-full-item-re)
7406 (match-string 3)))))
7407 (let (begn endn)
7408 (when (org-buffer-narrowed-p)
7409 (setq begn (point-min) endn (point-max))
7410 (widen))
7411 (let* ((empty-line-p nil)
7412 (eops (equal arg '(16))) ; insert at end of parent subtree
7413 (org-insert-heading-respect-content
7414 (or (not (null arg)) org-insert-heading-respect-content))
7415 (level nil)
7416 (on-heading (org-at-heading-p))
7417 (head (save-excursion
7418 (condition-case nil
7419 (progn
7420 (org-back-to-heading invisible-ok)
7421 (when (and (not on-heading)
7422 (featurep 'org-inlinetask)
7423 (integerp org-inlinetask-min-level)
7424 (>= (length (match-string 0))
7425 org-inlinetask-min-level))
7426 ;; Find a heading level before the inline task
7427 (while (and (setq level (org-up-heading-safe))
7428 (>= level org-inlinetask-min-level)))
7429 (if (org-at-heading-p)
7430 (org-back-to-heading invisible-ok)
7431 (error "This should not happen")))
7432 (unless (and (save-excursion
7433 (save-match-data
7434 (org-backward-heading-same-level 1 invisible-ok))
7435 (= (point) (match-beginning 0)))
7436 (not (org-previous-line-empty-p t)))
7437 (setq empty-line-p (org-previous-line-empty-p)))
7438 (match-string 0))
7439 (error "* "))))
7440 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7441 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7442 pos hide-previous previous-pos)
7443 (if ;; At the beginning of a heading, open a new line for insertiong
7444 (and (bolp) (org-at-heading-p)
7445 (not eops)
7446 (or (bobp)
7447 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7448 (open-line (if blank 2 1))
7449 (save-excursion
7450 (setq previous-pos (point-at-bol))
7451 (end-of-line)
7452 (setq hide-previous (outline-invisible-p)))
7453 (and org-insert-heading-respect-content
7454 (save-excursion
7455 (while (outline-invisible-p)
7456 (org-show-subtree)
7457 (org-up-heading-safe))))
7458 (let ((split
7459 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7460 (save-excursion
7461 (let ((p (point)))
7462 (goto-char (point-at-bol))
7463 (and (looking-at org-complex-heading-regexp)
7464 (match-beginning 4)
7465 (> p (match-beginning 4)))))))
7466 tags pos)
7467 (cond
7468 ;; Insert a new line, possibly at end of parent subtree
7469 (org-insert-heading-respect-content
7470 (if (not eops)
7471 (progn
7472 (org-end-of-subtree nil t)
7473 (and (looking-at "^\\*") (backward-char 1))
7474 (while (and (not (bobp))
7475 ;; Don't delete spaces in empty headlines
7476 (not (looking-back org-outline-regexp))
7477 (member (char-before) '(?\ ?\t ?\n)))
7478 (backward-delete-char 1)))
7479 (let ((p (point)))
7480 (org-up-heading-safe)
7481 (if (= p (point))
7482 (goto-char (point-max))
7483 (org-end-of-subtree nil t))))
7484 (when (featurep 'org-inlinetask)
7485 (while (and (not (eobp))
7486 (looking-at "\\(\\*+\\)[ \t]+")
7487 (>= (length (match-string 1))
7488 org-inlinetask-min-level))
7489 (org-end-of-subtree nil t)))
7490 (or (bolp) (newline))
7491 (or (org-previous-line-empty-p)
7492 (and blank (newline)))
7493 (if (or empty-line-p eops) (open-line 1)))
7494 ;; Insert a headling containing text after point
7495 ((org-at-heading-p)
7496 (when hide-previous
7497 (show-children)
7498 (org-show-entry))
7499 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7500 (setq tags (and (match-end 2) (match-string 2)))
7501 (and (match-end 1)
7502 (delete-region (match-beginning 1) (match-end 1)))
7503 (setq pos (point-at-bol))
7504 (or split (end-of-line 1))
7505 (delete-horizontal-space)
7506 (if (string-match "\\`\\*+\\'"
7507 (buffer-substring (point-at-bol) (point)))
7508 (insert " "))
7509 (newline (if blank 2 1))
7510 (when tags
7511 (save-excursion
7512 (goto-char pos)
7513 (end-of-line 1)
7514 (insert " " tags)
7515 (org-set-tags nil 'align))))
7517 (or split (end-of-line 1))
7518 (newline (if blank 2 1))))))
7519 (insert head) (just-one-space)
7520 (setq pos (point))
7521 (end-of-line 1)
7522 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7523 (when (and org-insert-heading-respect-content hide-previous)
7524 (save-excursion
7525 (goto-char previous-pos)
7526 (hide-subtree)))
7527 (when (and begn endn)
7528 (narrow-to-region (min (point) begn) (max (point) endn)))
7529 (run-hooks 'org-insert-heading-hook))))))
7531 (defun org-get-heading (&optional no-tags no-todo)
7532 "Return the heading of the current entry, without the stars.
7533 When NO-TAGS is non-nil, don't include tags.
7534 When NO-TODO is non-nil, don't include TODO keywords."
7535 (save-excursion
7536 (org-back-to-heading t)
7537 (cond
7538 ((and no-tags no-todo)
7539 (looking-at org-complex-heading-regexp)
7540 (match-string 4))
7541 (no-tags
7542 (looking-at (concat org-outline-regexp
7543 "\\(.*?\\)"
7544 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7545 (match-string 1))
7546 (no-todo
7547 (looking-at org-todo-line-regexp)
7548 (match-string 3))
7549 (t (looking-at org-heading-regexp)
7550 (match-string 2)))))
7552 (defvar orgstruct-mode) ; defined below
7554 (defun org-heading-components ()
7555 "Return the components of the current heading.
7556 This is a list with the following elements:
7557 - the level as an integer
7558 - the reduced level, different if `org-odd-levels-only' is set.
7559 - the TODO keyword, or nil
7560 - the priority character, like ?A, or nil if no priority is given
7561 - the headline text itself, or the tags string if no headline text
7562 - the tags string, or nil."
7563 (save-excursion
7564 (org-back-to-heading t)
7565 (if (let (case-fold-search)
7566 (looking-at
7567 (if orgstruct-mode
7568 org-heading-regexp
7569 org-complex-heading-regexp)))
7570 (if orgstruct-mode
7571 (list (length (match-string 1))
7572 (org-reduced-level (length (match-string 1)))
7575 (match-string 2)
7576 nil)
7577 (list (length (match-string 1))
7578 (org-reduced-level (length (match-string 1)))
7579 (org-match-string-no-properties 2)
7580 (and (match-end 3) (aref (match-string 3) 2))
7581 (org-match-string-no-properties 4)
7582 (org-match-string-no-properties 5))))))
7584 (defun org-get-entry ()
7585 "Get the entry text, after heading, entire subtree."
7586 (save-excursion
7587 (org-back-to-heading t)
7588 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7590 (defun org-insert-heading-after-current ()
7591 "Insert a new heading with same level as current, after current subtree."
7592 (interactive)
7593 (org-back-to-heading)
7594 (org-insert-heading)
7595 (org-move-subtree-down)
7596 (end-of-line 1))
7598 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7599 "Insert heading with `org-insert-heading-respect-content' set to t."
7600 (interactive "P")
7601 (let ((org-insert-heading-respect-content t))
7602 (org-insert-heading arg invisible-ok)))
7604 (defun org-insert-todo-heading-respect-content (&optional force-state)
7605 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7606 (interactive "P")
7607 (let ((org-insert-heading-respect-content t))
7608 (org-insert-todo-heading force-state t)))
7610 (defun org-insert-todo-heading (arg &optional force-heading)
7611 "Insert a new heading with the same level and TODO state as current heading.
7612 If the heading has no TODO state, or if the state is DONE, use the first
7613 state (TODO by default). Also one prefix arg, force first state. With two
7614 prefix args, force inserting at the end of the parent subtree."
7615 (interactive "P")
7616 (when (or force-heading (not (org-insert-item 'checkbox)))
7617 (org-insert-heading (or (and (equal arg '(16)) '(16))
7618 force-heading))
7619 (save-excursion
7620 (org-back-to-heading)
7621 (outline-previous-heading)
7622 (looking-at org-todo-line-regexp))
7623 (let*
7624 ((new-mark-x
7625 (if (or arg
7626 (not (match-beginning 2))
7627 (member (match-string 2) org-done-keywords))
7628 (car org-todo-keywords-1)
7629 (match-string 2)))
7630 (new-mark
7632 (run-hook-with-args-until-success
7633 'org-todo-get-default-hook new-mark-x nil)
7634 new-mark-x)))
7635 (beginning-of-line 1)
7636 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7637 (if org-treat-insert-todo-heading-as-state-change
7638 (org-todo new-mark)
7639 (insert new-mark " "))))
7640 (when org-provide-todo-statistics
7641 (org-update-parent-todo-statistics))))
7643 (defun org-insert-subheading (arg)
7644 "Insert a new subheading and demote it.
7645 Works for outline headings and for plain lists alike."
7646 (interactive "P")
7647 (org-insert-heading arg)
7648 (cond
7649 ((org-at-heading-p) (org-do-demote))
7650 ((org-at-item-p) (org-indent-item))))
7652 (defun org-insert-todo-subheading (arg)
7653 "Insert a new subheading with TODO keyword or checkbox and demote it.
7654 Works for outline headings and for plain lists alike."
7655 (interactive "P")
7656 (org-insert-todo-heading arg)
7657 (cond
7658 ((org-at-heading-p) (org-do-demote))
7659 ((org-at-item-p) (org-indent-item))))
7661 ;;; Promotion and Demotion
7663 (defvar org-after-demote-entry-hook nil
7664 "Hook run after an entry has been demoted.
7665 The cursor will be at the beginning of the entry.
7666 When a subtree is being demoted, the hook will be called for each node.")
7668 (defvar org-after-promote-entry-hook nil
7669 "Hook run after an entry has been promoted.
7670 The cursor will be at the beginning of the entry.
7671 When a subtree is being promoted, the hook will be called for each node.")
7673 (defun org-promote-subtree ()
7674 "Promote the entire subtree.
7675 See also `org-promote'."
7676 (interactive)
7677 (save-excursion
7678 (org-with-limited-levels (org-map-tree 'org-promote)))
7679 (org-fix-position-after-promote))
7681 (defun org-demote-subtree ()
7682 "Demote the entire subtree. See `org-demote'.
7683 See also `org-promote'."
7684 (interactive)
7685 (save-excursion
7686 (org-with-limited-levels (org-map-tree 'org-demote)))
7687 (org-fix-position-after-promote))
7690 (defun org-do-promote ()
7691 "Promote the current heading higher up the tree.
7692 If the region is active in `transient-mark-mode', promote all headings
7693 in the region."
7694 (interactive)
7695 (save-excursion
7696 (if (org-region-active-p)
7697 (org-map-region 'org-promote (region-beginning) (region-end))
7698 (org-promote)))
7699 (org-fix-position-after-promote))
7701 (defun org-do-demote ()
7702 "Demote the current heading lower down the tree.
7703 If the region is active in `transient-mark-mode', demote all headings
7704 in the region."
7705 (interactive)
7706 (save-excursion
7707 (if (org-region-active-p)
7708 (org-map-region 'org-demote (region-beginning) (region-end))
7709 (org-demote)))
7710 (org-fix-position-after-promote))
7712 (defun org-fix-position-after-promote ()
7713 "Make sure that after pro/demotion cursor position is right."
7714 (let ((pos (point)))
7715 (when (save-excursion
7716 (beginning-of-line 1)
7717 (looking-at org-todo-line-regexp)
7718 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7719 (cond ((eobp) (insert " "))
7720 ((eolp) (insert " "))
7721 ((equal (char-after) ?\ ) (forward-char 1))))))
7723 (defun org-current-level ()
7724 "Return the level of the current entry, or nil if before the first headline.
7725 The level is the number of stars at the beginning of the headline."
7726 (save-excursion
7727 (org-with-limited-levels
7728 (if (ignore-errors (org-back-to-heading t))
7729 (funcall outline-level)))))
7731 (defun org-get-previous-line-level ()
7732 "Return the outline depth of the last headline before the current line.
7733 Returns 0 for the first headline in the buffer, and nil if before the
7734 first headline."
7735 (let ((current-level (org-current-level))
7736 (prev-level (when (> (line-number-at-pos) 1)
7737 (save-excursion
7738 (beginning-of-line 0)
7739 (org-current-level)))))
7740 (cond ((null current-level) nil) ; Before first headline
7741 ((null prev-level) 0) ; At first headline
7742 (prev-level))))
7744 (defun org-reduced-level (l)
7745 "Compute the effective level of a heading.
7746 This takes into account the setting of `org-odd-levels-only'."
7747 (cond
7748 ((zerop l) 0)
7749 (org-odd-levels-only (1+ (floor (/ l 2))))
7750 (t l)))
7752 (defun org-level-increment ()
7753 "Return the number of stars that will be added or removed at a
7754 time to headlines when structure editing, based on the value of
7755 `org-odd-levels-only'."
7756 (if org-odd-levels-only 2 1))
7758 (defun org-get-valid-level (level &optional change)
7759 "Rectify a level change under the influence of `org-odd-levels-only'
7760 LEVEL is a current level, CHANGE is by how much the level should be
7761 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7762 even level numbers will become the next higher odd number."
7763 (if org-odd-levels-only
7764 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7765 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7766 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7767 (max 1 (+ level (or change 0)))))
7769 (if (boundp 'define-obsolete-function-alias)
7770 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7771 (define-obsolete-function-alias 'org-get-legal-level
7772 'org-get-valid-level)
7773 (define-obsolete-function-alias 'org-get-legal-level
7774 'org-get-valid-level "23.1")))
7776 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7777 ;; ̀org-with-limited-levels'
7778 (defun org-promote ()
7779 "Promote the current heading higher up the tree.
7780 If the region is active in `transient-mark-mode', promote all headings
7781 in the region."
7782 (org-back-to-heading t)
7783 (let* ((level (save-match-data (funcall outline-level)))
7784 (after-change-functions (remove 'flyspell-after-change-function
7785 after-change-functions))
7786 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7787 (diff (abs (- level (length up-head) -1))))
7788 (cond ((and (= level 1) org-called-with-limited-levels
7789 org-allow-promoting-top-level-subtree)
7790 (replace-match "# " nil t))
7791 ((= level 1)
7792 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7793 (t (replace-match up-head nil t)))
7794 ;; Fixup tag positioning
7795 (unless (= level 1)
7796 (and org-auto-align-tags (org-set-tags nil t))
7797 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7798 (run-hooks 'org-after-promote-entry-hook)))
7800 (defun org-demote ()
7801 "Demote the current heading lower down the tree.
7802 If the region is active in `transient-mark-mode', demote all headings
7803 in the region."
7804 (org-back-to-heading t)
7805 (let* ((level (save-match-data (funcall outline-level)))
7806 (after-change-functions (remove 'flyspell-after-change-function
7807 after-change-functions))
7808 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7809 (diff (abs (- level (length down-head) -1))))
7810 (replace-match down-head nil t)
7811 ;; Fixup tag positioning
7812 (and org-auto-align-tags (org-set-tags nil t))
7813 (if org-adapt-indentation (org-fixup-indentation diff))
7814 (run-hooks 'org-after-demote-entry-hook)))
7816 (defun org-cycle-level ()
7817 "Cycle the level of an empty headline through possible states.
7818 This goes first to child, then to parent, level, then up the hierarchy.
7819 After top level, it switches back to sibling level."
7820 (interactive)
7821 (let ((org-adapt-indentation nil))
7822 (when (org-point-at-end-of-empty-headline)
7823 (setq this-command 'org-cycle-level) ; Only needed for caching
7824 (let ((cur-level (org-current-level))
7825 (prev-level (org-get-previous-line-level)))
7826 (cond
7827 ;; If first headline in file, promote to top-level.
7828 ((= prev-level 0)
7829 (loop repeat (/ (- cur-level 1) (org-level-increment))
7830 do (org-do-promote)))
7831 ;; If same level as prev, demote one.
7832 ((= prev-level cur-level)
7833 (org-do-demote))
7834 ;; If parent is top-level, promote to top level if not already.
7835 ((= prev-level 1)
7836 (loop repeat (/ (- cur-level 1) (org-level-increment))
7837 do (org-do-promote)))
7838 ;; If top-level, return to prev-level.
7839 ((= cur-level 1)
7840 (loop repeat (/ (- prev-level 1) (org-level-increment))
7841 do (org-do-demote)))
7842 ;; If less than prev-level, promote one.
7843 ((< cur-level prev-level)
7844 (org-do-promote))
7845 ;; If deeper than prev-level, promote until higher than
7846 ;; prev-level.
7847 ((> cur-level prev-level)
7848 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7849 do (org-do-promote))))
7850 t))))
7852 (defun org-map-tree (fun)
7853 "Call FUN for every heading underneath the current one."
7854 (org-back-to-heading)
7855 (let ((level (funcall outline-level)))
7856 (save-excursion
7857 (funcall fun)
7858 (while (and (progn
7859 (outline-next-heading)
7860 (> (funcall outline-level) level))
7861 (not (eobp)))
7862 (funcall fun)))))
7864 (defun org-map-region (fun beg end)
7865 "Call FUN for every heading between BEG and END."
7866 (let ((org-ignore-region t))
7867 (save-excursion
7868 (setq end (copy-marker end))
7869 (goto-char beg)
7870 (if (and (re-search-forward org-outline-regexp-bol nil t)
7871 (< (point) end))
7872 (funcall fun))
7873 (while (and (progn
7874 (outline-next-heading)
7875 (< (point) end))
7876 (not (eobp)))
7877 (funcall fun)))))
7879 (defvar org-property-end-re) ; silence byte-compiler
7880 (defun org-fixup-indentation (diff)
7881 "Change the indentation in the current entry by DIFF.
7882 However, if any line in the current entry has no indentation, or if it
7883 would end up with no indentation after the change, nothing at all is done."
7884 (save-excursion
7885 (let ((end (save-excursion (outline-next-heading)
7886 (point-marker)))
7887 (prohibit (if (> diff 0)
7888 "^\\S-"
7889 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7890 col)
7891 (unless (save-excursion (end-of-line 1)
7892 (re-search-forward prohibit end t))
7893 (while (and (< (point) end)
7894 (re-search-forward "^[ \t]+" end t))
7895 (goto-char (match-end 0))
7896 (setq col (current-column))
7897 (if (< diff 0) (replace-match ""))
7898 (org-indent-to-column (+ diff col))))
7899 (move-marker end nil))))
7901 (defun org-convert-to-odd-levels ()
7902 "Convert an org-mode file with all levels allowed to one with odd levels.
7903 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7904 level 5 etc."
7905 (interactive)
7906 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7907 (let ((outline-level 'org-outline-level)
7908 (org-odd-levels-only nil) n)
7909 (save-excursion
7910 (goto-char (point-min))
7911 (while (re-search-forward "^\\*\\*+ " nil t)
7912 (setq n (- (length (match-string 0)) 2))
7913 (while (>= (setq n (1- n)) 0)
7914 (org-demote))
7915 (end-of-line 1))))))
7917 (defun org-convert-to-oddeven-levels ()
7918 "Convert an org-mode file with only odd levels to one with odd/even levels.
7919 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7920 file contains a section with an even level, conversion would
7921 destroy the structure of the file. An error is signaled in this
7922 case."
7923 (interactive)
7924 (goto-char (point-min))
7925 ;; First check if there are no even levels
7926 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7927 (org-show-context t)
7928 (error "Not all levels are odd in this file. Conversion not possible"))
7929 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7930 (let ((outline-regexp org-outline-regexp)
7931 (outline-level 'org-outline-level)
7932 (org-odd-levels-only nil) n)
7933 (save-excursion
7934 (goto-char (point-min))
7935 (while (re-search-forward "^\\*\\*+ " nil t)
7936 (setq n (/ (1- (length (match-string 0))) 2))
7937 (while (>= (setq n (1- n)) 0)
7938 (org-promote))
7939 (end-of-line 1))))))
7941 (defun org-tr-level (n)
7942 "Make N odd if required."
7943 (if org-odd-levels-only (1+ (/ n 2)) n))
7945 ;;; Vertical tree motion, cutting and pasting of subtrees
7947 (defun org-move-subtree-up (&optional arg)
7948 "Move the current subtree up past ARG headlines of the same level."
7949 (interactive "p")
7950 (org-move-subtree-down (- (prefix-numeric-value arg))))
7952 (defun org-move-subtree-down (&optional arg)
7953 "Move the current subtree down past ARG headlines of the same level."
7954 (interactive "p")
7955 (setq arg (prefix-numeric-value arg))
7956 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7957 'org-get-last-sibling))
7958 (ins-point (make-marker))
7959 (cnt (abs arg))
7960 (col (current-column))
7961 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7962 ;; Select the tree
7963 (org-back-to-heading)
7964 (setq beg0 (point))
7965 (save-excursion
7966 (setq ne-beg (org-back-over-empty-lines))
7967 (setq beg (point)))
7968 (save-match-data
7969 (save-excursion (outline-end-of-heading)
7970 (setq folded (outline-invisible-p)))
7971 (outline-end-of-subtree))
7972 (outline-next-heading)
7973 (setq ne-end (org-back-over-empty-lines))
7974 (setq end (point))
7975 (goto-char beg0)
7976 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7977 ;; include less whitespace
7978 (save-excursion
7979 (goto-char beg)
7980 (forward-line (- ne-beg ne-end))
7981 (setq beg (point))))
7982 ;; Find insertion point, with error handling
7983 (while (> cnt 0)
7984 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7985 (progn (goto-char beg0)
7986 (user-error "Cannot move past superior level or buffer limit")))
7987 (setq cnt (1- cnt)))
7988 (if (> arg 0)
7989 ;; Moving forward - still need to move over subtree
7990 (progn (org-end-of-subtree t t)
7991 (save-excursion
7992 (org-back-over-empty-lines)
7993 (or (bolp) (newline)))))
7994 (setq ne-ins (org-back-over-empty-lines))
7995 (move-marker ins-point (point))
7996 (setq txt (buffer-substring beg end))
7997 (org-save-markers-in-region beg end)
7998 (delete-region beg end)
7999 (org-remove-empty-overlays-at beg)
8000 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8001 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8002 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8003 (let ((bbb (point)))
8004 (insert-before-markers txt)
8005 (org-reinstall-markers-in-region bbb)
8006 (move-marker ins-point bbb))
8007 (or (bolp) (insert "\n"))
8008 (setq ins-end (point))
8009 (goto-char ins-point)
8010 (org-skip-whitespace)
8011 (when (and (< arg 0)
8012 (org-first-sibling-p)
8013 (> ne-ins ne-beg))
8014 ;; Move whitespace back to beginning
8015 (save-excursion
8016 (goto-char ins-end)
8017 (let ((kill-whole-line t))
8018 (kill-line (- ne-ins ne-beg)) (point)))
8019 (insert (make-string (- ne-ins ne-beg) ?\n)))
8020 (move-marker ins-point nil)
8021 (if folded
8022 (hide-subtree)
8023 (org-show-entry)
8024 (show-children)
8025 (org-cycle-hide-drawers 'children))
8026 (org-clean-visibility-after-subtree-move)
8027 ;; move back to the initial column we were at
8028 (move-to-column col)))
8030 (defvar org-subtree-clip ""
8031 "Clipboard for cut and paste of subtrees.
8032 This is actually only a copy of the kill, because we use the normal kill
8033 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8035 (defvar org-subtree-clip-folded nil
8036 "Was the last copied subtree folded?
8037 This is used to fold the tree back after pasting.")
8039 (defun org-cut-subtree (&optional n)
8040 "Cut the current subtree into the clipboard.
8041 With prefix arg N, cut this many sequential subtrees.
8042 This is a short-hand for marking the subtree and then cutting it."
8043 (interactive "p")
8044 (org-copy-subtree n 'cut))
8046 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8047 "Cut the current subtree into the clipboard.
8048 With prefix arg N, cut this many sequential subtrees.
8049 This is a short-hand for marking the subtree and then copying it.
8050 If CUT is non-nil, actually cut the subtree.
8051 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8052 of some markers in the region, even if CUT is non-nil. This is
8053 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8054 (interactive "p")
8055 (let (beg end folded (beg0 (point)))
8056 (if (org-called-interactively-p 'any)
8057 (org-back-to-heading nil) ; take what looks like a subtree
8058 (org-back-to-heading t)) ; take what is really there
8059 (setq beg (point))
8060 (skip-chars-forward " \t\r\n")
8061 (save-match-data
8062 (if nosubtrees
8063 (outline-next-heading)
8064 (save-excursion (outline-end-of-heading)
8065 (setq folded (outline-invisible-p)))
8066 (condition-case nil
8067 (org-forward-heading-same-level (1- n) t)
8068 (error nil))
8069 (org-end-of-subtree t t)))
8070 (setq end (point))
8071 (goto-char beg0)
8072 (when (> end beg)
8073 (setq org-subtree-clip-folded folded)
8074 (when (or cut force-store-markers)
8075 (org-save-markers-in-region beg end))
8076 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8077 (setq org-subtree-clip (current-kill 0))
8078 (message "%s: Subtree(s) with %d characters"
8079 (if cut "Cut" "Copied")
8080 (length org-subtree-clip)))))
8082 (defun org-paste-subtree (&optional level tree for-yank)
8083 "Paste the clipboard as a subtree, with modification of headline level.
8084 The entire subtree is promoted or demoted in order to match a new headline
8085 level.
8087 If the cursor is at the beginning of a headline, the same level as
8088 that headline is used to paste the tree.
8090 If not, the new level is derived from the *visible* headings
8091 before and after the insertion point, and taken to be the inferior headline
8092 level of the two. So if the previous visible heading is level 3 and the
8093 next is level 4 (or vice versa), level 4 will be used for insertion.
8094 This makes sure that the subtree remains an independent subtree and does
8095 not swallow low level entries.
8097 You can also force a different level, either by using a numeric prefix
8098 argument, or by inserting the heading marker by hand. For example, if the
8099 cursor is after \"*****\", then the tree will be shifted to level 5.
8101 If optional TREE is given, use this text instead of the kill ring.
8103 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8104 move back over whitespace before inserting, and move point to the end of
8105 the inserted text when done."
8106 (interactive "P")
8107 (setq tree (or tree (and kill-ring (current-kill 0))))
8108 (unless (org-kill-is-subtree-p tree)
8109 (error "%s"
8110 (substitute-command-keys
8111 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8112 (org-with-limited-levels
8113 (let* ((visp (not (outline-invisible-p)))
8114 (txt tree)
8115 (^re_ "\\(\\*+\\)[ \t]*")
8116 (old-level (if (string-match org-outline-regexp-bol txt)
8117 (- (match-end 0) (match-beginning 0) 1)
8118 -1))
8119 (force-level (cond (level (prefix-numeric-value level))
8120 ((and (looking-at "[ \t]*$")
8121 (string-match
8122 "^\\*+$" (buffer-substring
8123 (point-at-bol) (point))))
8124 (- (match-end 1) (match-beginning 1)))
8125 ((and (bolp)
8126 (looking-at org-outline-regexp))
8127 (- (match-end 0) (point) 1))))
8128 (previous-level (save-excursion
8129 (condition-case nil
8130 (progn
8131 (outline-previous-visible-heading 1)
8132 (if (looking-at ^re_)
8133 (- (match-end 0) (match-beginning 0) 1)
8135 (error 1))))
8136 (next-level (save-excursion
8137 (condition-case nil
8138 (progn
8139 (or (looking-at org-outline-regexp)
8140 (outline-next-visible-heading 1))
8141 (if (looking-at ^re_)
8142 (- (match-end 0) (match-beginning 0) 1)
8144 (error 1))))
8145 (new-level (or force-level (max previous-level next-level)))
8146 (shift (if (or (= old-level -1)
8147 (= new-level -1)
8148 (= old-level new-level))
8150 (- new-level old-level)))
8151 (delta (if (> shift 0) -1 1))
8152 (func (if (> shift 0) 'org-demote 'org-promote))
8153 (org-odd-levels-only nil)
8154 beg end newend)
8155 ;; Remove the forced level indicator
8156 (if force-level
8157 (delete-region (point-at-bol) (point)))
8158 ;; Paste
8159 (beginning-of-line (if (bolp) 1 2))
8160 (setq beg (point))
8161 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8162 (insert-before-markers txt)
8163 (unless (string-match "\n\\'" txt) (insert "\n"))
8164 (setq newend (point))
8165 (org-reinstall-markers-in-region beg)
8166 (setq end (point))
8167 (goto-char beg)
8168 (skip-chars-forward " \t\n\r")
8169 (setq beg (point))
8170 (if (and (outline-invisible-p) visp)
8171 (save-excursion (outline-show-heading)))
8172 ;; Shift if necessary
8173 (unless (= shift 0)
8174 (save-restriction
8175 (narrow-to-region beg end)
8176 (while (not (= shift 0))
8177 (org-map-region func (point-min) (point-max))
8178 (setq shift (+ delta shift)))
8179 (goto-char (point-min))
8180 (setq newend (point-max))))
8181 (when (or (org-called-interactively-p 'interactive) for-yank)
8182 (message "Clipboard pasted as level %d subtree" new-level))
8183 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8184 kill-ring
8185 (eq org-subtree-clip (current-kill 0))
8186 org-subtree-clip-folded)
8187 ;; The tree was folded before it was killed/copied
8188 (hide-subtree))
8189 (and for-yank (goto-char newend)))))
8191 (defun org-kill-is-subtree-p (&optional txt)
8192 "Check if the current kill is an outline subtree, or a set of trees.
8193 Returns nil if kill does not start with a headline, or if the first
8194 headline level is not the largest headline level in the tree.
8195 So this will actually accept several entries of equal levels as well,
8196 which is OK for `org-paste-subtree'.
8197 If optional TXT is given, check this string instead of the current kill."
8198 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8199 (re (org-get-limited-outline-regexp))
8200 (^re (concat "^" re))
8201 (start-level (and kill
8202 (string-match
8203 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8204 kill)
8205 (- (match-end 2) (match-beginning 2) 1)))
8206 (start (1+ (or (match-beginning 2) -1))))
8207 (if (not start-level)
8208 (progn
8209 nil) ;; does not even start with a heading
8210 (catch 'exit
8211 (while (setq start (string-match ^re kill (1+ start)))
8212 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8213 (throw 'exit nil)))
8214 t))))
8216 (defvar org-markers-to-move nil
8217 "Markers that should be moved with a cut-and-paste operation.
8218 Those markers are stored together with their positions relative to
8219 the start of the region.")
8221 (defun org-save-markers-in-region (beg end)
8222 "Check markers in region.
8223 If these markers are between BEG and END, record their position relative
8224 to BEG, so that after moving the block of text, we can put the markers back
8225 into place.
8226 This function gets called just before an entry or tree gets cut from the
8227 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8228 called immediately, to move the markers with the entries."
8229 (setq org-markers-to-move nil)
8230 (when (featurep 'org-clock)
8231 (org-clock-save-markers-for-cut-and-paste beg end))
8232 (when (featurep 'org-agenda)
8233 (org-agenda-save-markers-for-cut-and-paste beg end)))
8235 (defun org-check-and-save-marker (marker beg end)
8236 "Check if MARKER is between BEG and END.
8237 If yes, remember the marker and the distance to BEG."
8238 (when (and (marker-buffer marker)
8239 (equal (marker-buffer marker) (current-buffer)))
8240 (if (and (>= marker beg) (< marker end))
8241 (push (cons marker (- marker beg)) org-markers-to-move))))
8243 (defun org-reinstall-markers-in-region (beg)
8244 "Move all remembered markers to their position relative to BEG."
8245 (mapc (lambda (x)
8246 (move-marker (car x) (+ beg (cdr x))))
8247 org-markers-to-move)
8248 (setq org-markers-to-move nil))
8250 (defun org-narrow-to-subtree ()
8251 "Narrow buffer to the current subtree."
8252 (interactive)
8253 (save-excursion
8254 (save-match-data
8255 (org-with-limited-levels
8256 (narrow-to-region
8257 (progn (org-back-to-heading t) (point))
8258 (progn (org-end-of-subtree t t)
8259 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8260 (point)))))))
8262 (defun org-narrow-to-block ()
8263 "Narrow buffer to the current block."
8264 (interactive)
8265 (let* ((case-fold-search t)
8266 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8267 "^[ \t]*#\\+end_.*")))
8268 (if blockp
8269 (narrow-to-region (car blockp) (cdr blockp))
8270 (error "Not in a block"))))
8272 (eval-when-compile
8273 (defvar org-property-drawer-re))
8275 (defvar org-property-start-re) ;; defined below
8276 (defun org-clone-subtree-with-time-shift (n &optional shift)
8277 "Clone the task (subtree) at point N times.
8278 The clones will be inserted as siblings.
8280 In interactive use, the user will be prompted for the number of
8281 clones to be produced. When called with a universal prefix argument
8282 and if the entry has a timestamp, the user will also be prompted for
8283 a time shift, which may be a repeater as used in time stamps, for
8284 example `+3d'.
8286 When a valid repeater is given and the entry contains any time
8287 stamps, the clones will become a sequence in time, with time
8288 stamps in the subtree shifted for each clone produced. If SHIFT
8289 is nil or the empty string, time stamps will be left alone. The
8290 ID property of the original subtree is removed.
8292 If the original subtree did contain time stamps with a repeater,
8293 the following will happen:
8294 - the repeater will be removed in each clone
8295 - an additional clone will be produced, with the current, unshifted
8296 date(s) in the entry.
8297 - the original entry will be placed *after* all the clones, with
8298 repeater intact.
8299 - the start days in the repeater in the original entry will be shifted
8300 to past the last clone.
8301 In this way you can spell out a number of instances of a repeating task,
8302 and still retain the repeater to cover future instances of the task."
8303 (interactive "nNumber of clones to produce: ")
8304 (let ((shift
8305 (or shift
8306 (if (and (equal current-prefix-arg '(4))
8307 (save-excursion
8308 (re-search-forward org-ts-regexp-both
8309 (save-excursion
8310 (org-end-of-subtree t)
8311 (point)) t)))
8312 (read-from-minibuffer
8313 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8314 ""))) ;; No time shift
8315 (n-no-remove -1)
8316 (drawer-re org-drawer-regexp)
8317 beg end template task idprop
8318 shift-n shift-what doshift nmin nmax)
8319 (if (not (and (integerp n) (> n 0)))
8320 (error "Invalid number of replications %s" n))
8321 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8322 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8323 shift)))
8324 (error "Invalid shift specification %s" shift))
8325 (when doshift
8326 (setq shift-n (string-to-number (match-string 1 shift))
8327 shift-what (cdr (assoc (match-string 2 shift)
8328 '(("d" . day) ("w" . week)
8329 ("m" . month) ("y" . year))))))
8330 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8331 (setq nmin 1 nmax n)
8332 (org-back-to-heading t)
8333 (setq beg (point))
8334 (setq idprop (org-entry-get nil "ID"))
8335 (org-end-of-subtree t t)
8336 (or (bolp) (insert "\n"))
8337 (setq end (point))
8338 (setq template (buffer-substring beg end))
8339 (when (and doshift
8340 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8341 (delete-region beg end)
8342 (setq end beg)
8343 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8344 (goto-char end)
8345 (loop for n from nmin to nmax do
8346 ;; prepare clone
8347 (with-temp-buffer
8348 (insert template)
8349 (org-mode)
8350 (goto-char (point-min))
8351 (org-show-subtree)
8352 (and idprop (if org-clone-delete-id
8353 (org-entry-delete nil "ID")
8354 (org-id-get-create t)))
8355 (unless (= n 0)
8356 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8357 (kill-whole-line))
8358 (goto-char (point-min))
8359 (while (re-search-forward drawer-re nil t)
8360 (mapc (lambda (d)
8361 (org-remove-empty-drawer-at d (point))) org-drawers)))
8362 (goto-char (point-min))
8363 (when doshift
8364 (while (re-search-forward org-ts-regexp-both nil t)
8365 (org-timestamp-change (* n shift-n) shift-what))
8366 (unless (= n n-no-remove)
8367 (goto-char (point-min))
8368 (while (re-search-forward org-ts-regexp nil t)
8369 (save-excursion
8370 (goto-char (match-beginning 0))
8371 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8372 (delete-region (match-beginning 1) (match-end 1)))))))
8373 (setq task (buffer-string)))
8374 (insert task))
8375 (goto-char beg)))
8377 ;;; Outline Sorting
8379 (defun org-sort (with-case)
8380 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8381 Optional argument WITH-CASE means sort case-sensitively."
8382 (interactive "P")
8383 (cond
8384 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8385 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8387 (org-call-with-arg 'org-sort-entries with-case))))
8389 (defun org-sort-remove-invisible (s)
8390 "Remove invisible links from string S."
8391 (remove-text-properties 0 (length s) org-rm-props s)
8392 (while (string-match org-bracket-link-regexp s)
8393 (setq s (replace-match (if (match-end 2)
8394 (match-string 3 s)
8395 (match-string 1 s)) t t s)))
8396 (let ((st (format " %s " s)))
8397 (while (string-match org-emph-re st)
8398 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8399 (setq s (substring st 1 -1)))
8402 (defvar org-priority-regexp) ; defined later in the file
8404 (defvar org-after-sorting-entries-or-items-hook nil
8405 "Hook that is run after a bunch of entries or items have been sorted.
8406 When children are sorted, the cursor is in the parent line when this
8407 hook gets called. When a region or a plain list is sorted, the cursor
8408 will be in the first entry of the sorted region/list.")
8410 (defun org-sort-entries
8411 (&optional with-case sorting-type getkey-func compare-func property)
8412 "Sort entries on a certain level of an outline tree.
8413 If there is an active region, the entries in the region are sorted.
8414 Else, if the cursor is before the first entry, sort the top-level items.
8415 Else, the children of the entry at point are sorted.
8417 Sorting can be alphabetically, numerically, by date/time as given by
8418 a time stamp, by a property, by priority order, or by a custom function.
8420 The command prompts for the sorting type unless it has been given to the
8421 function through the SORTING-TYPE argument, which needs to be a character,
8422 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8423 precise meaning of each character:
8425 n Numerically, by converting the beginning of the entry/item to a number.
8426 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8427 o By order of TODO keywords.
8428 t By date/time, either the first active time stamp in the entry, or, if
8429 none exist, by the first inactive one.
8430 s By the scheduled date/time.
8431 d By deadline date/time.
8432 c By creation time, which is assumed to be the first inactive time stamp
8433 at the beginning of a line.
8434 p By priority according to the cookie.
8435 r By the value of a property.
8437 Capital letters will reverse the sort order.
8439 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8440 called with point at the beginning of the record. It must return either
8441 a string or a number that should serve as the sorting key for that record.
8443 Comparing entries ignores case by default. However, with an optional argument
8444 WITH-CASE, the sorting considers case as well.
8446 Sorting is done against the visible part of the headlines, it ignores hidden
8447 links."
8448 (interactive "P")
8449 (let ((case-func (if with-case 'identity 'downcase))
8450 (cmstr
8451 ;; The clock marker is lost when using `sort-subr', let's
8452 ;; store the clocking string.
8453 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8454 (save-excursion
8455 (goto-char org-clock-marker)
8456 (looking-back "^.*") (match-string-no-properties 0))))
8457 start beg end stars re re2
8458 txt what tmp)
8459 ;; Find beginning and end of region to sort
8460 (cond
8461 ((org-region-active-p)
8462 ;; we will sort the region
8463 (setq end (region-end)
8464 what "region")
8465 (goto-char (region-beginning))
8466 (if (not (org-at-heading-p)) (outline-next-heading))
8467 (setq start (point)))
8468 ((or (org-at-heading-p)
8469 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8470 ;; we will sort the children of the current headline
8471 (org-back-to-heading)
8472 (setq start (point)
8473 end (progn (org-end-of-subtree t t)
8474 (or (bolp) (insert "\n"))
8475 (org-back-over-empty-lines)
8476 (point))
8477 what "children")
8478 (goto-char start)
8479 (show-subtree)
8480 (outline-next-heading))
8482 ;; we will sort the top-level entries in this file
8483 (goto-char (point-min))
8484 (or (org-at-heading-p) (outline-next-heading))
8485 (setq start (point))
8486 (goto-char (point-max))
8487 (beginning-of-line 1)
8488 (when (looking-at ".*?\\S-")
8489 ;; File ends in a non-white line
8490 (end-of-line 1)
8491 (insert "\n"))
8492 (setq end (point-max))
8493 (setq what "top-level")
8494 (goto-char start)
8495 (show-all)))
8497 (setq beg (point))
8498 (if (>= beg end) (error "Nothing to sort"))
8500 (looking-at "\\(\\*+\\)")
8501 (setq stars (match-string 1)
8502 re (concat "^" (regexp-quote stars) " +")
8503 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8504 txt (buffer-substring beg end))
8505 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8506 (if (and (not (equal stars "*")) (string-match re2 txt))
8507 (error "Region to sort contains a level above the first entry"))
8509 (unless sorting-type
8510 (message
8511 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8512 [t]ime [s]cheduled [d]eadline [c]reated
8513 A/N/P/R/O/F/T/S/D/C means reversed:"
8514 what)
8515 (setq sorting-type (read-char-exclusive))
8517 (unless getkey-func
8518 (and (= (downcase sorting-type) ?f)
8519 (setq getkey-func
8520 (org-icompleting-read "Sort using function: "
8521 obarray 'fboundp t nil nil))
8522 (setq getkey-func (intern getkey-func))))
8524 (and (= (downcase sorting-type) ?r)
8525 (not property)
8526 (setq property
8527 (org-icompleting-read "Property: "
8528 (mapcar 'list (org-buffer-property-keys t))
8529 nil t))))
8531 (message "Sorting entries...")
8533 (save-restriction
8534 (narrow-to-region start end)
8535 (let ((dcst (downcase sorting-type))
8536 (case-fold-search nil)
8537 (now (current-time)))
8538 (sort-subr
8539 (/= dcst sorting-type)
8540 ;; This function moves to the beginning character of the "record" to
8541 ;; be sorted.
8542 (lambda nil
8543 (if (re-search-forward re nil t)
8544 (goto-char (match-beginning 0))
8545 (goto-char (point-max))))
8546 ;; This function moves to the last character of the "record" being
8547 ;; sorted.
8548 (lambda nil
8549 (save-match-data
8550 (condition-case nil
8551 (outline-forward-same-level 1)
8552 (error
8553 (goto-char (point-max))))))
8554 ;; This function returns the value that gets sorted against.
8555 (lambda nil
8556 (cond
8557 ((= dcst ?n)
8558 (if (looking-at org-complex-heading-regexp)
8559 (string-to-number (org-sort-remove-invisible (match-string 4)))
8560 nil))
8561 ((= dcst ?a)
8562 (if (looking-at org-complex-heading-regexp)
8563 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8564 nil))
8565 ((= dcst ?t)
8566 (let ((end (save-excursion (outline-next-heading) (point))))
8567 (if (or (re-search-forward org-ts-regexp end t)
8568 (re-search-forward org-ts-regexp-both end t))
8569 (org-time-string-to-seconds (match-string 0))
8570 (org-float-time now))))
8571 ((= dcst ?c)
8572 (let ((end (save-excursion (outline-next-heading) (point))))
8573 (if (re-search-forward
8574 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8575 end t)
8576 (org-time-string-to-seconds (match-string 0))
8577 (org-float-time now))))
8578 ((= dcst ?s)
8579 (let ((end (save-excursion (outline-next-heading) (point))))
8580 (if (re-search-forward org-scheduled-time-regexp end t)
8581 (org-time-string-to-seconds (match-string 1))
8582 (org-float-time now))))
8583 ((= dcst ?d)
8584 (let ((end (save-excursion (outline-next-heading) (point))))
8585 (if (re-search-forward org-deadline-time-regexp end t)
8586 (org-time-string-to-seconds (match-string 1))
8587 (org-float-time now))))
8588 ((= dcst ?p)
8589 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8590 (string-to-char (match-string 2))
8591 org-default-priority))
8592 ((= dcst ?r)
8593 (or (org-entry-get nil property) ""))
8594 ((= dcst ?o)
8595 (if (looking-at org-complex-heading-regexp)
8596 (- 9999 (length (member (match-string 2)
8597 org-todo-keywords-1)))))
8598 ((= dcst ?f)
8599 (if getkey-func
8600 (progn
8601 (setq tmp (funcall getkey-func))
8602 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8603 tmp)
8604 (error "Invalid key function `%s'" getkey-func)))
8605 (t (error "Invalid sorting type `%c'" sorting-type))))
8607 (cond
8608 ((= dcst ?a) 'string<)
8609 ((= dcst ?f) compare-func)
8610 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8611 (run-hooks 'org-after-sorting-entries-or-items-hook)
8612 ;; Reset the clock marker if needed
8613 (when cmstr
8614 (save-excursion
8615 (goto-char start)
8616 (search-forward cmstr nil t)
8617 (move-marker org-clock-marker (point))))
8618 (message "Sorting entries...done")))
8620 (defun org-do-sort (table what &optional with-case sorting-type)
8621 "Sort TABLE of WHAT according to SORTING-TYPE.
8622 The user will be prompted for the SORTING-TYPE if the call to this
8623 function does not specify it. WHAT is only for the prompt, to indicate
8624 what is being sorted. The sorting key will be extracted from
8625 the car of the elements of the table.
8626 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8627 (unless sorting-type
8628 (message
8629 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8630 what)
8631 (setq sorting-type (read-char-exclusive)))
8632 (let ((dcst (downcase sorting-type))
8633 extractfun comparefun)
8634 ;; Define the appropriate functions
8635 (cond
8636 ((= dcst ?n)
8637 (setq extractfun 'string-to-number
8638 comparefun (if (= dcst sorting-type) '< '>)))
8639 ((= dcst ?a)
8640 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8641 (lambda(x) (downcase (org-sort-remove-invisible x))))
8642 comparefun (if (= dcst sorting-type)
8643 'string<
8644 (lambda (a b) (and (not (string< a b))
8645 (not (string= a b)))))))
8646 ((= dcst ?t)
8647 (setq extractfun
8648 (lambda (x)
8649 (if (or (string-match org-ts-regexp x)
8650 (string-match org-ts-regexp-both x))
8651 (org-float-time
8652 (org-time-string-to-time (match-string 0 x)))
8654 comparefun (if (= dcst sorting-type) '< '>)))
8655 (t (error "Invalid sorting type `%c'" sorting-type)))
8657 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8658 table)
8659 (lambda (a b) (funcall comparefun (car a) (car b))))))
8662 ;;; The orgstruct minor mode
8664 ;; Define a minor mode which can be used in other modes in order to
8665 ;; integrate the org-mode structure editing commands.
8667 ;; This is really a hack, because the org-mode structure commands use
8668 ;; keys which normally belong to the major mode. Here is how it
8669 ;; works: The minor mode defines all the keys necessary to operate the
8670 ;; structure commands, but wraps the commands into a function which
8671 ;; tests if the cursor is currently at a headline or a plain list
8672 ;; item. If that is the case, the structure command is used,
8673 ;; temporarily setting many Org-mode variables like regular
8674 ;; expressions for filling etc. However, when any of those keys is
8675 ;; used at a different location, function uses `key-binding' to look
8676 ;; up if the key has an associated command in another currently active
8677 ;; keymap (minor modes, major mode, global), and executes that
8678 ;; command. There might be problems if any of the keys is otherwise
8679 ;; used as a prefix key.
8681 (defcustom orgstruct-heading-prefix-regexp nil
8682 "Regexp that matches the custom prefix of Org headlines in
8683 orgstruct(++)-mode."
8684 :group 'org
8685 :version "24.4"
8686 :package-version '(Org . "8.0")
8687 :type 'string)
8688 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8690 (defcustom orgstruct-setup-hook nil
8691 "Hook run after orgstruct-mode-map is filled."
8692 :group 'org
8693 :version "24.4"
8694 :package-version '(Org . "8.0")
8695 :type 'hook)
8697 (defvar orgstruct-initialized nil)
8699 (defvar org-local-vars nil
8700 "List of local variables, for use by `orgstruct-mode'.")
8702 ;;;###autoload
8703 (define-minor-mode orgstruct-mode
8704 "Toggle the minor mode `orgstruct-mode'.
8705 This mode is for using Org-mode structure commands in other
8706 modes. The following keys behave as if Org-mode were active, if
8707 the cursor is on a headline, or on a plain list item (both as
8708 defined by Org-mode)."
8709 nil " OrgStruct" (make-sparse-keymap)
8710 (funcall (if orgstruct-mode
8711 'add-to-invisibility-spec
8712 'remove-from-invisibility-spec)
8713 '(outline . t))
8714 (when orgstruct-mode
8715 (org-load-modules-maybe)
8716 (unless orgstruct-initialized
8717 (orgstruct-setup)
8718 (setq orgstruct-initialized t))))
8720 ;;;###autoload
8721 (defun turn-on-orgstruct ()
8722 "Unconditionally turn on `orgstruct-mode'."
8723 (orgstruct-mode 1))
8725 (defvar org-fb-vars nil)
8726 (make-variable-buffer-local 'org-fb-vars)
8727 (defun orgstruct++-mode (&optional arg)
8728 "Toggle `orgstruct-mode', the enhanced version of it.
8729 In addition to setting orgstruct-mode, this also exports all
8730 indentation and autofilling variables from org-mode into the
8731 buffer. It will also recognize item context in multiline items."
8732 (interactive "P")
8733 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8734 (if (< arg 1)
8735 (progn (orgstruct-mode -1)
8736 (mapc (lambda(v)
8737 (org-set-local (car v)
8738 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8739 org-fb-vars))
8740 (orgstruct-mode 1)
8741 (setq org-fb-vars nil)
8742 (let (var val)
8743 (mapc
8744 (lambda (x)
8745 (when (string-match
8746 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8747 (symbol-name (car x)))
8748 (setq var (car x) val (nth 1 x))
8749 (push (list var `(quote ,(eval var))) org-fb-vars)
8750 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8751 org-local-vars)
8752 (org-set-local 'orgstruct-is-++ t))))
8754 (defvar orgstruct-is-++ nil
8755 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8756 (make-variable-buffer-local 'orgstruct-is-++)
8758 ;;;###autoload
8759 (defun turn-on-orgstruct++ ()
8760 "Unconditionally turn on `orgstruct++-mode'."
8761 (orgstruct++-mode 1))
8763 (defun orgstruct-error ()
8764 "Error when there is no default binding for a structure key."
8765 (interactive)
8766 (funcall (if (fboundp 'user-error)
8767 'user-error
8768 'error)
8769 "This key has no function outside structure elements"))
8771 (defun orgstruct-setup ()
8772 "Setup orgstruct keymap."
8773 (dolist (cell '((org-demote . t)
8774 (org-metaleft . t)
8775 (org-metaright . t)
8776 (org-promote . t)
8777 (org-shiftmetaleft . t)
8778 (org-shiftmetaright . t)
8779 org-backward-element
8780 org-backward-heading-same-level
8781 org-ctrl-c-ret
8782 org-ctrl-c-minus
8783 org-ctrl-c-star
8784 org-cycle
8785 org-forward-heading-same-level
8786 org-insert-heading
8787 org-insert-heading-respect-content
8788 org-kill-note-or-show-branches
8789 org-mark-subtree
8790 org-meta-return
8791 org-metadown
8792 org-metaup
8793 org-narrow-to-subtree
8794 org-promote-subtree
8795 org-reveal
8796 org-shiftdown
8797 org-shiftleft
8798 org-shiftmetadown
8799 org-shiftmetaup
8800 org-shiftright
8801 org-shifttab
8802 org-shifttab
8803 org-shiftup
8804 org-show-subtree
8805 org-sort
8806 org-up-element
8807 outline-demote
8808 outline-next-visible-heading
8809 outline-previous-visible-heading
8810 outline-promote
8811 outline-up-heading
8812 show-children))
8813 (let ((f (or (car-safe cell) cell))
8814 (disable-when-heading-prefix (cdr-safe cell)))
8815 (when (fboundp f)
8816 (dolist (binding (nconc (where-is-internal f org-mode-map)
8817 (where-is-internal f outline-mode-map)))
8818 ;; TODO use local-function-key-map
8819 (dolist (rep '(("<tab>" . "TAB")
8820 ("<return>" . "RET")
8821 ("<escape>" . "ESC")
8822 ("<delete>" . "DEL")))
8823 (setq binding (read-kbd-macro
8824 (let ((case-fold-search))
8825 (replace-regexp-in-string
8826 (regexp-quote (cdr rep))
8827 (car rep)
8828 (key-description binding))))))
8829 (let ((key (lookup-key orgstruct-mode-map binding)))
8830 (when (or (not key) (numberp key))
8831 (condition-case nil
8832 (org-defkey orgstruct-mode-map
8833 binding
8834 (orgstruct-make-binding f binding disable-when-heading-prefix))
8835 (error nil))))))))
8836 (run-hooks 'orgstruct-setup-hook))
8838 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8839 "Create a function for binding in the structure minor mode.
8840 FUN is the command to call inside a table. KEY is the key that
8841 should be checked in for a command to execute outside of tables.
8842 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8843 if `orgstruct-heading-prefix-regexp' is non-nil."
8844 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8845 (let ((nname name)
8846 (i 0))
8847 (while (fboundp (intern nname))
8848 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8849 (setq name (intern nname)))
8850 (eval
8851 (let ((bindings '((org-heading-regexp
8852 (concat "^"
8853 orgstruct-heading-prefix-regexp
8854 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8855 (org-outline-regexp
8856 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8857 (org-outline-regexp-bol
8858 (concat "^" org-outline-regexp))
8859 (outline-regexp org-outline-regexp)
8860 (outline-heading-end-regexp "\n")
8861 (outline-level 'org-outline-level)
8862 (outline-heading-alist))))
8863 `(defun ,name (arg)
8864 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8865 "Outside of structure, run the binding of `"
8866 (key-description key) "'."
8867 (when disable-when-heading-prefix
8868 (concat
8869 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8870 "back to the default binding due to limitations of Org's implementation of\n"
8871 "`" (symbol-name fun) "'.")))
8872 (interactive "p")
8873 (let* ((disable
8874 ,(when disable-when-heading-prefix
8875 '(and orgstruct-heading-prefix-regexp
8876 (not (string= orgstruct-heading-prefix-regexp "")))))
8877 (fallback
8878 (or disable
8879 (not
8880 (let* ,bindings
8881 (org-context-p 'headline 'item
8882 ,(when (memq fun '(org-insert-heading))
8883 '(when orgstruct-is-++
8884 'item-body))))))))
8885 (if fallback
8886 (let* ((orgstruct-mode)
8887 (binding
8888 (loop with key = ,key
8889 for rep in '(nil
8890 ("<tab>" . "TAB")
8891 ("<return>" . "RET")
8892 ("<escape>" . "ESC")
8893 ("<delete>" . "DEL"))
8895 (when rep
8896 (setq key (read-kbd-macro
8897 (let ((case-fold-search))
8898 (replace-regexp-in-string
8899 (regexp-quote (car rep))
8900 (cdr rep)
8901 (key-description key))))))
8902 thereis (key-binding key))))
8903 (if (keymapp binding)
8904 (set-temporary-overlay-map binding)
8905 (let ((func (or binding
8906 (unless disable
8907 'orgstruct-error))))
8908 (when func
8909 (call-interactively func)))))
8910 (org-run-like-in-org-mode
8911 (lambda ()
8912 (interactive)
8913 (let* ,bindings
8914 (call-interactively ',fun)))))))))
8915 name))
8917 (defun org-contextualize-keys (alist contexts)
8918 "Return valid elements in ALIST depending on CONTEXTS.
8920 `org-agenda-custom-commands' or `org-capture-templates' are the
8921 values used for ALIST, and `org-agenda-custom-commands-contexts'
8922 or `org-capture-templates-contexts' are the associated contexts
8923 definitions."
8924 (let ((contexts
8925 ;; normalize contexts
8926 (mapcar
8927 (lambda(c) (cond ((listp (cadr c))
8928 (list (car c) (car c) (cadr c)))
8929 ((string= "" (cadr c))
8930 (list (car c) (car c) (caddr c)))
8931 (t c))) contexts))
8932 (a alist) c r s)
8933 ;; loop over all commands or templates
8934 (while (setq c (pop a))
8935 (let (vrules repl)
8936 (cond
8937 ((not (assoc (car c) contexts))
8938 (push c r))
8939 ((and (assoc (car c) contexts)
8940 (setq vrules (org-contextualize-validate-key
8941 (car c) contexts)))
8942 (mapc (lambda (vr)
8943 (when (not (equal (car vr) (cadr vr)))
8944 (setq repl vr))) vrules)
8945 (if (not repl) (push c r)
8946 (push (cadr repl) s)
8947 (push
8948 (cons (car c)
8949 (cdr (or (assoc (cadr repl) alist)
8950 (error "Undefined key `%s' as contextual replacement for `%s'"
8951 (cadr repl) (car c)))))
8952 r))))))
8953 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8954 (delq
8956 (delete-dups
8957 (mapcar (lambda (x)
8958 (let ((tpl (car x)))
8959 (when (not (delq
8961 (mapcar (lambda(y)
8962 (equal y tpl)) s))) x)))
8963 (reverse r))))))
8965 (defun org-contextualize-validate-key (key contexts)
8966 "Check CONTEXTS for agenda or capture KEY."
8967 (let (r rr res)
8968 (while (setq r (pop contexts))
8969 (mapc
8970 (lambda (rr)
8971 (when
8972 (and (equal key (car r))
8973 (if (functionp rr) (funcall rr)
8974 (or (and (eq (car rr) 'in-file)
8975 (buffer-file-name)
8976 (string-match (cdr rr) (buffer-file-name)))
8977 (and (eq (car rr) 'in-mode)
8978 (string-match (cdr rr) (symbol-name major-mode)))
8979 (and (eq (car rr) 'in-buffer)
8980 (string-match (cdr rr) (buffer-name)))
8981 (when (and (eq (car rr) 'not-in-file)
8982 (buffer-file-name))
8983 (not (string-match (cdr rr) (buffer-file-name))))
8984 (when (eq (car rr) 'not-in-mode)
8985 (not (string-match (cdr rr) (symbol-name major-mode))))
8986 (when (eq (car rr) 'not-in-buffer)
8987 (not (string-match (cdr rr) (buffer-name)))))))
8988 (push r res)))
8989 (car (last r))))
8990 (delete-dups (delq nil res))))
8992 (defun org-context-p (&rest contexts)
8993 "Check if local context is any of CONTEXTS.
8994 Possible values in the list of contexts are `table', `headline', and `item'."
8995 (let ((pos (point)))
8996 (goto-char (point-at-bol))
8997 (prog1 (or (and (memq 'table contexts)
8998 (looking-at "[ \t]*|"))
8999 (and (memq 'headline contexts)
9000 (looking-at org-outline-regexp))
9001 (and (memq 'item contexts)
9002 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9003 (and (memq 'item-body contexts)
9004 (org-in-item-p)))
9005 (goto-char pos))))
9007 (defun org-get-local-variables ()
9008 "Return a list of all local variables in an Org mode buffer."
9009 (let (varlist)
9010 (with-current-buffer (get-buffer-create "*Org tmp*")
9011 (erase-buffer)
9012 (org-mode)
9013 (setq varlist (buffer-local-variables)))
9014 (kill-buffer "*Org tmp*")
9015 (delq nil
9016 (mapcar
9017 (lambda (x)
9018 (setq x
9019 (if (symbolp x)
9020 (list x)
9021 (list (car x) (cdr x))))
9022 (if (and (not (get (car x) 'org-state))
9023 (string-match
9024 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9025 (symbol-name (car x))))
9026 x nil))
9027 varlist))))
9029 (defun org-clone-local-variables (from-buffer &optional regexp)
9030 "Clone local variables from FROM-BUFFER.
9031 Optional argument REGEXP selects variables to clone."
9032 (mapc
9033 (lambda (pair)
9034 (and (symbolp (car pair))
9035 (or (null regexp)
9036 (string-match regexp (symbol-name (car pair))))
9037 (set (make-local-variable (car pair))
9038 (cdr pair))))
9039 (buffer-local-variables from-buffer)))
9041 ;;;###autoload
9042 (defun org-run-like-in-org-mode (cmd)
9043 "Run a command, pretending that the current buffer is in Org-mode.
9044 This will temporarily bind local variables that are typically bound in
9045 Org-mode to the values they have in Org-mode, and then interactively
9046 call CMD."
9047 (org-load-modules-maybe)
9048 (unless org-local-vars
9049 (setq org-local-vars (org-get-local-variables)))
9050 (let (binds)
9051 (dolist (var org-local-vars)
9052 (when (or (not (boundp (car var)))
9053 (eq (symbol-value (car var))
9054 (default-value (car var))))
9055 (push (list (car var) `(quote ,(cadr var))) binds)))
9056 (eval `(let ,binds
9057 (call-interactively (quote ,cmd))))))
9059 ;;;; Archiving
9061 (defun org-get-category (&optional pos force-refresh)
9062 "Get the category applying to position POS."
9063 (save-match-data
9064 (if force-refresh (org-refresh-category-properties))
9065 (let ((pos (or pos (point))))
9066 (or (get-text-property pos 'org-category)
9067 (progn (org-refresh-category-properties)
9068 (get-text-property pos 'org-category))))))
9070 (defun org-refresh-category-properties ()
9071 "Refresh category text properties in the buffer."
9072 (let ((case-fold-search t)
9073 (inhibit-read-only t)
9074 (def-cat (cond
9075 ((null org-category)
9076 (if buffer-file-name
9077 (file-name-sans-extension
9078 (file-name-nondirectory buffer-file-name))
9079 "???"))
9080 ((symbolp org-category) (symbol-name org-category))
9081 (t org-category)))
9082 beg end cat pos optionp)
9083 (org-with-silent-modifications
9084 (save-excursion
9085 (save-restriction
9086 (widen)
9087 (goto-char (point-min))
9088 (put-text-property (point) (point-max) 'org-category def-cat)
9089 (while (re-search-forward
9090 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9091 (setq pos (match-end 0)
9092 optionp (equal (char-after (match-beginning 0)) ?#)
9093 cat (org-trim (match-string 2)))
9094 (if optionp
9095 (setq beg (point-at-bol) end (point-max))
9096 (org-back-to-heading t)
9097 (setq beg (point) end (org-end-of-subtree t t)))
9098 (put-text-property beg end 'org-category cat)
9099 (put-text-property beg end 'org-category-position beg)
9100 (goto-char pos)))))))
9102 (defun org-refresh-properties (dprop tprop)
9103 "Refresh buffer text properties.
9104 DPROP is the drawer property and TPROP is the corresponding text
9105 property to set."
9106 (let ((case-fold-search t)
9107 (inhibit-read-only t) p)
9108 (org-with-silent-modifications
9109 (save-excursion
9110 (save-restriction
9111 (widen)
9112 (goto-char (point-min))
9113 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9114 (setq p (org-match-string-no-properties 1))
9115 (save-excursion
9116 (org-back-to-heading t)
9117 (put-text-property
9118 (point-at-bol) (point-at-eol) tprop p))))))))
9121 ;;;; Link Stuff
9123 ;;; Link abbreviations
9125 (defun org-link-expand-abbrev (link)
9126 "Apply replacements as defined in `org-link-abbrev-alist'."
9127 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9128 (let* ((key (match-string 1 link))
9129 (as (or (assoc key org-link-abbrev-alist-local)
9130 (assoc key org-link-abbrev-alist)))
9131 (tag (and (match-end 2) (match-string 3 link)))
9132 rpl)
9133 (if (not as)
9134 link
9135 (setq rpl (cdr as))
9136 (cond
9137 ((symbolp rpl) (funcall rpl tag))
9138 ((string-match "%(\\([^)]+\\))" rpl)
9139 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9140 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9141 ((string-match "%h" rpl)
9142 (replace-match (url-hexify-string (or tag "")) t t rpl))
9143 (t (concat rpl tag)))))
9144 link))
9146 ;;; Storing and inserting links
9148 (defvar org-insert-link-history nil
9149 "Minibuffer history for links inserted with `org-insert-link'.")
9151 (defvar org-stored-links nil
9152 "Contains the links stored with `org-store-link'.")
9154 (defvar org-store-link-plist nil
9155 "Plist with info about the most recently link created with `org-store-link'.")
9157 (defvar org-link-protocols nil
9158 "Link protocols added to Org-mode using `org-add-link-type'.")
9160 (defvar org-store-link-functions nil
9161 "List of functions that are called to create and store a link.
9162 Each function will be called in turn until one returns a non-nil
9163 value. Each function should check if it is responsible for creating
9164 this link (for example by looking at the major mode).
9165 If not, it must exit and return nil.
9166 If yes, it should return a non-nil value after a calling
9167 `org-store-link-props' with a list of properties and values.
9168 Special properties are:
9170 :type The link prefix, like \"http\". This must be given.
9171 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9172 This is obligatory as well.
9173 :description Optional default description for the second pair
9174 of brackets in an Org-mode link. The user can still change
9175 this when inserting this link into an Org-mode buffer.
9177 In addition to these, any additional properties can be specified
9178 and then used in capture templates.")
9180 (defun org-add-link-type (type &optional follow export)
9181 "Add TYPE to the list of `org-link-types'.
9182 Re-compute all regular expressions depending on `org-link-types'
9184 FOLLOW and EXPORT are two functions.
9186 FOLLOW should take the link path as the single argument and do whatever
9187 is necessary to follow the link, for example find a file or display
9188 a mail message.
9190 EXPORT should format the link path for export to one of the export formats.
9191 It should be a function accepting three arguments:
9193 path the path of the link, the text after the prefix (like \"http:\")
9194 desc the description of the link, if any, or a description added by
9195 org-export-normalize-links if there is none
9196 format the export format, a symbol like `html' or `latex' or `ascii'..
9198 The function may use the FORMAT information to return different values
9199 depending on the format. The return value will be put literally into
9200 the exported file. If the return value is nil, this means Org should
9201 do what it normally does with links which do not have EXPORT defined.
9203 Org-mode has a built-in default for exporting links. If you are happy with
9204 this default, there is no need to define an export function for the link
9205 type. For a simple example of an export function, see `org-bbdb.el'."
9206 (add-to-list 'org-link-types type t)
9207 (org-make-link-regexps)
9208 (if (assoc type org-link-protocols)
9209 (setcdr (assoc type org-link-protocols) (list follow export))
9210 (push (list type follow export) org-link-protocols)))
9212 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9213 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9215 ;;;###autoload
9216 (defun org-store-link (arg &optional ignore-region)
9217 "\\<org-mode-map>Store an org-link to the current location.
9218 This link is added to `org-stored-links' and can later be inserted
9219 into an org-buffer with \\[org-insert-link].
9221 For some link types, a prefix arg is interpreted.
9222 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9223 For file links, arg negates `org-context-in-file-links'.
9225 A double prefix arg force skipping storing functions that are not
9226 part of Org's core.
9228 When the region is active and IGNORE-REGION is nil, store each line
9229 in the region as a separate link."
9230 (interactive "P")
9231 (org-load-modules-maybe)
9232 (setq org-store-link-plist nil) ; reset
9233 (if (and (org-region-active-p) (not ignore-region))
9234 (save-excursion
9235 (let ((beg (region-beginning)) (end (region-end)))
9236 (goto-char beg)
9237 (while (< (point-at-eol) end)
9238 (funcall 'org-store-link arg t)
9239 (move-beginning-of-line 2))))
9240 (org-with-limited-levels
9241 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9242 (cond
9243 ((and (not (equal arg '(16)))
9244 (setq sfuns
9245 (delq
9246 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9247 org-store-link-functions))
9248 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9249 (or (and (cdr sfuns)
9250 (funcall (intern
9251 (completing-read "Which function for creating the link? "
9252 sfunsn t (car sfunsn)))))
9253 (funcall (caar sfuns)))
9254 (setq link (plist-get org-store-link-plist :link)
9255 desc (or (plist-get org-store-link-plist :description) link))))
9256 ((org-src-edit-buffer-p)
9257 (let (label gc)
9258 (while (or (not label)
9259 (save-excursion
9260 (save-restriction
9261 (widen)
9262 (goto-char (point-min))
9263 (re-search-forward
9264 (regexp-quote (format org-coderef-label-format label))
9265 nil t))))
9266 (when label (message "Label exists already") (sit-for 2))
9267 (setq label (read-string "Code line label: " label)))
9268 (end-of-line 1)
9269 (setq link (format org-coderef-label-format label))
9270 (setq gc (- 79 (length link)))
9271 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9272 (insert link)
9273 (setq link (concat "(" label ")") desc nil)))
9275 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9276 ;; We are in the agenda, link to referenced location
9277 (let ((m (or (get-text-property (point) 'org-hd-marker)
9278 (get-text-property (point) 'org-marker))))
9279 (when m
9280 (org-with-point-at m
9281 (setq agenda-link
9282 (if (org-called-interactively-p 'any)
9283 (call-interactively 'org-store-link)
9284 (org-store-link nil)))))))
9286 ((eq major-mode 'calendar-mode)
9287 (let ((cd (calendar-cursor-to-date)))
9288 (setq link
9289 (format-time-string
9290 (car org-time-stamp-formats)
9291 (apply 'encode-time
9292 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9293 nil nil nil))))
9294 (org-store-link-props :type "calendar" :date cd)))
9296 ((eq major-mode 'help-mode)
9297 (setq link (concat "help:" (save-excursion
9298 (goto-char (point-min))
9299 (looking-at "^[^ ]+")
9300 (match-string 0))))
9301 (org-store-link-props :type "help"))
9303 ((eq major-mode 'w3-mode)
9304 (setq cpltxt (if (and (buffer-name)
9305 (not (string-match "Untitled" (buffer-name))))
9306 (buffer-name)
9307 (url-view-url t))
9308 link (url-view-url t))
9309 (org-store-link-props :type "w3" :url (url-view-url t)))
9311 ((setq search (run-hook-with-args-until-success
9312 'org-create-file-search-functions))
9313 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9314 "::" search))
9315 (setq cpltxt (or description link)))
9317 ((eq major-mode 'image-mode)
9318 (setq cpltxt (concat "file:"
9319 (abbreviate-file-name buffer-file-name))
9320 link cpltxt)
9321 (org-store-link-props :type "image" :file buffer-file-name))
9323 ((eq major-mode 'dired-mode)
9324 ;; link to the file in the current line
9325 (let ((file (dired-get-filename nil t)))
9326 (setq file (if file
9327 (abbreviate-file-name
9328 (expand-file-name (dired-get-filename nil t)))
9329 ;; otherwise, no file so use current directory.
9330 default-directory))
9331 (setq cpltxt (concat "file:" file)
9332 link cpltxt)))
9334 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9335 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9336 (cond
9337 ((org-in-regexp "<<\\(.*?\\)>>")
9338 (setq cpltxt
9339 (concat "file:"
9340 (abbreviate-file-name
9341 (buffer-file-name (buffer-base-buffer)))
9342 "::" (match-string 1))
9343 link cpltxt))
9344 ((and (featurep 'org-id)
9345 (or (eq org-id-link-to-org-use-id t)
9346 (and (org-called-interactively-p 'any)
9347 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9348 (and (eq org-id-link-to-org-use-id
9349 'create-if-interactive-and-no-custom-id)
9350 (not custom-id))))
9351 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9352 ;; We can make a link using the ID.
9353 (setq link (condition-case nil
9354 (prog1 (org-id-store-link)
9355 (setq desc (plist-get org-store-link-plist :description)))
9356 (error
9357 ;; probably before first headline, link to file only
9358 (concat "file:"
9359 (abbreviate-file-name
9360 (buffer-file-name (buffer-base-buffer))))))))
9362 ;; Just link to current headline
9363 (setq cpltxt (concat "file:"
9364 (abbreviate-file-name
9365 (buffer-file-name (buffer-base-buffer)))))
9366 ;; Add a context search string
9367 (when (org-xor org-context-in-file-links arg)
9368 (let* ((ee (org-element-at-point))
9369 (et (org-element-type ee))
9370 (ev (plist-get (cadr ee) :value)))
9371 (setq txt (cond
9372 ((org-at-heading-p) nil)
9373 ((eq et 'keyword) ev)
9374 ((org-region-active-p)
9375 (buffer-substring (region-beginning) (region-end)))))
9376 (when (or (null txt) (string-match "\\S-" txt))
9377 (setq cpltxt
9378 (concat cpltxt "::"
9379 (condition-case nil
9380 (org-make-org-heading-search-string txt)
9381 (error "")))
9382 desc (or (and (eq et 'keyword) ev)
9383 (nth 4 (ignore-errors (org-heading-components)))
9384 "NONE")))))
9385 (if (string-match "::\\'" cpltxt)
9386 (setq cpltxt (substring cpltxt 0 -2)))
9387 (setq link cpltxt))))
9389 ((buffer-file-name (buffer-base-buffer))
9390 ;; Just link to this file here.
9391 (setq cpltxt (concat "file:"
9392 (abbreviate-file-name
9393 (buffer-file-name (buffer-base-buffer)))))
9394 ;; Add a context string
9395 (when (org-xor org-context-in-file-links arg)
9396 (setq txt (if (org-region-active-p)
9397 (buffer-substring (region-beginning) (region-end))
9398 (buffer-substring (point-at-bol) (point-at-eol))))
9399 ;; Only use search option if there is some text.
9400 (when (string-match "\\S-" txt)
9401 (setq cpltxt
9402 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9403 desc "NONE")))
9404 (setq link cpltxt))
9406 ((org-called-interactively-p 'interactive)
9407 (user-error "No method for storing a link from this buffer"))
9409 (t (setq link nil)))
9411 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9412 (setq link (or link cpltxt)
9413 desc (or desc cpltxt))
9414 (cond ((equal desc "NONE") (setq desc nil))
9415 ((string-match org-bracket-link-regexp desc)
9416 (setq desc (replace-regexp-in-string
9417 org-bracket-link-regexp
9418 (concat "\\3" (if (equal (length (match-string 0 desc))
9419 (length desc)) "*" "")) desc))))
9421 (if (and (or (org-called-interactively-p 'any)
9422 executing-kbd-macro ignore-region) link)
9423 (progn
9424 (setq org-stored-links
9425 (cons (list link desc) org-stored-links))
9426 (message "Stored: %s" (or desc link))
9427 (when custom-id
9428 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9429 "::#" custom-id))
9430 (setq org-stored-links
9431 (cons (list link desc) org-stored-links))))
9432 (or agenda-link (and link (org-make-link-string link desc))))))))
9434 (defun org-store-link-props (&rest plist)
9435 "Store link properties, extract names and addresses."
9436 (let (x adr)
9437 (when (setq x (plist-get plist :from))
9438 (setq adr (mail-extract-address-components x))
9439 (setq plist (plist-put plist :fromname (car adr)))
9440 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9441 (when (setq x (plist-get plist :to))
9442 (setq adr (mail-extract-address-components x))
9443 (setq plist (plist-put plist :toname (car adr)))
9444 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9445 (let ((from (plist-get plist :from))
9446 (to (plist-get plist :to)))
9447 (when (and from to org-from-is-user-regexp)
9448 (setq plist
9449 (plist-put plist :fromto
9450 (if (string-match org-from-is-user-regexp from)
9451 (concat "to %t")
9452 (concat "from %f"))))))
9453 (setq org-store-link-plist plist))
9455 (defun org-add-link-props (&rest plist)
9456 "Add these properties to the link property list."
9457 (let (key value)
9458 (while plist
9459 (setq key (pop plist) value (pop plist))
9460 (setq org-store-link-plist
9461 (plist-put org-store-link-plist key value)))))
9463 (defun org-email-link-description (&optional fmt)
9464 "Return the description part of an email link.
9465 This takes information from `org-store-link-plist' and formats it
9466 according to FMT (default from `org-email-link-description-format')."
9467 (setq fmt (or fmt org-email-link-description-format))
9468 (let* ((p org-store-link-plist)
9469 (to (plist-get p :toaddress))
9470 (from (plist-get p :fromaddress))
9471 (table
9472 (list
9473 (cons "%c" (plist-get p :fromto))
9474 (cons "%F" (plist-get p :from))
9475 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9476 (cons "%T" (plist-get p :to))
9477 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9478 (cons "%s" (plist-get p :subject))
9479 (cons "%d" (plist-get p :date))
9480 (cons "%m" (plist-get p :message-id)))))
9481 (when (string-match "%c" fmt)
9482 ;; Check if the user wrote this message
9483 (if (and org-from-is-user-regexp from to
9484 (save-match-data (string-match org-from-is-user-regexp from)))
9485 (setq fmt (replace-match "to %t" t t fmt))
9486 (setq fmt (replace-match "from %f" t t fmt))))
9487 (org-replace-escapes fmt table)))
9489 (defun org-make-org-heading-search-string (&optional string)
9490 "Make search string for the current headline or STRING."
9491 (let ((s (or string
9492 (and (derived-mode-p 'org-mode)
9493 (save-excursion
9494 (org-back-to-heading t)
9495 (org-element-property :raw-value (org-element-at-point))))))
9496 (lines org-context-in-file-links))
9497 (or string (setq s (concat "*" s))) ; Add * for headlines
9498 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9499 (when (and string (integerp lines) (> lines 0))
9500 (let ((slines (org-split-string s "\n")))
9501 (when (< lines (length slines))
9502 (setq s (mapconcat
9503 'identity
9504 (reverse (nthcdr (- (length slines) lines)
9505 (reverse slines))) "\n")))))
9506 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9508 (defun org-make-link-string (link &optional description)
9509 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9510 (unless (string-match "\\S-" link)
9511 (error "Empty link"))
9512 (when (and description
9513 (stringp description)
9514 (not (string-match "\\S-" description)))
9515 (setq description nil))
9516 (when (stringp description)
9517 ;; Remove brackets from the description, they are fatal.
9518 (while (string-match "\\[" description)
9519 (setq description (replace-match "{" t t description)))
9520 (while (string-match "\\]" description)
9521 (setq description (replace-match "}" t t description))))
9522 (when (equal link description)
9523 ;; No description needed, it is identical
9524 (setq description nil))
9525 (when (and (not description)
9526 (not (string-match (org-image-file-name-regexp) link))
9527 (not (equal link (org-link-escape link))))
9528 (setq description (org-extract-attributes link)))
9529 (setq link
9530 (cond ((string-match (org-image-file-name-regexp) link) link)
9531 ((string-match org-link-types-re link)
9532 (concat (match-string 1 link)
9533 (org-link-escape (substring link (match-end 1)))))
9534 (t (org-link-escape link))))
9535 (concat "[[" link "]"
9536 (if description (concat "[" description "]") "")
9537 "]"))
9539 (defconst org-link-escape-chars
9540 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9541 "List of characters that should be escaped in link.
9542 This is the list that is used for internal purposes.")
9544 (defconst org-link-escape-chars-browser
9545 '(?\ )
9546 "List of escapes for characters that are problematic in links.
9547 This is the list that is used before handing over to the browser.")
9549 (defun org-link-escape (text &optional table merge)
9550 "Return percent escaped representation of TEXT.
9551 TEXT is a string with the text to escape.
9552 Optional argument TABLE is a list with characters that should be
9553 escaped. When nil, `org-link-escape-chars' is used.
9554 If optional argument MERGE is set, merge TABLE into
9555 `org-link-escape-chars'."
9556 (cond
9557 ((and table merge)
9558 (mapc (lambda (defchr)
9559 (unless (member defchr table)
9560 (setq table (cons defchr table)))) org-link-escape-chars))
9561 ((null table)
9562 (setq table org-link-escape-chars)))
9563 (mapconcat
9564 (lambda (char)
9565 (if (or (member char table)
9566 (and (or (< char 32) (= char 37) (> char 126))
9567 org-url-hexify-p))
9568 (mapconcat (lambda (sequence-element)
9569 (format "%%%.2X" sequence-element))
9570 (or (encode-coding-char char 'utf-8)
9571 (error "Unable to percent escape character: %s"
9572 (char-to-string char))) "")
9573 (char-to-string char))) text ""))
9575 (defun org-link-unescape (str)
9576 "Unhex hexified Unicode strings as returned from the JavaScript function
9577 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9578 (unless (and (null str) (string= "" str))
9579 (let ((pos 0) (case-fold-search t) unhexed)
9580 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9581 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9582 (setq str (replace-match unhexed t t str))
9583 (setq pos (+ pos (length unhexed))))))
9584 str)
9586 (defun org-link-unescape-compound (hex)
9587 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9588 Note: this function also decodes single byte encodings like
9589 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9590 (save-match-data
9591 (let* ((bytes (cdr (split-string hex "%")))
9592 (ret "")
9593 (eat 0)
9594 (sum 0))
9595 (while bytes
9596 (let* ((val (string-to-number (pop bytes) 16))
9597 (shift-xor
9598 (if (= 0 eat)
9599 (cond
9600 ((>= val 252) (cons 6 252))
9601 ((>= val 248) (cons 5 248))
9602 ((>= val 240) (cons 4 240))
9603 ((>= val 224) (cons 3 224))
9604 ((>= val 192) (cons 2 192))
9605 (t (cons 0 0)))
9606 (cons 6 128))))
9607 (if (>= val 192) (setq eat (car shift-xor)))
9608 (setq val (logxor val (cdr shift-xor)))
9609 (setq sum (+ (lsh sum (car shift-xor)) val))
9610 (if (> eat 0) (setq eat (- eat 1)))
9611 (cond
9612 ((= 0 eat) ;multi byte
9613 (setq ret (concat ret (org-char-to-string sum)))
9614 (setq sum 0))
9615 ((not bytes) ; single byte(s)
9616 (setq ret (org-link-unescape-single-byte-sequence hex))))
9617 )) ;; end (while bytes
9618 ret )))
9620 (defun org-link-unescape-single-byte-sequence (hex)
9621 "Unhexify hex-encoded single byte character sequences."
9622 (mapconcat (lambda (byte)
9623 (char-to-string (string-to-number byte 16)))
9624 (cdr (split-string hex "%")) ""))
9626 (defun org-xor (a b)
9627 "Exclusive or."
9628 (if a (not b) b))
9630 (defun org-fixup-message-id-for-http (s)
9631 "Replace special characters in a message id, so it can be used in an http query."
9632 (when (string-match "%" s)
9633 (setq s (mapconcat (lambda (c)
9634 (if (eq c ?%)
9635 "%25"
9636 (char-to-string c)))
9637 s "")))
9638 (while (string-match "<" s)
9639 (setq s (replace-match "%3C" t t s)))
9640 (while (string-match ">" s)
9641 (setq s (replace-match "%3E" t t s)))
9642 (while (string-match "@" s)
9643 (setq s (replace-match "%40" t t s)))
9646 (defun org-link-prettify (link)
9647 "Return a human-readable representation of LINK.
9648 The car of LINK must be a raw link the cdr of LINK must be either
9649 a link description or nil."
9650 (let ((desc (or (cadr link) "<no description>")))
9651 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9652 "<" (car link) ">")))
9654 ;;;###autoload
9655 (defun org-insert-link-global ()
9656 "Insert a link like Org-mode does.
9657 This command can be called in any mode to insert a link in Org-mode syntax."
9658 (interactive)
9659 (org-load-modules-maybe)
9660 (org-run-like-in-org-mode 'org-insert-link))
9662 (defun org-insert-all-links (&optional keep)
9663 "Insert all links in `org-stored-links'."
9664 (interactive "P")
9665 (let ((links (copy-sequence org-stored-links)) l)
9666 (while (setq l (if keep (pop links) (pop org-stored-links)))
9667 (insert "- ")
9668 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9669 (insert "\n"))))
9671 (defun org-link-fontify-links-to-this-file ()
9672 "Fontify links to the current file in `org-stored-links'."
9673 (let ((f (buffer-file-name)) a b)
9674 (setq a (mapcar (lambda(l)
9675 (let ((ll (car l)))
9676 (when (and (string-match "^file:\\(.+\\)::" ll)
9677 (equal f (expand-file-name (match-string 1 ll))))
9678 ll)))
9679 org-stored-links))
9680 (when (featurep 'org-id)
9681 (setq b (mapcar (lambda(l)
9682 (let ((ll (car l)))
9683 (when (and (string-match "^id:\\(.+\\)$" ll)
9684 (equal f (expand-file-name
9685 (or (org-id-find-id-file
9686 (match-string 1 ll)) ""))))
9687 ll)))
9688 org-stored-links)))
9689 (mapcar (lambda(l)
9690 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9691 (delq nil (append a b)))))
9693 (defvar org-link-links-in-this-file nil)
9694 (defun org-insert-link (&optional complete-file link-location default-description)
9695 "Insert a link. At the prompt, enter the link.
9697 Completion can be used to insert any of the link protocol prefixes like
9698 http or ftp in use.
9700 The history can be used to select a link previously stored with
9701 `org-store-link'. When the empty string is entered (i.e. if you just
9702 press RET at the prompt), the link defaults to the most recently
9703 stored link. As SPC triggers completion in the minibuffer, you need to
9704 use M-SPC or C-q SPC to force the insertion of a space character.
9706 You will also be prompted for a description, and if one is given, it will
9707 be displayed in the buffer instead of the link.
9709 If there is already a link at point, this command will allow you to edit link
9710 and description parts.
9712 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9713 be selected using completion. The path to the file will be relative to the
9714 current directory if the file is in the current directory or a subdirectory.
9715 Otherwise, the link will be the absolute path as completed in the minibuffer
9716 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9717 option `org-link-file-path-type'.
9719 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9720 the current directory or below.
9722 With three \\[universal-argument] prefixes, negate the meaning of
9723 `org-keep-stored-link-after-insertion'.
9725 If `org-make-link-description-function' is non-nil, this function will be
9726 called with the link target, and the result will be the default
9727 link description.
9729 If the LINK-LOCATION parameter is non-nil, this value will be
9730 used as the link location instead of reading one interactively.
9732 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9733 be used as the default description."
9734 (interactive "P")
9735 (let* ((wcf (current-window-configuration))
9736 (origbuf (current-buffer))
9737 (region (if (org-region-active-p)
9738 (buffer-substring (region-beginning) (region-end))))
9739 (remove (and region (list (region-beginning) (region-end))))
9740 (desc region)
9741 tmphist ; byte-compile incorrectly complains about this
9742 (link link-location)
9743 (abbrevs org-link-abbrev-alist-local)
9744 entry file all-prefixes auto-desc)
9745 (cond
9746 (link-location) ; specified by arg, just use it.
9747 ((org-in-regexp org-bracket-link-regexp 1)
9748 ;; We do have a link at point, and we are going to edit it.
9749 (setq remove (list (match-beginning 0) (match-end 0)))
9750 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9751 (setq link (read-string "Link: "
9752 (org-link-unescape
9753 (org-match-string-no-properties 1)))))
9754 ((or (org-in-regexp org-angle-link-re)
9755 (org-in-regexp org-plain-link-re))
9756 ;; Convert to bracket link
9757 (setq remove (list (match-beginning 0) (match-end 0))
9758 link (read-string "Link: "
9759 (org-remove-angle-brackets (match-string 0)))))
9760 ((member complete-file '((4) (16)))
9761 ;; Completing read for file names.
9762 (setq link (org-file-complete-link complete-file)))
9764 ;; Read link, with completion for stored links.
9765 (org-link-fontify-links-to-this-file)
9766 (org-switch-to-buffer-other-window "*Org Links*")
9767 (with-current-buffer "*Org Links*"
9768 (erase-buffer)
9769 (insert "Insert a link.
9770 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9771 (when org-stored-links
9772 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9773 (insert (mapconcat 'org-link-prettify
9774 (reverse org-stored-links) "\n")))
9775 (goto-char (point-min)))
9776 (let ((cw (selected-window)))
9777 (select-window (get-buffer-window "*Org Links*" 'visible))
9778 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9779 (unless (pos-visible-in-window-p (point-max))
9780 (org-fit-window-to-buffer))
9781 (and (window-live-p cw) (select-window cw)))
9782 ;; Fake a link history, containing the stored links.
9783 (setq tmphist (append (mapcar 'car org-stored-links)
9784 org-insert-link-history))
9785 (setq all-prefixes (append (mapcar 'car abbrevs)
9786 (mapcar 'car org-link-abbrev-alist)
9787 org-link-types))
9788 (unwind-protect
9789 (progn
9790 (setq link
9791 (org-completing-read
9792 "Link: "
9793 (append
9794 (mapcar (lambda (x) (concat x ":"))
9795 all-prefixes)
9796 (mapcar 'car org-stored-links))
9797 nil nil nil
9798 'tmphist
9799 (caar org-stored-links)))
9800 (if (not (string-match "\\S-" link))
9801 (error "No link selected"))
9802 (mapc (lambda(l)
9803 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9804 org-stored-links)
9805 (if (or (member link all-prefixes)
9806 (and (equal ":" (substring link -1))
9807 (member (substring link 0 -1) all-prefixes)
9808 (setq link (substring link 0 -1))))
9809 (setq link (with-current-buffer origbuf
9810 (org-link-try-special-completion link)))))
9811 (set-window-configuration wcf)
9812 (kill-buffer "*Org Links*"))
9813 (setq entry (assoc link org-stored-links))
9814 (or entry (push link org-insert-link-history))
9815 (setq desc (or desc (nth 1 entry)))))
9817 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9818 (not org-keep-stored-link-after-insertion))
9819 (setq org-stored-links (delq (assoc link org-stored-links)
9820 org-stored-links)))
9822 (if (string-match org-plain-link-re link)
9823 ;; URL-like link, normalize the use of angular brackets.
9824 (setq link (org-remove-angle-brackets link)))
9826 ;; Check if we are linking to the current file with a search
9827 ;; option If yes, simplify the link by using only the search
9828 ;; option.
9829 (when (and buffer-file-name
9830 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9831 (let* ((path (match-string 1 link))
9832 (case-fold-search nil)
9833 (search (match-string 2 link)))
9834 (save-match-data
9835 (if (equal (file-truename buffer-file-name) (file-truename path))
9836 ;; We are linking to this same file, with a search option
9837 (setq link search)))))
9839 ;; Check if we can/should use a relative path. If yes, simplify the link
9840 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9841 (let* ((type (match-string 1 link))
9842 (path (match-string 2 link))
9843 (origpath path)
9844 (case-fold-search nil))
9845 (cond
9846 ((or (eq org-link-file-path-type 'absolute)
9847 (equal complete-file '(16)))
9848 (setq path (abbreviate-file-name (expand-file-name path))))
9849 ((eq org-link-file-path-type 'noabbrev)
9850 (setq path (expand-file-name path)))
9851 ((eq org-link-file-path-type 'relative)
9852 (setq path (file-relative-name path)))
9854 (save-match-data
9855 (if (string-match (concat "^" (regexp-quote
9856 (expand-file-name
9857 (file-name-as-directory
9858 default-directory))))
9859 (expand-file-name path))
9860 ;; We are linking a file with relative path name.
9861 (setq path (substring (expand-file-name path)
9862 (match-end 0)))
9863 (setq path (abbreviate-file-name (expand-file-name path)))))))
9864 (setq link (concat type path))
9865 (if (equal desc origpath)
9866 (setq desc path))))
9868 (if org-make-link-description-function
9869 (setq desc
9870 (or (condition-case nil
9871 (funcall org-make-link-description-function link desc)
9872 (error (progn (message "Can't get link description from `%s'"
9873 (symbol-name org-make-link-description-function))
9874 (sit-for 2) nil)))
9875 (read-string "Description: " default-description)))
9876 (if default-description (setq desc default-description)
9877 (setq desc (or (and auto-desc desc)
9878 (read-string "Description: " desc)))))
9880 (unless (string-match "\\S-" desc) (setq desc nil))
9881 (if remove (apply 'delete-region remove))
9882 (insert (org-make-link-string link desc))))
9884 (defun org-link-try-special-completion (type)
9885 "If there is completion support for link type TYPE, offer it."
9886 (let ((fun (intern (concat "org-" type "-complete-link"))))
9887 (if (functionp fun)
9888 (funcall fun)
9889 (read-string "Link (no completion support): " (concat type ":")))))
9891 (defun org-file-complete-link (&optional arg)
9892 "Create a file link using completion."
9893 (let (file link)
9894 (setq file (org-iread-file-name "File: "))
9895 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9896 (pwd1 (file-name-as-directory (abbreviate-file-name
9897 (expand-file-name ".")))))
9898 (cond
9899 ((equal arg '(16))
9900 (setq link (concat
9901 "file:"
9902 (abbreviate-file-name (expand-file-name file)))))
9903 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9904 (setq link (concat "file:" (match-string 1 file))))
9905 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9906 (expand-file-name file))
9907 (setq link (concat
9908 "file:" (match-string 1 (expand-file-name file)))))
9909 (t (setq link (concat "file:" file)))))
9910 link))
9912 (defun org-iread-file-name (&rest args)
9913 "Read-file-name using `ido-mode' speedup if available.
9914 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9915 See `read-file-name' for a description of parameters."
9916 (org-without-partial-completion
9917 (if (and org-completion-use-ido
9918 (fboundp 'ido-read-file-name)
9919 (boundp 'ido-mode) ido-mode
9920 (listp (second args)))
9921 (let ((ido-enter-matching-directory nil))
9922 (apply 'ido-read-file-name args))
9923 (apply 'read-file-name args))))
9925 (defun org-completing-read (&rest args)
9926 "Completing-read with SPACE being a normal character."
9927 (let ((enable-recursive-minibuffers t)
9928 (minibuffer-local-completion-map
9929 (copy-keymap minibuffer-local-completion-map)))
9930 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9931 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9932 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9933 (apply 'org-icompleting-read args)))
9935 (defun org-completing-read-no-i (&rest args)
9936 (let (org-completion-use-ido org-completion-use-iswitchb)
9937 (apply 'org-completing-read args)))
9939 (defun org-iswitchb-completing-read (prompt choices &rest args)
9940 "Use iswitch as a completing-read replacement to choose from choices.
9941 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9942 from."
9943 (let* ((iswitchb-use-virtual-buffers nil)
9944 (iswitchb-make-buflist-hook
9945 (lambda ()
9946 (setq iswitchb-temp-buflist choices))))
9947 (iswitchb-read-buffer prompt)))
9949 (defun org-icompleting-read (&rest args)
9950 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9951 (org-without-partial-completion
9952 (if (and org-completion-use-ido
9953 (fboundp 'ido-completing-read)
9954 (boundp 'ido-mode) ido-mode
9955 (listp (second args)))
9956 (let ((ido-enter-matching-directory nil))
9957 (apply 'ido-completing-read (concat (car args))
9958 (if (consp (car (nth 1 args)))
9959 (mapcar 'car (nth 1 args))
9960 (nth 1 args))
9961 (cddr args)))
9962 (if (and org-completion-use-iswitchb
9963 (boundp 'iswitchb-mode) iswitchb-mode
9964 (listp (second args)))
9965 (apply 'org-iswitchb-completing-read (concat (car args))
9966 (if (consp (car (nth 1 args)))
9967 (mapcar 'car (nth 1 args))
9968 (nth 1 args))
9969 (cddr args))
9970 (apply 'completing-read args)))))
9972 (defun org-extract-attributes (s)
9973 "Extract the attributes cookie from a string and set as text property."
9974 (let (a attr (start 0) key value)
9975 (save-match-data
9976 (when (string-match "{{\\([^}]+\\)}}$" s)
9977 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9978 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9979 (setq key (match-string 1 a) value (match-string 2 a)
9980 start (match-end 0)
9981 attr (plist-put attr (intern key) value))))
9982 (org-add-props s nil 'org-attr attr))
9985 (defun org-extract-attributes-from-string (tag)
9986 (let (key value attr)
9987 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9988 (setq key (match-string 1 tag) value (match-string 2 tag)
9989 tag (replace-match "" t t tag)
9990 attr (plist-put attr (intern key) value)))
9991 (cons tag attr)))
9993 (defun org-attributes-to-string (plist)
9994 "Format a property list into an HTML attribute list."
9995 (let ((s "") key value)
9996 (while plist
9997 (setq key (pop plist) value (pop plist))
9998 (and value
9999 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10002 ;;; Opening/following a link
10004 (defvar org-link-search-failed nil)
10006 (defvar org-open-link-functions nil
10007 "Hook for functions finding a plain text link.
10008 These functions must take a single argument, the link content.
10009 They will be called for links that look like [[link text][description]]
10010 when LINK TEXT does not have a protocol like \"http:\" and does not look
10011 like a filename (e.g. \"./blue.png\").
10013 These functions will be called *before* Org attempts to resolve the
10014 link by doing text searches in the current buffer - so if you want a
10015 link \"[[target]]\" to still find \"<<target>>\", your function should
10016 handle this as a special case.
10018 When the function does handle the link, it must return a non-nil value.
10019 If it decides that it is not responsible for this link, it must return
10020 nil to indicate that that Org-mode can continue with other options
10021 like exact and fuzzy text search.")
10023 (defun org-next-link (&optional search-backward)
10024 "Move forward to the next link.
10025 If the link is in hidden text, expose it."
10026 (interactive "P")
10027 (when (and org-link-search-failed (eq this-command last-command))
10028 (goto-char (point-min))
10029 (message "Link search wrapped back to beginning of buffer"))
10030 (setq org-link-search-failed nil)
10031 (let* ((pos (point))
10032 (ct (org-context))
10033 (a (assoc :link ct))
10034 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10035 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10036 ((looking-at org-any-link-re)
10037 ;; Don't stay stuck at link without an org-link face
10038 (forward-char (if search-backward -1 1))))
10039 (if (funcall srch-fun org-any-link-re nil t)
10040 (progn
10041 (goto-char (match-beginning 0))
10042 (if (outline-invisible-p) (org-show-context)))
10043 (goto-char pos)
10044 (setq org-link-search-failed t)
10045 (message "No further link found"))))
10047 (defun org-previous-link ()
10048 "Move backward to the previous link.
10049 If the link is in hidden text, expose it."
10050 (interactive)
10051 (funcall 'org-next-link t))
10053 (defun org-translate-link (s)
10054 "Translate a link string if a translation function has been defined."
10055 (if (and org-link-translation-function
10056 (fboundp org-link-translation-function)
10057 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10058 (progn
10059 (setq s (funcall org-link-translation-function
10060 (match-string 1 s) (match-string 2 s)))
10061 (concat (car s) ":" (cdr s)))
10064 (defun org-translate-link-from-planner (type path)
10065 "Translate a link from Emacs Planner syntax so that Org can follow it.
10066 This is still an experimental function, your mileage may vary."
10067 (cond
10068 ((member type '("http" "https" "news" "ftp"))
10069 ;; standard Internet links are the same.
10070 nil)
10071 ((and (equal type "irc") (string-match "^//" path))
10072 ;; Planner has two / at the beginning of an irc link, we have 1.
10073 ;; We should have zero, actually....
10074 (setq path (substring path 1)))
10075 ((and (equal type "lisp") (string-match "^/" path))
10076 ;; Planner has a slash, we do not.
10077 (setq type "elisp" path (substring path 1)))
10078 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10079 ;; A typical message link. Planner has the id after the final slash,
10080 ;; we separate it with a hash mark
10081 (setq path (concat (match-string 1 path) "#"
10082 (org-remove-angle-brackets (match-string 2 path)))))
10084 (cons type path))
10086 (defun org-find-file-at-mouse (ev)
10087 "Open file link or URL at mouse."
10088 (interactive "e")
10089 (mouse-set-point ev)
10090 (org-open-at-point 'in-emacs))
10092 (defun org-open-at-mouse (ev)
10093 "Open file link or URL at mouse.
10094 See the docstring of `org-open-file' for details."
10095 (interactive "e")
10096 (mouse-set-point ev)
10097 (if (eq major-mode 'org-agenda-mode)
10098 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10099 (org-open-at-point))
10101 (defvar org-window-config-before-follow-link nil
10102 "The window configuration before following a link.
10103 This is saved in case the need arises to restore it.")
10105 (defvar org-open-link-marker (make-marker)
10106 "Marker pointing to the location where `org-open-at-point; was called.")
10108 ;;;###autoload
10109 (defun org-open-at-point-global ()
10110 "Follow a link like Org-mode does.
10111 This command can be called in any mode to follow a link that has
10112 Org-mode syntax."
10113 (interactive)
10114 (org-run-like-in-org-mode 'org-open-at-point))
10116 ;;;###autoload
10117 (defun org-open-link-from-string (s &optional arg reference-buffer)
10118 "Open a link in the string S, as if it was in Org-mode."
10119 (interactive "sLink: \nP")
10120 (let ((reference-buffer (or reference-buffer (current-buffer))))
10121 (with-temp-buffer
10122 (let ((org-inhibit-startup (not reference-buffer)))
10123 (org-mode)
10124 (insert s)
10125 (goto-char (point-min))
10126 (when reference-buffer
10127 (setq org-link-abbrev-alist-local
10128 (with-current-buffer reference-buffer
10129 org-link-abbrev-alist-local)))
10130 (org-open-at-point arg reference-buffer)))))
10132 (defvar org-open-at-point-functions nil
10133 "Hook that is run when following a link at point.
10135 Functions in this hook must return t if they identify and follow
10136 a link at point. If they don't find anything interesting at point,
10137 they must return nil.")
10139 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10140 (defun org-open-at-point (&optional arg reference-buffer)
10141 "Open link at or after point.
10142 If there is no link at point, this function will search forward up to
10143 the end of the current line.
10144 Normally, files will be opened by an appropriate application. If the
10145 optional prefix argument ARG is non-nil, Emacs will visit the file.
10146 With a double prefix argument, try to open outside of Emacs, in the
10147 application the system uses for this file type."
10148 (interactive "P")
10149 ;; if in a code block, then open the block's results
10150 (unless (call-interactively #'org-babel-open-src-block-result)
10151 (org-load-modules-maybe)
10152 (move-marker org-open-link-marker (point))
10153 (setq org-window-config-before-follow-link (current-window-configuration))
10154 (org-remove-occur-highlights nil nil t)
10155 (cond
10156 ((and (org-at-heading-p)
10157 (not (org-at-timestamp-p t))
10158 (not (org-in-regexp
10159 (concat org-plain-link-re "\\|"
10160 org-bracket-link-regexp "\\|"
10161 org-angle-link-re "\\|"
10162 "[ \t]:[^ \t\n]+:[ \t]*$")))
10163 (not (get-text-property (point) 'org-linked-text)))
10164 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10165 (lk0 (car lkall))
10166 (lk (if (stringp lk0) (list lk0) lk0))
10167 (lkend (cdr lkall)))
10168 (mapcar (lambda(l)
10169 (search-forward l nil lkend)
10170 (goto-char (match-beginning 0))
10171 (org-open-at-point))
10172 lk))
10173 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10174 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10175 ((and (org-at-timestamp-p t)
10176 (not (org-in-regexp org-bracket-link-regexp)))
10177 (org-follow-timestamp-link))
10178 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10179 (not (org-in-regexp org-any-link-re)))
10180 (org-footnote-action))
10182 (let (type path link line search (pos (point)))
10183 (catch 'match
10184 (save-excursion
10185 (skip-chars-forward "^]\n\r")
10186 (when (org-in-regexp org-bracket-link-regexp 1)
10187 (setq link (org-extract-attributes
10188 (org-link-unescape (org-match-string-no-properties 1))))
10189 (while (string-match " *\n *" link)
10190 (setq link (replace-match " " t t link)))
10191 (setq link (org-link-expand-abbrev link))
10192 (cond
10193 ((or (file-name-absolute-p link)
10194 (string-match "^\\.\\.?/" link))
10195 (setq type "file" path link))
10196 ((string-match org-link-re-with-space3 link)
10197 (setq type (match-string 1 link) path (match-string 2 link)))
10198 ((string-match "^help:+\\(.+\\)" link)
10199 (setq type "help" path (match-string 1 link)))
10200 (t (setq type "thisfile" path link)))
10201 (throw 'match t)))
10203 (when (get-text-property (point) 'org-linked-text)
10204 (setq type "thisfile"
10205 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10206 (1+ (point)) (point))
10207 path (buffer-substring
10208 (or (previous-single-property-change pos 'org-linked-text)
10209 (point-min))
10210 (or (next-single-property-change pos 'org-linked-text)
10211 (point-max))))
10212 (throw 'match t))
10214 (save-excursion
10215 (when (or (org-in-regexp org-angle-link-re)
10216 (let ((match (org-in-regexp org-plain-link-re)))
10217 ;; Check a plain link is not within a bracket link
10218 (and match
10219 (save-excursion
10220 (progn
10221 (goto-char (car match))
10222 (not (org-in-regexp org-bracket-link-regexp))))))
10223 (let ((line_ending (save-excursion (end-of-line) (point))))
10224 ;; We are in a line before a plain or bracket link
10225 (or (re-search-forward org-plain-link-re line_ending t)
10226 (re-search-forward org-bracket-link-regexp line_ending t))))
10227 (setq type (match-string 1)
10228 path (org-link-unescape (match-string 2)))
10229 (throw 'match t)))
10230 (save-excursion
10231 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10232 (setq type "tags"
10233 path (match-string 1))
10234 (while (string-match ":" path)
10235 (setq path (replace-match "+" t t path)))
10236 (throw 'match t)))
10237 (when (org-in-regexp "<\\([^><\n]+\\)>")
10238 (setq type "tree-match"
10239 path (match-string 1))
10240 (throw 'match t)))
10241 (unless path
10242 (user-error "No link found"))
10244 ;; switch back to reference buffer
10245 ;; needed when if called in a temporary buffer through
10246 ;; org-open-link-from-string
10247 (with-current-buffer (or reference-buffer (current-buffer))
10249 ;; Remove any trailing spaces in path
10250 (if (string-match " +\\'" path)
10251 (setq path (replace-match "" t t path)))
10252 (if (and org-link-translation-function
10253 (fboundp org-link-translation-function))
10254 ;; Check if we need to translate the link
10255 (let ((tmp (funcall org-link-translation-function type path)))
10256 (setq type (car tmp) path (cdr tmp))))
10258 (cond
10260 ((assoc type org-link-protocols)
10261 (funcall (nth 1 (assoc type org-link-protocols)) path))
10263 ((equal type "help")
10264 (let ((f-or-v (intern path)))
10265 (cond ((fboundp f-or-v)
10266 (describe-function f-or-v))
10267 ((boundp f-or-v)
10268 (describe-variable f-or-v))
10269 (t (error "Not a known function or variable")))))
10271 ((equal type "mailto")
10272 (let ((cmd (car org-link-mailto-program))
10273 (args (cdr org-link-mailto-program)) args1
10274 (address path) (subject "") a)
10275 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10276 (setq address (match-string 1 path)
10277 subject (org-link-escape (match-string 2 path))))
10278 (while args
10279 (cond
10280 ((not (stringp (car args))) (push (pop args) args1))
10281 (t (setq a (pop args))
10282 (if (string-match "%a" a)
10283 (setq a (replace-match address t t a)))
10284 (if (string-match "%s" a)
10285 (setq a (replace-match subject t t a)))
10286 (push a args1))))
10287 (apply cmd (nreverse args1))))
10289 ((member type '("http" "https" "ftp" "news"))
10290 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10291 (org-link-escape
10292 path org-link-escape-chars-browser)
10293 path))))
10295 ((string= type "doi")
10296 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10297 (org-link-escape
10298 path org-link-escape-chars-browser)
10299 path))))
10301 ((member type '("message"))
10302 (browse-url (concat type ":" path)))
10304 ((string= type "tags")
10305 (org-tags-view arg path))
10307 ((string= type "tree-match")
10308 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10310 ((string= type "file")
10311 (if (string-match "::\\([0-9]+\\)\\'" path)
10312 (setq line (string-to-number (match-string 1 path))
10313 path (substring path 0 (match-beginning 0)))
10314 (if (string-match "::\\(.+\\)\\'" path)
10315 (setq search (match-string 1 path)
10316 path (substring path 0 (match-beginning 0)))))
10317 (if (string-match "[*?{]" (file-name-nondirectory path))
10318 (dired path)
10319 (org-open-file path arg line search)))
10321 ((string= type "shell")
10322 (let ((buf (generate-new-buffer "*Org Shell Output"))
10323 (cmd path))
10324 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10325 (string-match org-confirm-shell-link-not-regexp cmd))
10326 (not org-confirm-shell-link-function)
10327 (funcall org-confirm-shell-link-function
10328 (format "Execute \"%s\" in shell? "
10329 (org-add-props cmd nil
10330 'face 'org-warning))))
10331 (progn
10332 (message "Executing %s" cmd)
10333 (shell-command cmd buf)
10334 (if (featurep 'midnight)
10335 (setq clean-buffer-list-kill-buffer-names
10336 (cons buf clean-buffer-list-kill-buffer-names))))
10337 (error "Abort"))))
10339 ((string= type "elisp")
10340 (let ((cmd path))
10341 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10342 (string-match org-confirm-elisp-link-not-regexp cmd))
10343 (not org-confirm-elisp-link-function)
10344 (funcall org-confirm-elisp-link-function
10345 (format "Execute \"%s\" as elisp? "
10346 (org-add-props cmd nil
10347 'face 'org-warning))))
10348 (message "%s => %s" cmd
10349 (if (equal (string-to-char cmd) ?\()
10350 (eval (read cmd))
10351 (call-interactively (read cmd))))
10352 (error "Abort"))))
10354 ((and (string= type "thisfile")
10355 (run-hook-with-args-until-success
10356 'org-open-link-functions path)))
10358 ((string= type "thisfile")
10359 (if arg
10360 (switch-to-buffer-other-window
10361 (org-get-buffer-for-internal-link (current-buffer)))
10362 (org-mark-ring-push))
10363 (let ((cmd `(org-link-search
10364 ,path
10365 ,(cond ((equal arg '(4)) ''occur)
10366 ((equal arg '(16)) ''org-occur))
10367 ,pos)))
10368 (condition-case nil (let ((org-link-search-inhibit-query t))
10369 (eval cmd))
10370 (error (progn (widen) (eval cmd))))))
10372 (t (browse-url-at-point)))))))
10373 (move-marker org-open-link-marker nil)
10374 (run-hook-with-args 'org-follow-link-hook)))
10376 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10377 "Offer links in the current entry and return the selected link.
10378 If there is only one link, return it.
10379 If NTH is an integer, return the NTH link found.
10380 If ZERO is a string, check also this string for a link, and if
10381 there is one, return it."
10382 (with-current-buffer buffer
10383 (save-excursion
10384 (save-restriction
10385 (widen)
10386 (goto-char marker)
10387 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10388 "\\(" org-angle-link-re "\\)\\|"
10389 "\\(" org-plain-link-re "\\)"))
10390 (cnt ?0)
10391 (in-emacs (if (integerp nth) nil nth))
10392 have-zero end links link c)
10393 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10394 (push (match-string 0 zero) links)
10395 (setq cnt (1- cnt) have-zero t))
10396 (save-excursion
10397 (org-back-to-heading t)
10398 (setq end (save-excursion (outline-next-heading) (point)))
10399 (while (re-search-forward re end t)
10400 (push (match-string 0) links))
10401 (setq links (org-uniquify (reverse links))))
10402 (cond
10403 ((null links)
10404 (message "No links"))
10405 ((equal (length links) 1)
10406 (setq link (car links)))
10407 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10408 (setq link (nth (if have-zero nth (1- nth)) links)))
10409 (t ; we have to select a link
10410 (save-excursion
10411 (save-window-excursion
10412 (delete-other-windows)
10413 (with-output-to-temp-buffer "*Select Link*"
10414 (mapc (lambda (l)
10415 (if (not (string-match org-bracket-link-regexp l))
10416 (princ (format "[%c] %s\n" (incf cnt)
10417 (org-remove-angle-brackets l)))
10418 (if (match-end 3)
10419 (princ (format "[%c] %s (%s)\n" (incf cnt)
10420 (match-string 3 l) (match-string 1 l)))
10421 (princ (format "[%c] %s\n" (incf cnt)
10422 (match-string 1 l))))))
10423 links))
10424 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10425 (message "Select link to open, RET to open all:")
10426 (setq c (read-char-exclusive))
10427 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10428 (when (equal c ?q) (error "Abort"))
10429 (if (equal c ?\C-m)
10430 (setq link links)
10431 (setq nth (- c ?0))
10432 (if have-zero (setq nth (1+ nth)))
10433 (unless (and (integerp nth) (>= (length links) nth))
10434 (error "Invalid link selection"))
10435 (setq link (nth (1- nth) links)))))
10436 (cons link end))))))
10438 ;; Add special file links that specify the way of opening
10440 (org-add-link-type "file+sys" 'org-open-file-with-system)
10441 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10442 (defun org-open-file-with-system (path)
10443 "Open file at PATH using the system way of opening it."
10444 (org-open-file path 'system))
10445 (defun org-open-file-with-emacs (path)
10446 "Open file at PATH in Emacs."
10447 (org-open-file path 'emacs))
10450 ;;; File search
10452 (defvar org-create-file-search-functions nil
10453 "List of functions to construct the right search string for a file link.
10454 These functions are called in turn with point at the location to
10455 which the link should point.
10457 A function in the hook should first test if it would like to
10458 handle this file type, for example by checking the `major-mode'
10459 or the file extension. If it decides not to handle this file, it
10460 should just return nil to give other functions a chance. If it
10461 does handle the file, it must return the search string to be used
10462 when following the link. The search string will be part of the
10463 file link, given after a double colon, and `org-open-at-point'
10464 will automatically search for it. If special measures must be
10465 taken to make the search successful, another function should be
10466 added to the companion hook `org-execute-file-search-functions',
10467 which see.
10469 A function in this hook may also use `setq' to set the variable
10470 `description' to provide a suggestion for the descriptive text to
10471 be used for this link when it gets inserted into an Org-mode
10472 buffer with \\[org-insert-link].")
10474 (defvar org-execute-file-search-functions nil
10475 "List of functions to execute a file search triggered by a link.
10477 Functions added to this hook must accept a single argument, the
10478 search string that was part of the file link, the part after the
10479 double colon. The function must first check if it would like to
10480 handle this search, for example by checking the `major-mode' or
10481 the file extension. If it decides not to handle this search, it
10482 should just return nil to give other functions a chance. If it
10483 does handle the search, it must return a non-nil value to keep
10484 other functions from trying.
10486 Each function can access the current prefix argument through the
10487 variable `current-prefix-arg'. Note that a single prefix is used
10488 to force opening a link in Emacs, so it may be good to only use a
10489 numeric or double prefix to guide the search function.
10491 In case this is needed, a function in this hook can also restore
10492 the window configuration before `org-open-at-point' was called using:
10494 (set-window-configuration org-window-config-before-follow-link)")
10496 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10497 (defun org-link-search (s &optional type avoid-pos stealth)
10498 "Search for a link search option.
10499 If S is surrounded by forward slashes, it is interpreted as a
10500 regular expression. In org-mode files, this will create an `org-occur'
10501 sparse tree. In ordinary files, `occur' will be used to list matches.
10502 If the current buffer is in `dired-mode', grep will be used to search
10503 in all files. If AVOID-POS is given, ignore matches near that position.
10505 When optional argument STEALTH is non-nil, do not modify
10506 visibility around point, thus ignoring
10507 `org-show-hierarchy-above', `org-show-following-heading' and
10508 `org-show-siblings' variables."
10509 (let ((case-fold-search t)
10510 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10511 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10512 (append '(("") (" ") ("\t") ("\n"))
10513 org-emphasis-alist)
10514 "\\|") "\\)"))
10515 (pos (point))
10516 (pre nil) (post nil)
10517 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10518 (cond
10519 ;; First check if there are any special search functions
10520 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10521 ;; Now try the builtin stuff
10522 ((and (equal (string-to-char s0) ?#)
10523 (> (length s0) 1)
10524 (save-excursion
10525 (goto-char (point-min))
10526 (and
10527 (re-search-forward
10528 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10529 (setq type 'dedicated
10530 pos (match-beginning 0))))
10531 ;; There is an exact target for this
10532 (goto-char pos)
10533 (org-back-to-heading t)))
10534 ((save-excursion
10535 (goto-char (point-min))
10536 (and
10537 (re-search-forward
10538 (concat "<<" (regexp-quote s0) ">>") nil t)
10539 (setq type 'dedicated
10540 pos (match-beginning 0))))
10541 ;; There is an exact target for this
10542 (goto-char pos))
10543 ((save-excursion
10544 (goto-char (point-min))
10545 (and
10546 (re-search-forward
10547 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10548 (setq type 'dedicated pos (match-beginning 0))))
10549 ;; Found an invisible target.
10550 (goto-char pos))
10551 ((save-excursion
10552 (goto-char (point-min))
10553 (and
10554 (re-search-forward
10555 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10556 (setq type 'dedicated pos (match-beginning 0))))
10557 ;; Found an element with a matching #+name affiliated keyword.
10558 (goto-char pos))
10559 ((and (string-match "^(\\(.*\\))$" s0)
10560 (save-excursion
10561 (goto-char (point-min))
10562 (and
10563 (re-search-forward
10564 (concat "[^[]" (regexp-quote
10565 (format org-coderef-label-format
10566 (match-string 1 s0))))
10567 nil t)
10568 (setq type 'dedicated
10569 pos (1+ (match-beginning 0))))))
10570 ;; There is a coderef target for this
10571 (goto-char pos))
10572 ((string-match "^/\\(.*\\)/$" s)
10573 ;; A regular expression
10574 (cond
10575 ((derived-mode-p 'org-mode)
10576 (org-occur (match-string 1 s)))
10577 (t (org-do-occur (match-string 1 s)))))
10578 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10579 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10580 (goto-char (point-min))
10581 (cond
10582 ((let (case-fold-search)
10583 (re-search-forward (format org-complex-heading-regexp-format
10584 (regexp-quote s))
10585 nil t))
10586 ;; OK, found a match
10587 (setq type 'dedicated)
10588 (goto-char (match-beginning 0)))
10589 ((and (not org-link-search-inhibit-query)
10590 (eq org-link-search-must-match-exact-headline 'query-to-create)
10591 (y-or-n-p "No match - create this as a new heading? "))
10592 (goto-char (point-max))
10593 (or (bolp) (newline))
10594 (insert "* " s "\n")
10595 (beginning-of-line 0))
10597 (goto-char pos)
10598 (error "No match"))))
10600 ;; A normal search string
10601 (when (equal (string-to-char s) ?*)
10602 ;; Anchor on headlines, post may include tags.
10603 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10604 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10605 s (substring s 1)))
10606 (remove-text-properties
10607 0 (length s)
10608 '(face nil mouse-face nil keymap nil fontified nil) s)
10609 ;; Make a series of regular expressions to find a match
10610 (setq words (org-split-string s "[ \n\r\t]+")
10612 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10613 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10614 "\\)" markers)
10615 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10616 re2a (concat "[ \t\r\n]" re2a_)
10617 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10618 re4 (concat "[^a-zA-Z_]" re4_)
10620 re1 (concat pre re2 post)
10621 re3 (concat pre (if pre re4_ re4) post)
10622 re5 (concat pre ".*" re4)
10623 re2 (concat pre re2)
10624 re2a (concat pre (if pre re2a_ re2a))
10625 re4 (concat pre (if pre re4_ re4))
10626 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10627 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10628 re5 "\\)"
10630 (cond
10631 ((eq type 'org-occur) (org-occur reall))
10632 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10633 (t (goto-char (point-min))
10634 (setq type 'fuzzy)
10635 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10636 (org-search-not-self 1 re1 nil t)
10637 (org-search-not-self 1 re2 nil t)
10638 (org-search-not-self 1 re2a nil t)
10639 (org-search-not-self 1 re3 nil t)
10640 (org-search-not-self 1 re4 nil t)
10641 (org-search-not-self 1 re5 nil t)
10643 (goto-char (match-beginning 1))
10644 (goto-char pos)
10645 (error "No match"))))))
10646 (and (derived-mode-p 'org-mode)
10647 (not stealth)
10648 (org-show-context 'link-search))
10649 type))
10651 (defun org-search-not-self (group &rest args)
10652 "Execute `re-search-forward', but only accept matches that do not
10653 enclose the position of `org-open-link-marker'."
10654 (let ((m org-open-link-marker))
10655 (catch 'exit
10656 (while (apply 're-search-forward args)
10657 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10658 (goto-char (match-end group))
10659 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10660 (> (match-beginning 0) (marker-position m))
10661 (< (match-end 0) (marker-position m)))
10662 (save-match-data
10663 (or (not (org-in-regexp
10664 org-bracket-link-analytic-regexp 1))
10665 (not (match-end 4)) ; no description
10666 (and (<= (match-beginning 4) (point))
10667 (>= (match-end 4) (point))))))
10668 (throw 'exit (point))))))))
10670 (defun org-get-buffer-for-internal-link (buffer)
10671 "Return a buffer to be used for displaying the link target of internal links."
10672 (cond
10673 ((not org-display-internal-link-with-indirect-buffer)
10674 buffer)
10675 ((string-match "(Clone)$" (buffer-name buffer))
10676 (message "Buffer is already a clone, not making another one")
10677 ;; we also do not modify visibility in this case
10678 buffer)
10679 (t ; make a new indirect buffer for displaying the link
10680 (let* ((bn (buffer-name buffer))
10681 (ibn (concat bn "(Clone)"))
10682 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10683 (with-current-buffer ib (org-overview))
10684 ib))))
10686 (defun org-do-occur (regexp &optional cleanup)
10687 "Call the Emacs command `occur'.
10688 If CLEANUP is non-nil, remove the printout of the regular expression
10689 in the *Occur* buffer. This is useful if the regex is long and not useful
10690 to read."
10691 (occur regexp)
10692 (when cleanup
10693 (let ((cwin (selected-window)) win beg end)
10694 (when (setq win (get-buffer-window "*Occur*"))
10695 (select-window win))
10696 (goto-char (point-min))
10697 (when (re-search-forward "match[a-z]+" nil t)
10698 (setq beg (match-end 0))
10699 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10700 (setq end (1- (match-beginning 0)))))
10701 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10702 (goto-char (point-min))
10703 (select-window cwin))))
10705 ;;; The mark ring for links jumps
10707 (defvar org-mark-ring nil
10708 "Mark ring for positions before jumps in Org-mode.")
10709 (defvar org-mark-ring-last-goto nil
10710 "Last position in the mark ring used to go back.")
10711 ;; Fill and close the ring
10712 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10713 (loop for i from 1 to org-mark-ring-length do
10714 (push (make-marker) org-mark-ring))
10715 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10716 org-mark-ring)
10718 (defun org-mark-ring-push (&optional pos buffer)
10719 "Put the current position or POS into the mark ring and rotate it."
10720 (interactive)
10721 (setq pos (or pos (point)))
10722 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10723 (move-marker (car org-mark-ring)
10724 (or pos (point))
10725 (or buffer (current-buffer)))
10726 (message "%s"
10727 (substitute-command-keys
10728 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10730 (defun org-mark-ring-goto (&optional n)
10731 "Jump to the previous position in the mark ring.
10732 With prefix arg N, jump back that many stored positions. When
10733 called several times in succession, walk through the entire ring.
10734 Org-mode commands jumping to a different position in the current file,
10735 or to another Org-mode file, automatically push the old position
10736 onto the ring."
10737 (interactive "p")
10738 (let (p m)
10739 (if (eq last-command this-command)
10740 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10741 (setq p org-mark-ring))
10742 (setq org-mark-ring-last-goto p)
10743 (setq m (car p))
10744 (org-pop-to-buffer-same-window (marker-buffer m))
10745 (goto-char m)
10746 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10748 (defun org-remove-angle-brackets (s)
10749 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10750 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10752 (defun org-add-angle-brackets (s)
10753 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10754 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10756 (defun org-remove-double-quotes (s)
10757 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10758 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10761 ;;; Following specific links
10763 (defun org-follow-timestamp-link ()
10764 "Open an agenda view for the time-stamp date/range at point."
10765 (cond
10766 ((org-at-date-range-p t)
10767 (let ((org-agenda-start-on-weekday)
10768 (t1 (match-string 1))
10769 (t2 (match-string 2)) tt1 tt2)
10770 (setq tt1 (time-to-days (org-time-string-to-time t1))
10771 tt2 (time-to-days (org-time-string-to-time t2)))
10772 (let ((org-agenda-buffer-tmp-name
10773 (format "*Org Agenda(a:%s)"
10774 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10775 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10776 ((org-at-timestamp-p t)
10777 (let ((org-agenda-buffer-tmp-name
10778 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10779 (org-agenda-list nil (time-to-days (org-time-string-to-time
10780 (substring (match-string 1) 0 10)))
10781 1)))
10782 (t (error "This should not happen"))))
10785 ;;; Following file links
10786 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10787 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10788 (declare-function mailcap-mime-info
10789 "mailcap" (string &optional request no-decode))
10790 (defvar org-wait nil)
10791 (defun org-open-file (path &optional in-emacs line search)
10792 "Open the file at PATH.
10793 First, this expands any special file name abbreviations. Then the
10794 configuration variable `org-file-apps' is checked if it contains an
10795 entry for this file type, and if yes, the corresponding command is launched.
10797 If no application is found, Emacs simply visits the file.
10799 With optional prefix argument IN-EMACS, Emacs will visit the file.
10800 With a double \\[universal-argument] \\[universal-argument] \
10801 prefix arg, Org tries to avoid opening in Emacs
10802 and to use an external application to visit the file.
10804 Optional LINE specifies a line to go to, optional SEARCH a string
10805 to search for. If LINE or SEARCH is given, the file will be
10806 opened in Emacs, unless an entry from org-file-apps that makes
10807 use of groups in a regexp matches.
10809 If you want to change the way frames are used when following a
10810 link, please customize `org-link-frame-setup'.
10812 If the file does not exist, an error is thrown."
10813 (let* ((file (if (equal path "")
10814 buffer-file-name
10815 (substitute-in-file-name (expand-file-name path))))
10816 (file-apps (append org-file-apps (org-default-apps)))
10817 (apps (org-remove-if
10818 'org-file-apps-entry-match-against-dlink-p file-apps))
10819 (apps-dlink (org-remove-if-not
10820 'org-file-apps-entry-match-against-dlink-p file-apps))
10821 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10822 (dirp (if remp nil (file-directory-p file)))
10823 (file (if (and dirp org-open-directory-means-index-dot-org)
10824 (concat (file-name-as-directory file) "index.org")
10825 file))
10826 (a-m-a-p (assq 'auto-mode apps))
10827 (dfile (downcase file))
10828 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10829 (link (cond ((and (eq line nil)
10830 (eq search nil))
10831 file)
10832 (line
10833 (concat file "::" (number-to-string line)))
10834 (search
10835 (concat file "::" search))))
10836 (dlink (downcase link))
10837 (old-buffer (current-buffer))
10838 (old-pos (point))
10839 (old-mode major-mode)
10840 ext cmd link-match-data)
10841 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10842 (setq ext (match-string 1 dfile))
10843 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10844 (setq ext (match-string 1 dfile))))
10845 (cond
10846 ((member in-emacs '((16) system))
10847 (setq cmd (cdr (assoc 'system apps))))
10848 (in-emacs (setq cmd 'emacs))
10850 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10851 (and dirp (cdr (assoc 'directory apps)))
10852 ; first, try matching against apps-dlink
10853 ; if we get a match here, store the match data for later
10854 (let ((match (assoc-default dlink apps-dlink
10855 'string-match)))
10856 (if match
10857 (progn (setq link-match-data (match-data))
10858 match)
10859 (progn (setq in-emacs (or in-emacs line search))
10860 nil))) ; if we have no match in apps-dlink,
10861 ; always open the file in emacs if line or search
10862 ; is given (for backwards compatibility)
10863 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10864 'string-match)
10865 (cdr (assoc ext apps))
10866 (cdr (assoc t apps))))))
10867 (when (eq cmd 'system)
10868 (setq cmd (cdr (assoc 'system apps))))
10869 (when (eq cmd 'default)
10870 (setq cmd (cdr (assoc t apps))))
10871 (when (eq cmd 'mailcap)
10872 (require 'mailcap)
10873 (mailcap-parse-mailcaps)
10874 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10875 (command (mailcap-mime-info mime-type)))
10876 (if (stringp command)
10877 (setq cmd command)
10878 (setq cmd 'emacs))))
10879 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10880 (not (file-exists-p file))
10881 (not org-open-non-existing-files))
10882 (error "No such file: %s" file))
10883 (cond
10884 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10885 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10886 (while (string-match "['\"]%s['\"]" cmd)
10887 (setq cmd (replace-match "%s" t t cmd)))
10888 (while (string-match "%s" cmd)
10889 (setq cmd (replace-match
10890 (save-match-data
10891 (shell-quote-argument
10892 (convert-standard-filename file)))
10893 t t cmd)))
10895 ;; Replace "%1", "%2" etc. in command with group matches from regex
10896 (save-match-data
10897 (let ((match-index 1)
10898 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10899 (set-match-data link-match-data)
10900 (while (<= match-index number-of-groups)
10901 (let ((regex (concat "%" (number-to-string match-index)))
10902 (replace-with (match-string match-index dlink)))
10903 (while (string-match regex cmd)
10904 (setq cmd (replace-match replace-with t t cmd))))
10905 (setq match-index (+ match-index 1)))))
10907 (save-window-excursion
10908 (message "Running %s...done" cmd)
10909 (start-process-shell-command cmd nil cmd)
10910 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10911 ((or (stringp cmd)
10912 (eq cmd 'emacs))
10913 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10914 (widen)
10915 (if line (org-goto-line line)
10916 (if search (org-link-search search))))
10917 ((consp cmd)
10918 (let ((file (convert-standard-filename file)))
10919 (save-match-data
10920 (set-match-data link-match-data)
10921 (eval cmd))))
10922 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10923 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10924 (or (not (equal old-buffer (current-buffer)))
10925 (not (equal old-pos (point))))
10926 (org-mark-ring-push old-pos old-buffer))))
10928 (defun org-file-apps-entry-match-against-dlink-p (entry)
10929 "This function returns non-nil if `entry' uses a regular
10930 expression which should be matched against the whole link by
10931 org-open-file.
10933 It assumes that is the case when the entry uses a regular
10934 expression which has at least one grouping construct and the
10935 action is either a lisp form or a command string containing
10936 '%1', i.e. using at least one subexpression match as a
10937 parameter."
10938 (let ((selector (car entry))
10939 (action (cdr entry)))
10940 (if (stringp selector)
10941 (and (> (regexp-opt-depth selector) 0)
10942 (or (and (stringp action)
10943 (string-match "%[0-9]" action))
10944 (consp action)))
10945 nil)))
10947 (defun org-default-apps ()
10948 "Return the default applications for this operating system."
10949 (cond
10950 ((eq system-type 'darwin)
10951 org-file-apps-defaults-macosx)
10952 ((eq system-type 'windows-nt)
10953 org-file-apps-defaults-windowsnt)
10954 (t org-file-apps-defaults-gnu)))
10956 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10957 "Convert extensions to regular expressions in the cars of LIST.
10958 Also, weed out any non-string entries, because the return value is used
10959 only for regexp matching.
10960 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10961 point to the symbol `emacs', indicating that the file should
10962 be opened in Emacs."
10963 (append
10964 (delq nil
10965 (mapcar (lambda (x)
10966 (if (not (stringp (car x)))
10968 (if (string-match "\\W" (car x))
10970 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10971 list))
10972 (if add-auto-mode
10973 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10975 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10976 (defun org-file-remote-p (file)
10977 "Test whether FILE specifies a location on a remote system.
10978 Return non-nil if the location is indeed remote.
10980 For example, the filename \"/user@host:/foo\" specifies a location
10981 on the system \"/user@host:\"."
10982 (cond ((fboundp 'file-remote-p)
10983 (file-remote-p file))
10984 ((fboundp 'tramp-handle-file-remote-p)
10985 (tramp-handle-file-remote-p file))
10986 ((and (boundp 'ange-ftp-name-format)
10987 (string-match (car ange-ftp-name-format) file))
10988 t)))
10991 ;;;; Refiling
10993 (defun org-get-org-file ()
10994 "Read a filename, with default directory `org-directory'."
10995 (let ((default (or org-default-notes-file remember-data-file)))
10996 (read-file-name (format "File name [%s]: " default)
10997 (file-name-as-directory org-directory)
10998 default)))
11000 (defun org-notes-order-reversed-p ()
11001 "Check if the current file should receive notes in reversed order."
11002 (cond
11003 ((not org-reverse-note-order) nil)
11004 ((eq t org-reverse-note-order) t)
11005 ((not (listp org-reverse-note-order)) nil)
11006 (t (catch 'exit
11007 (let ((all org-reverse-note-order)
11008 entry)
11009 (while (setq entry (pop all))
11010 (if (string-match (car entry) buffer-file-name)
11011 (throw 'exit (cdr entry))))
11012 nil)))))
11014 (defvar org-refile-target-table nil
11015 "The list of refile targets, created by `org-refile'.")
11017 (defvar org-agenda-new-buffers nil
11018 "Buffers created to visit agenda files.")
11020 (defvar org-refile-cache nil
11021 "Cache for refile targets.")
11023 (defvar org-refile-markers nil
11024 "All the markers used for caching refile locations.")
11026 (defun org-refile-marker (pos)
11027 "Get a new refile marker, but only if caching is in use."
11028 (if (not org-refile-use-cache)
11030 (let ((m (make-marker)))
11031 (move-marker m pos)
11032 (push m org-refile-markers)
11033 m)))
11035 (defun org-refile-cache-clear ()
11036 "Clear the refile cache and disable all the markers."
11037 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11038 (setq org-refile-markers nil)
11039 (setq org-refile-cache nil)
11040 (message "Refile cache has been cleared"))
11042 (defun org-refile-cache-check-set (set)
11043 "Check if all the markers in the cache still have live buffers."
11044 (let (marker)
11045 (catch 'exit
11046 (while (and set (setq marker (nth 3 (pop set))))
11047 ;; if org-refile-use-outline-path is 'file, marker may be nil
11048 (when (and marker (null (marker-buffer marker)))
11049 (message "not found") (sit-for 3)
11050 (throw 'exit nil)))
11051 t)))
11053 (defun org-refile-cache-put (set &rest identifiers)
11054 "Push the refile targets SET into the cache, under IDENTIFIERS."
11055 (let* ((key (sha1 (prin1-to-string identifiers)))
11056 (entry (assoc key org-refile-cache)))
11057 (if entry
11058 (setcdr entry set)
11059 (push (cons key set) org-refile-cache))))
11061 (defun org-refile-cache-get (&rest identifiers)
11062 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11063 (cond
11064 ((not org-refile-cache) nil)
11065 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11067 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11068 org-refile-cache))))
11069 (and set (org-refile-cache-check-set set) set)))))
11071 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11072 "Produce a table with refile targets."
11073 (let ((case-fold-search nil)
11074 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11075 (entries (or org-refile-targets '((nil . (:level . 1)))))
11076 targets tgs txt re files f desc descre fast-path-p level pos0)
11077 (message "Getting targets...")
11078 (with-current-buffer (or default-buffer (current-buffer))
11079 (while (setq entry (pop entries))
11080 (setq files (car entry) desc (cdr entry))
11081 (setq fast-path-p nil)
11082 (cond
11083 ((null files) (setq files (list (current-buffer))))
11084 ((eq files 'org-agenda-files)
11085 (setq files (org-agenda-files 'unrestricted)))
11086 ((and (symbolp files) (fboundp files))
11087 (setq files (funcall files)))
11088 ((and (symbolp files) (boundp files))
11089 (setq files (symbol-value files))))
11090 (if (stringp files) (setq files (list files)))
11091 (cond
11092 ((eq (car desc) :tag)
11093 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11094 ((eq (car desc) :todo)
11095 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11096 ((eq (car desc) :regexp)
11097 (setq descre (cdr desc)))
11098 ((eq (car desc) :level)
11099 (setq descre (concat "^\\*\\{" (number-to-string
11100 (if org-odd-levels-only
11101 (1- (* 2 (cdr desc)))
11102 (cdr desc)))
11103 "\\}[ \t]")))
11104 ((eq (car desc) :maxlevel)
11105 (setq fast-path-p t)
11106 (setq descre (concat "^\\*\\{1," (number-to-string
11107 (if org-odd-levels-only
11108 (1- (* 2 (cdr desc)))
11109 (cdr desc)))
11110 "\\}[ \t]")))
11111 (t (error "Bad refiling target description %s" desc)))
11112 (while (setq f (pop files))
11113 (with-current-buffer
11114 (if (bufferp f) f (org-get-agenda-file-buffer f))
11116 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11117 (progn
11118 (if (bufferp f) (setq f (buffer-file-name
11119 (buffer-base-buffer f))))
11120 (setq f (and f (expand-file-name f)))
11121 (if (eq org-refile-use-outline-path 'file)
11122 (push (list (file-name-nondirectory f) f nil nil) tgs))
11123 (save-excursion
11124 (save-restriction
11125 (widen)
11126 (goto-char (point-min))
11127 (while (re-search-forward descre nil t)
11128 (goto-char (setq pos0 (point-at-bol)))
11129 (catch 'next
11130 (when org-refile-target-verify-function
11131 (save-match-data
11132 (or (funcall org-refile-target-verify-function)
11133 (throw 'next t))))
11134 (when (and (looking-at org-complex-heading-regexp)
11135 (not (member (match-string 4) excluded-entries))
11136 (match-string 4))
11137 (setq level (org-reduced-level
11138 (- (match-end 1) (match-beginning 1)))
11139 txt (org-link-display-format (match-string 4))
11140 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11141 re (format org-complex-heading-regexp-format
11142 (regexp-quote (match-string 4))))
11143 (when org-refile-use-outline-path
11144 (setq txt (mapconcat
11145 'org-protect-slash
11146 (append
11147 (if (eq org-refile-use-outline-path
11148 'file)
11149 (list (file-name-nondirectory
11150 (buffer-file-name
11151 (buffer-base-buffer))))
11152 (if (eq org-refile-use-outline-path
11153 'full-file-path)
11154 (list (buffer-file-name
11155 (buffer-base-buffer)))))
11156 (org-get-outline-path fast-path-p
11157 level txt)
11158 (list txt))
11159 "/")))
11160 (push (list txt f re (org-refile-marker (point)))
11161 tgs)))
11162 (when (= (point) pos0)
11163 ;; verification function has not moved point
11164 (goto-char (point-at-eol))))))))
11165 (when org-refile-use-cache
11166 (org-refile-cache-put tgs (buffer-file-name) descre))
11167 (setq targets (append tgs targets))
11168 ))))
11169 (message "Getting targets...done")
11170 (nreverse targets)))
11172 (defun org-protect-slash (s)
11173 (while (string-match "/" s)
11174 (setq s (replace-match "\\" t t s)))
11177 (defvar org-olpa (make-vector 20 nil))
11179 (defun org-get-outline-path (&optional fastp level heading)
11180 "Return the outline path to the current entry, as a list.
11182 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11183 routine which makes outline path derivations for an entire file,
11184 avoiding backtracing. Refile target collection makes use of that."
11185 (if fastp
11186 (progn
11187 (if (> level 19)
11188 (error "Outline path failure, more than 19 levels"))
11189 (loop for i from level upto 19 do
11190 (aset org-olpa i nil))
11191 (prog1
11192 (delq nil (append org-olpa nil))
11193 (aset org-olpa level heading)))
11194 (let (rtn case-fold-search)
11195 (save-excursion
11196 (save-restriction
11197 (widen)
11198 (while (org-up-heading-safe)
11199 (when (looking-at org-complex-heading-regexp)
11200 (push (org-match-string-no-properties 4) rtn)))
11201 rtn)))))
11203 (defun org-format-outline-path (path &optional width prefix separator)
11204 "Format the outline path PATH for display.
11205 WIDTH is the maximum number of characters that is available.
11206 PREFIX is a prefix to be included in the returned string,
11207 such as the file name.
11208 SEPARATOR is inserted between the different parts of the path,
11209 the default is \"/\"."
11210 (setq width (or width 79))
11211 (if prefix (setq width (- width (length prefix))))
11212 (if (not path)
11213 (or prefix "")
11214 (let* ((nsteps (length path))
11215 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11216 (maxwidth (if (<= total-width width)
11217 10000 ;; everything fits
11218 ;; we need to shorten the level headings
11219 (/ (- width nsteps) nsteps)))
11220 (org-odd-levels-only nil)
11221 (n 0)
11222 (total (1+ (length prefix))))
11223 (setq maxwidth (max maxwidth 10))
11224 (concat prefix
11225 (if prefix (or separator "/"))
11226 (mapconcat
11227 (lambda (h)
11228 (setq n (1+ n))
11229 (if (and (= n nsteps) (< maxwidth 10000))
11230 (setq maxwidth (- total-width total)))
11231 (if (< (length h) maxwidth)
11232 (progn (setq total (+ total (length h) 1)) h)
11233 (setq h (substring h 0 (- maxwidth 2))
11234 total (+ total maxwidth 1))
11235 (if (string-match "[ \t]+\\'" h)
11236 (setq h (substring h 0 (match-beginning 0))))
11237 (setq h (concat h "..")))
11238 (org-add-props h nil 'face
11239 (nth (% (1- n) org-n-level-faces)
11240 org-level-faces))
11242 path (or separator "/"))))))
11244 (defun org-display-outline-path (&optional file current separator just-return-string)
11245 "Display the current outline path in the echo area.
11247 If FILE is non-nil, prepend the output with the file name.
11248 If CURRENT is non-nil, append the current heading to the output.
11249 SEPARATOR is passed through to `org-format-outline-path'. It separates
11250 the different parts of the path and defaults to \"/\".
11251 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11252 (interactive "P")
11253 (let* (case-fold-search
11254 message-log-max ; Don't populate the *Messages* buffer
11255 (bfn (buffer-file-name (buffer-base-buffer)))
11256 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11257 res)
11258 (if current (setq path (append path
11259 (save-excursion
11260 (org-back-to-heading t)
11261 (if (looking-at org-complex-heading-regexp)
11262 (list (match-string 4)))))))
11263 (setq res
11264 (org-format-outline-path
11265 path
11266 (1- (frame-width))
11267 (and file bfn (concat (file-name-nondirectory bfn) separator))
11268 separator))
11269 (if just-return-string
11270 (org-no-properties res)
11271 (message "%s" res))))
11273 (defvar org-refile-history nil
11274 "History for refiling operations.")
11276 (defvar org-after-refile-insert-hook nil
11277 "Hook run after `org-refile' has inserted its stuff at the new location.
11278 Note that this is still *before* the stuff will be removed from
11279 the *old* location.")
11281 (defvar org-capture-last-stored-marker)
11282 (defvar org-refile-keep nil
11283 "Non-nil means `org-refile' will copy instead of refile.")
11285 (defun org-copy ()
11286 "Like `org-refile', but copy."
11287 (interactive)
11288 (let ((org-refile-keep t))
11289 (funcall 'org-refile nil nil nil "Copy")))
11291 (defun org-refile (&optional goto default-buffer rfloc msg)
11292 "Move the entry or entries at point to another heading.
11293 The list of target headings is compiled using the information in
11294 `org-refile-targets', which see.
11296 At the target location, the entry is filed as a subitem of the target
11297 heading. Depending on `org-reverse-note-order', the new subitem will
11298 either be the first or the last subitem.
11300 If there is an active region, all entries in that region will be moved.
11301 However, the region must fulfill the requirement that the first heading
11302 is the first one sets the top-level of the moved text - at most siblings
11303 below it are allowed.
11305 With prefix arg GOTO, the command will only visit the target location
11306 and not actually move anything.
11308 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11309 go to the location where the last refiling operation has put the subtree.
11310 With a prefix argument of `2', refile to the running clock.
11312 RFLOC can be a refile location obtained in a different way.
11314 MSG is a string to replace \"Refile\" in the default prompt with
11315 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11317 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11319 If you are using target caching (see `org-refile-use-cache'),
11320 you have to clear the target cache in order to find new targets.
11321 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11322 prefix argument (`C-u C-u C-u C-c C-w')."
11324 (interactive "P")
11325 (if (member goto '(0 (64)))
11326 (org-refile-cache-clear)
11327 (let* ((actionmsg (or msg "Refile"))
11328 (cbuf (current-buffer))
11329 (regionp (org-region-active-p))
11330 (region-start (and regionp (region-beginning)))
11331 (region-end (and regionp (region-end)))
11332 (region-length (and regionp (- region-end region-start)))
11333 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11334 pos it nbuf file re level reversed)
11335 (setq last-command nil)
11336 (when regionp
11337 (goto-char region-start)
11338 (or (bolp) (goto-char (point-at-bol)))
11339 (setq region-start (point))
11340 (unless (or (org-kill-is-subtree-p
11341 (buffer-substring region-start region-end))
11342 (prog1 org-refile-active-region-within-subtree
11343 (org-toggle-heading)))
11344 (error "The region is not a (sequence of) subtree(s)")))
11345 (if (equal goto '(16))
11346 (org-refile-goto-last-stored)
11347 (when (or
11348 (and (equal goto 2)
11349 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11350 (prog1
11351 (setq it (list (or org-clock-heading "running clock")
11352 (buffer-file-name
11353 (marker-buffer org-clock-hd-marker))
11355 (marker-position org-clock-hd-marker)))
11356 (setq goto nil)))
11357 (setq it (or rfloc
11358 (let (heading-text)
11359 (save-excursion
11360 (unless goto
11361 (org-back-to-heading t)
11362 (setq heading-text
11363 (nth 4 (org-heading-components))))
11365 (org-refile-get-location
11366 (cond (goto "Goto")
11367 (regionp (concat actionmsg " region to"))
11368 (t (concat actionmsg " subtree \""
11369 heading-text "\" to")))
11370 default-buffer
11371 (and (not (equal '(4) goto))
11372 org-refile-allow-creating-parent-nodes)
11373 goto))))))
11374 (setq file (nth 1 it)
11375 re (nth 2 it)
11376 pos (nth 3 it))
11377 (if (and (not goto)
11379 (equal (buffer-file-name) file)
11380 (if regionp
11381 (and (>= pos region-start)
11382 (<= pos region-end))
11383 (and (>= pos (point))
11384 (< pos (save-excursion
11385 (org-end-of-subtree t t))))))
11386 (error "Cannot refile to position inside the tree or region"))
11388 (setq nbuf (or (find-buffer-visiting file)
11389 (find-file-noselect file)))
11390 (if goto
11391 (progn
11392 (org-pop-to-buffer-same-window nbuf)
11393 (goto-char pos)
11394 (org-show-context 'org-goto))
11395 (if regionp
11396 (progn
11397 (org-kill-new (buffer-substring region-start region-end))
11398 (org-save-markers-in-region region-start region-end))
11399 (org-copy-subtree 1 nil t))
11400 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11401 (find-file-noselect file)))
11402 (setq reversed (org-notes-order-reversed-p))
11403 (save-excursion
11404 (save-restriction
11405 (widen)
11406 (if pos
11407 (progn
11408 (goto-char pos)
11409 (looking-at org-outline-regexp)
11410 (setq level (org-get-valid-level (funcall outline-level) 1))
11411 (goto-char
11412 (if reversed
11413 (or (outline-next-heading) (point-max))
11414 (or (save-excursion (org-get-next-sibling))
11415 (org-end-of-subtree t t)
11416 (point-max)))))
11417 (setq level 1)
11418 (if (not reversed)
11419 (goto-char (point-max))
11420 (goto-char (point-min))
11421 (or (outline-next-heading) (goto-char (point-max)))))
11422 (if (not (bolp)) (newline))
11423 (org-paste-subtree level)
11424 (when org-log-refile
11425 (org-add-log-setup 'refile nil nil 'findpos
11426 org-log-refile)
11427 (unless (eq org-log-refile 'note)
11428 (save-excursion (org-add-log-note))))
11429 (and org-auto-align-tags
11430 (let ((org-loop-over-headlines-in-active-region nil))
11431 (org-set-tags nil t)))
11432 (with-demoted-errors
11433 (bookmark-set "org-refile-last-stored"))
11434 ;; If we are refiling for capture, make sure that the
11435 ;; last-capture pointers point here
11436 (when (org-bound-and-true-p org-refile-for-capture)
11437 (with-demoted-errors
11438 (bookmark-set "org-capture-last-stored-marker"))
11439 (move-marker org-capture-last-stored-marker (point)))
11440 (if (fboundp 'deactivate-mark) (deactivate-mark))
11441 (run-hooks 'org-after-refile-insert-hook))))
11442 (unless org-refile-keep
11443 (if regionp
11444 (delete-region (point) (+ (point) region-length))
11445 (org-cut-subtree)))
11446 (when (featurep 'org-inlinetask)
11447 (org-inlinetask-remove-END-maybe))
11448 (setq org-markers-to-move nil)
11449 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11451 (defun org-refile-goto-last-stored ()
11452 "Go to the location where the last refile was stored."
11453 (interactive)
11454 (bookmark-jump "org-refile-last-stored")
11455 (message "This is the location of the last refile"))
11457 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11458 no-exclude)
11459 "Prompt the user for a refile location, using PROMPT.
11460 PROMPT should not be suffixed with a colon and a space, because
11461 this function appends the default value from
11462 `org-refile-history' automatically, if that is not empty.
11463 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11464 this is used for the GOTO interface."
11465 (let ((org-refile-targets org-refile-targets)
11466 (org-refile-use-outline-path org-refile-use-outline-path)
11467 excluded-entries)
11468 (when (and (derived-mode-p 'org-mode)
11469 (not org-refile-use-cache)
11470 (not no-exclude))
11471 (org-map-tree
11472 (lambda()
11473 (setq excluded-entries
11474 (append excluded-entries (list (org-get-heading t t)))))))
11475 (setq org-refile-target-table
11476 (org-refile-get-targets default-buffer excluded-entries)))
11477 (unless org-refile-target-table
11478 (error "No refile targets"))
11479 (let* ((cbuf (current-buffer))
11480 (partial-completion-mode nil)
11481 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11482 (cfunc (if (and org-refile-use-outline-path
11483 org-outline-path-complete-in-steps)
11484 'org-olpath-completing-read
11485 'org-icompleting-read))
11486 (extra (if org-refile-use-outline-path "/" ""))
11487 (cbnex (concat (buffer-name) extra))
11488 (filename (and cfn (expand-file-name cfn)))
11489 (tbl (mapcar
11490 (lambda (x)
11491 (if (and (not (member org-refile-use-outline-path
11492 '(file full-file-path)))
11493 (not (equal filename (nth 1 x))))
11494 (cons (concat (car x) extra " ("
11495 (file-name-nondirectory (nth 1 x)) ")")
11496 (cdr x))
11497 (cons (concat (car x) extra) (cdr x))))
11498 org-refile-target-table))
11499 (completion-ignore-case t)
11500 cdef
11501 (prompt (concat prompt
11502 (or (and (car org-refile-history)
11503 (concat " (default " (car org-refile-history) ")"))
11504 (and (assoc cbnex tbl) (setq cdef cbnex)
11505 (concat " (default " cbnex ")"))) ": "))
11506 pa answ parent-target child parent old-hist)
11507 (setq old-hist org-refile-history)
11508 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11509 nil 'org-refile-history (or cdef (car org-refile-history))))
11510 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11511 (org-refile-check-position pa)
11512 (if pa
11513 (progn
11514 (when (or (not org-refile-history)
11515 (not (eq old-hist org-refile-history))
11516 (not (equal (car pa) (car org-refile-history))))
11517 (setq org-refile-history
11518 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11519 org-refile-history
11520 (cdr org-refile-history))))
11521 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11522 (pop org-refile-history)))
11524 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11525 (progn
11526 (setq parent (match-string 1 answ)
11527 child (match-string 2 answ))
11528 (setq parent-target (or (assoc parent tbl)
11529 (assoc (concat parent "/") tbl)))
11530 (when (and parent-target
11531 (or (eq new-nodes t)
11532 (and (eq new-nodes 'confirm)
11533 (y-or-n-p (format "Create new node \"%s\"? "
11534 child)))))
11535 (org-refile-new-child parent-target child)))
11536 (error "Invalid target location")))))
11538 (declare-function org-string-nw-p "org-macs" (s))
11539 (defun org-refile-check-position (refile-pointer)
11540 "Check if the refile pointer matches the headline to which it points."
11541 (let* ((file (nth 1 refile-pointer))
11542 (re (nth 2 refile-pointer))
11543 (pos (nth 3 refile-pointer))
11544 buffer)
11545 (if (and (not (markerp pos)) (not file))
11546 (error "Please save the buffer to a file before refiling")
11547 (when (org-string-nw-p re)
11548 (setq buffer (if (markerp pos)
11549 (marker-buffer pos)
11550 (or (find-buffer-visiting file)
11551 (find-file-noselect file))))
11552 (with-current-buffer buffer
11553 (save-excursion
11554 (save-restriction
11555 (widen)
11556 (goto-char pos)
11557 (beginning-of-line 1)
11558 (unless (org-looking-at-p re)
11559 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11561 (defun org-refile-new-child (parent-target child)
11562 "Use refile target PARENT-TARGET to add new CHILD below it."
11563 (unless parent-target
11564 (error "Cannot find parent for new node"))
11565 (let ((file (nth 1 parent-target))
11566 (pos (nth 3 parent-target))
11567 level)
11568 (with-current-buffer (or (find-buffer-visiting file)
11569 (find-file-noselect file))
11570 (save-excursion
11571 (save-restriction
11572 (widen)
11573 (if pos
11574 (goto-char pos)
11575 (goto-char (point-max))
11576 (if (not (bolp)) (newline)))
11577 (when (looking-at org-outline-regexp)
11578 (setq level (funcall outline-level))
11579 (org-end-of-subtree t t))
11580 (org-back-over-empty-lines)
11581 (insert "\n" (make-string
11582 (if pos (org-get-valid-level level 1) 1) ?*)
11583 " " child "\n")
11584 (beginning-of-line 0)
11585 (list (concat (car parent-target) "/" child) file "" (point)))))))
11587 (defun org-olpath-completing-read (prompt collection &rest args)
11588 "Read an outline path like a file name."
11589 (let ((thetable collection)
11590 (org-completion-use-ido nil) ; does not work with ido.
11591 (org-completion-use-iswitchb nil)) ; or iswitchb
11592 (apply
11593 'org-icompleting-read prompt
11594 (lambda (string predicate &optional flag)
11595 (let (rtn r f (l (length string)))
11596 (cond
11597 ((eq flag nil)
11598 ;; try completion
11599 (try-completion string thetable))
11600 ((eq flag t)
11601 ;; all-completions
11602 (setq rtn (all-completions string thetable predicate))
11603 (mapcar
11604 (lambda (x)
11605 (setq r (substring x l))
11606 (if (string-match " ([^)]*)$" x)
11607 (setq f (match-string 0 x))
11608 (setq f ""))
11609 (if (string-match "/" r)
11610 (concat string (substring r 0 (match-end 0)) f)
11612 rtn))
11613 ((eq flag 'lambda)
11614 ;; exact match?
11615 (assoc string thetable)))))
11616 args)))
11618 ;;;; Dynamic blocks
11620 (defun org-find-dblock (name)
11621 "Find the first dynamic block with name NAME in the buffer.
11622 If not found, stay at current position and return nil."
11623 (let ((case-fold-search t) pos)
11624 (save-excursion
11625 (goto-char (point-min))
11626 (setq pos (and (re-search-forward
11627 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11628 (match-beginning 0))))
11629 (if pos (goto-char pos))
11630 pos))
11632 (defconst org-dblock-start-re
11633 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11634 "Matches the start line of a dynamic block, with parameters.")
11636 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11637 "Matches the end of a dynamic block.")
11639 (defun org-create-dblock (plist)
11640 "Create a dynamic block section, with parameters taken from PLIST.
11641 PLIST must contain a :name entry which is used as name of the block."
11642 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11643 (end-of-line 1)
11644 (newline))
11645 (let ((col (current-column))
11646 (name (plist-get plist :name)))
11647 (insert "#+BEGIN: " name)
11648 (while plist
11649 (if (eq (car plist) :name)
11650 (setq plist (cddr plist))
11651 (insert " " (prin1-to-string (pop plist)))))
11652 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11653 (beginning-of-line -2)))
11655 (defun org-prepare-dblock ()
11656 "Prepare dynamic block for refresh.
11657 This empties the block, puts the cursor at the insert position and returns
11658 the property list including an extra property :name with the block name."
11659 (unless (looking-at org-dblock-start-re)
11660 (error "Not at a dynamic block"))
11661 (let* ((begdel (1+ (match-end 0)))
11662 (name (org-no-properties (match-string 1)))
11663 (params (append (list :name name)
11664 (read (concat "(" (match-string 3) ")")))))
11665 (save-excursion
11666 (beginning-of-line 1)
11667 (skip-chars-forward " \t")
11668 (setq params (plist-put params :indentation-column (current-column))))
11669 (unless (re-search-forward org-dblock-end-re nil t)
11670 (error "Dynamic block not terminated"))
11671 (setq params
11672 (append params
11673 (list :content (buffer-substring
11674 begdel (match-beginning 0)))))
11675 (delete-region begdel (match-beginning 0))
11676 (goto-char begdel)
11677 (open-line 1)
11678 params))
11680 (defun org-map-dblocks (&optional command)
11681 "Apply COMMAND to all dynamic blocks in the current buffer.
11682 If COMMAND is not given, use `org-update-dblock'."
11683 (let ((cmd (or command 'org-update-dblock)))
11684 (save-excursion
11685 (goto-char (point-min))
11686 (while (re-search-forward org-dblock-start-re nil t)
11687 (goto-char (match-beginning 0))
11688 (save-excursion
11689 (condition-case nil
11690 (funcall cmd)
11691 (error (message "Error during update of dynamic block"))))
11692 (unless (re-search-forward org-dblock-end-re nil t)
11693 (error "Dynamic block not terminated"))))))
11695 (defun org-dblock-update (&optional arg)
11696 "User command for updating dynamic blocks.
11697 Update the dynamic block at point. With prefix ARG, update all dynamic
11698 blocks in the buffer."
11699 (interactive "P")
11700 (if arg
11701 (org-update-all-dblocks)
11702 (or (looking-at org-dblock-start-re)
11703 (org-beginning-of-dblock))
11704 (org-update-dblock)))
11706 (defun org-update-dblock ()
11707 "Update the dynamic block at point.
11708 This means to empty the block, parse for parameters and then call
11709 the correct writing function."
11710 (interactive)
11711 (save-window-excursion
11712 (let* ((pos (point))
11713 (line (org-current-line))
11714 (params (org-prepare-dblock))
11715 (name (plist-get params :name))
11716 (indent (plist-get params :indentation-column))
11717 (cmd (intern (concat "org-dblock-write:" name))))
11718 (message "Updating dynamic block `%s' at line %d..." name line)
11719 (funcall cmd params)
11720 (message "Updating dynamic block `%s' at line %d...done" name line)
11721 (goto-char pos)
11722 (when (and indent (> indent 0))
11723 (setq indent (make-string indent ?\ ))
11724 (save-excursion
11725 (org-beginning-of-dblock)
11726 (forward-line 1)
11727 (while (not (looking-at org-dblock-end-re))
11728 (insert indent)
11729 (beginning-of-line 2))
11730 (when (looking-at org-dblock-end-re)
11731 (and (looking-at "[ \t]+")
11732 (replace-match ""))
11733 (insert indent)))))))
11735 (defun org-beginning-of-dblock ()
11736 "Find the beginning of the dynamic block at point.
11737 Error if there is no such block at point."
11738 (let ((pos (point))
11739 beg)
11740 (end-of-line 1)
11741 (if (and (re-search-backward org-dblock-start-re nil t)
11742 (setq beg (match-beginning 0))
11743 (re-search-forward org-dblock-end-re nil t)
11744 (> (match-end 0) pos))
11745 (goto-char beg)
11746 (goto-char pos)
11747 (error "Not in a dynamic block"))))
11749 (defun org-update-all-dblocks ()
11750 "Update all dynamic blocks in the buffer.
11751 This function can be used in a hook."
11752 (interactive)
11753 (when (derived-mode-p 'org-mode)
11754 (org-map-dblocks 'org-update-dblock)))
11757 ;;;; Completion
11759 (defun org-get-export-keywords ()
11760 "Return a list of all currently understood export keywords.
11761 Export keywords include options, block names, attributes and
11762 keywords relative to each registered export back-end."
11763 (delq nil
11764 (let (keywords)
11765 (mapc
11766 (lambda (back-end)
11767 (let ((props (cdr back-end)))
11768 ;; Back-end name (for keywords, like #+LATEX:)
11769 (push (upcase (symbol-name (car back-end))) keywords)
11770 ;; Back-end options.
11771 (mapc (lambda (option) (push (cadr option) keywords))
11772 (plist-get (cdr back-end) :options-alist))))
11773 (org-bound-and-true-p org-export-registered-backends))
11774 keywords)))
11776 (defconst org-options-keywords
11777 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11778 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11779 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11780 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11781 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11783 (defcustom org-structure-template-alist
11784 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11785 "<src lang=\"?\">\n\n</src>")
11786 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11787 "<example>\n?\n</example>")
11788 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11789 "<quote>\n?\n</quote>")
11790 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11791 "<verse>\n?\n</verse>")
11792 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11793 "<verbatim>\n?\n</verbatim>")
11794 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11795 "<center>\n?\n</center>")
11796 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11797 "<literal style=\"latex\">\n?\n</literal>")
11798 ("L" "#+LaTeX: "
11799 "<literal style=\"latex\">?</literal>")
11800 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11801 "<literal style=\"html\">\n?\n</literal>")
11802 ("H" "#+HTML: "
11803 "<literal style=\"html\">?</literal>")
11804 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11805 ("A" "#+ASCII: ")
11806 ("i" "#+INDEX: ?"
11807 "#+INDEX: ?")
11808 ("I" "#+INCLUDE: %file ?"
11809 "<include file=%file markup=\"?\">"))
11810 "Structure completion elements.
11811 This is a list of abbreviation keys and values. The value gets inserted
11812 if you type `<' followed by the key and then press the completion key,
11813 usually `M-TAB'. %file will be replaced by a file name after prompting
11814 for the file using completion. The cursor will be placed at the position
11815 of the `?` in the template.
11816 There are two templates for each key, the first uses the original Org syntax,
11817 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11818 the default when the /org-mtags.el/ module has been loaded. See also the
11819 variable `org-mtags-prefer-muse-templates'."
11820 :group 'org-completion
11821 :type '(repeat
11822 (string :tag "Key")
11823 (string :tag "Template")
11824 (string :tag "Muse Template")))
11826 (defun org-try-structure-completion ()
11827 "Try to complete a structure template before point.
11828 This looks for strings like \"<e\" on an otherwise empty line and
11829 expands them."
11830 (let ((l (buffer-substring (point-at-bol) (point)))
11832 (when (and (looking-at "[ \t]*$")
11833 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11834 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11835 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11836 (match-beginning 1)) a)
11837 t)))
11839 (defun org-complete-expand-structure-template (start cell)
11840 "Expand a structure template."
11841 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11842 (rpl (nth (if musep 2 1) cell))
11843 (ind ""))
11844 (delete-region start (point))
11845 (when (string-match "\\`#\\+" rpl)
11846 (cond
11847 ((bolp))
11848 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11849 (setq ind (buffer-substring (point-at-bol) (point))))
11850 (t (newline))))
11851 (setq start (point))
11852 (if (string-match "%file" rpl)
11853 (setq rpl (replace-match
11854 (concat
11855 "\""
11856 (save-match-data
11857 (abbreviate-file-name (read-file-name "Include file: ")))
11858 "\"")
11859 t t rpl)))
11860 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11861 (concat "\n" ind)))
11862 (insert rpl)
11863 (if (re-search-backward "\\?" start t) (delete-char 1))))
11865 ;;;; TODO, DEADLINE, Comments
11867 (defun org-toggle-comment ()
11868 "Change the COMMENT state of an entry."
11869 (interactive)
11870 (save-excursion
11871 (org-back-to-heading)
11872 (let (case-fold-search)
11873 (cond
11874 ((looking-at (format org-heading-keyword-regexp-format
11875 org-comment-string))
11876 (goto-char (match-end 1))
11877 (looking-at (concat " +" org-comment-string))
11878 (replace-match "" t t)
11879 (when (eolp) (insert " ")))
11880 ((looking-at org-outline-regexp)
11881 (goto-char (match-end 0))
11882 (insert org-comment-string " "))))))
11884 (defvar org-last-todo-state-is-todo nil
11885 "This is non-nil when the last TODO state change led to a TODO state.
11886 If the last change removed the TODO tag or switched to DONE, then
11887 this is nil.")
11889 (defvar org-setting-tags nil) ; dynamically skipped
11891 (defvar org-todo-setup-filter-hook nil
11892 "Hook for functions that pre-filter todo specs.
11893 Each function takes a todo spec and returns either nil or the spec
11894 transformed into canonical form." )
11896 (defvar org-todo-get-default-hook nil
11897 "Hook for functions that get a default item for todo.
11898 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11899 nil or a string to be used for the todo mark." )
11901 (defvar org-agenda-headline-snapshot-before-repeat)
11903 (defun org-current-effective-time ()
11904 "Return current time adjusted for `org-extend-today-until' variable."
11905 (let* ((ct (org-current-time))
11906 (dct (decode-time ct))
11907 (ct1
11908 (cond
11909 (org-use-last-clock-out-time-as-effective-time
11910 (or (org-clock-get-last-clock-out-time) ct))
11911 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11912 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11913 (t ct))))
11914 ct1))
11916 (defun org-todo-yesterday (&optional arg)
11917 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11918 (interactive "P")
11919 (if (eq major-mode 'org-agenda-mode)
11920 (apply 'org-agenda-todo-yesterday arg)
11921 (let* ((hour (third (decode-time
11922 (org-current-time))))
11923 (org-extend-today-until (1+ hour)))
11924 (org-todo arg))))
11926 (defvar org-block-entry-blocking ""
11927 "First entry preventing the TODO state change.")
11929 (defun org-todo (&optional arg)
11930 "Change the TODO state of an item.
11931 The state of an item is given by a keyword at the start of the heading,
11932 like
11933 *** TODO Write paper
11934 *** DONE Call mom
11936 The different keywords are specified in the variable `org-todo-keywords'.
11937 By default the available states are \"TODO\" and \"DONE\".
11938 So for this example: when the item starts with TODO, it is changed to DONE.
11939 When it starts with DONE, the DONE is removed. And when neither TODO nor
11940 DONE are present, add TODO at the beginning of the heading.
11942 With \\[universal-argument] prefix arg, use completion to determine the new \
11943 state.
11944 With numeric prefix arg, switch to that state.
11945 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11946 keywords (nextset).
11947 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11948 With a numeric prefix arg of 0, inhibit note taking for the change.
11950 For calling through lisp, arg is also interpreted in the following way:
11951 'none -> empty state
11952 \"\"(empty string) -> switch to empty state
11953 'done -> switch to DONE
11954 'nextset -> switch to the next set of keywords
11955 'previousset -> switch to the previous set of keywords
11956 \"WAITING\" -> switch to the specified keyword, but only if it
11957 really is a member of `org-todo-keywords'."
11958 (interactive "P")
11959 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11960 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11961 'region-start-level 'region))
11962 org-loop-over-headlines-in-active-region)
11963 (org-map-entries
11964 `(org-todo ,arg)
11965 org-loop-over-headlines-in-active-region
11966 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11967 (if (equal arg '(16)) (setq arg 'nextset))
11968 (let ((org-blocker-hook org-blocker-hook)
11969 commentp
11970 case-fold-search)
11971 (when (equal arg '(64))
11972 (setq arg nil org-blocker-hook nil))
11973 (when (and org-blocker-hook
11974 (or org-inhibit-blocking
11975 (org-entry-get nil "NOBLOCKING")))
11976 (setq org-blocker-hook nil))
11977 (save-excursion
11978 (catch 'exit
11979 (org-back-to-heading t)
11980 (when (looking-at (concat "^\\*+ " org-comment-string))
11981 (org-toggle-comment)
11982 (setq commentp t))
11983 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11984 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11985 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11986 (let* ((match-data (match-data))
11987 (startpos (point-at-bol))
11988 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11989 (org-log-done org-log-done)
11990 (org-log-repeat org-log-repeat)
11991 (org-todo-log-states org-todo-log-states)
11992 (org-inhibit-logging
11993 (if (equal arg 0)
11994 (progn (setq arg nil) 'note) org-inhibit-logging))
11995 (this (match-string 1))
11996 (hl-pos (match-beginning 0))
11997 (head (org-get-todo-sequence-head this))
11998 (ass (assoc head org-todo-kwd-alist))
11999 (interpret (nth 1 ass))
12000 (done-word (nth 3 ass))
12001 (final-done-word (nth 4 ass))
12002 (org-last-state (or this ""))
12003 (completion-ignore-case t)
12004 (member (member this org-todo-keywords-1))
12005 (tail (cdr member))
12006 (org-state (cond
12007 ((and org-todo-key-trigger
12008 (or (and (equal arg '(4))
12009 (eq org-use-fast-todo-selection 'prefix))
12010 (and (not arg) org-use-fast-todo-selection
12011 (not (eq org-use-fast-todo-selection
12012 'prefix)))))
12013 ;; Use fast selection
12014 (org-fast-todo-selection))
12015 ((and (equal arg '(4))
12016 (or (not org-use-fast-todo-selection)
12017 (not org-todo-key-trigger)))
12018 ;; Read a state with completion
12019 (org-icompleting-read
12020 "State: " (mapcar (lambda(x) (list x))
12021 org-todo-keywords-1)
12022 nil t))
12023 ((eq arg 'right)
12024 (if this
12025 (if tail (car tail) nil)
12026 (car org-todo-keywords-1)))
12027 ((eq arg 'left)
12028 (if (equal member org-todo-keywords-1)
12030 (if this
12031 (nth (- (length org-todo-keywords-1)
12032 (length tail) 2)
12033 org-todo-keywords-1)
12034 (org-last org-todo-keywords-1))))
12035 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12036 (setq arg nil))) ; hack to fall back to cycling
12037 (arg
12038 ;; user or caller requests a specific state
12039 (cond
12040 ((equal arg "") nil)
12041 ((eq arg 'none) nil)
12042 ((eq arg 'done) (or done-word (car org-done-keywords)))
12043 ((eq arg 'nextset)
12044 (or (car (cdr (member head org-todo-heads)))
12045 (car org-todo-heads)))
12046 ((eq arg 'previousset)
12047 (let ((org-todo-heads (reverse org-todo-heads)))
12048 (or (car (cdr (member head org-todo-heads)))
12049 (car org-todo-heads))))
12050 ((car (member arg org-todo-keywords-1)))
12051 ((stringp arg)
12052 (error "State `%s' not valid in this file" arg))
12053 ((nth (1- (prefix-numeric-value arg))
12054 org-todo-keywords-1))))
12055 ((null member) (or head (car org-todo-keywords-1)))
12056 ((equal this final-done-word) nil) ;; -> make empty
12057 ((null tail) nil) ;; -> first entry
12058 ((memq interpret '(type priority))
12059 (if (eq this-command last-command)
12060 (car tail)
12061 (if (> (length tail) 0)
12062 (or done-word (car org-done-keywords))
12063 nil)))
12065 (car tail))))
12066 (org-state (or
12067 (run-hook-with-args-until-success
12068 'org-todo-get-default-hook org-state org-last-state)
12069 org-state))
12070 (next (if org-state (concat " " org-state " ") " "))
12071 (change-plist (list :type 'todo-state-change :from this :to org-state
12072 :position startpos))
12073 dolog now-done-p)
12074 (when org-blocker-hook
12075 (setq org-last-todo-state-is-todo
12076 (not (member this org-done-keywords)))
12077 (unless (save-excursion
12078 (save-match-data
12079 (org-with-wide-buffer
12080 (run-hook-with-args-until-failure
12081 'org-blocker-hook change-plist))))
12082 (if (org-called-interactively-p 'interactive)
12083 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12084 this org-state org-block-entry-blocking)
12085 ;; fail silently
12086 (message "TODO state change from %s to %s blocked (by \"%s\")"
12087 this org-state org-block-entry-blocking)
12088 (throw 'exit nil))))
12089 (store-match-data match-data)
12090 (replace-match next t t)
12091 (unless (pos-visible-in-window-p hl-pos)
12092 (message "TODO state changed to %s" (org-trim next)))
12093 (unless head
12094 (setq head (org-get-todo-sequence-head org-state)
12095 ass (assoc head org-todo-kwd-alist)
12096 interpret (nth 1 ass)
12097 done-word (nth 3 ass)
12098 final-done-word (nth 4 ass)))
12099 (when (memq arg '(nextset previousset))
12100 (message "Keyword-Set %d/%d: %s"
12101 (- (length org-todo-sets) -1
12102 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12103 (length org-todo-sets)
12104 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12105 (setq org-last-todo-state-is-todo
12106 (not (member org-state org-done-keywords)))
12107 (setq now-done-p (and (member org-state org-done-keywords)
12108 (not (member this org-done-keywords))))
12109 (and logging (org-local-logging logging))
12110 (when (and (or org-todo-log-states org-log-done)
12111 (not (eq org-inhibit-logging t))
12112 (not (memq arg '(nextset previousset))))
12113 ;; we need to look at recording a time and note
12114 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12115 (nth 2 (assoc this org-todo-log-states))))
12116 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12117 (setq dolog 'time))
12118 (when (and org-state
12119 (member org-state org-not-done-keywords)
12120 (not (member this org-not-done-keywords)))
12121 ;; This is now a todo state and was not one before
12122 ;; If there was a CLOSED time stamp, get rid of it.
12123 (org-add-planning-info nil nil 'closed))
12124 (when (and now-done-p org-log-done)
12125 ;; It is now done, and it was not done before
12126 (org-add-planning-info 'closed (org-current-effective-time))
12127 (if (and (not dolog) (eq 'note org-log-done))
12128 (org-add-log-setup 'done org-state this 'findpos 'note)))
12129 (when (and org-state dolog)
12130 ;; This is a non-nil state, and we need to log it
12131 (org-add-log-setup 'state org-state this 'findpos dolog)))
12132 ;; Fixup tag positioning
12133 (org-todo-trigger-tag-changes org-state)
12134 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12135 (when org-provide-todo-statistics
12136 (org-update-parent-todo-statistics))
12137 (run-hooks 'org-after-todo-state-change-hook)
12138 (if (and arg (not (member org-state org-done-keywords)))
12139 (setq head (org-get-todo-sequence-head org-state)))
12140 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12141 ;; Do we need to trigger a repeat?
12142 (when now-done-p
12143 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12144 ;; This is for the agenda, take a snapshot of the headline.
12145 (save-match-data
12146 (setq org-agenda-headline-snapshot-before-repeat
12147 (org-get-heading))))
12148 (org-auto-repeat-maybe org-state))
12149 ;; Fixup cursor location if close to the keyword
12150 (if (and (outline-on-heading-p)
12151 (not (bolp))
12152 (save-excursion (beginning-of-line 1)
12153 (looking-at org-todo-line-regexp))
12154 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12155 (progn
12156 (goto-char (or (match-end 2) (match-end 1)))
12157 (and (looking-at " ") (just-one-space))))
12158 (when org-trigger-hook
12159 (save-excursion
12160 (run-hook-with-args 'org-trigger-hook change-plist)))
12161 (when commentp (org-toggle-comment))))))))
12163 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12164 "Block turning an entry into a TODO, using the hierarchy.
12165 This checks whether the current task should be blocked from state
12166 changes. Such blocking occurs when:
12168 1. The task has children which are not all in a completed state.
12170 2. A task has a parent with the property :ORDERED:, and there
12171 are siblings prior to the current task with incomplete
12172 status.
12174 3. The parent of the task is blocked because it has siblings that should
12175 be done first, or is child of a block grandparent TODO entry."
12177 (if (not org-enforce-todo-dependencies)
12178 t ; if locally turned off don't block
12179 (catch 'dont-block
12180 ;; If this is not a todo state change, or if this entry is already DONE,
12181 ;; do not block
12182 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12183 (member (plist-get change-plist :from)
12184 (cons 'done org-done-keywords))
12185 (member (plist-get change-plist :to)
12186 (cons 'todo org-not-done-keywords))
12187 (not (plist-get change-plist :to)))
12188 (throw 'dont-block t))
12189 ;; If this task has children, and any are undone, it's blocked
12190 (save-excursion
12191 (org-back-to-heading t)
12192 (let ((this-level (funcall outline-level)))
12193 (outline-next-heading)
12194 (let ((child-level (funcall outline-level)))
12195 (while (and (not (eobp))
12196 (> child-level this-level))
12197 ;; this todo has children, check whether they are all
12198 ;; completed
12199 (if (and (not (org-entry-is-done-p))
12200 (org-entry-is-todo-p))
12201 (progn (setq org-block-entry-blocking (org-get-heading))
12202 (throw 'dont-block nil)))
12203 (outline-next-heading)
12204 (setq child-level (funcall outline-level))))))
12205 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12206 ;; any previous siblings are undone, it's blocked
12207 (save-excursion
12208 (org-back-to-heading t)
12209 (let* ((pos (point))
12210 (parent-pos (and (org-up-heading-safe) (point))))
12211 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12212 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12213 (forward-line 1)
12214 (re-search-forward org-not-done-heading-regexp pos t))
12215 (setq org-block-entry-blocking (match-string 0))
12216 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12217 ;; Search further up the hierarchy, to see if an ancestor is blocked
12218 (while t
12219 (goto-char parent-pos)
12220 (if (not (looking-at org-not-done-heading-regexp))
12221 (throw 'dont-block t)) ; do not block, parent is not a TODO
12222 (setq pos (point))
12223 (setq parent-pos (and (org-up-heading-safe) (point)))
12224 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12225 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12226 (forward-line 1)
12227 (re-search-forward org-not-done-heading-regexp pos t)
12228 (setq org-block-entry-blocking (org-get-heading)))
12229 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12231 (defcustom org-track-ordered-property-with-tag nil
12232 "Should the ORDERED property also be shown as a tag?
12233 The ORDERED property decides if an entry should require subtasks to be
12234 completed in sequence. Since a property is not very visible, setting
12235 this option means that toggling the ORDERED property with the command
12236 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12237 not relevant for the behavior, but it makes things more visible.
12239 Note that toggling the tag with tags commands will not change the property
12240 and therefore not influence behavior!
12242 This can be t, meaning the tag ORDERED should be used, It can also be a
12243 string to select a different tag for this task."
12244 :group 'org-todo
12245 :type '(choice
12246 (const :tag "No tracking" nil)
12247 (const :tag "Track with ORDERED tag" t)
12248 (string :tag "Use other tag")))
12250 (defun org-toggle-ordered-property ()
12251 "Toggle the ORDERED property of the current entry.
12252 For better visibility, you can track the value of this property with a tag.
12253 See variable `org-track-ordered-property-with-tag'."
12254 (interactive)
12255 (let* ((t1 org-track-ordered-property-with-tag)
12256 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12257 (save-excursion
12258 (org-back-to-heading)
12259 (if (org-entry-get nil "ORDERED")
12260 (progn
12261 (org-delete-property "ORDERED" "PROPERTIES")
12262 (and tag (org-toggle-tag tag 'off))
12263 (message "Subtasks can be completed in arbitrary order"))
12264 (org-entry-put nil "ORDERED" "t")
12265 (and tag (org-toggle-tag tag 'on))
12266 (message "Subtasks must be completed in sequence")))))
12268 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12269 (defun org-block-todo-from-checkboxes (change-plist)
12270 "Block turning an entry into a TODO, using checkboxes.
12271 This checks whether the current task should be blocked from state
12272 changes because there are unchecked boxes in this entry."
12273 (if (not org-enforce-todo-checkbox-dependencies)
12274 t ; if locally turned off don't block
12275 (catch 'dont-block
12276 ;; If this is not a todo state change, or if this entry is already DONE,
12277 ;; do not block
12278 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12279 (member (plist-get change-plist :from)
12280 (cons 'done org-done-keywords))
12281 (member (plist-get change-plist :to)
12282 (cons 'todo org-not-done-keywords))
12283 (not (plist-get change-plist :to)))
12284 (throw 'dont-block t))
12285 ;; If this task has checkboxes that are not checked, it's blocked
12286 (save-excursion
12287 (org-back-to-heading t)
12288 (let ((beg (point)) end)
12289 (outline-next-heading)
12290 (setq end (point))
12291 (goto-char beg)
12292 (if (org-list-search-forward
12293 (concat (org-item-beginning-re)
12294 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12295 "\\[[- ]\\]")
12296 end t)
12297 (progn
12298 (if (boundp 'org-blocked-by-checkboxes)
12299 (setq org-blocked-by-checkboxes t))
12300 (throw 'dont-block nil)))))
12301 t))) ; do not block
12303 (defun org-entry-blocked-p ()
12304 "Is the current entry blocked?"
12305 (org-with-silent-modifications
12306 (if (org-entry-get nil "NOBLOCKING")
12307 nil ;; Never block this entry
12308 (not (run-hook-with-args-until-failure
12309 'org-blocker-hook
12310 (list :type 'todo-state-change
12311 :position (point)
12312 :from 'todo
12313 :to 'done))))))
12315 (defun org-update-statistics-cookies (all)
12316 "Update the statistics cookie, either from TODO or from checkboxes.
12317 This should be called with the cursor in a line with a statistics cookie."
12318 (interactive "P")
12319 (if all
12320 (progn
12321 (org-update-checkbox-count 'all)
12322 (org-map-entries 'org-update-parent-todo-statistics))
12323 (if (not (org-at-heading-p))
12324 (org-update-checkbox-count)
12325 (let ((pos (point-marker))
12326 end l1 l2)
12327 (ignore-errors (org-back-to-heading t))
12328 (if (not (org-at-heading-p))
12329 (org-update-checkbox-count)
12330 (setq l1 (org-outline-level))
12331 (setq end (save-excursion
12332 (outline-next-heading)
12333 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12334 (point)))
12335 (if (and (save-excursion
12336 (re-search-forward
12337 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12338 (not (save-excursion (re-search-forward
12339 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12340 (org-update-checkbox-count)
12341 (if (and l2 (> l2 l1))
12342 (progn
12343 (goto-char end)
12344 (org-update-parent-todo-statistics))
12345 (goto-char pos)
12346 (beginning-of-line 1)
12347 (while (re-search-forward
12348 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12349 (point-at-eol) t)
12350 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12351 (goto-char pos)
12352 (move-marker pos nil)))))
12354 (defvar org-entry-property-inherited-from) ;; defined below
12355 (defun org-update-parent-todo-statistics ()
12356 "Update any statistics cookie in the parent of the current headline.
12357 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12358 the entire subtree and this will travel up the hierarchy and update
12359 statistics everywhere."
12360 (let* ((prop (save-excursion (org-up-heading-safe)
12361 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12362 (recursive (or (not org-hierarchical-todo-statistics)
12363 (and prop (string-match "\\<recursive\\>" prop))))
12364 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12366 (first t)
12367 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12368 level ltoggle l1 new ndel
12369 (cnt-all 0) (cnt-done 0) is-percent kwd
12370 checkbox-beg ov ovs ove cookie-present)
12371 (catch 'exit
12372 (save-excursion
12373 (beginning-of-line 1)
12374 (setq ltoggle (funcall outline-level))
12375 ;; Three situations are to consider:
12377 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12378 ;; to the top-level ancestor on the headline;
12380 ;; 2. If parent has "recursive" property, repeat up to the
12381 ;; headline setting that property, taking inheritance into
12382 ;; account;
12384 ;; 3. Else, move up to direct parent and proceed only once.
12385 (while (and (setq level (org-up-heading-safe))
12386 (or recursive first)
12387 (>= (point) lim))
12388 (setq first nil cookie-present nil)
12389 (unless (and level
12390 (not (string-match
12391 "\\<checkbox\\>"
12392 (downcase (or (org-entry-get nil "COOKIE_DATA")
12393 "")))))
12394 (throw 'exit nil))
12395 (while (re-search-forward box-re (point-at-eol) t)
12396 (setq cnt-all 0 cnt-done 0 cookie-present t)
12397 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12398 (save-match-data
12399 (unless (outline-next-heading) (throw 'exit nil))
12400 (while (and (looking-at org-complex-heading-regexp)
12401 (> (setq l1 (length (match-string 1))) level))
12402 (setq kwd (and (or recursive (= l1 ltoggle))
12403 (match-string 2)))
12404 (if (or (eq org-provide-todo-statistics 'all-headlines)
12405 (and (listp org-provide-todo-statistics)
12406 (or (member kwd org-provide-todo-statistics)
12407 (member kwd org-done-keywords))))
12408 (setq cnt-all (1+ cnt-all))
12409 (if (eq org-provide-todo-statistics t)
12410 (and kwd (setq cnt-all (1+ cnt-all)))))
12411 (and (member kwd org-done-keywords)
12412 (setq cnt-done (1+ cnt-done)))
12413 (outline-next-heading)))
12414 (setq new
12415 (if is-percent
12416 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12417 (format "[%d/%d]" cnt-done cnt-all))
12418 ndel (- (match-end 0) checkbox-beg))
12419 ;; handle overlays when updating cookie from column view
12420 (when (setq ov (car (overlays-at checkbox-beg)))
12421 (setq ovs (overlay-start ov) ove (overlay-end ov))
12422 (delete-overlay ov))
12423 (goto-char checkbox-beg)
12424 (insert new)
12425 (delete-region (point) (+ (point) ndel))
12426 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12427 (when ov (move-overlay ov ovs ove)))
12428 (when cookie-present
12429 (run-hook-with-args 'org-after-todo-statistics-hook
12430 cnt-done (- cnt-all cnt-done))))))
12431 (run-hooks 'org-todo-statistics-hook)))
12433 (defvar org-after-todo-statistics-hook nil
12434 "Hook that is called after a TODO statistics cookie has been updated.
12435 Each function is called with two arguments: the number of not-done entries
12436 and the number of done entries.
12438 For example, the following function, when added to this hook, will switch
12439 an entry to DONE when all children are done, and back to TODO when new
12440 entries are set to a TODO status. Note that this hook is only called
12441 when there is a statistics cookie in the headline!
12443 (defun org-summary-todo (n-done n-not-done)
12444 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12445 (let (org-log-done org-log-states) ; turn off logging
12446 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12449 (defvar org-todo-statistics-hook nil
12450 "Hook that is run whenever Org thinks TODO statistics should be updated.
12451 This hook runs even if there is no statistics cookie present, in which case
12452 `org-after-todo-statistics-hook' would not run.")
12454 (defun org-todo-trigger-tag-changes (state)
12455 "Apply the changes defined in `org-todo-state-tags-triggers'."
12456 (let ((l org-todo-state-tags-triggers)
12457 changes)
12458 (when (or (not state) (equal state ""))
12459 (setq changes (append changes (cdr (assoc "" l)))))
12460 (when (and (stringp state) (> (length state) 0))
12461 (setq changes (append changes (cdr (assoc state l)))))
12462 (when (member state org-not-done-keywords)
12463 (setq changes (append changes (cdr (assoc 'todo l)))))
12464 (when (member state org-done-keywords)
12465 (setq changes (append changes (cdr (assoc 'done l)))))
12466 (dolist (c changes)
12467 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12469 (defun org-local-logging (value)
12470 "Get logging settings from a property VALUE."
12471 (let* (words w a)
12472 ;; directly set the variables, they are already local.
12473 (setq org-log-done nil
12474 org-log-repeat nil
12475 org-todo-log-states nil)
12476 (setq words (org-split-string value))
12477 (while (setq w (pop words))
12478 (cond
12479 ((setq a (assoc w org-startup-options))
12480 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12481 (set (nth 1 a) (nth 2 a))))
12482 ((setq a (org-extract-log-state-settings w))
12483 (and (member (car a) org-todo-keywords-1)
12484 (push a org-todo-log-states)))))))
12486 (defun org-get-todo-sequence-head (kwd)
12487 "Return the head of the TODO sequence to which KWD belongs.
12488 If KWD is not set, check if there is a text property remembering the
12489 right sequence."
12490 (let (p)
12491 (cond
12492 ((not kwd)
12493 (or (get-text-property (point-at-bol) 'org-todo-head)
12494 (progn
12495 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12496 nil (point-at-eol)))
12497 (get-text-property p 'org-todo-head))))
12498 ((not (member kwd org-todo-keywords-1))
12499 (car org-todo-keywords-1))
12500 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12502 (defun org-fast-todo-selection ()
12503 "Fast TODO keyword selection with single keys.
12504 Returns the new TODO keyword, or nil if no state change should occur."
12505 (let* ((fulltable org-todo-key-alist)
12506 (done-keywords org-done-keywords) ;; needed for the faces.
12507 (maxlen (apply 'max (mapcar
12508 (lambda (x)
12509 (if (stringp (car x)) (string-width (car x)) 0))
12510 fulltable)))
12511 (expert nil)
12512 (fwidth (+ maxlen 3 1 3))
12513 (ncol (/ (- (window-width) 4) fwidth))
12514 tg cnt e c tbl
12515 groups ingroup)
12516 (save-excursion
12517 (save-window-excursion
12518 (if expert
12519 (set-buffer (get-buffer-create " *Org todo*"))
12520 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12521 (erase-buffer)
12522 (org-set-local 'org-done-keywords done-keywords)
12523 (setq tbl fulltable cnt 0)
12524 (while (setq e (pop tbl))
12525 (cond
12526 ((equal e '(:startgroup))
12527 (push '() groups) (setq ingroup t)
12528 (when (not (= cnt 0))
12529 (setq cnt 0)
12530 (insert "\n"))
12531 (insert "{ "))
12532 ((equal e '(:endgroup))
12533 (setq ingroup nil cnt 0)
12534 (insert "}\n"))
12535 ((equal e '(:newline))
12536 (when (not (= cnt 0))
12537 (setq cnt 0)
12538 (insert "\n")
12539 (setq e (car tbl))
12540 (while (equal (car tbl) '(:newline))
12541 (insert "\n")
12542 (setq tbl (cdr tbl)))))
12544 (setq tg (car e) c (cdr e))
12545 (if ingroup (push tg (car groups)))
12546 (setq tg (org-add-props tg nil 'face
12547 (org-get-todo-face tg)))
12548 (if (and (= cnt 0) (not ingroup)) (insert " "))
12549 (insert "[" c "] " tg (make-string
12550 (- fwidth 4 (length tg)) ?\ ))
12551 (when (= (setq cnt (1+ cnt)) ncol)
12552 (insert "\n")
12553 (if ingroup (insert " "))
12554 (setq cnt 0)))))
12555 (insert "\n")
12556 (goto-char (point-min))
12557 (if (not expert) (org-fit-window-to-buffer))
12558 (message "[a-z..]:Set [SPC]:clear")
12559 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12560 (cond
12561 ((or (= c ?\C-g)
12562 (and (= c ?q) (not (rassoc c fulltable))))
12563 (setq quit-flag t))
12564 ((= c ?\ ) nil)
12565 ((setq e (rassoc c fulltable) tg (car e))
12567 (t (setq quit-flag t)))))))
12569 (defun org-entry-is-todo-p ()
12570 (member (org-get-todo-state) org-not-done-keywords))
12572 (defun org-entry-is-done-p ()
12573 (member (org-get-todo-state) org-done-keywords))
12575 (defun org-get-todo-state ()
12576 (save-excursion
12577 (org-back-to-heading t)
12578 (and (looking-at org-todo-line-regexp)
12579 (match-end 2)
12580 (match-string 2))))
12582 (defun org-at-date-range-p (&optional inactive-ok)
12583 "Is the cursor inside a date range?"
12584 (interactive)
12585 (save-excursion
12586 (catch 'exit
12587 (let ((pos (point)))
12588 (skip-chars-backward "^[<\r\n")
12589 (skip-chars-backward "<[")
12590 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12591 (>= (match-end 0) pos)
12592 (throw 'exit t))
12593 (skip-chars-backward "^<[\r\n")
12594 (skip-chars-backward "<[")
12595 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12596 (>= (match-end 0) pos)
12597 (throw 'exit t)))
12598 nil)))
12600 (defun org-get-repeat (&optional tagline)
12601 "Check if there is a deadline/schedule with repeater in this entry."
12602 (save-match-data
12603 (save-excursion
12604 (org-back-to-heading t)
12605 (and (re-search-forward (if tagline
12606 (concat tagline "\\s-*" org-repeat-re)
12607 org-repeat-re)
12608 (org-entry-end-position) t)
12609 (match-string-no-properties 1)))))
12611 (defvar org-last-changed-timestamp)
12612 (defvar org-last-inserted-timestamp)
12613 (defvar org-log-post-message)
12614 (defvar org-log-note-purpose)
12615 (defvar org-log-note-how)
12616 (defvar org-log-note-extra)
12617 (defun org-auto-repeat-maybe (done-word)
12618 "Check if the current headline contains a repeated deadline/schedule.
12619 If yes, set TODO state back to what it was and change the base date
12620 of repeating deadline/scheduled time stamps to new date.
12621 This function is run automatically after each state change to a DONE state."
12622 ;; last-state is dynamically scoped into this function
12623 (let* ((repeat (org-get-repeat))
12624 (aa (assoc org-last-state org-todo-kwd-alist))
12625 (interpret (nth 1 aa))
12626 (head (nth 2 aa))
12627 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12628 (msg "Entry repeats: ")
12629 (org-log-done nil)
12630 (org-todo-log-states nil)
12631 re type n what ts time to-state)
12632 (when repeat
12633 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12634 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12635 org-todo-repeat-to-state))
12636 (unless (and to-state (member to-state org-todo-keywords-1))
12637 (setq to-state (if (eq interpret 'type) org-last-state head)))
12638 (org-todo to-state)
12639 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12640 (org-entry-put nil "LAST_REPEAT" (format-time-string
12641 (org-time-stamp-format t t))))
12642 (when org-log-repeat
12643 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12644 (memq 'org-add-log-note post-command-hook))
12645 ;; OK, we are already setup for some record
12646 (if (eq org-log-repeat 'note)
12647 ;; make sure we take a note, not only a time stamp
12648 (setq org-log-note-how 'note))
12649 ;; Set up for taking a record
12650 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12651 org-last-state
12652 'findpos org-log-repeat)))
12653 (org-back-to-heading t)
12654 (org-add-planning-info nil nil 'closed)
12655 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12656 org-deadline-time-regexp "\\)\\|\\("
12657 org-ts-regexp "\\)"))
12658 (while (re-search-forward
12659 re (save-excursion (outline-next-heading) (point)) t)
12660 (setq type (if (match-end 1) org-scheduled-string
12661 (if (match-end 3) org-deadline-string "Plain:"))
12662 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12663 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12664 (setq n (string-to-number (match-string 2 ts))
12665 what (match-string 3 ts))
12666 (if (equal what "w") (setq n (* n 7) what "d"))
12667 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12668 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12669 ;; Preparation, see if we need to modify the start date for the change
12670 (when (match-end 1)
12671 (setq time (save-match-data (org-time-string-to-time ts)))
12672 (cond
12673 ((equal (match-string 1 ts) ".")
12674 ;; Shift starting date to today
12675 (org-timestamp-change
12676 (- (org-today) (time-to-days time))
12677 'day))
12678 ((equal (match-string 1 ts) "+")
12679 (let ((nshiftmax 10) (nshift 0))
12680 (while (or (= nshift 0)
12681 (<= (time-to-days time)
12682 (time-to-days (current-time))))
12683 (when (= (incf nshift) nshiftmax)
12684 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12685 (error "Abort")))
12686 (org-timestamp-change n (cdr (assoc what whata)))
12687 (org-at-timestamp-p t)
12688 (setq ts (match-string 1))
12689 (setq time (save-match-data (org-time-string-to-time ts)))))
12690 (org-timestamp-change (- n) (cdr (assoc what whata)))
12691 ;; rematch, so that we have everything in place for the real shift
12692 (org-at-timestamp-p t)
12693 (setq ts (match-string 1))
12694 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12695 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12696 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12697 (setq org-log-post-message msg)
12698 (message "%s" msg))))
12700 (defun org-show-todo-tree (arg)
12701 "Make a compact tree which shows all headlines marked with TODO.
12702 The tree will show the lines where the regexp matches, and all higher
12703 headlines above the match.
12704 With a \\[universal-argument] prefix, prompt for a regexp to match.
12705 With a numeric prefix N, construct a sparse tree for the Nth element
12706 of `org-todo-keywords-1'."
12707 (interactive "P")
12708 (let ((case-fold-search nil)
12709 (kwd-re
12710 (cond ((null arg) org-not-done-regexp)
12711 ((equal arg '(4))
12712 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12713 (mapcar 'list org-todo-keywords-1))))
12714 (concat "\\("
12715 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12716 "\\)\\>")))
12717 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12718 (regexp-quote (nth (1- (prefix-numeric-value arg))
12719 org-todo-keywords-1)))
12720 (t (error "Invalid prefix argument: %s" arg)))))
12721 (message "%d TODO entries found"
12722 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12724 (defun org-deadline (arg &optional time)
12725 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12726 With one universal prefix argument, remove any deadline from the item.
12727 With two universal prefix arguments, prompt for a warning delay.
12728 With argument TIME, set the deadline at the corresponding date. TIME
12729 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12730 (interactive "P")
12731 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12732 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12733 'region-start-level 'region))
12734 org-loop-over-headlines-in-active-region)
12735 (org-map-entries
12736 `(org-deadline ',arg ,time)
12737 org-loop-over-headlines-in-active-region
12738 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12739 (let* ((old-date (org-entry-get nil "DEADLINE"))
12740 (old-date-time (if old-date (org-time-string-to-time old-date)))
12741 (repeater (and old-date
12742 (string-match
12743 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12744 old-date)
12745 (match-string 1 old-date))))
12746 (cond
12747 ((equal arg '(4))
12748 (when (and old-date org-log-redeadline)
12749 (org-add-log-setup 'deldeadline nil old-date 'findpos
12750 org-log-redeadline))
12751 (org-remove-timestamp-with-keyword org-deadline-string)
12752 (message "Item no longer has a deadline."))
12753 ((equal arg '(16))
12754 (save-excursion
12755 (if (re-search-forward
12756 org-deadline-time-regexp
12757 (save-excursion (outline-next-heading) (point)) t)
12758 (let* ((rpl0 (match-string 1))
12759 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12760 (replace-match
12761 (concat org-deadline-string
12762 " <" rpl
12763 (format " -%dd"
12764 (abs
12765 (- (time-to-days
12766 (save-match-data
12767 (org-read-date nil t nil "Warn starting from" old-date-time)))
12768 (time-to-days old-date-time))))
12769 ">") t t))
12770 (user-error "No deadline information to update"))))
12772 (org-add-planning-info 'deadline time 'closed)
12773 (when (and old-date org-log-redeadline
12774 (not (equal old-date
12775 (substring org-last-inserted-timestamp 1 -1))))
12776 (org-add-log-setup 'redeadline nil old-date 'findpos
12777 org-log-redeadline))
12778 (when repeater
12779 (save-excursion
12780 (org-back-to-heading t)
12781 (when (re-search-forward (concat org-deadline-string " "
12782 org-last-inserted-timestamp)
12783 (save-excursion
12784 (outline-next-heading) (point)) t)
12785 (goto-char (1- (match-end 0)))
12786 (insert " " repeater)
12787 (setq org-last-inserted-timestamp
12788 (concat (substring org-last-inserted-timestamp 0 -1)
12789 " " repeater
12790 (substring org-last-inserted-timestamp -1))))))
12791 (message "Deadline on %s" org-last-inserted-timestamp))))))
12793 (defun org-schedule (arg &optional time)
12794 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12795 With one universal prefix argument, remove any scheduling date from the item.
12796 With two universal prefix arguments, prompt for a delay cookie.
12797 With argument TIME, scheduled at the corresponding date. TIME can
12798 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12799 (interactive "P")
12800 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12801 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12802 'region-start-level 'region))
12803 org-loop-over-headlines-in-active-region)
12804 (org-map-entries
12805 `(org-schedule ',arg ,time)
12806 org-loop-over-headlines-in-active-region
12807 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12808 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12809 (old-date-time (if old-date (org-time-string-to-time old-date)))
12810 (repeater (and old-date
12811 (string-match
12812 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12813 old-date)
12814 (match-string 1 old-date))))
12815 (cond
12816 ((equal arg '(4))
12817 (progn
12818 (when (and old-date org-log-reschedule)
12819 (org-add-log-setup 'delschedule nil old-date 'findpos
12820 org-log-reschedule))
12821 (org-remove-timestamp-with-keyword org-scheduled-string)
12822 (message "Item is no longer scheduled.")))
12823 ((equal arg '(16))
12824 (save-excursion
12825 (if (re-search-forward
12826 org-scheduled-time-regexp
12827 (save-excursion (outline-next-heading) (point)) t)
12828 (let* ((rpl0 (match-string 1))
12829 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12830 (replace-match
12831 (concat org-scheduled-string
12832 " <" rpl
12833 (format " -%dd"
12834 (abs
12835 (- (time-to-days
12836 (save-match-data
12837 (org-read-date nil t nil "Delay until" old-date-time)))
12838 (time-to-days old-date-time))))
12839 ">") t t))
12840 (user-error "No scheduled information to update"))))
12842 (org-add-planning-info 'scheduled time 'closed)
12843 (when (and old-date org-log-reschedule
12844 (not (equal old-date
12845 (substring org-last-inserted-timestamp 1 -1))))
12846 (org-add-log-setup 'reschedule nil old-date 'findpos
12847 org-log-reschedule))
12848 (when repeater
12849 (save-excursion
12850 (org-back-to-heading t)
12851 (when (re-search-forward (concat org-scheduled-string " "
12852 org-last-inserted-timestamp)
12853 (save-excursion
12854 (outline-next-heading) (point)) t)
12855 (goto-char (1- (match-end 0)))
12856 (insert " " repeater)
12857 (setq org-last-inserted-timestamp
12858 (concat (substring org-last-inserted-timestamp 0 -1)
12859 " " repeater
12860 (substring org-last-inserted-timestamp -1))))))
12861 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12863 (defun org-get-scheduled-time (pom &optional inherit)
12864 "Get the scheduled time as a time tuple, of a format suitable
12865 for calling org-schedule with, or if there is no scheduling,
12866 returns nil."
12867 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12868 (when time
12869 (apply 'encode-time (org-parse-time-string time)))))
12871 (defun org-get-deadline-time (pom &optional inherit)
12872 "Get the deadline as a time tuple, of a format suitable for
12873 calling org-deadline with, or if there is no scheduling, returns
12874 nil."
12875 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12876 (when time
12877 (apply 'encode-time (org-parse-time-string time)))))
12879 (defun org-remove-timestamp-with-keyword (keyword)
12880 "Remove all time stamps with KEYWORD in the current entry."
12881 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12882 beg)
12883 (save-excursion
12884 (org-back-to-heading t)
12885 (setq beg (point))
12886 (outline-next-heading)
12887 (while (re-search-backward re beg t)
12888 (replace-match "")
12889 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12890 (equal (char-before) ?\ ))
12891 (backward-delete-char 1)
12892 (if (string-match "^[ \t]*$" (buffer-substring
12893 (point-at-bol) (point-at-eol)))
12894 (delete-region (point-at-bol)
12895 (min (point-max) (1+ (point-at-eol))))))))))
12897 (defun org-add-planning-info (what &optional time &rest remove)
12898 "Insert new timestamp with keyword in the line directly after the headline.
12899 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12900 If non is given, the user is prompted for a date.
12901 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12902 be removed."
12903 (interactive)
12904 (let (org-time-was-given org-end-time-was-given ts
12905 end default-time default-input)
12907 (catch 'exit
12908 (when (and (memq what '(scheduled deadline))
12909 (or (not time)
12910 (and (stringp time)
12911 (string-match "^[-+]+[0-9]" time))))
12912 ;; Try to get a default date/time from existing timestamp
12913 (save-excursion
12914 (org-back-to-heading t)
12915 (setq end (save-excursion (outline-next-heading) (point)))
12916 (when (re-search-forward (if (eq what 'scheduled)
12917 org-scheduled-time-regexp
12918 org-deadline-time-regexp)
12919 end t)
12920 (setq ts (match-string 1)
12921 default-time
12922 (apply 'encode-time (org-parse-time-string ts))
12923 default-input (and ts (org-get-compact-tod ts))))))
12924 (when what
12925 (setq time
12926 (if (stringp time)
12927 ;; This is a string (relative or absolute), set proper date
12928 (apply 'encode-time
12929 (org-read-date-analyze
12930 time default-time (decode-time default-time)))
12931 ;; If necessary, get the time from the user
12932 (or time (org-read-date nil 'to-time nil nil
12933 default-time default-input)))))
12935 (when (and org-insert-labeled-timestamps-at-point
12936 (member what '(scheduled deadline)))
12937 (insert
12938 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12939 (org-insert-time-stamp time org-time-was-given
12940 nil nil nil (list org-end-time-was-given))
12941 (setq what nil))
12942 (save-excursion
12943 (save-restriction
12944 (let (col list elt ts buffer-invisibility-spec)
12945 (org-back-to-heading t)
12946 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12947 (goto-char (match-end 1))
12948 (setq col (current-column))
12949 (goto-char (match-end 0))
12950 (if (eobp) (insert "\n") (forward-char 1))
12951 (when (and (not what)
12952 (not (looking-at
12953 (concat "[ \t]*"
12954 org-keyword-time-not-clock-regexp))))
12955 ;; Nothing to add, nothing to remove...... :-)
12956 (throw 'exit nil))
12957 (if (and (not (looking-at org-outline-regexp))
12958 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12959 "[^\r\n]*"))
12960 (not (equal (match-string 1) org-clock-string)))
12961 (narrow-to-region (match-beginning 0) (match-end 0))
12962 (insert-before-markers "\n")
12963 (backward-char 1)
12964 (narrow-to-region (point) (point))
12965 (and org-adapt-indentation (org-indent-to-column col)))
12966 ;; Check if we have to remove something.
12967 (setq list (cons what remove))
12968 (while list
12969 (setq elt (pop list))
12970 (when (or (and (eq elt 'scheduled)
12971 (re-search-forward org-scheduled-time-regexp nil t))
12972 (and (eq elt 'deadline)
12973 (re-search-forward org-deadline-time-regexp nil t))
12974 (and (eq elt 'closed)
12975 (re-search-forward org-closed-time-regexp nil t)))
12976 (replace-match "")
12977 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12978 (and (looking-at "[ \t]+") (replace-match ""))
12979 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12980 (when what
12981 (insert
12982 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12983 (cond ((eq what 'scheduled) org-scheduled-string)
12984 ((eq what 'deadline) org-deadline-string)
12985 ((eq what 'closed) org-closed-string))
12986 " ")
12987 (setq ts (org-insert-time-stamp
12988 time
12989 (or org-time-was-given
12990 (and (eq what 'closed) org-log-done-with-time))
12991 (eq what 'closed)
12992 nil nil (list org-end-time-was-given)))
12993 (insert
12994 (if (not (or (bolp) (eq (char-before) ?\ )
12995 (memq (char-after) '(32 10))
12996 (eobp))) " " ""))
12997 (end-of-line 1))
12998 (goto-char (point-min))
12999 (widen)
13000 (if (and (looking-at "[ \t]*\n")
13001 (equal (char-before) ?\n))
13002 (delete-region (1- (point)) (point-at-eol)))
13003 ts))))))
13005 (defvar org-log-note-marker (make-marker))
13006 (defvar org-log-note-purpose nil)
13007 (defvar org-log-note-state nil)
13008 (defvar org-log-note-previous-state nil)
13009 (defvar org-log-note-how nil)
13010 (defvar org-log-note-extra nil)
13011 (defvar org-log-note-window-configuration nil)
13012 (defvar org-log-note-return-to (make-marker))
13013 (defvar org-log-note-effective-time nil
13014 "Remembered current time so that dynamically scoped
13015 `org-extend-today-until' affects tha timestamps in state change
13016 log")
13018 (defvar org-log-post-message nil
13019 "Message to be displayed after a log note has been stored.
13020 The auto-repeater uses this.")
13022 (defun org-add-note ()
13023 "Add a note to the current entry.
13024 This is done in the same way as adding a state change note."
13025 (interactive)
13026 (org-add-log-setup 'note nil nil 'findpos nil))
13028 (defvar org-property-end-re)
13029 (defun org-add-log-setup (&optional purpose state prev-state
13030 findpos how extra)
13031 "Set up the post command hook to take a note.
13032 If this is about to TODO state change, the new state is expected in STATE.
13033 When FINDPOS is non-nil, find the correct position for the note in
13034 the current entry. If not, assume that it can be inserted at point.
13035 HOW is an indicator what kind of note should be created.
13036 EXTRA is additional text that will be inserted into the notes buffer."
13037 (let* ((org-log-into-drawer (org-log-into-drawer))
13038 (drawer (cond ((stringp org-log-into-drawer)
13039 org-log-into-drawer)
13040 (org-log-into-drawer "LOGBOOK"))))
13041 (save-restriction
13042 (save-excursion
13043 (when findpos
13044 (org-back-to-heading t)
13045 (narrow-to-region (point) (save-excursion
13046 (outline-next-heading) (point)))
13047 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13048 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13049 "[^\r\n]*\\)?"))
13050 (goto-char (match-end 0))
13051 (cond
13052 (drawer
13053 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13054 nil t)
13055 (progn
13056 (goto-char (match-end 0))
13057 (or org-log-states-order-reversed
13058 (and (re-search-forward org-property-end-re nil t)
13059 (goto-char (1- (match-beginning 0))))))
13060 (insert "\n:" drawer ":\n:END:")
13061 (beginning-of-line 0)
13062 (org-indent-line)
13063 (beginning-of-line 2)
13064 (org-indent-line)
13065 (end-of-line 0)))
13066 ((and org-log-state-notes-insert-after-drawers
13067 (save-excursion
13068 (forward-line) (looking-at org-drawer-regexp)))
13069 (forward-line)
13070 (while (looking-at org-drawer-regexp)
13071 (goto-char (match-end 0))
13072 (re-search-forward org-property-end-re (point-max) t)
13073 (forward-line))
13074 (forward-line -1)))
13075 (unless org-log-states-order-reversed
13076 (and (= (char-after) ?\n) (forward-char 1))
13077 (org-skip-over-state-notes)
13078 (skip-chars-backward " \t\n\r")))
13079 (move-marker org-log-note-marker (point))
13080 (setq org-log-note-purpose purpose
13081 org-log-note-state state
13082 org-log-note-previous-state prev-state
13083 org-log-note-how how
13084 org-log-note-extra extra
13085 org-log-note-effective-time (org-current-effective-time))
13086 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13088 (defun org-skip-over-state-notes ()
13089 "Skip past the list of State notes in an entry."
13090 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13091 (when (ignore-errors (goto-char (org-in-item-p)))
13092 (let* ((struct (org-list-struct))
13093 (prevs (org-list-prevs-alist struct)))
13094 (while (looking-at "[ \t]*- State")
13095 (goto-char (or (org-list-get-next-item (point) struct prevs)
13096 (org-list-get-item-end (point) struct)))))))
13098 (defun org-add-log-note (&optional purpose)
13099 "Pop up a window for taking a note, and add this note later at point."
13100 (remove-hook 'post-command-hook 'org-add-log-note)
13101 (setq org-log-note-window-configuration (current-window-configuration))
13102 (delete-other-windows)
13103 (move-marker org-log-note-return-to (point))
13104 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13105 (goto-char org-log-note-marker)
13106 (org-switch-to-buffer-other-window "*Org Note*")
13107 (erase-buffer)
13108 (if (memq org-log-note-how '(time state))
13109 (let (current-prefix-arg) (org-store-log-note))
13110 (let ((org-inhibit-startup t)) (org-mode))
13111 (insert (format "# Insert note for %s.
13112 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13113 (cond
13114 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13115 ((eq org-log-note-purpose 'done) "closed todo item")
13116 ((eq org-log-note-purpose 'state)
13117 (format "state change from \"%s\" to \"%s\""
13118 (or org-log-note-previous-state "")
13119 (or org-log-note-state "")))
13120 ((eq org-log-note-purpose 'reschedule)
13121 "rescheduling")
13122 ((eq org-log-note-purpose 'delschedule)
13123 "no longer scheduled")
13124 ((eq org-log-note-purpose 'redeadline)
13125 "changing deadline")
13126 ((eq org-log-note-purpose 'deldeadline)
13127 "removing deadline")
13128 ((eq org-log-note-purpose 'refile)
13129 "refiling")
13130 ((eq org-log-note-purpose 'note)
13131 "this entry")
13132 (t (error "This should not happen")))))
13133 (if org-log-note-extra (insert org-log-note-extra))
13134 (org-set-local 'org-finish-function 'org-store-log-note)
13135 (run-hooks 'org-log-buffer-setup-hook)))
13137 (defvar org-note-abort nil) ; dynamically scoped
13138 (defun org-store-log-note ()
13139 "Finish taking a log note, and insert it to where it belongs."
13140 (let ((txt (buffer-string)))
13141 (kill-buffer (current-buffer))
13142 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13143 lines ind bul)
13144 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13145 (setq txt (replace-match "" t t txt)))
13146 (if (string-match "\\s-+\\'" txt)
13147 (setq txt (replace-match "" t t txt)))
13148 (setq lines (org-split-string txt "\n"))
13149 (when (and note (string-match "\\S-" note))
13150 (setq note
13151 (org-replace-escapes
13152 note
13153 (list (cons "%u" (user-login-name))
13154 (cons "%U" user-full-name)
13155 (cons "%t" (format-time-string
13156 (org-time-stamp-format 'long 'inactive)
13157 org-log-note-effective-time))
13158 (cons "%T" (format-time-string
13159 (org-time-stamp-format 'long nil)
13160 org-log-note-effective-time))
13161 (cons "%d" (format-time-string
13162 (org-time-stamp-format nil 'inactive)
13163 org-log-note-effective-time))
13164 (cons "%D" (format-time-string
13165 (org-time-stamp-format nil nil)
13166 org-log-note-effective-time))
13167 (cons "%s" (if org-log-note-state
13168 (concat "\"" org-log-note-state "\"")
13169 ""))
13170 (cons "%S" (if org-log-note-previous-state
13171 (concat "\"" org-log-note-previous-state "\"")
13172 "\"\"")))))
13173 (if lines (setq note (concat note " \\\\")))
13174 (push note lines))
13175 (when (or current-prefix-arg org-note-abort)
13176 (when org-log-into-drawer
13177 (org-remove-empty-drawer-at
13178 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13179 org-log-note-marker))
13180 (setq lines nil))
13181 (when lines
13182 (with-current-buffer (marker-buffer org-log-note-marker)
13183 (save-excursion
13184 (goto-char org-log-note-marker)
13185 (move-marker org-log-note-marker nil)
13186 (end-of-line 1)
13187 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13188 (setq ind (save-excursion
13189 (if (ignore-errors (goto-char (org-in-item-p)))
13190 (let ((struct (org-list-struct)))
13191 (org-list-get-ind
13192 (org-list-get-top-point struct) struct))
13193 (skip-chars-backward " \r\t\n")
13194 (cond
13195 ((and (org-at-heading-p)
13196 org-adapt-indentation)
13197 (1+ (org-current-level)))
13198 ((org-at-heading-p) 0)
13199 (t (org-get-indentation))))))
13200 (setq bul (org-list-bullet-string "-"))
13201 (org-indent-line-to ind)
13202 (insert bul (pop lines))
13203 (let ((ind-body (+ (length bul) ind)))
13204 (while lines
13205 (insert "\n")
13206 (org-indent-line-to ind-body)
13207 (insert (pop lines))))
13208 (message "Note stored")
13209 (org-back-to-heading t)
13210 (org-cycle-hide-drawers 'children))))))
13211 (set-window-configuration org-log-note-window-configuration)
13212 (with-current-buffer (marker-buffer org-log-note-return-to)
13213 (goto-char org-log-note-return-to))
13214 (move-marker org-log-note-return-to nil)
13215 (and org-log-post-message (message "%s" org-log-post-message)))
13217 (defun org-remove-empty-drawer-at (drawer pos)
13218 "Remove an empty drawer DRAWER at position POS.
13219 POS may also be a marker."
13220 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13221 (save-excursion
13222 (save-restriction
13223 (widen)
13224 (goto-char pos)
13225 (if (org-in-regexp
13226 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13227 (replace-match ""))))))
13229 (defvar org-ts-type nil)
13230 (defun org-sparse-tree (&optional arg type)
13231 "Create a sparse tree, prompt for the details.
13232 This command can create sparse trees. You first need to select the type
13233 of match used to create the tree:
13235 t Show all TODO entries.
13236 T Show entries with a specific TODO keyword.
13237 m Show entries selected by a tags/property match.
13238 p Enter a property name and its value (both with completion on existing
13239 names/values) and show entries with that property.
13240 r Show entries matching a regular expression (`/' can be used as well).
13241 b Show deadlines and scheduled items before a date.
13242 a Show deadlines and scheduled items after a date.
13243 d Show deadlines due within `org-deadline-warning-days'.
13244 D Show deadlines and scheduled items between a date range."
13245 (interactive "P")
13246 (let (ans kwd value ts-type)
13247 (setq type (or type org-sparse-tree-default-date-type))
13248 (setq org-ts-type type)
13249 (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"
13250 (cond ((eq type 'all) "all timestamps")
13251 ((eq type 'scheduled) "only scheduled")
13252 ((eq type 'deadline) "only deadline")
13253 ((eq type 'active) "only active timestamps")
13254 ((eq type 'inactive) "only inactive timestamps")
13255 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13256 (t "scheduled/deadline")))
13257 (setq ans (read-char-exclusive))
13258 (cond
13259 ((equal ans ?c)
13260 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13261 ((equal ans ?d)
13262 (call-interactively 'org-check-deadlines))
13263 ((equal ans ?b)
13264 (call-interactively 'org-check-before-date))
13265 ((equal ans ?a)
13266 (call-interactively 'org-check-after-date))
13267 ((equal ans ?D)
13268 (call-interactively 'org-check-dates-range))
13269 ((equal ans ?t)
13270 (call-interactively 'org-show-todo-tree))
13271 ((equal ans ?T)
13272 (org-show-todo-tree '(4)))
13273 ((member ans '(?T ?m))
13274 (call-interactively 'org-match-sparse-tree))
13275 ((member ans '(?p ?P))
13276 (setq kwd (org-icompleting-read "Property: "
13277 (mapcar 'list (org-buffer-property-keys))))
13278 (setq value (org-icompleting-read "Value: "
13279 (mapcar 'list (org-property-values kwd))))
13280 (unless (string-match "\\`{.*}\\'" value)
13281 (setq value (concat "\"" value "\"")))
13282 (org-match-sparse-tree arg (concat kwd "=" value)))
13283 ((member ans '(?r ?R ?/))
13284 (call-interactively 'org-occur))
13285 (t (error "No such sparse tree command \"%c\"" ans)))))
13287 (defvar org-occur-highlights nil
13288 "List of overlays used for occur matches.")
13289 (make-variable-buffer-local 'org-occur-highlights)
13290 (defvar org-occur-parameters nil
13291 "Parameters of the active org-occur calls.
13292 This is a list, each call to org-occur pushes as cons cell,
13293 containing the regular expression and the callback, onto the list.
13294 The list can contain several entries if `org-occur' has been called
13295 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13296 will only contain one set of parameters. When the highlights are
13297 removed (for example with `C-c C-c', or with the next edit (depending
13298 on `org-remove-highlights-with-change'), this variable is emptied
13299 as well.")
13300 (make-variable-buffer-local 'org-occur-parameters)
13302 (defun org-occur (regexp &optional keep-previous callback)
13303 "Make a compact tree which shows all matches of REGEXP.
13304 The tree will show the lines where the regexp matches, and all higher
13305 headlines above the match. It will also show the heading after the match,
13306 to make sure editing the matching entry is easy.
13307 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13308 call to `org-occur' will be kept, to allow stacking of calls to this
13309 command.
13310 If CALLBACK is non-nil, it is a function which is called to confirm
13311 that the match should indeed be shown."
13312 (interactive "sRegexp: \nP")
13313 (when (equal regexp "")
13314 (error "Regexp cannot be empty"))
13315 (unless keep-previous
13316 (org-remove-occur-highlights nil nil t))
13317 (push (cons regexp callback) org-occur-parameters)
13318 (let ((cnt 0))
13319 (save-excursion
13320 (goto-char (point-min))
13321 (if (or (not keep-previous) ; do not want to keep
13322 (not org-occur-highlights)) ; no previous matches
13323 ;; hide everything
13324 (org-overview))
13325 (while (re-search-forward regexp nil t)
13326 (when (or (not callback)
13327 (save-match-data (funcall callback)))
13328 (setq cnt (1+ cnt))
13329 (when org-highlight-sparse-tree-matches
13330 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13331 (org-show-context 'occur-tree))))
13332 (when org-remove-highlights-with-change
13333 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13334 nil 'local))
13335 (unless org-sparse-tree-open-archived-trees
13336 (org-hide-archived-subtrees (point-min) (point-max)))
13337 (run-hooks 'org-occur-hook)
13338 (if (org-called-interactively-p 'interactive)
13339 (message "%d match(es) for regexp %s" cnt regexp))
13340 cnt))
13342 (defun org-occur-next-match (&optional n reset)
13343 "Function for `next-error-function' to find sparse tree matches.
13344 N is the number of matches to move, when negative move backwards.
13345 RESET is entirely ignored - this function always goes back to the
13346 starting point when no match is found."
13347 (let* ((limit (if (< n 0) (point-min) (point-max)))
13348 (search-func (if (< n 0)
13349 'previous-single-char-property-change
13350 'next-single-char-property-change))
13351 (n (abs n))
13352 (pos (point))
13354 (catch 'exit
13355 (while (setq p1 (funcall search-func (point) 'org-type))
13356 (when (equal p1 limit)
13357 (goto-char pos)
13358 (error "No more matches"))
13359 (when (equal (get-char-property p1 'org-type) 'org-occur)
13360 (setq n (1- n))
13361 (when (= n 0)
13362 (goto-char p1)
13363 (throw 'exit (point))))
13364 (goto-char p1))
13365 (goto-char p1)
13366 (error "No more matches"))))
13368 (defun org-show-context (&optional key)
13369 "Make sure point and context are visible.
13370 How much context is shown depends upon the variables
13371 `org-show-hierarchy-above', `org-show-following-heading',
13372 `org-show-entry-below' and `org-show-siblings'."
13373 (let ((heading-p (org-at-heading-p t))
13374 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13375 (following-p (org-get-alist-option org-show-following-heading key))
13376 (entry-p (org-get-alist-option org-show-entry-below key))
13377 (siblings-p (org-get-alist-option org-show-siblings key)))
13378 ;; Show heading or entry text
13379 (if (and heading-p (not entry-p))
13380 (org-flag-heading nil) ; only show the heading
13381 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13382 (org-show-hidden-entry))) ; show entire entry
13383 (when following-p
13384 ;; Show next sibling, or heading below text
13385 (save-excursion
13386 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13387 (org-flag-heading nil))))
13388 (when siblings-p (org-show-siblings))
13389 (when hierarchy-p
13390 ;; show all higher headings, possibly with siblings
13391 (save-excursion
13392 (while (and (condition-case nil
13393 (progn (org-up-heading-all 1) t)
13394 (error nil))
13395 (not (bobp)))
13396 (org-flag-heading nil)
13397 (when siblings-p (org-show-siblings)))))
13398 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13400 (defvar org-reveal-start-hook nil
13401 "Hook run before revealing a location.")
13403 (defun org-reveal (&optional siblings)
13404 "Show current entry, hierarchy above it, and the following headline.
13405 This can be used to show a consistent set of context around locations
13406 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13407 not t for the search context.
13409 With optional argument SIBLINGS, on each level of the hierarchy all
13410 siblings are shown. This repairs the tree structure to what it would
13411 look like when opened with hierarchical calls to `org-cycle'.
13412 With double optional argument \\[universal-argument] \\[universal-argument], \
13413 go to the parent and show the
13414 entire tree."
13415 (interactive "P")
13416 (run-hooks 'org-reveal-start-hook)
13417 (let ((org-show-hierarchy-above t)
13418 (org-show-following-heading t)
13419 (org-show-siblings (if siblings t org-show-siblings)))
13420 (org-show-context nil))
13421 (when (equal siblings '(16))
13422 (save-excursion
13423 (when (org-up-heading-safe)
13424 (org-show-subtree)
13425 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13427 (defun org-highlight-new-match (beg end)
13428 "Highlight from BEG to END and mark the highlight is an occur headline."
13429 (let ((ov (make-overlay beg end)))
13430 (overlay-put ov 'face 'secondary-selection)
13431 (overlay-put ov 'org-type 'org-occur)
13432 (push ov org-occur-highlights)))
13434 (defun org-remove-occur-highlights (&optional beg end noremove)
13435 "Remove the occur highlights from the buffer.
13436 BEG and END are ignored. If NOREMOVE is nil, remove this function
13437 from the `before-change-functions' in the current buffer."
13438 (interactive)
13439 (unless org-inhibit-highlight-removal
13440 (mapc 'delete-overlay org-occur-highlights)
13441 (setq org-occur-highlights nil)
13442 (setq org-occur-parameters nil)
13443 (unless noremove
13444 (remove-hook 'before-change-functions
13445 'org-remove-occur-highlights 'local))))
13447 ;;;; Priorities
13449 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13450 "Regular expression matching the priority indicator.")
13452 (defvar org-remove-priority-next-time nil)
13454 (defun org-priority-up ()
13455 "Increase the priority of the current item."
13456 (interactive)
13457 (org-priority 'up))
13459 (defun org-priority-down ()
13460 "Decrease the priority of the current item."
13461 (interactive)
13462 (org-priority 'down))
13464 (defun org-priority (&optional action show)
13465 "Change the priority of an item.
13466 ACTION can be `set', `up', `down', or a character."
13467 (interactive "P")
13468 (if (equal action '(4))
13469 (org-show-priority)
13470 (unless org-enable-priority-commands
13471 (error "Priority commands are disabled"))
13472 (setq action (or action 'set))
13473 (let (current new news have remove)
13474 (save-excursion
13475 (org-back-to-heading t)
13476 (if (looking-at org-priority-regexp)
13477 (setq current (string-to-char (match-string 2))
13478 have t))
13479 (cond
13480 ((eq action 'remove)
13481 (setq remove t new ?\ ))
13482 ((or (eq action 'set)
13483 (if (featurep 'xemacs) (characterp action) (integerp action)))
13484 (if (not (eq action 'set))
13485 (setq new action)
13486 (message "Priority %c-%c, SPC to remove: "
13487 org-highest-priority org-lowest-priority)
13488 (save-match-data
13489 (setq new (read-char-exclusive))))
13490 (if (and (= (upcase org-highest-priority) org-highest-priority)
13491 (= (upcase org-lowest-priority) org-lowest-priority))
13492 (setq new (upcase new)))
13493 (cond ((equal new ?\ ) (setq remove t))
13494 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13495 (error "Priority must be between `%c' and `%c'"
13496 org-highest-priority org-lowest-priority))))
13497 ((eq action 'up)
13498 (setq new (if have
13499 (1- current) ; normal cycling
13500 ;; last priority was empty
13501 (if (eq last-command this-command)
13502 org-lowest-priority ; wrap around empty to lowest
13503 ;; default
13504 (if org-priority-start-cycle-with-default
13505 org-default-priority
13506 (1- org-default-priority))))))
13507 ((eq action 'down)
13508 (setq new (if have
13509 (1+ current) ; normal cycling
13510 ;; last priority was empty
13511 (if (eq last-command this-command)
13512 org-highest-priority ; wrap around empty to highest
13513 ;; default
13514 (if org-priority-start-cycle-with-default
13515 org-default-priority
13516 (1+ org-default-priority))))))
13517 (t (error "Invalid action")))
13518 (if (or (< (upcase new) org-highest-priority)
13519 (> (upcase new) org-lowest-priority))
13520 (if (and (memq action '(up down))
13521 (not have) (not (eq last-command this-command)))
13522 ;; `new' is from default priority
13523 (error
13524 "The default can not be set, see `org-default-priority' why")
13525 ;; normal cycling: `new' is beyond highest/lowest priority
13526 ;; and is wrapped around to the empty priority
13527 (setq remove t)))
13528 (setq news (format "%c" new))
13529 (if have
13530 (if remove
13531 (replace-match "" t t nil 1)
13532 (replace-match news t t nil 2))
13533 (if remove
13534 (error "No priority cookie found in line")
13535 (let ((case-fold-search nil))
13536 (looking-at org-todo-line-regexp))
13537 (if (match-end 2)
13538 (progn
13539 (goto-char (match-end 2))
13540 (insert " [#" news "]"))
13541 (goto-char (match-beginning 3))
13542 (insert "[#" news "] "))))
13543 (org-preserve-lc (org-set-tags nil 'align)))
13544 (if remove
13545 (message "Priority removed")
13546 (message "Priority of current item set to %s" news)))))
13548 (defun org-show-priority ()
13549 "Show the priority of the current item.
13550 This priority is composed of the main priority given with the [#A] cookies,
13551 and by additional input from the age of a schedules or deadline entry."
13552 (interactive)
13553 (let ((pri (if (eq major-mode 'org-agenda-mode)
13554 (org-get-at-bol 'priority)
13555 (save-excursion
13556 (save-match-data
13557 (beginning-of-line)
13558 (and (looking-at org-heading-regexp)
13559 (org-get-priority (match-string 0))))))))
13560 (message "Priority is %d" (if pri pri -1000))))
13562 (defun org-get-priority (s)
13563 "Find priority cookie and return priority."
13564 (save-match-data
13565 (if (functionp org-get-priority-function)
13566 (funcall org-get-priority-function)
13567 (if (not (string-match org-priority-regexp s))
13568 (* 1000 (- org-lowest-priority org-default-priority))
13569 (* 1000 (- org-lowest-priority
13570 (string-to-char (match-string 2 s))))))))
13572 ;;;; Tags
13574 (defvar org-agenda-archives-mode)
13575 (defvar org-map-continue-from nil
13576 "Position from where mapping should continue.
13577 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13579 (defvar org-scanner-tags nil
13580 "The current tag list while the tags scanner is running.")
13581 (defvar org-trust-scanner-tags nil
13582 "Should `org-get-tags-at' use the tags for the scanner.
13583 This is for internal dynamical scoping only.
13584 When this is non-nil, the function `org-get-tags-at' will return the value
13585 of `org-scanner-tags' instead of building the list by itself. This
13586 can lead to large speed-ups when the tags scanner is used in a file with
13587 many entries, and when the list of tags is retrieved, for example to
13588 obtain a list of properties. Building the tags list for each entry in such
13589 a file becomes an N^2 operation - but with this variable set, it scales
13590 as N.")
13592 (defun org-scan-tags (action matcher todo-only &optional start-level)
13593 "Sca headline tags with inheritance and produce output ACTION.
13595 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13596 or `agenda' to produce an entry list for an agenda view. It can also be
13597 a Lisp form or a function that should be called at each matched headline, in
13598 this case the return value is a list of all return values from these calls.
13600 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13601 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13602 only lines with a not-done TODO keyword are included in the output.
13603 This should be the same variable that was scoped into
13604 and set by `org-make-tags-matcher' when it constructed MATCHER.
13606 START-LEVEL can be a string with asterisks, reducing the scope to
13607 headlines matching this string."
13608 (require 'org-agenda)
13609 (let* ((re (concat "^"
13610 (if start-level
13611 ;; Get the correct level to match
13612 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13613 org-outline-regexp)
13614 " *\\(\\<\\("
13615 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13616 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13617 (props (list 'face 'default
13618 'done-face 'org-agenda-done
13619 'undone-face 'default
13620 'mouse-face 'highlight
13621 'org-not-done-regexp org-not-done-regexp
13622 'org-todo-regexp org-todo-regexp
13623 'org-complex-heading-regexp org-complex-heading-regexp
13624 'help-echo
13625 (format "mouse-2 or RET jump to org file %s"
13626 (abbreviate-file-name
13627 (or (buffer-file-name (buffer-base-buffer))
13628 (buffer-name (buffer-base-buffer)))))))
13629 (case-fold-search nil)
13630 (org-map-continue-from nil)
13631 lspos tags tags-list
13632 (tags-alist (list (cons 0 org-file-tags)))
13633 (llast 0) rtn rtn1 level category i txt
13634 todo marker entry priority)
13635 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13636 (setq action (list 'lambda nil action)))
13637 (save-excursion
13638 (goto-char (point-min))
13639 (when (eq action 'sparse-tree)
13640 (org-overview)
13641 (org-remove-occur-highlights))
13642 (while (re-search-forward re nil t)
13643 (setq org-map-continue-from nil)
13644 (catch :skip
13645 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13646 tags (if (match-end 4) (org-match-string-no-properties 4)))
13647 (goto-char (setq lspos (match-beginning 0)))
13648 (setq level (org-reduced-level (org-outline-level))
13649 category (org-get-category))
13650 (setq i llast llast level)
13651 ;; remove tag lists from same and sublevels
13652 (while (>= i level)
13653 (when (setq entry (assoc i tags-alist))
13654 (setq tags-alist (delete entry tags-alist)))
13655 (setq i (1- i)))
13656 ;; add the next tags
13657 (when tags
13658 (setq tags (org-split-string tags ":")
13659 tags-alist
13660 (cons (cons level tags) tags-alist)))
13661 ;; compile tags for current headline
13662 (setq tags-list
13663 (if org-use-tag-inheritance
13664 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13665 tags)
13666 org-scanner-tags tags-list)
13667 (when org-use-tag-inheritance
13668 (setcdr (car tags-alist)
13669 (mapcar (lambda (x)
13670 (setq x (copy-sequence x))
13671 (org-add-prop-inherited x))
13672 (cdar tags-alist))))
13673 (when (and tags org-use-tag-inheritance
13674 (or (not (eq t org-use-tag-inheritance))
13675 org-tags-exclude-from-inheritance))
13676 ;; selective inheritance, remove uninherited ones
13677 (setcdr (car tags-alist)
13678 (org-remove-uninherited-tags (cdar tags-alist))))
13679 (when (and
13681 ;; eval matcher only when the todo condition is OK
13682 (and (or (not todo-only) (member todo org-not-done-keywords))
13683 (let ((case-fold-search t) (org-trust-scanner-tags t))
13684 (eval matcher)))
13686 ;; Call the skipper, but return t if it does not skip,
13687 ;; so that the `and' form continues evaluating
13688 (progn
13689 (unless (eq action 'sparse-tree) (org-agenda-skip))
13692 ;; Check if timestamps are deselecting this entry
13693 (or (not todo-only)
13694 (and (member todo org-not-done-keywords)
13695 (or (not org-agenda-tags-todo-honor-ignore-options)
13696 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13698 ;; select this headline
13699 (cond
13700 ((eq action 'sparse-tree)
13701 (and org-highlight-sparse-tree-matches
13702 (org-get-heading) (match-end 0)
13703 (org-highlight-new-match
13704 (match-beginning 1) (match-end 1)))
13705 (org-show-context 'tags-tree))
13706 ((eq action 'agenda)
13707 (setq txt (org-agenda-format-item
13709 (concat
13710 (if (eq org-tags-match-list-sublevels 'indented)
13711 (make-string (1- level) ?.) "")
13712 (org-get-heading))
13713 level category
13714 tags-list)
13715 priority (org-get-priority txt))
13716 (goto-char lspos)
13717 (setq marker (org-agenda-new-marker))
13718 (org-add-props txt props
13719 'org-marker marker 'org-hd-marker marker 'org-category category
13720 'todo-state todo
13721 'priority priority 'type "tagsmatch")
13722 (push txt rtn))
13723 ((functionp action)
13724 (setq org-map-continue-from nil)
13725 (save-excursion
13726 (setq rtn1 (funcall action))
13727 (push rtn1 rtn)))
13728 (t (error "Invalid action")))
13730 ;; if we are to skip sublevels, jump to end of subtree
13731 (unless org-tags-match-list-sublevels
13732 (org-end-of-subtree t)
13733 (backward-char 1))))
13734 ;; Get the correct position from where to continue
13735 (if org-map-continue-from
13736 (goto-char org-map-continue-from)
13737 (and (= (point) lspos) (end-of-line 1)))))
13738 (when (and (eq action 'sparse-tree)
13739 (not org-sparse-tree-open-archived-trees))
13740 (org-hide-archived-subtrees (point-min) (point-max)))
13741 (nreverse rtn)))
13743 (defun org-remove-uninherited-tags (tags)
13744 "Remove all tags that are not inherited from the list TAGS."
13745 (cond
13746 ((eq org-use-tag-inheritance t)
13747 (if org-tags-exclude-from-inheritance
13748 (org-delete-all org-tags-exclude-from-inheritance tags)
13749 tags))
13750 ((not org-use-tag-inheritance) nil)
13751 ((stringp org-use-tag-inheritance)
13752 (delq nil (mapcar
13753 (lambda (x)
13754 (if (and (string-match org-use-tag-inheritance x)
13755 (not (member x org-tags-exclude-from-inheritance)))
13756 x nil))
13757 tags)))
13758 ((listp org-use-tag-inheritance)
13759 (delq nil (mapcar
13760 (lambda (x)
13761 (if (member x org-use-tag-inheritance) x nil))
13762 tags)))))
13764 (defun org-match-sparse-tree (&optional todo-only match)
13765 "Create a sparse tree according to tags string MATCH.
13766 MATCH can contain positive and negative selection of tags, like
13767 \"+WORK+URGENT-WITHBOSS\".
13768 If optional argument TODO-ONLY is non-nil, only select lines that are
13769 also TODO lines."
13770 (interactive "P")
13771 (org-agenda-prepare-buffers (list (current-buffer)))
13772 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13774 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13776 (defvar org-cached-props nil)
13777 (defun org-cached-entry-get (pom property)
13778 (if (or (eq t org-use-property-inheritance)
13779 (and (stringp org-use-property-inheritance)
13780 (string-match org-use-property-inheritance property))
13781 (and (listp org-use-property-inheritance)
13782 (member property org-use-property-inheritance)))
13783 ;; Caching is not possible, check it directly
13784 (org-entry-get pom property 'inherit)
13785 ;; Get all properties, so that we can do complicated checks easily
13786 (cdr (assoc property (or org-cached-props
13787 (setq org-cached-props
13788 (org-entry-properties pom)))))))
13790 (defun org-global-tags-completion-table (&optional files)
13791 "Return the list of all tags in all agenda buffer/files.
13792 Optional FILES argument is a list of files which can be used
13793 instead of the agenda files."
13794 (save-excursion
13795 (org-uniquify
13796 (delq nil
13797 (apply 'append
13798 (mapcar
13799 (lambda (file)
13800 (set-buffer (find-file-noselect file))
13801 (append (org-get-buffer-tags)
13802 (mapcar (lambda (x) (if (stringp (car-safe x))
13803 (list (car-safe x)) nil))
13804 org-tag-alist)))
13805 (if (and files (car files))
13806 files
13807 (org-agenda-files))))))))
13809 (defun org-make-tags-matcher (match)
13810 "Create the TAGS/TODO matcher form for the selection string MATCH.
13812 The variable `todo-only' is scoped dynamically into this function.
13813 It will be set to t if the matcher restricts matching to TODO entries,
13814 otherwise will not be touched.
13816 Returns a cons of the selection string MATCH and the constructed
13817 lisp form implementing the matcher. The matcher is to be evaluated
13818 at an Org entry, with point on the headline, and returns t if the
13819 entry matches the selection string MATCH. The returned lisp form
13820 references two variables with information about the entry, which
13821 must be bound around the form's evaluation: todo, the TODO keyword
13822 at the entry (or nil of none); and tags-list, the list of all tags
13823 at the entry including inherited ones. Additionally, the category
13824 of the entry (if any) must be specified as the text property
13825 'org-category on the headline.
13827 See also `org-scan-tags'.
13829 (declare (special todo-only))
13830 (unless (boundp 'todo-only)
13831 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13832 (unless match
13833 ;; Get a new match request, with completion
13834 (let ((org-last-tags-completion-table
13835 (org-global-tags-completion-table)))
13836 (setq match (org-completing-read-no-i
13837 "Match: " 'org-tags-completion-function nil nil nil
13838 'org-tags-history))))
13840 ;; Parse the string and create a lisp form
13841 (let ((match0 match)
13842 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13843 minus tag mm
13844 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13845 orterms term orlist re-p str-p level-p level-op time-p
13846 prop-p pn pv po gv rest)
13847 (if (string-match "/+" match)
13848 ;; match contains also a todo-matching request
13849 (progn
13850 (setq tagsmatch (substring match 0 (match-beginning 0))
13851 todomatch (substring match (match-end 0)))
13852 (if (string-match "^!" todomatch)
13853 (setq todo-only t todomatch (substring todomatch 1)))
13854 (if (string-match "^\\s-*$" todomatch)
13855 (setq todomatch nil)))
13856 ;; only matching tags
13857 (setq tagsmatch match todomatch nil))
13859 ;; Make the tags matcher
13860 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13861 (setq tagsmatcher t)
13862 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13863 (while (setq term (pop orterms))
13864 (while (and (equal (substring term -1) "\\") orterms)
13865 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13866 (while (string-match re term)
13867 (setq rest (substring term (match-end 0))
13868 minus (and (match-end 1)
13869 (equal (match-string 1 term) "-"))
13870 tag (save-match-data (replace-regexp-in-string
13871 "\\\\-" "-"
13872 (match-string 2 term)))
13873 re-p (equal (string-to-char tag) ?{)
13874 level-p (match-end 4)
13875 prop-p (match-end 5)
13876 mm (cond
13877 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13878 (level-p
13879 (setq level-op (org-op-to-function (match-string 3 term)))
13880 `(,level-op level ,(string-to-number
13881 (match-string 4 term))))
13882 (prop-p
13883 (setq pn (match-string 5 term)
13884 po (match-string 6 term)
13885 pv (match-string 7 term)
13886 re-p (equal (string-to-char pv) ?{)
13887 str-p (equal (string-to-char pv) ?\")
13888 time-p (save-match-data
13889 (string-match "^\"[[<].*[]>]\"$" pv))
13890 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13891 (if time-p (setq pv (org-matcher-time pv)))
13892 (setq po (org-op-to-function po (if time-p 'time str-p)))
13893 (cond
13894 ((equal pn "CATEGORY")
13895 (setq gv '(get-text-property (point) 'org-category)))
13896 ((equal pn "TODO")
13897 (setq gv 'todo))
13899 (setq gv `(org-cached-entry-get nil ,pn))))
13900 (if re-p
13901 (if (eq po 'org<>)
13902 `(not (string-match ,pv (or ,gv "")))
13903 `(string-match ,pv (or ,gv "")))
13904 (if str-p
13905 `(,po (or ,gv "") ,pv)
13906 `(,po (string-to-number (or ,gv ""))
13907 ,(string-to-number pv) ))))
13908 (t `(member ,tag tags-list)))
13909 mm (if minus (list 'not mm) mm)
13910 term rest)
13911 (push mm tagsmatcher))
13912 (push (if (> (length tagsmatcher) 1)
13913 (cons 'and tagsmatcher)
13914 (car tagsmatcher))
13915 orlist)
13916 (setq tagsmatcher nil))
13917 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13918 (setq tagsmatcher
13919 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13920 ;; Make the todo matcher
13921 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13922 (setq todomatcher t)
13923 (setq orterms (org-split-string todomatch "|") orlist nil)
13924 (while (setq term (pop orterms))
13925 (while (string-match re term)
13926 (setq minus (and (match-end 1)
13927 (equal (match-string 1 term) "-"))
13928 kwd (match-string 2 term)
13929 re-p (equal (string-to-char kwd) ?{)
13930 term (substring term (match-end 0))
13931 mm (if re-p
13932 `(string-match ,(substring kwd 1 -1) todo)
13933 (list 'equal 'todo kwd))
13934 mm (if minus (list 'not mm) mm))
13935 (push mm todomatcher))
13936 (push (if (> (length todomatcher) 1)
13937 (cons 'and todomatcher)
13938 (car todomatcher))
13939 orlist)
13940 (setq todomatcher nil))
13941 (setq todomatcher (if (> (length orlist) 1)
13942 (cons 'or orlist) (car orlist))))
13944 ;; Return the string and lisp forms of the matcher
13945 (setq matcher (if todomatcher
13946 (list 'and tagsmatcher todomatcher)
13947 tagsmatcher))
13948 (when todo-only
13949 (setq matcher (list 'and '(member todo org-not-done-keywords)
13950 matcher)))
13951 (cons match0 matcher)))
13953 (defun org-op-to-function (op &optional stringp)
13954 "Turn an operator into the appropriate function."
13955 (setq op
13956 (cond
13957 ((equal op "<" ) '(< string< org-time<))
13958 ((equal op ">" ) '(> org-string> org-time>))
13959 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13960 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13961 ((member op '("=" "==")) '(= string= org-time=))
13962 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13963 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13965 (defun org<> (a b) (not (= a b)))
13966 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13967 (defun org-string>= (a b) (not (string< a b)))
13968 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13969 (defun org-string<> (a b) (not (string= 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) (<= a b)))
13973 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13974 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13975 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13976 (defun org-2ft (s)
13977 "Convert S to a floating point time.
13978 If S is already a number, just return it. If it is a string, parse
13979 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13980 (cond
13981 ((numberp s) s)
13982 ((stringp s)
13983 (condition-case nil
13984 (float-time (apply 'encode-time (org-parse-time-string s)))
13985 (error 0.)))
13986 (t 0.)))
13988 (defun org-time-today ()
13989 "Time in seconds today at 0:00.
13990 Returns the float number of seconds since the beginning of the
13991 epoch to the beginning of today (00:00)."
13992 (float-time (apply 'encode-time
13993 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13995 (defun org-matcher-time (s)
13996 "Interpret a time comparison value."
13997 (save-match-data
13998 (cond
13999 ((string= s "<now>") (float-time))
14000 ((string= s "<today>") (org-time-today))
14001 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14002 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14003 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14004 (+ (org-time-today)
14005 (* (string-to-number (match-string 1 s))
14006 (cdr (assoc (match-string 2 s)
14007 '(("d" . 86400.0) ("w" . 604800.0)
14008 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14009 (t (org-2ft s)))))
14011 (defun org-match-any-p (re list)
14012 "Does re match any element of list?"
14013 (setq list (mapcar (lambda (x) (string-match re x)) list))
14014 (delq nil list))
14016 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14017 (defvar org-tags-overlay (make-overlay 1 1))
14018 (org-detach-overlay org-tags-overlay)
14020 (defun org-get-local-tags-at (&optional pos)
14021 "Get a list of tags defined in the current headline."
14022 (org-get-tags-at pos 'local))
14024 (defun org-get-local-tags ()
14025 "Get a list of tags defined in the current headline."
14026 (org-get-tags-at nil 'local))
14028 (defun org-get-tags-at (&optional pos local)
14029 "Get a list of all headline tags applicable at POS.
14030 POS defaults to point. If tags are inherited, the list contains
14031 the targets in the same sequence as the headlines appear, i.e.
14032 the tags of the current headline come last.
14033 When LOCAL is non-nil, only return tags from the current headline,
14034 ignore inherited ones."
14035 (interactive)
14036 (if (and org-trust-scanner-tags
14037 (or (not pos) (equal pos (point)))
14038 (not local))
14039 org-scanner-tags
14040 (let (tags ltags lastpos parent)
14041 (save-excursion
14042 (save-restriction
14043 (widen)
14044 (goto-char (or pos (point)))
14045 (save-match-data
14046 (catch 'done
14047 (condition-case nil
14048 (progn
14049 (org-back-to-heading t)
14050 (while (not (equal lastpos (point)))
14051 (setq lastpos (point))
14052 (when (looking-at
14053 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14054 (setq ltags (org-split-string
14055 (org-match-string-no-properties 1) ":"))
14056 (when parent
14057 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14058 (setq tags (append
14059 (if parent
14060 (org-remove-uninherited-tags ltags)
14061 ltags)
14062 tags)))
14063 (or org-use-tag-inheritance (throw 'done t))
14064 (if local (throw 'done t))
14065 (or (org-up-heading-safe) (error nil))
14066 (setq parent t)))
14067 (error nil)))))
14068 (if local
14069 tags
14070 (reverse (delete-dups
14071 (reverse (append
14072 (org-remove-uninherited-tags
14073 org-file-tags) tags)))))))))
14075 (defun org-add-prop-inherited (s)
14076 (add-text-properties 0 (length s) '(inherited t) s)
14079 (defun org-toggle-tag (tag &optional onoff)
14080 "Toggle the tag TAG for the current line.
14081 If ONOFF is `on' or `off', don't toggle but set to this state."
14082 (let (res current)
14083 (save-excursion
14084 (org-back-to-heading t)
14085 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14086 (point-at-eol) t)
14087 (progn
14088 (setq current (match-string 1))
14089 (replace-match ""))
14090 (setq current ""))
14091 (setq current (nreverse (org-split-string current ":")))
14092 (cond
14093 ((eq onoff 'on)
14094 (setq res t)
14095 (or (member tag current) (push tag current)))
14096 ((eq onoff 'off)
14097 (or (not (member tag current)) (setq current (delete tag current))))
14098 (t (if (member tag current)
14099 (setq current (delete tag current))
14100 (setq res t)
14101 (push tag current))))
14102 (end-of-line 1)
14103 (if current
14104 (progn
14105 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14106 (org-set-tags nil t))
14107 (delete-horizontal-space))
14108 (run-hooks 'org-after-tags-change-hook))
14109 res))
14111 (defun org-align-tags-here (to-col)
14112 ;; Assumes that this is a headline
14113 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14114 (beginning-of-line 1)
14115 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14116 (< pos (match-beginning 2)))
14117 (progn
14118 (setq tags-l (- (match-end 2) (match-beginning 2)))
14119 (goto-char (match-beginning 1))
14120 (insert " ")
14121 (delete-region (point) (1+ (match-beginning 2)))
14122 (setq ncol (max (current-column)
14123 (1+ col)
14124 (if (> to-col 0)
14125 to-col
14126 (- (abs to-col) tags-l))))
14127 (setq p (point))
14128 (insert (make-string (- ncol (current-column)) ?\ ))
14129 (setq ncol (current-column))
14130 (when indent-tabs-mode (tabify p (point-at-eol)))
14131 (org-move-to-column (min ncol col) t))
14132 (goto-char pos))))
14134 (defun org-set-tags-command (&optional arg just-align)
14135 "Call the set-tags command for the current entry."
14136 (interactive "P")
14137 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14138 (org-set-tags arg just-align)
14139 (save-excursion
14140 (unless (and (org-region-active-p)
14141 org-loop-over-headlines-in-active-region)
14142 (org-back-to-heading t))
14143 (org-set-tags arg just-align))))
14145 (defun org-set-tags-to (data)
14146 "Set the tags of the current entry to DATA, replacing the current tags.
14147 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14148 If DATA is nil or the empty string, any tags will be removed."
14149 (interactive "sTags: ")
14150 (setq data
14151 (cond
14152 ((eq data nil) "")
14153 ((equal data "") "")
14154 ((stringp data)
14155 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14156 ":"))
14157 ((listp data)
14158 (concat ":" (mapconcat 'identity data ":") ":"))))
14159 (when data
14160 (save-excursion
14161 (org-back-to-heading t)
14162 (when (looking-at org-complex-heading-regexp)
14163 (if (match-end 5)
14164 (progn
14165 (goto-char (match-beginning 5))
14166 (insert data)
14167 (delete-region (point) (point-at-eol))
14168 (org-set-tags nil 'align))
14169 (goto-char (point-at-eol))
14170 (insert " " data)
14171 (org-set-tags nil 'align)))
14172 (beginning-of-line 1)
14173 (if (looking-at ".*?\\([ \t]+\\)$")
14174 (delete-region (match-beginning 1) (match-end 1))))))
14176 (defun org-align-all-tags ()
14177 "Align the tags i all headings."
14178 (interactive)
14179 (save-excursion
14180 (or (ignore-errors (org-back-to-heading t))
14181 (outline-next-heading))
14182 (if (org-at-heading-p)
14183 (org-set-tags t)
14184 (message "No headings"))))
14186 (defvar org-indent-indentation-per-level)
14187 (defun org-set-tags (&optional arg just-align)
14188 "Set the tags for the current headline.
14189 With prefix ARG, realign all tags in headings in the current buffer."
14190 (interactive "P")
14191 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14192 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14193 'region-start-level 'region))
14194 org-loop-over-headlines-in-active-region)
14195 (org-map-entries
14196 ;; We don't use ARG and JUST-ALIGN here these args are not
14197 ;; useful when looping over headlines
14198 `(org-set-tags)
14199 org-loop-over-headlines-in-active-region
14200 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14201 (let* ((re org-outline-regexp-bol)
14202 (current (unless arg (org-get-tags-string)))
14203 (col (current-column))
14204 (org-setting-tags t)
14205 table current-tags inherited-tags ; computed below when needed
14206 tags p0 c0 c1 rpl di tc level)
14207 (if arg
14208 (save-excursion
14209 (goto-char (point-min))
14210 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14211 (while (re-search-forward re nil t)
14212 (org-set-tags nil t)
14213 (end-of-line 1)))
14214 (message "All tags realigned to column %d" org-tags-column))
14215 (if just-align
14216 (setq tags current)
14217 ;; Get a new set of tags from the user
14218 (save-excursion
14219 (setq table (append org-tag-persistent-alist
14220 (or org-tag-alist (org-get-buffer-tags))
14221 (and
14222 org-complete-tags-always-offer-all-agenda-tags
14223 (org-global-tags-completion-table
14224 (org-agenda-files))))
14225 org-last-tags-completion-table table
14226 current-tags (org-split-string current ":")
14227 inherited-tags (nreverse
14228 (nthcdr (length current-tags)
14229 (nreverse (org-get-tags-at))))
14230 tags
14231 (if (or (eq t org-use-fast-tag-selection)
14232 (and org-use-fast-tag-selection
14233 (delq nil (mapcar 'cdr table))))
14234 (org-fast-tag-selection
14235 current-tags inherited-tags table
14236 (if org-fast-tag-selection-include-todo
14237 org-todo-key-alist))
14238 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14239 (org-trim
14240 (org-icompleting-read "Tags: "
14241 'org-tags-completion-function
14242 nil nil current 'org-tags-history))))))
14243 (while (string-match "[-+&]+" tags)
14244 ;; No boolean logic, just a list
14245 (setq tags (replace-match ":" t t tags))))
14247 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14249 (if org-tags-sort-function
14250 (setq tags (mapconcat 'identity
14251 (sort (org-split-string
14252 tags (org-re "[^[:alnum:]_@#%]+"))
14253 org-tags-sort-function) ":")))
14255 (if (string-match "\\`[\t ]*\\'" tags)
14256 (setq tags "")
14257 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14258 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14260 ;; Insert new tags at the correct column
14261 (beginning-of-line 1)
14262 (setq level (or (and (looking-at org-outline-regexp)
14263 (- (match-end 0) (point) 1))
14265 (cond
14266 ((and (equal current "") (equal tags "")))
14267 ((re-search-forward
14268 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14269 (point-at-eol) t)
14270 (if (equal tags "")
14271 (setq rpl "")
14272 (goto-char (match-beginning 0))
14273 (setq c0 (current-column)
14274 ;; compute offset for the case of org-indent-mode active
14275 di (if org-indent-mode
14276 (* (1- org-indent-indentation-per-level) (1- level))
14278 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14279 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14280 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14281 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14282 (replace-match rpl t t)
14283 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14284 tags)
14285 (t (error "Tags alignment failed")))
14286 (org-move-to-column col)
14287 (unless just-align
14288 (run-hooks 'org-after-tags-change-hook))))))
14290 (defun org-change-tag-in-region (beg end tag off)
14291 "Add or remove TAG for each entry in the region.
14292 This works in the agenda, and also in an org-mode buffer."
14293 (interactive
14294 (list (region-beginning) (region-end)
14295 (let ((org-last-tags-completion-table
14296 (if (derived-mode-p 'org-mode)
14297 (org-get-buffer-tags)
14298 (org-global-tags-completion-table))))
14299 (org-icompleting-read
14300 "Tag: " 'org-tags-completion-function nil nil nil
14301 'org-tags-history))
14302 (progn
14303 (message "[s]et or [r]emove? ")
14304 (equal (read-char-exclusive) ?r))))
14305 (if (fboundp 'deactivate-mark) (deactivate-mark))
14306 (let ((agendap (equal major-mode 'org-agenda-mode))
14307 l1 l2 m buf pos newhead (cnt 0))
14308 (goto-char end)
14309 (setq l2 (1- (org-current-line)))
14310 (goto-char beg)
14311 (setq l1 (org-current-line))
14312 (loop for l from l1 to l2 do
14313 (org-goto-line l)
14314 (setq m (get-text-property (point) 'org-hd-marker))
14315 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14316 (and agendap m))
14317 (setq buf (if agendap (marker-buffer m) (current-buffer))
14318 pos (if agendap m (point)))
14319 (with-current-buffer buf
14320 (save-excursion
14321 (save-restriction
14322 (goto-char pos)
14323 (setq cnt (1+ cnt))
14324 (org-toggle-tag tag (if off 'off 'on))
14325 (setq newhead (org-get-heading)))))
14326 (and agendap (org-agenda-change-all-lines newhead m))))
14327 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14329 (defun org-tags-completion-function (string predicate &optional flag)
14330 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14331 (confirm (lambda (x) (stringp (car x)))))
14332 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14333 (setq s1 (match-string 1 string)
14334 s2 (match-string 2 string))
14335 (setq s1 "" s2 string))
14336 (cond
14337 ((eq flag nil)
14338 ;; try completion
14339 (setq rtn (try-completion s2 ctable confirm))
14340 (if (stringp rtn)
14341 (setq rtn
14342 (concat s1 s2 (substring rtn (length s2))
14343 (if (and org-add-colon-after-tag-completion
14344 (assoc rtn ctable))
14345 ":" ""))))
14346 rtn)
14347 ((eq flag t)
14348 ;; all-completions
14349 (all-completions s2 ctable confirm)
14351 ((eq flag 'lambda)
14352 ;; exact match?
14353 (assoc s2 ctable)))
14356 (defun org-fast-tag-insert (kwd tags face &optional end)
14357 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14358 (insert (format "%-12s" (concat kwd ":"))
14359 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14360 (or end "")))
14362 (defun org-fast-tag-show-exit (flag)
14363 (save-excursion
14364 (org-goto-line 3)
14365 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14366 (replace-match ""))
14367 (when flag
14368 (end-of-line 1)
14369 (org-move-to-column (- (window-width) 19) t)
14370 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14372 (defun org-set-current-tags-overlay (current prefix)
14373 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14374 (if (featurep 'xemacs)
14375 (org-overlay-display org-tags-overlay (concat prefix s)
14376 'secondary-selection)
14377 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14378 (org-overlay-display org-tags-overlay (concat prefix s)))))
14380 (defvar org-last-tag-selection-key nil)
14381 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14382 "Fast tag selection with single keys.
14383 CURRENT is the current list of tags in the headline, INHERITED is the
14384 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14385 possibly with grouping information. TODO-TABLE is a similar table with
14386 TODO keywords, should these have keys assigned to them.
14387 If the keys are nil, a-z are automatically assigned.
14388 Returns the new tags string, or nil to not change the current settings."
14389 (let* ((fulltable (append table todo-table))
14390 (maxlen (apply 'max (mapcar
14391 (lambda (x)
14392 (if (stringp (car x)) (string-width (car x)) 0))
14393 fulltable)))
14394 (buf (current-buffer))
14395 (expert (eq org-fast-tag-selection-single-key 'expert))
14396 (buffer-tags nil)
14397 (fwidth (+ maxlen 3 1 3))
14398 (ncol (/ (- (window-width) 4) fwidth))
14399 (i-face 'org-done)
14400 (c-face 'org-todo)
14401 tg cnt e c char c1 c2 ntable tbl rtn
14402 ov-start ov-end ov-prefix
14403 (exit-after-next org-fast-tag-selection-single-key)
14404 (done-keywords org-done-keywords)
14405 groups ingroup)
14406 (save-excursion
14407 (beginning-of-line 1)
14408 (if (looking-at
14409 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14410 (setq ov-start (match-beginning 1)
14411 ov-end (match-end 1)
14412 ov-prefix "")
14413 (setq ov-start (1- (point-at-eol))
14414 ov-end (1+ ov-start))
14415 (skip-chars-forward "^\n\r")
14416 (setq ov-prefix
14417 (concat
14418 (buffer-substring (1- (point)) (point))
14419 (if (> (current-column) org-tags-column)
14421 (make-string (- org-tags-column (current-column)) ?\ ))))))
14422 (move-overlay org-tags-overlay ov-start ov-end)
14423 (save-window-excursion
14424 (if expert
14425 (set-buffer (get-buffer-create " *Org tags*"))
14426 (delete-other-windows)
14427 (split-window-vertically)
14428 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14429 (erase-buffer)
14430 (org-set-local 'org-done-keywords done-keywords)
14431 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14432 (org-fast-tag-insert "Current" current c-face "\n\n")
14433 (org-fast-tag-show-exit exit-after-next)
14434 (org-set-current-tags-overlay current ov-prefix)
14435 (setq tbl fulltable char ?a cnt 0)
14436 (while (setq e (pop tbl))
14437 (cond
14438 ((equal (car e) :startgroup)
14439 (push '() groups) (setq ingroup t)
14440 (when (not (= cnt 0))
14441 (setq cnt 0)
14442 (insert "\n"))
14443 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14444 ((equal (car e) :endgroup)
14445 (setq ingroup nil cnt 0)
14446 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14447 ((equal e '(:newline))
14448 (when (not (= cnt 0))
14449 (setq cnt 0)
14450 (insert "\n")
14451 (setq e (car tbl))
14452 (while (equal (car tbl) '(:newline))
14453 (insert "\n")
14454 (setq tbl (cdr tbl)))))
14456 (setq tg (copy-sequence (car e)) c2 nil)
14457 (if (cdr e)
14458 (setq c (cdr e))
14459 ;; automatically assign a character.
14460 (setq c1 (string-to-char
14461 (downcase (substring
14462 tg (if (= (string-to-char tg) ?@) 1 0)))))
14463 (if (or (rassoc c1 ntable) (rassoc c1 table))
14464 (while (or (rassoc char ntable) (rassoc char table))
14465 (setq char (1+ char)))
14466 (setq c2 c1))
14467 (setq c (or c2 char)))
14468 (if ingroup (push tg (car groups)))
14469 (setq tg (org-add-props tg nil 'face
14470 (cond
14471 ((not (assoc tg table))
14472 (org-get-todo-face tg))
14473 ((member tg current) c-face)
14474 ((member tg inherited) i-face))))
14475 (if (and (= cnt 0) (not ingroup)) (insert " "))
14476 (insert "[" c "] " tg (make-string
14477 (- fwidth 4 (length tg)) ?\ ))
14478 (push (cons tg c) ntable)
14479 (when (= (setq cnt (1+ cnt)) ncol)
14480 (insert "\n")
14481 (if ingroup (insert " "))
14482 (setq cnt 0)))))
14483 (setq ntable (nreverse ntable))
14484 (insert "\n")
14485 (goto-char (point-min))
14486 (if (not expert) (org-fit-window-to-buffer))
14487 (setq rtn
14488 (catch 'exit
14489 (while t
14490 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14491 (if (not groups) "no " "")
14492 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14493 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14494 (setq org-last-tag-selection-key c)
14495 (cond
14496 ((= c ?\r) (throw 'exit t))
14497 ((= c ?!)
14498 (setq groups (not groups))
14499 (goto-char (point-min))
14500 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14501 ((= c ?\C-c)
14502 (if (not expert)
14503 (org-fast-tag-show-exit
14504 (setq exit-after-next (not exit-after-next)))
14505 (setq expert nil)
14506 (delete-other-windows)
14507 (set-window-buffer (split-window-vertically) " *Org tags*")
14508 (org-switch-to-buffer-other-window " *Org tags*")
14509 (org-fit-window-to-buffer)))
14510 ((or (= c ?\C-g)
14511 (and (= c ?q) (not (rassoc c ntable))))
14512 (org-detach-overlay org-tags-overlay)
14513 (setq quit-flag t))
14514 ((= c ?\ )
14515 (setq current nil)
14516 (if exit-after-next (setq exit-after-next 'now)))
14517 ((= c ?\t)
14518 (condition-case nil
14519 (setq tg (org-icompleting-read
14520 "Tag: "
14521 (or buffer-tags
14522 (with-current-buffer buf
14523 (org-get-buffer-tags)))))
14524 (quit (setq tg "")))
14525 (when (string-match "\\S-" tg)
14526 (add-to-list 'buffer-tags (list tg))
14527 (if (member tg current)
14528 (setq current (delete tg current))
14529 (push tg current)))
14530 (if exit-after-next (setq exit-after-next 'now)))
14531 ((setq e (rassoc c todo-table) tg (car e))
14532 (with-current-buffer buf
14533 (save-excursion (org-todo tg)))
14534 (if exit-after-next (setq exit-after-next 'now)))
14535 ((setq e (rassoc c ntable) tg (car e))
14536 (if (member tg current)
14537 (setq current (delete tg current))
14538 (loop for g in groups do
14539 (if (member tg g)
14540 (mapc (lambda (x)
14541 (setq current (delete x current)))
14542 g)))
14543 (push tg current))
14544 (if exit-after-next (setq exit-after-next 'now))))
14546 ;; Create a sorted list
14547 (setq current
14548 (sort current
14549 (lambda (a b)
14550 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14551 (if (eq exit-after-next 'now) (throw 'exit t))
14552 (goto-char (point-min))
14553 (beginning-of-line 2)
14554 (delete-region (point) (point-at-eol))
14555 (org-fast-tag-insert "Current" current c-face)
14556 (org-set-current-tags-overlay current ov-prefix)
14557 (while (re-search-forward
14558 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14559 (setq tg (match-string 1))
14560 (add-text-properties
14561 (match-beginning 1) (match-end 1)
14562 (list 'face
14563 (cond
14564 ((member tg current) c-face)
14565 ((member tg inherited) i-face)
14566 (t (get-text-property (match-beginning 1) 'face))))))
14567 (goto-char (point-min)))))
14568 (org-detach-overlay org-tags-overlay)
14569 (if rtn
14570 (mapconcat 'identity current ":")
14571 nil))))
14573 (defun org-get-tags-string ()
14574 "Get the TAGS string in the current headline."
14575 (unless (org-at-heading-p t)
14576 (error "Not on a heading"))
14577 (save-excursion
14578 (beginning-of-line 1)
14579 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14580 (org-match-string-no-properties 1)
14581 "")))
14583 (defun org-get-tags ()
14584 "Get the list of tags specified in the current headline."
14585 (org-split-string (org-get-tags-string) ":"))
14587 (defun org-get-buffer-tags ()
14588 "Get a table of all tags used in the buffer, for completion."
14589 (let (tags)
14590 (save-excursion
14591 (goto-char (point-min))
14592 (while (re-search-forward
14593 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14594 (when (equal (char-after (point-at-bol 0)) ?*)
14595 (mapc (lambda (x) (add-to-list 'tags x))
14596 (org-split-string (org-match-string-no-properties 1) ":")))))
14597 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14598 (mapcar 'list tags)))
14600 ;;;; The mapping API
14602 (defun org-map-entries (func &optional match scope &rest skip)
14603 "Call FUNC at each headline selected by MATCH in SCOPE.
14605 FUNC is a function or a lisp form. The function will be called without
14606 arguments, with the cursor positioned at the beginning of the headline.
14607 The return values of all calls to the function will be collected and
14608 returned as a list.
14610 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14611 does not need to preserve point. After evaluation, the cursor will be
14612 moved to the end of the line (presumably of the headline of the
14613 processed entry) and search continues from there. Under some
14614 circumstances, this may not produce the wanted results. For example,
14615 if you have removed (e.g. archived) the current (sub)tree it could
14616 mean that the next entry will be skipped entirely. In such cases, you
14617 can specify the position from where search should continue by making
14618 FUNC set the variable `org-map-continue-from' to the desired buffer
14619 position.
14621 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14622 Only headlines that are matched by this query will be considered during
14623 the iteration. When MATCH is nil or t, all headlines will be
14624 visited by the iteration.
14626 SCOPE determines the scope of this command. It can be any of:
14628 nil The current buffer, respecting the restriction if any
14629 tree The subtree started with the entry at point
14630 region The entries within the active region, if any
14631 region-start-level
14632 The entries within the active region, but only those at
14633 the same level than the first one.
14634 file The current buffer, without restriction
14635 file-with-archives
14636 The current buffer, and any archives associated with it
14637 agenda All agenda files
14638 agenda-with-archives
14639 All agenda files with any archive files associated with them
14640 \(file1 file2 ...)
14641 If this is a list, all files in the list will be scanned
14643 The remaining args are treated as settings for the skipping facilities of
14644 the scanner. The following items can be given here:
14646 archive skip trees with the archive tag
14647 comment skip trees with the COMMENT keyword
14648 function or Emacs Lisp form:
14649 will be used as value for `org-agenda-skip-function', so
14650 whenever the function returns a position, FUNC will not be
14651 called for that entry and search will continue from the
14652 position returned
14654 If your function needs to retrieve the tags including inherited tags
14655 at the *current* entry, you can use the value of the variable
14656 `org-scanner-tags' which will be much faster than getting the value
14657 with `org-get-tags-at'. If your function gets properties with
14658 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14659 to t around the call to `org-entry-properties' to get the same speedup.
14660 Note that if your function moves around to retrieve tags and properties at
14661 a *different* entry, you cannot use these techniques."
14662 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14663 (not (org-region-active-p)))
14664 (let* ((org-agenda-archives-mode nil) ; just to make sure
14665 (org-agenda-skip-archived-trees (memq 'archive skip))
14666 (org-agenda-skip-comment-trees (memq 'comment skip))
14667 (org-agenda-skip-function
14668 (car (org-delete-all '(comment archive) skip)))
14669 (org-tags-match-list-sublevels t)
14670 (start-level (eq scope 'region-start-level))
14671 matcher file res
14672 org-todo-keywords-for-agenda
14673 org-done-keywords-for-agenda
14674 org-todo-keyword-alist-for-agenda
14675 org-drawers-for-agenda
14676 org-tag-alist-for-agenda
14677 todo-only)
14679 (cond
14680 ((eq match t) (setq matcher t))
14681 ((eq match nil) (setq matcher t))
14682 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14684 (save-window-excursion
14685 (save-restriction
14686 (cond ((eq scope 'tree)
14687 (org-back-to-heading t)
14688 (org-narrow-to-subtree)
14689 (setq scope nil))
14690 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14691 (org-region-active-p))
14692 ;; If needed, set start-level to a string like "2"
14693 (when start-level
14694 (save-excursion
14695 (goto-char (region-beginning))
14696 (unless (org-at-heading-p) (outline-next-heading))
14697 (setq start-level (org-current-level))))
14698 (narrow-to-region (region-beginning)
14699 (save-excursion
14700 (goto-char (region-end))
14701 (unless (and (bolp) (org-at-heading-p))
14702 (outline-next-heading))
14703 (point)))
14704 (setq scope nil)))
14706 (if (not scope)
14707 (progn
14708 (org-agenda-prepare-buffers
14709 (list (buffer-file-name (current-buffer))))
14710 (setq res (org-scan-tags func matcher todo-only start-level)))
14711 ;; Get the right scope
14712 (cond
14713 ((and scope (listp scope) (symbolp (car scope)))
14714 (setq scope (eval scope)))
14715 ((eq scope 'agenda)
14716 (setq scope (org-agenda-files t)))
14717 ((eq scope 'agenda-with-archives)
14718 (setq scope (org-agenda-files t))
14719 (setq scope (org-add-archive-files scope)))
14720 ((eq scope 'file)
14721 (setq scope (list (buffer-file-name))))
14722 ((eq scope 'file-with-archives)
14723 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14724 (org-agenda-prepare-buffers scope)
14725 (while (setq file (pop scope))
14726 (with-current-buffer (org-find-base-buffer-visiting file)
14727 (save-excursion
14728 (save-restriction
14729 (widen)
14730 (goto-char (point-min))
14731 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14732 res)))
14734 ;;;; Properties
14736 ;;; Setting and retrieving properties
14738 (defconst org-special-properties
14739 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14740 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14741 "The special properties valid in Org-mode.
14743 These are properties that are not defined in the property drawer,
14744 but in some other way.")
14746 (defconst org-default-properties
14747 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14748 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14749 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14750 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14751 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14752 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14753 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14754 "Some properties that are used by Org-mode for various purposes.
14755 Being in this list makes sure that they are offered for completion.")
14757 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14758 "Regular expression matching the first line of a property drawer.")
14760 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14761 "Regular expression matching the last line of a property drawer.")
14763 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14764 "Regular expression matching the first line of a property drawer.")
14766 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14767 "Regular expression matching the first line of a property drawer.")
14769 (defconst org-property-drawer-re
14770 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14771 org-property-end-re "\\)\n?")
14772 "Matches an entire property drawer.")
14774 (defconst org-clock-drawer-re
14775 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14776 org-property-end-re "\\)\n?")
14777 "Matches an entire clock drawer.")
14779 (defsubst org-re-property (property)
14780 "Return a regexp matching a PROPERTY line.
14781 Match group 1 will be set to the value."
14782 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14784 (defsubst org-re-property-keyword (property)
14785 "Return a regexp matching a PROPERTY line, possibly with no
14786 value for the property."
14787 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14789 (defun org-property-action ()
14790 "Do an action on properties."
14791 (interactive)
14792 (let (c)
14793 (org-at-property-p)
14794 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14795 (setq c (read-char-exclusive))
14796 (cond
14797 ((equal c ?s)
14798 (call-interactively 'org-set-property))
14799 ((equal c ?d)
14800 (call-interactively 'org-delete-property))
14801 ((equal c ?D)
14802 (call-interactively 'org-delete-property-globally))
14803 ((equal c ?c)
14804 (call-interactively 'org-compute-property-at-point))
14805 (t (error "No such property action %c" c)))))
14807 (defun org-inc-effort ()
14808 "Increment the value of the effort property in the current entry."
14809 (interactive)
14810 (org-set-effort nil t))
14812 (defvar org-clock-effort) ;; Defined in org-clock.el
14813 (defvar org-clock-current-task) ;; Defined in org-clock.el
14814 (defun org-set-effort (&optional value increment)
14815 "Set the effort property of the current entry.
14816 With numerical prefix arg, use the nth allowed value, 0 stands for the
14817 10th allowed value.
14819 When INCREMENT is non-nil, set the property to the next allowed value."
14820 (interactive "P")
14821 (if (equal value 0) (setq value 10))
14822 (let* ((completion-ignore-case t)
14823 (prop org-effort-property)
14824 (cur (org-entry-get nil prop))
14825 (allowed (org-property-get-allowed-values nil prop 'table))
14826 (existing (mapcar 'list (org-property-values prop)))
14827 (heading (nth 4 (org-heading-components)))
14829 (val (cond
14830 ((stringp value) value)
14831 ((and allowed (integerp value))
14832 (or (car (nth (1- value) allowed))
14833 (car (org-last allowed))))
14834 ((and allowed increment)
14835 (or (caadr (member (list cur) allowed))
14836 (error "Allowed effort values are not set")))
14837 (allowed
14838 (message "Select 1-9,0, [RET%s]: %s"
14839 (if cur (concat "=" cur) "")
14840 (mapconcat 'car allowed " "))
14841 (setq rpl (read-char-exclusive))
14842 (if (equal rpl ?\r)
14844 (setq rpl (- rpl ?0))
14845 (if (equal rpl 0) (setq rpl 10))
14846 (if (and (> rpl 0) (<= rpl (length allowed)))
14847 (car (nth (1- rpl) allowed))
14848 (org-completing-read "Effort: " allowed nil))))
14850 (let (org-completion-use-ido org-completion-use-iswitchb)
14851 (org-completing-read
14852 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14853 (concat "[" cur "]") "")
14854 ": ")
14855 existing nil nil "" nil cur))))))
14856 (unless (equal (org-entry-get nil prop) val)
14857 (org-entry-put nil prop val))
14858 (save-excursion
14859 (org-back-to-heading t)
14860 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14861 (when (string= heading org-clock-current-task)
14862 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14863 (org-clock-update-mode-line))
14864 (message "%s is now %s" prop val)))
14866 (defun org-at-property-p ()
14867 "Is cursor inside a property drawer?"
14868 (save-excursion
14869 (beginning-of-line 1)
14870 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14871 (save-match-data ;; Used by calling procedures
14872 (let ((p (point))
14873 (range (unless (org-before-first-heading-p)
14874 (org-get-property-block))))
14875 (and range (<= (car range) p) (< p (cdr range))))))))
14877 (defun org-get-property-block (&optional beg end force)
14878 "Return the (beg . end) range of the body of the property drawer.
14879 BEG and END are the beginning and end of the current subtree, or of
14880 the part before the first headline. If they are not given, they will
14881 be found. If the drawer does not exist and FORCE is non-nil, create
14882 the drawer."
14883 (catch 'exit
14884 (save-excursion
14885 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14886 (progn (org-back-to-heading t) (point))))
14887 (end (or end (and (not (outline-next-heading)) (point-max))
14888 (point))))
14889 (goto-char beg)
14890 (if (re-search-forward org-property-start-re end t)
14891 (setq beg (1+ (match-end 0)))
14892 (if force
14893 (save-excursion
14894 (org-insert-property-drawer)
14895 (setq end (progn (outline-next-heading) (point))))
14896 (throw 'exit nil))
14897 (goto-char beg)
14898 (if (re-search-forward org-property-start-re end t)
14899 (setq beg (1+ (match-end 0)))))
14900 (if (re-search-forward org-property-end-re end t)
14901 (setq end (match-beginning 0))
14902 (or force (throw 'exit nil))
14903 (goto-char beg)
14904 (setq end beg)
14905 (org-indent-line)
14906 (insert ":END:\n"))
14907 (cons beg end)))))
14909 (defun org-entry-properties (&optional pom which specific)
14910 "Get all properties of the entry at point-or-marker POM.
14911 This includes the TODO keyword, the tags, time strings for deadline,
14912 scheduled, and clocking, and any additional properties defined in the
14913 entry. The return value is an alist, keys may occur multiple times
14914 if the property key was used several times.
14915 POM may also be nil, in which case the current entry is used.
14916 If WHICH is nil or `all', get all properties. If WHICH is
14917 `special' or `standard', only get that subclass. If WHICH
14918 is a string only get exactly this property. SPECIFIC can be a string, the
14919 specific property we are interested in. Specifying it can speed
14920 things up because then unnecessary parsing is avoided."
14921 (setq which (or which 'all))
14922 (org-with-point-at pom
14923 (let ((clockstr (substring org-clock-string 0 -1))
14924 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14925 (case-fold-search nil)
14926 beg end range props sum-props key key1 value string clocksum clocksumt)
14927 (save-excursion
14928 (when (condition-case nil
14929 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14930 (error nil))
14931 (setq beg (point))
14932 (setq sum-props (get-text-property (point) 'org-summaries))
14933 (setq clocksum (get-text-property (point) :org-clock-minutes)
14934 clocksumt (get-text-property (point) :org-clock-minutes-today))
14935 (outline-next-heading)
14936 (setq end (point))
14937 (when (memq which '(all special))
14938 ;; Get the special properties, like TODO and tags
14939 (goto-char beg)
14940 (when (and (or (not specific) (string= specific "TODO"))
14941 (looking-at org-todo-line-regexp) (match-end 2))
14942 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14943 (when (and (or (not specific) (string= specific "PRIORITY"))
14944 (looking-at org-priority-regexp))
14945 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14946 (when (or (not specific) (string= specific "FILE"))
14947 (push (cons "FILE" buffer-file-name) props))
14948 (when (and (or (not specific) (string= specific "TAGS"))
14949 (setq value (org-get-tags-string))
14950 (string-match "\\S-" value))
14951 (push (cons "TAGS" value) props))
14952 (when (and (or (not specific) (string= specific "ALLTAGS"))
14953 (setq value (org-get-tags-at)))
14954 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14955 ":"))
14956 props))
14957 (when (or (not specific) (string= specific "BLOCKED"))
14958 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14959 (when (or (not specific)
14960 (member specific
14961 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14962 "TIMESTAMP" "TIMESTAMP_IA")))
14963 (catch 'match
14964 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14965 (setq key (if (match-end 1)
14966 (substring (org-match-string-no-properties 1)
14967 0 -1))
14968 string (if (equal key clockstr)
14969 (org-trim
14970 (buffer-substring-no-properties
14971 (match-beginning 3) (goto-char
14972 (point-at-eol))))
14973 (substring (org-match-string-no-properties 3)
14974 1 -1)))
14975 ;; Get the correct property name from the key. This is
14976 ;; necessary if the user has configured time keywords.
14977 (setq key1 (concat key ":"))
14978 (cond
14979 ((not key)
14980 (setq key
14981 (if (= (char-after (match-beginning 3)) ?\[)
14982 "TIMESTAMP_IA" "TIMESTAMP")))
14983 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14984 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14985 ((equal key1 org-closed-string) (setq key "CLOSED"))
14986 ((equal key1 org-clock-string) (setq key "CLOCK")))
14987 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14988 (progn
14989 (push (cons key string) props)
14990 ;; no need to search further if match is found
14991 (throw 'match t))
14992 (when (or (equal key "CLOCK") (not (assoc key props)))
14993 (push (cons key string) props)))))))
14995 (when (memq which '(all standard))
14996 ;; Get the standard properties, like :PROP: ...
14997 (setq range (org-get-property-block beg end))
14998 (when range
14999 (goto-char (car range))
15000 (while (re-search-forward
15001 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15002 (cdr range) t)
15003 (setq key (org-match-string-no-properties 1)
15004 value (org-trim (or (org-match-string-no-properties 2) "")))
15005 (unless (member key excluded)
15006 (push (cons key (or value "")) props)))))
15007 (if clocksum
15008 (push (cons "CLOCKSUM"
15009 (org-columns-number-to-string (/ (float clocksum) 60.)
15010 'add_times))
15011 props))
15012 (if clocksumt
15013 (push (cons "CLOCKSUM_T"
15014 (org-columns-number-to-string (/ (float clocksumt) 60.)
15015 'add_times))
15016 props))
15017 (unless (assoc "CATEGORY" props)
15018 (push (cons "CATEGORY" (org-get-category)) props))
15019 (append sum-props (nreverse props)))))))
15021 (defun org-entry-get (pom property &optional inherit literal-nil)
15022 "Get value of PROPERTY for entry or content at point-or-marker POM.
15023 If INHERIT is non-nil and the entry does not have the property,
15024 then also check higher levels of the hierarchy.
15025 If INHERIT is the symbol `selective', use inheritance only if the setting
15026 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15027 If the property is present but empty, the return value is the empty string.
15028 If the property is not present at all, nil is returned.
15030 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15031 do not interpret it as the list atom nil. This is used for inheritance
15032 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15033 (org-with-point-at pom
15034 (if (and inherit (if (eq inherit 'selective)
15035 (org-property-inherit-p property)
15037 (org-entry-get-with-inheritance property literal-nil)
15038 (if (member property org-special-properties)
15039 ;; We need a special property. Use `org-entry-properties' to
15040 ;; retrieve it, but specify the wanted property
15041 (cdr (assoc property (org-entry-properties nil 'special property)))
15042 (let ((range (org-get-property-block)))
15043 (when (and range (not (eq (car range) (cdr range))))
15044 (let* ((props (list (or (assoc property org-file-properties)
15045 (assoc property org-global-properties)
15046 (assoc property org-global-properties-fixed))))
15047 (ap (lambda (key)
15048 (when (re-search-forward
15049 (org-re-property key) (cdr range) t)
15050 (setq props
15051 (org-update-property-plist
15053 (if (match-end 1)
15054 (org-match-string-no-properties 1) "")
15055 props)))))
15056 val)
15057 (goto-char (car range))
15058 (funcall ap property)
15059 (goto-char (car range))
15060 (while (funcall ap (concat property "+")))
15061 (setq val (cdr (assoc property props)))
15062 (when val (if literal-nil val (org-not-nil val))))))))))
15064 (defun org-property-or-variable-value (var &optional inherit)
15065 "Check if there is a property fixing the value of VAR.
15066 If yes, return this value. If not, return the current value of the variable."
15067 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15068 (if (and prop (stringp prop) (string-match "\\S-" prop))
15069 (read prop)
15070 (symbol-value var))))
15072 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15073 "Delete the property PROPERTY from entry at point-or-marker POM.
15074 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15075 an empty drawer to delete."
15076 (org-with-point-at pom
15077 (if (member property org-special-properties)
15078 nil ; cannot delete these properties.
15079 (let ((range (org-get-property-block)))
15080 (if (and range
15081 (goto-char (car range))
15082 (re-search-forward
15083 (org-re-property property)
15084 (cdr range) t))
15085 (progn
15086 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15087 (and delete-empty-drawer
15088 (org-remove-empty-drawer-at
15089 delete-empty-drawer (car range)))
15091 nil)))))
15093 ;; Multi-values properties are properties that contain multiple values
15094 ;; These values are assumed to be single words, separated by whitespace.
15095 (defun org-entry-add-to-multivalued-property (pom property value)
15096 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15097 (let* ((old (org-entry-get pom property))
15098 (values (and old (org-split-string old "[ \t]"))))
15099 (setq value (org-entry-protect-space value))
15100 (unless (member value values)
15101 (setq values (append values (list value)))
15102 (org-entry-put pom property
15103 (mapconcat 'identity values " ")))))
15105 (defun org-entry-remove-from-multivalued-property (pom property value)
15106 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15107 (let* ((old (org-entry-get pom property))
15108 (values (and old (org-split-string old "[ \t]"))))
15109 (setq value (org-entry-protect-space value))
15110 (when (member value values)
15111 (setq values (delete value values))
15112 (org-entry-put pom property
15113 (mapconcat 'identity values " ")))))
15115 (defun org-entry-member-in-multivalued-property (pom property value)
15116 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15117 (let* ((old (org-entry-get pom property))
15118 (values (and old (org-split-string old "[ \t]"))))
15119 (setq value (org-entry-protect-space value))
15120 (member value values)))
15122 (defun org-entry-get-multivalued-property (pom property)
15123 "Return a list of values in a multivalued property."
15124 (let* ((value (org-entry-get pom property))
15125 (values (and value (org-split-string value "[ \t]"))))
15126 (mapcar 'org-entry-restore-space values)))
15128 (defun org-entry-put-multivalued-property (pom property &rest values)
15129 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15130 VALUES should be a list of strings. Spaces will be protected."
15131 (org-entry-put pom property
15132 (mapconcat 'org-entry-protect-space values " "))
15133 (let* ((value (org-entry-get pom property))
15134 (values (and value (org-split-string value "[ \t]"))))
15135 (mapcar 'org-entry-restore-space values)))
15137 (defun org-entry-protect-space (s)
15138 "Protect spaces and newline in string S."
15139 (while (string-match " " s)
15140 (setq s (replace-match "%20" t t s)))
15141 (while (string-match "\n" s)
15142 (setq s (replace-match "%0A" t t s)))
15145 (defun org-entry-restore-space (s)
15146 "Restore spaces and newline in string S."
15147 (while (string-match "%20" s)
15148 (setq s (replace-match " " t t s)))
15149 (while (string-match "%0A" s)
15150 (setq s (replace-match "\n" t t s)))
15153 (defvar org-entry-property-inherited-from (make-marker)
15154 "Marker pointing to the entry from where a property was inherited.
15155 Each call to `org-entry-get-with-inheritance' will set this marker to the
15156 location of the entry where the inheritance search matched. If there was
15157 no match, the marker will point nowhere.
15158 Note that also `org-entry-get' calls this function, if the INHERIT flag
15159 is set.")
15161 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15162 "Get PROPERTY of entry or content at point, search higher levels if needed.
15163 The search will stop at the first ancestor which has the property defined.
15164 If the value found is \"nil\", return nil to show that the property
15165 should be considered as undefined (this is the meaning of nil here).
15166 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15167 (move-marker org-entry-property-inherited-from nil)
15168 (let (tmp)
15169 (save-excursion
15170 (save-restriction
15171 (widen)
15172 (catch 'ex
15173 (while t
15174 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15175 (or (ignore-errors (org-back-to-heading t))
15176 (goto-char (point-min)))
15177 (move-marker org-entry-property-inherited-from (point))
15178 (throw 'ex tmp))
15179 (or (ignore-errors (org-up-heading-safe))
15180 (throw 'ex nil))))))
15181 (setq tmp (or tmp
15182 (cdr (assoc property org-file-properties))
15183 (cdr (assoc property org-global-properties))
15184 (cdr (assoc property org-global-properties-fixed))))
15185 (if literal-nil tmp (org-not-nil tmp))))
15187 (defvar org-property-changed-functions nil
15188 "Hook called when the value of a property has changed.
15189 Each hook function should accept two arguments, the name of the property
15190 and the new value.")
15192 (defun org-entry-put (pom property value)
15193 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15194 (org-with-point-at pom
15195 (org-back-to-heading t)
15196 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15197 range)
15198 (cond
15199 ((equal property "TODO")
15200 (when (and (stringp value) (string-match "\\S-" value)
15201 (not (member value org-todo-keywords-1)))
15202 (error "\"%s\" is not a valid TODO state" value))
15203 (if (or (not value)
15204 (not (string-match "\\S-" value)))
15205 (setq value 'none))
15206 (org-todo value)
15207 (org-set-tags nil 'align))
15208 ((equal property "PRIORITY")
15209 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15210 (string-to-char value) ?\ ))
15211 (org-set-tags nil 'align))
15212 ((equal property "CLOCKSUM")
15213 (if (not (re-search-forward
15214 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15215 (error "Cannot find a clock log")
15216 (goto-char (- (match-end 1) 2))
15217 (cond
15218 ((eq value 'earlier) (org-timestamp-down))
15219 ((eq value 'later) (org-timestamp-up)))
15220 (org-clock-sum-current-item)))
15221 ((equal property "SCHEDULED")
15222 (if (re-search-forward org-scheduled-time-regexp end t)
15223 (cond
15224 ((eq value 'earlier) (org-timestamp-change -1 'day))
15225 ((eq value 'later) (org-timestamp-change 1 'day))
15226 (t (call-interactively 'org-schedule)))
15227 (call-interactively 'org-schedule)))
15228 ((equal property "DEADLINE")
15229 (if (re-search-forward org-deadline-time-regexp end t)
15230 (cond
15231 ((eq value 'earlier) (org-timestamp-change -1 'day))
15232 ((eq value 'later) (org-timestamp-change 1 'day))
15233 (t (call-interactively 'org-deadline)))
15234 (call-interactively 'org-deadline)))
15235 ((member property org-special-properties)
15236 (error "The %s property can not yet be set with `org-entry-put'"
15237 property))
15238 (t ; a non-special property
15239 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15240 (setq range (org-get-property-block beg end 'force))
15241 (goto-char (car range))
15242 (if (re-search-forward
15243 (org-re-property-keyword property) (cdr range) t)
15244 (progn
15245 (delete-region (match-beginning 0) (match-end 0))
15246 (goto-char (match-beginning 0)))
15247 (goto-char (cdr range))
15248 (insert "\n")
15249 (backward-char 1)
15250 (org-indent-line))
15251 (insert ":" property ":")
15252 (and value (insert " " value))
15253 (org-indent-line)))))
15254 (run-hook-with-args 'org-property-changed-functions property value)))
15256 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15257 "Get all property keys in the current buffer.
15258 With INCLUDE-SPECIALS, also list the special properties that reflect things
15259 like tags and TODO state.
15260 With INCLUDE-DEFAULTS, also include properties that has special meaning
15261 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15262 and others.
15263 With INCLUDE-COLUMNS, also include property names given in COLUMN
15264 formats in the current buffer."
15265 (let (rtn range cfmt s p)
15266 (save-excursion
15267 (save-restriction
15268 (widen)
15269 (goto-char (point-min))
15270 (while (re-search-forward org-property-start-re nil t)
15271 (setq range (org-get-property-block))
15272 (goto-char (car range))
15273 (while (re-search-forward
15274 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15275 (cdr range) t)
15276 (add-to-list 'rtn (org-match-string-no-properties 1)))
15277 (outline-next-heading))))
15279 (when include-specials
15280 (setq rtn (append org-special-properties rtn)))
15282 (when include-defaults
15283 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15284 (add-to-list 'rtn org-effort-property))
15286 (when include-columns
15287 (save-excursion
15288 (save-restriction
15289 (widen)
15290 (goto-char (point-min))
15291 (while (re-search-forward
15292 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15293 nil t)
15294 (setq cfmt (match-string 2) s 0)
15295 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15296 cfmt s)
15297 (setq s (match-end 0)
15298 p (match-string 1 cfmt))
15299 (unless (or (equal p "ITEM")
15300 (member p org-special-properties))
15301 (add-to-list 'rtn (match-string 1 cfmt))))))))
15303 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15305 (defun org-property-values (key)
15306 "Return a list of all values of property KEY in the current buffer."
15307 (save-excursion
15308 (save-restriction
15309 (widen)
15310 (goto-char (point-min))
15311 (let ((re (org-re-property key))
15312 values)
15313 (while (re-search-forward re nil t)
15314 (add-to-list 'values (org-trim (match-string 1))))
15315 (delete "" values)))))
15317 (defun org-insert-property-drawer ()
15318 "Insert a property drawer into the current entry."
15319 (org-back-to-heading t)
15320 (looking-at org-outline-regexp)
15321 (let ((indent (if org-adapt-indentation
15322 (- (match-end 0) (match-beginning 0))
15324 (beg (point))
15325 (re (concat "^[ \t]*" org-keyword-time-regexp))
15326 end hiddenp)
15327 (outline-next-heading)
15328 (setq end (point))
15329 (goto-char beg)
15330 (while (re-search-forward re end t))
15331 (setq hiddenp (outline-invisible-p))
15332 (end-of-line 1)
15333 (and (equal (char-after) ?\n) (forward-char 1))
15334 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15335 (if (member (match-string 1) '("CLOCK:" ":END:"))
15336 ;; just skip this line
15337 (beginning-of-line 2)
15338 ;; Drawer start, find the end
15339 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15340 (beginning-of-line 1)))
15341 (org-skip-over-state-notes)
15342 (skip-chars-backward " \t\n\r")
15343 (if (eq (char-before) ?*) (forward-char 1))
15344 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15345 (beginning-of-line 0)
15346 (org-indent-to-column indent)
15347 (beginning-of-line 2)
15348 (org-indent-to-column indent)
15349 (beginning-of-line 0)
15350 (if hiddenp
15351 (save-excursion
15352 (org-back-to-heading t)
15353 (hide-entry))
15354 (org-flag-drawer t))))
15356 (defun org-insert-drawer (&optional arg drawer)
15357 "Insert a drawer at point.
15359 Optional argument DRAWER, when non-nil, is a string representing
15360 drawer's name. Otherwise, the user is prompted for a name.
15362 If a region is active, insert the drawer around that region
15363 instead.
15365 Point is left between drawer's boundaries."
15366 (interactive "P")
15367 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15368 "LOGBOOK"))
15369 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15370 ;; internally by Org. They are meant to be inserted
15371 ;; automatically.
15372 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15373 ;; Remove system drawers from list. Note: For some reason,
15374 ;; `org-completing-read' ignores the predicate while
15375 ;; `completing-read' handles it fine.
15376 (drawer (if arg "PROPERTIES"
15377 (or drawer
15378 (completing-read
15379 "Drawer: " org-drawers
15380 (lambda (d) (not (member d system-drawers))))))))
15381 (cond
15382 ;; With C-u, fall back on `org-insert-property-drawer'
15383 (arg (org-insert-property-drawer))
15384 ;; With an active region, insert a drawer at point.
15385 ((not (org-region-active-p))
15386 (progn
15387 (unless (bolp) (insert "\n"))
15388 (insert (format ":%s:\n\n:END:\n" drawer))
15389 (forward-line -2)))
15390 ;; Otherwise, insert the drawer at point
15392 (let ((rbeg (region-beginning))
15393 (rend (copy-marker (region-end))))
15394 (unwind-protect
15395 (progn
15396 (goto-char rbeg)
15397 (beginning-of-line)
15398 (when (save-excursion
15399 (re-search-forward org-outline-regexp-bol rend t))
15400 (error "Drawers cannot contain headlines"))
15401 ;; Position point at the beginning of the first
15402 ;; non-blank line in region. Insert drawer's opening
15403 ;; there, then indent it.
15404 (org-skip-whitespace)
15405 (beginning-of-line)
15406 (insert ":" drawer ":\n")
15407 (forward-line -1)
15408 (indent-for-tab-command)
15409 ;; Move point to the beginning of the first blank line
15410 ;; after the last non-blank line in region. Insert
15411 ;; drawer's closing, then indent it.
15412 (goto-char rend)
15413 (skip-chars-backward " \r\t\n")
15414 (insert "\n:END:")
15415 (deactivate-mark t)
15416 (indent-for-tab-command)
15417 (unless (eolp) (insert "\n")))
15418 ;; Clear marker, whatever the outcome of insertion is.
15419 (set-marker rend nil)))))))
15421 (defvar org-property-set-functions-alist nil
15422 "Property set function alist.
15423 Each entry should have the following format:
15425 (PROPERTY . READ-FUNCTION)
15427 The read function will be called with the same argument as
15428 `org-completing-read'.")
15430 (defun org-set-property-function (property)
15431 "Get the function that should be used to set PROPERTY.
15432 This is computed according to `org-property-set-functions-alist'."
15433 (or (cdr (assoc property org-property-set-functions-alist))
15434 'org-completing-read))
15436 (defun org-read-property-value (property)
15437 "Read PROPERTY value from user."
15438 (let* ((completion-ignore-case t)
15439 (allowed (org-property-get-allowed-values nil property 'table))
15440 (cur (org-entry-get nil property))
15441 (prompt (concat property " value"
15442 (if (and cur (string-match "\\S-" cur))
15443 (concat " [" cur "]") "") ": "))
15444 (set-function (org-set-property-function property))
15445 (val (if allowed
15446 (funcall set-function prompt allowed nil
15447 (not (get-text-property 0 'org-unrestricted
15448 (caar allowed))))
15449 (let (org-completion-use-ido org-completion-use-iswitchb)
15450 (funcall set-function prompt
15451 (mapcar 'list (org-property-values property))
15452 nil nil "" nil cur)))))
15453 (if (equal val "")
15455 val)))
15457 (defvar org-last-set-property nil)
15458 (defvar org-last-set-property-value nil)
15459 (defun org-read-property-name ()
15460 "Read a property name."
15461 (let* ((completion-ignore-case t)
15462 (keys (org-buffer-property-keys nil t t))
15463 (default-prop (or (save-excursion
15464 (save-match-data
15465 (beginning-of-line)
15466 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15467 (null (string= (match-string 1) "END"))
15468 (match-string 1))))
15469 org-last-set-property))
15470 (property (org-icompleting-read
15471 (concat "Property"
15472 (if default-prop (concat " [" default-prop "]") "")
15473 ": ")
15474 (mapcar 'list keys)
15475 nil nil nil nil
15476 default-prop)))
15477 (if (member property keys)
15478 property
15479 (or (cdr (assoc (downcase property)
15480 (mapcar (lambda (x) (cons (downcase x) x))
15481 keys)))
15482 property))))
15484 (defun org-set-property-and-value (use-last)
15485 "Allow to set [PROPERTY]: [value] direction from prompt.
15486 When use-default, don't even ask, just use the last
15487 \"[PROPERTY]: [value]\" string from the history."
15488 (interactive "P")
15489 (let* ((completion-ignore-case t)
15490 (pv (or (and use-last org-last-set-property-value)
15491 (org-completing-read
15492 "Enter a \"[Property]: [value]\" pair: "
15493 nil nil nil nil nil
15494 org-last-set-property-value)))
15495 prop val)
15496 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15497 (setq prop (match-string 1 pv)
15498 val (match-string 2 pv))
15499 (org-set-property prop val))))
15501 (defun org-set-property (property value)
15502 "In the current entry, set PROPERTY to VALUE.
15503 When called interactively, this will prompt for a property name, offering
15504 completion on existing and default properties. And then it will prompt
15505 for a value, offering completion either on allowed values (via an inherited
15506 xxx_ALL property) or on existing values in other instances of this property
15507 in the current file."
15508 (interactive (list nil nil))
15509 (let* ((property (or property (org-read-property-name)))
15510 (value (or value (org-read-property-value property)))
15511 (fn (cdr (assoc property org-properties-postprocess-alist))))
15512 (setq org-last-set-property property)
15513 (setq org-last-set-property-value (concat property ": " value))
15514 ;; Possibly postprocess the inserted value:
15515 (when fn (setq value (funcall fn value)))
15516 (unless (equal (org-entry-get nil property) value)
15517 (org-entry-put nil property value))))
15519 (defun org-delete-property (property &optional delete-empty-drawer)
15520 "In the current entry, delete PROPERTY.
15521 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15522 an empty drawer to delete."
15523 (interactive
15524 (let* ((completion-ignore-case t)
15525 (prop (org-icompleting-read "Property: "
15526 (org-entry-properties nil 'standard))))
15527 (list prop)))
15528 (message "Property %s %s" property
15529 (if (org-entry-delete nil property delete-empty-drawer)
15530 "deleted"
15531 "was not present in the entry")))
15533 (defun org-delete-property-globally (property)
15534 "Remove PROPERTY globally, from all entries."
15535 (interactive
15536 (let* ((completion-ignore-case t)
15537 (prop (org-icompleting-read
15538 "Globally remove property: "
15539 (mapcar 'list (org-buffer-property-keys)))))
15540 (list prop)))
15541 (save-excursion
15542 (save-restriction
15543 (widen)
15544 (goto-char (point-min))
15545 (let ((cnt 0))
15546 (while (re-search-forward
15547 (org-re-property property)
15548 nil t)
15549 (setq cnt (1+ cnt))
15550 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15551 (message "Property \"%s\" removed from %d entries" property cnt)))))
15553 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15555 (defun org-compute-property-at-point ()
15556 "Compute the property at point.
15557 This looks for an enclosing column format, extracts the operator and
15558 then applies it to the property in the column format's scope."
15559 (interactive)
15560 (unless (org-at-property-p)
15561 (error "Not at a property"))
15562 (let ((prop (org-match-string-no-properties 2)))
15563 (org-columns-get-format-and-top-level)
15564 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15565 (error "No operator defined for property %s" prop))
15566 (org-columns-compute prop)))
15568 (defvar org-property-allowed-value-functions nil
15569 "Hook for functions supplying allowed values for a specific property.
15570 The functions must take a single argument, the name of the property, and
15571 return a flat list of allowed values. If \":ETC\" is one of
15572 the values, this means that these values are intended as defaults for
15573 completion, but that other values should be allowed too.
15574 The functions must return nil if they are not responsible for this
15575 property.")
15577 (defun org-property-get-allowed-values (pom property &optional table)
15578 "Get allowed values for the property PROPERTY.
15579 When TABLE is non-nil, return an alist that can directly be used for
15580 completion."
15581 (let (vals)
15582 (cond
15583 ((equal property "TODO")
15584 (setq vals (org-with-point-at pom
15585 (append org-todo-keywords-1 '("")))))
15586 ((equal property "PRIORITY")
15587 (let ((n org-lowest-priority))
15588 (while (>= n org-highest-priority)
15589 (push (char-to-string n) vals)
15590 (setq n (1- n)))))
15591 ((member property org-special-properties))
15592 ((setq vals (run-hook-with-args-until-success
15593 'org-property-allowed-value-functions property)))
15595 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15596 (when (and vals (string-match "\\S-" vals))
15597 (setq vals (car (read-from-string (concat "(" vals ")"))))
15598 (setq vals (mapcar (lambda (x)
15599 (cond ((stringp x) x)
15600 ((numberp x) (number-to-string x))
15601 ((symbolp x) (symbol-name x))
15602 (t "???")))
15603 vals)))))
15604 (when (member ":ETC" vals)
15605 (setq vals (remove ":ETC" vals))
15606 (org-add-props (car vals) '(org-unrestricted t)))
15607 (if table (mapcar 'list vals) vals)))
15609 (defun org-property-previous-allowed-value (&optional previous)
15610 "Switch to the next allowed value for this property."
15611 (interactive)
15612 (org-property-next-allowed-value t))
15614 (defun org-property-next-allowed-value (&optional previous)
15615 "Switch to the next allowed value for this property."
15616 (interactive)
15617 (unless (org-at-property-p)
15618 (error "Not at a property"))
15619 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15620 (key (match-string 2))
15621 (value (match-string 3))
15622 (allowed (or (org-property-get-allowed-values (point) key)
15623 (and (member value '("[ ]" "[-]" "[X]"))
15624 '("[ ]" "[X]"))))
15625 (heading (save-match-data (nth 4 (org-heading-components))))
15626 nval)
15627 (unless allowed
15628 (error "Allowed values for this property have not been defined"))
15629 (if previous (setq allowed (reverse allowed)))
15630 (if (member value allowed)
15631 (setq nval (car (cdr (member value allowed)))))
15632 (setq nval (or nval (car allowed)))
15633 (if (equal nval value)
15634 (error "Only one allowed value for this property"))
15635 (org-at-property-p)
15636 (replace-match (concat " :" key ": " nval) t t)
15637 (org-indent-line)
15638 (beginning-of-line 1)
15639 (skip-chars-forward " \t")
15640 (when (equal prop org-effort-property)
15641 (save-excursion
15642 (org-back-to-heading t)
15643 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15644 (when (string= org-clock-current-task heading)
15645 (setq org-clock-effort nval)
15646 (org-clock-update-mode-line)))
15647 (run-hook-with-args 'org-property-changed-functions key nval)))
15649 (defun org-find-olp (path &optional this-buffer)
15650 "Return a marker pointing to the entry at outline path OLP.
15651 If anything goes wrong, throw an error.
15652 You can wrap this call to catch the error like this:
15654 (condition-case msg
15655 (org-mobile-locate-entry (match-string 4))
15656 (error (nth 1 msg)))
15658 The return value will then be either a string with the error message,
15659 or a marker if everything is OK.
15661 If THIS-BUFFER is set, the outline path does not contain a file,
15662 only headings."
15663 (let* ((file (if this-buffer buffer-file-name (pop path)))
15664 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15665 (level 1)
15666 (lmin 1)
15667 (lmax 1)
15668 limit re end found pos heading cnt flevel)
15669 (unless buffer (error "File not found :%s" file))
15670 (with-current-buffer buffer
15671 (save-excursion
15672 (save-restriction
15673 (widen)
15674 (setq limit (point-max))
15675 (goto-char (point-min))
15676 (while (setq heading (pop path))
15677 (setq re (format org-complex-heading-regexp-format
15678 (regexp-quote heading)))
15679 (setq cnt 0 pos (point))
15680 (while (re-search-forward re end t)
15681 (setq level (- (match-end 1) (match-beginning 1)))
15682 (if (and (>= level lmin) (<= level lmax))
15683 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15684 (when (= cnt 0) (error "Heading not found on level %d: %s"
15685 lmax heading))
15686 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15687 lmax heading))
15688 (goto-char found)
15689 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15690 (setq end (save-excursion (org-end-of-subtree t t))))
15691 (when (org-at-heading-p)
15692 (point-marker)))))))
15694 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15695 "Find node HEADING in BUFFER.
15696 Return a marker to the heading if it was found, or nil if not.
15697 If POS-ONLY is set, return just the position instead of a marker.
15699 The heading text must match exact, but it may have a TODO keyword,
15700 a priority cookie and tags in the standard locations."
15701 (with-current-buffer (or buffer (current-buffer))
15702 (save-excursion
15703 (save-restriction
15704 (widen)
15705 (goto-char (point-min))
15706 (let (case-fold-search)
15707 (if (re-search-forward
15708 (format org-complex-heading-regexp-format
15709 (regexp-quote heading)) nil t)
15710 (if pos-only
15711 (match-beginning 0)
15712 (move-marker (make-marker) (match-beginning 0)))))))))
15714 (defun org-find-exact-heading-in-directory (heading &optional dir)
15715 "Find Org node headline HEADING in all .org files in directory DIR.
15716 When the target headline is found, return a marker to this location."
15717 (let ((files (directory-files (or dir default-directory)
15718 nil "\\`[^.#].*\\.org\\'"))
15719 file visiting m buffer)
15720 (catch 'found
15721 (while (setq file (pop files))
15722 (message "trying %s" file)
15723 (setq visiting (org-find-base-buffer-visiting file))
15724 (setq buffer (or visiting (find-file-noselect file)))
15725 (setq m (org-find-exact-headline-in-buffer
15726 heading buffer))
15727 (when (and (not m) (not visiting)) (kill-buffer buffer))
15728 (and m (throw 'found m))))))
15730 (defun org-find-entry-with-id (ident)
15731 "Locate the entry that contains the ID property with exact value IDENT.
15732 IDENT can be a string, a symbol or a number, this function will search for
15733 the string representation of it.
15734 Return the position where this entry starts, or nil if there is no such entry."
15735 (interactive "sID: ")
15736 (let ((id (cond
15737 ((stringp ident) ident)
15738 ((symbol-name ident) (symbol-name ident))
15739 ((numberp ident) (number-to-string ident))
15740 (t (error "IDENT %s must be a string, symbol or number" ident))))
15741 (case-fold-search nil))
15742 (save-excursion
15743 (save-restriction
15744 (widen)
15745 (goto-char (point-min))
15746 (when (re-search-forward
15747 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15748 nil t)
15749 (org-back-to-heading t)
15750 (point))))))
15752 ;;;; Timestamps
15754 (defvar org-last-changed-timestamp nil)
15755 (defvar org-last-inserted-timestamp nil
15756 "The last time stamp inserted with `org-insert-time-stamp'.")
15757 (defvar org-time-was-given) ; dynamically scoped parameter
15758 (defvar org-end-time-was-given) ; dynamically scoped parameter
15759 (defvar org-ts-what) ; dynamically scoped parameter
15761 (defun org-time-stamp (arg &optional inactive)
15762 "Prompt for a date/time and insert a time stamp.
15763 If the user specifies a time like HH:MM or if this command is
15764 called with at least one prefix argument, the time stamp contains
15765 the date and the time. Otherwise, only the date is be included.
15767 All parts of a date not specified by the user is filled in from
15768 the current date/time. So if you just press return without
15769 typing anything, the time stamp will represent the current
15770 date/time.
15772 If there is already a timestamp at the cursor, it will be
15773 modified.
15775 With two universal prefix arguments, insert an active timestamp
15776 with the current time without prompting the user."
15777 (interactive "P")
15778 (let* ((ts nil)
15779 (default-time
15780 ;; Default time is either today, or, when entering a range,
15781 ;; the range start.
15782 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15783 (save-excursion
15784 (re-search-backward
15785 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15786 (- (point) 20) t)))
15787 (apply 'encode-time (org-parse-time-string (match-string 1)))
15788 (current-time)))
15789 (default-input (and ts (org-get-compact-tod ts)))
15790 (repeater (save-excursion
15791 (save-match-data
15792 (beginning-of-line)
15793 (when (re-search-forward
15794 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15795 (save-excursion (progn (end-of-line) (point))) t)
15796 (match-string 0)))))
15797 org-time-was-given org-end-time-was-given time)
15798 (cond
15799 ((and (org-at-timestamp-p t)
15800 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15801 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15802 (insert "--")
15803 (setq time (let ((this-command this-command))
15804 (org-read-date arg 'totime nil nil
15805 default-time default-input inactive)))
15806 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15807 ((org-at-timestamp-p t)
15808 (setq time (let ((this-command this-command))
15809 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15810 (when (org-at-timestamp-p t) ; just to get the match data
15811 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15812 (replace-match "")
15813 (setq org-last-changed-timestamp
15814 (org-insert-time-stamp
15815 time (or org-time-was-given arg)
15816 inactive nil nil (list org-end-time-was-given)))
15817 (when repeater (goto-char (1- (point))) (insert " " repeater)
15818 (setq org-last-changed-timestamp
15819 (concat (substring org-last-inserted-timestamp 0 -1)
15820 " " repeater ">"))))
15821 (message "Timestamp updated"))
15822 ((equal arg '(16))
15823 (org-insert-time-stamp (current-time) t))
15825 (setq time (let ((this-command this-command))
15826 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15827 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15828 nil nil (list org-end-time-was-given))))))
15830 ;; FIXME: can we use this for something else, like computing time differences?
15831 (defun org-get-compact-tod (s)
15832 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15833 (let* ((t1 (match-string 1 s))
15834 (h1 (string-to-number (match-string 2 s)))
15835 (m1 (string-to-number (match-string 3 s)))
15836 (t2 (and (match-end 4) (match-string 5 s)))
15837 (h2 (and t2 (string-to-number (match-string 6 s))))
15838 (m2 (and t2 (string-to-number (match-string 7 s))))
15839 dh dm)
15840 (if (not t2)
15842 (setq dh (- h2 h1) dm (- m2 m1))
15843 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15844 (concat t1 "+" (number-to-string dh)
15845 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15847 (defun org-time-stamp-inactive (&optional arg)
15848 "Insert an inactive time stamp.
15849 An inactive time stamp is enclosed in square brackets instead of angle
15850 brackets. It is inactive in the sense that it does not trigger agenda entries,
15851 does not link to the calendar and cannot be changed with the S-cursor keys.
15852 So these are more for recording a certain time/date."
15853 (interactive "P")
15854 (org-time-stamp arg 'inactive))
15856 (defvar org-date-ovl (make-overlay 1 1))
15857 (overlay-put org-date-ovl 'face 'org-date-selected)
15858 (org-detach-overlay org-date-ovl)
15860 (defvar org-ans1) ; dynamically scoped parameter
15861 (defvar org-ans2) ; dynamically scoped parameter
15863 (defvar org-plain-time-of-day-regexp) ; defined below
15865 (defvar org-overriding-default-time nil) ; dynamically scoped
15866 (defvar org-read-date-overlay nil)
15867 (defvar org-dcst nil) ; dynamically scoped
15868 (defvar org-read-date-history nil)
15869 (defvar org-read-date-final-answer nil)
15870 (defvar org-read-date-analyze-futurep nil)
15871 (defvar org-read-date-analyze-forced-year nil)
15872 (defvar org-read-date-inactive)
15874 (defvar org-read-date-minibuffer-local-map
15875 (let ((map (make-sparse-keymap)))
15876 (set-keymap-parent map minibuffer-local-map)
15877 (org-defkey map (kbd ".")
15878 (lambda () (interactive)
15879 (org-eval-in-calendar '(calendar-goto-today))))
15880 (org-defkey map [(meta shift left)]
15881 (lambda () (interactive)
15882 (org-eval-in-calendar '(calendar-backward-month 1))))
15883 (org-defkey map [(meta shift right)]
15884 (lambda () (interactive)
15885 (org-eval-in-calendar '(calendar-forward-month 1))))
15886 (org-defkey map [(meta shift up)]
15887 (lambda () (interactive)
15888 (org-eval-in-calendar '(calendar-backward-year 1))))
15889 (org-defkey map [(meta shift down)]
15890 (lambda () (interactive)
15891 (org-eval-in-calendar '(calendar-forward-year 1))))
15892 (org-defkey map [?\e (shift left)]
15893 (lambda () (interactive)
15894 (org-eval-in-calendar '(calendar-backward-month 1))))
15895 (org-defkey map [?\e (shift right)]
15896 (lambda () (interactive)
15897 (org-eval-in-calendar '(calendar-forward-month 1))))
15898 (org-defkey map [?\e (shift up)]
15899 (lambda () (interactive)
15900 (org-eval-in-calendar '(calendar-backward-year 1))))
15901 (org-defkey map [?\e (shift down)]
15902 (lambda () (interactive)
15903 (org-eval-in-calendar '(calendar-forward-year 1))))
15904 (org-defkey map [(shift up)]
15905 (lambda () (interactive)
15906 (org-eval-in-calendar '(calendar-backward-week 1))))
15907 (org-defkey map [(shift down)]
15908 (lambda () (interactive)
15909 (org-eval-in-calendar '(calendar-forward-week 1))))
15910 (org-defkey map [(shift left)]
15911 (lambda () (interactive)
15912 (org-eval-in-calendar '(calendar-backward-day 1))))
15913 (org-defkey map [(shift right)]
15914 (lambda () (interactive)
15915 (org-eval-in-calendar '(calendar-forward-day 1))))
15916 (org-defkey map "!"
15917 (lambda () (interactive)
15918 (org-eval-in-calendar '(diary-view-entries))
15919 (message "")))
15920 (org-defkey map ">"
15921 (lambda () (interactive)
15922 (org-eval-in-calendar '(scroll-calendar-left 1))))
15923 (org-defkey map "<"
15924 (lambda () (interactive)
15925 (org-eval-in-calendar '(scroll-calendar-right 1))))
15926 (org-defkey map "\C-v"
15927 (lambda () (interactive)
15928 (org-eval-in-calendar
15929 '(calendar-scroll-left-three-months 1))))
15930 (org-defkey map "\M-v"
15931 (lambda () (interactive)
15932 (org-eval-in-calendar
15933 '(calendar-scroll-right-three-months 1))))
15934 map)
15935 "Keymap for minibuffer commands when using `org-read-date'.")
15937 (defun org-read-date (&optional org-with-time to-time from-string prompt
15938 default-time default-input inactive)
15939 "Read a date, possibly a time, and make things smooth for the user.
15940 The prompt will suggest to enter an ISO date, but you can also enter anything
15941 which will at least partially be understood by `parse-time-string'.
15942 Unrecognized parts of the date will default to the current day, month, year,
15943 hour and minute. If this command is called to replace a timestamp at point,
15944 or to enter the second timestamp of a range, the default time is taken
15945 from the existing stamp. Furthermore, the command prefers the future,
15946 so if you are giving a date where the year is not given, and the day-month
15947 combination is already past in the current year, it will assume you
15948 mean next year. For details, see the manual. A few examples:
15950 3-2-5 --> 2003-02-05
15951 feb 15 --> currentyear-02-15
15952 2/15 --> currentyear-02-15
15953 sep 12 9 --> 2009-09-12
15954 12:45 --> today 12:45
15955 22 sept 0:34 --> currentyear-09-22 0:34
15956 12 --> currentyear-currentmonth-12
15957 Fri --> nearest Friday (today or later)
15958 etc.
15960 Furthermore you can specify a relative date by giving, as the *first* thing
15961 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15962 change in days weeks, months, years.
15963 With a single plus or minus, the date is relative to today. With a double
15964 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15965 +4d --> four days from today
15966 +4 --> same as above
15967 +2w --> two weeks from today
15968 ++5 --> five days from default date
15970 The function understands only English month and weekday abbreviations.
15972 While prompting, a calendar is popped up - you can also select the
15973 date with the mouse (button 1). The calendar shows a period of three
15974 months. To scroll it to other months, use the keys `>' and `<'.
15975 If you don't like the calendar, turn it off with
15976 \(setq org-read-date-popup-calendar nil)
15978 With optional argument TO-TIME, the date will immediately be converted
15979 to an internal time.
15980 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15981 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15982 still enter a time, and this function will inform the calling routine
15983 about this change. The calling routine may then choose to change the
15984 format used to insert the time stamp into the buffer to include the time.
15985 With optional argument FROM-STRING, read from this string instead from
15986 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15987 the time/date that is used for everything that is not specified by the
15988 user."
15989 (require 'parse-time)
15990 (let* ((org-time-stamp-rounding-minutes
15991 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15992 (org-dcst org-display-custom-times)
15993 (ct (org-current-time))
15994 (org-def (or org-overriding-default-time default-time ct))
15995 (org-defdecode (decode-time org-def))
15996 (dummy (progn
15997 (when (< (nth 2 org-defdecode) org-extend-today-until)
15998 (setcar (nthcdr 2 org-defdecode) -1)
15999 (setcar (nthcdr 1 org-defdecode) 59)
16000 (setq org-def (apply 'encode-time org-defdecode)
16001 org-defdecode (decode-time org-def)))))
16002 (mouse-autoselect-window nil) ; Don't let the mouse jump
16003 (calendar-frame-setup nil)
16004 (calendar-setup nil)
16005 (calendar-move-hook nil)
16006 (calendar-view-diary-initially-flag nil)
16007 (calendar-view-holidays-initially-flag nil)
16008 (timestr (format-time-string
16009 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16010 (prompt (concat (if prompt (concat prompt " ") "")
16011 (format "Date+time [%s]: " timestr)))
16012 ans (org-ans0 "") org-ans1 org-ans2 final)
16014 (cond
16015 (from-string (setq ans from-string))
16016 (org-read-date-popup-calendar
16017 (save-excursion
16018 (save-window-excursion
16019 (calendar)
16020 (org-eval-in-calendar '(setq cursor-type nil) t)
16021 (unwind-protect
16022 (progn
16023 (calendar-forward-day (- (time-to-days org-def)
16024 (calendar-absolute-from-gregorian
16025 (calendar-current-date))))
16026 (org-eval-in-calendar nil t)
16027 (let* ((old-map (current-local-map))
16028 (map (copy-keymap calendar-mode-map))
16029 (minibuffer-local-map
16030 (copy-keymap org-read-date-minibuffer-local-map)))
16031 (org-defkey map (kbd "RET") 'org-calendar-select)
16032 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16033 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16034 (unwind-protect
16035 (progn
16036 (use-local-map map)
16037 (setq org-read-date-inactive inactive)
16038 (add-hook 'post-command-hook 'org-read-date-display)
16039 (setq org-ans0 (read-string prompt default-input
16040 'org-read-date-history nil))
16041 ;; org-ans0: from prompt
16042 ;; org-ans1: from mouse click
16043 ;; org-ans2: from calendar motion
16044 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16045 (remove-hook 'post-command-hook 'org-read-date-display)
16046 (use-local-map old-map)
16047 (when org-read-date-overlay
16048 (delete-overlay org-read-date-overlay)
16049 (setq org-read-date-overlay nil)))))
16050 (bury-buffer "*Calendar*")))))
16052 (t ; Naked prompt only
16053 (unwind-protect
16054 (setq ans (read-string prompt default-input
16055 'org-read-date-history timestr))
16056 (when org-read-date-overlay
16057 (delete-overlay org-read-date-overlay)
16058 (setq org-read-date-overlay nil)))))
16060 (setq final (org-read-date-analyze ans org-def org-defdecode))
16062 (when org-read-date-analyze-forced-year
16063 (message "Year was forced into %s"
16064 (if org-read-date-force-compatible-dates
16065 "compatible range (1970-2037)"
16066 "range representable on this machine"))
16067 (ding))
16069 ;; One round trip to get rid of 34th of August and stuff like that....
16070 (setq final (decode-time (apply 'encode-time final)))
16072 (setq org-read-date-final-answer ans)
16074 (if to-time
16075 (apply 'encode-time final)
16076 (if (and (boundp 'org-time-was-given) org-time-was-given)
16077 (format "%04d-%02d-%02d %02d:%02d"
16078 (nth 5 final) (nth 4 final) (nth 3 final)
16079 (nth 2 final) (nth 1 final))
16080 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16082 (defvar org-def)
16083 (defvar org-defdecode)
16084 (defvar org-with-time)
16085 (defun org-read-date-display ()
16086 "Display the current date prompt interpretation in the minibuffer."
16087 (when org-read-date-display-live
16088 (when org-read-date-overlay
16089 (delete-overlay org-read-date-overlay))
16090 (when (minibufferp (current-buffer))
16091 (save-excursion
16092 (end-of-line 1)
16093 (while (not (equal (buffer-substring
16094 (max (point-min) (- (point) 4)) (point))
16095 " "))
16096 (insert " ")))
16097 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16098 " " (or org-ans1 org-ans2)))
16099 (org-end-time-was-given nil)
16100 (f (org-read-date-analyze ans org-def org-defdecode))
16101 (fmts (if org-dcst
16102 org-time-stamp-custom-formats
16103 org-time-stamp-formats))
16104 (fmt (if (or org-with-time
16105 (and (boundp 'org-time-was-given) org-time-was-given))
16106 (cdr fmts)
16107 (car fmts)))
16108 (txt (format-time-string fmt (apply 'encode-time f)))
16109 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16110 (txt (concat "=> " txt)))
16111 (when (and org-end-time-was-given
16112 (string-match org-plain-time-of-day-regexp txt))
16113 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16114 org-end-time-was-given
16115 (substring txt (match-end 0)))))
16116 (when org-read-date-analyze-futurep
16117 (setq txt (concat txt " (=>F)")))
16118 (setq org-read-date-overlay
16119 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16120 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16122 (defun org-read-date-analyze (ans org-def org-defdecode)
16123 "Analyze the combined answer of the date prompt."
16124 ;; FIXME: cleanup and comment
16125 (let ((nowdecode (decode-time (current-time)))
16126 delta deltan deltaw deltadef year month day
16127 hour minute second wday pm h2 m2 tl wday1
16128 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16129 (setq org-read-date-analyze-futurep nil
16130 org-read-date-analyze-forced-year nil)
16131 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16132 (setq ans "+0"))
16134 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16135 (setq ans (replace-match "" t t ans)
16136 deltan (car delta)
16137 deltaw (nth 1 delta)
16138 deltadef (nth 2 delta)))
16140 ;; Check if there is an iso week date in there. If yes, store the
16141 ;; info and postpone interpreting it until the rest of the parsing
16142 ;; is done.
16143 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16144 (setq iso-year (if (match-end 1)
16145 (org-small-year-to-year
16146 (string-to-number (match-string 1 ans))))
16147 iso-weekday (if (match-end 3)
16148 (string-to-number (match-string 3 ans)))
16149 iso-week (string-to-number (match-string 2 ans)))
16150 (setq ans (replace-match "" t t ans)))
16152 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16153 (when (string-match
16154 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16155 (setq year (if (match-end 2)
16156 (string-to-number (match-string 2 ans))
16157 (progn (setq kill-year t)
16158 (string-to-number (format-time-string "%Y"))))
16159 month (string-to-number (match-string 3 ans))
16160 day (string-to-number (match-string 4 ans)))
16161 (if (< year 100) (setq year (+ 2000 year)))
16162 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16163 t nil ans)))
16165 ;; Help matching dotted european dates
16166 (when (string-match
16167 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16168 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16169 (setq kill-year t)
16170 (string-to-number (format-time-string "%Y")))
16171 day (string-to-number (match-string 1 ans))
16172 month (string-to-number (match-string 2 ans))
16173 ans (replace-match (format "%04d-%02d-%02d" year month day)
16174 t nil ans)))
16176 ;; Help matching american dates, like 5/30 or 5/30/7
16177 (when (string-match
16178 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16179 (setq year (if (match-end 4)
16180 (string-to-number (match-string 4 ans))
16181 (progn (setq kill-year t)
16182 (string-to-number (format-time-string "%Y"))))
16183 month (string-to-number (match-string 1 ans))
16184 day (string-to-number (match-string 2 ans)))
16185 (if (< year 100) (setq year (+ 2000 year)))
16186 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16187 t nil ans)))
16188 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16189 ;; If there is a time with am/pm, and *no* time without it, we convert
16190 ;; so that matching will be successful.
16191 (loop for i from 1 to 2 do ; twice, for end time as well
16192 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16193 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16194 (setq hour (string-to-number (match-string 1 ans))
16195 minute (if (match-end 3)
16196 (string-to-number (match-string 3 ans))
16198 pm (equal ?p
16199 (string-to-char (downcase (match-string 4 ans)))))
16200 (if (and (= hour 12) (not pm))
16201 (setq hour 0)
16202 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16203 (setq ans (replace-match (format "%02d:%02d" hour minute)
16204 t t ans))))
16206 ;; Check if a time range is given as a duration
16207 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16208 (setq hour (string-to-number (match-string 1 ans))
16209 h2 (+ hour (string-to-number (match-string 3 ans)))
16210 minute (string-to-number (match-string 2 ans))
16211 m2 (+ minute (if (match-end 5) (string-to-number
16212 (match-string 5 ans))0)))
16213 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16214 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16215 t t ans)))
16217 ;; Check if there is a time range
16218 (when (boundp 'org-end-time-was-given)
16219 (setq org-time-was-given nil)
16220 (when (and (string-match org-plain-time-of-day-regexp ans)
16221 (match-end 8))
16222 (setq org-end-time-was-given (match-string 8 ans))
16223 (setq ans (concat (substring ans 0 (match-beginning 7))
16224 (substring ans (match-end 7))))))
16226 (setq tl (parse-time-string ans)
16227 day (or (nth 3 tl) (nth 3 org-defdecode))
16228 month (or (nth 4 tl)
16229 (if (and org-read-date-prefer-future
16230 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16231 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16232 (nth 4 org-defdecode)))
16233 year (or (and (not kill-year) (nth 5 tl))
16234 (if (and org-read-date-prefer-future
16235 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16236 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16237 (nth 5 org-defdecode)))
16238 hour (or (nth 2 tl) (nth 2 org-defdecode))
16239 minute (or (nth 1 tl) (nth 1 org-defdecode))
16240 second (or (nth 0 tl) 0)
16241 wday (nth 6 tl))
16243 (when (and (eq org-read-date-prefer-future 'time)
16244 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16245 (equal day (nth 3 nowdecode))
16246 (equal month (nth 4 nowdecode))
16247 (equal year (nth 5 nowdecode))
16248 (nth 2 tl)
16249 (or (< (nth 2 tl) (nth 2 nowdecode))
16250 (and (= (nth 2 tl) (nth 2 nowdecode))
16251 (nth 1 tl)
16252 (< (nth 1 tl) (nth 1 nowdecode)))))
16253 (setq day (1+ day)
16254 futurep t))
16256 ;; Special date definitions below
16257 (cond
16258 (iso-week
16259 ;; There was an iso week
16260 (require 'cal-iso)
16261 (setq futurep nil)
16262 (setq year (or iso-year year)
16263 day (or iso-weekday wday 1)
16264 wday nil ; to make sure that the trigger below does not match
16265 iso-date (calendar-gregorian-from-absolute
16266 (calendar-absolute-from-iso
16267 (list iso-week day year))))
16268 ; FIXME: Should we also push ISO weeks into the future?
16269 ; (when (and org-read-date-prefer-future
16270 ; (not iso-year)
16271 ; (< (calendar-absolute-from-gregorian iso-date)
16272 ; (time-to-days (current-time))))
16273 ; (setq year (1+ year)
16274 ; iso-date (calendar-gregorian-from-absolute
16275 ; (calendar-absolute-from-iso
16276 ; (list iso-week day year)))))
16277 (setq month (car iso-date)
16278 year (nth 2 iso-date)
16279 day (nth 1 iso-date)))
16280 (deltan
16281 (setq futurep nil)
16282 (unless deltadef
16283 (let ((now (decode-time (current-time))))
16284 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16285 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16286 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16287 ((equal deltaw "m") (setq month (+ month deltan)))
16288 ((equal deltaw "y") (setq year (+ year deltan)))))
16289 ((and wday (not (nth 3 tl)))
16290 ;; Weekday was given, but no day, so pick that day in the week
16291 ;; on or after the derived date.
16292 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16293 (unless (equal wday wday1)
16294 (setq day (+ day (% (- wday wday1 -7) 7))))))
16295 (if (and (boundp 'org-time-was-given)
16296 (nth 2 tl))
16297 (setq org-time-was-given t))
16298 (if (< year 100) (setq year (+ 2000 year)))
16299 ;; Check of the date is representable
16300 (if org-read-date-force-compatible-dates
16301 (progn
16302 (if (< year 1970)
16303 (setq year 1970 org-read-date-analyze-forced-year t))
16304 (if (> year 2037)
16305 (setq year 2037 org-read-date-analyze-forced-year t)))
16306 (condition-case nil
16307 (ignore (encode-time second minute hour day month year))
16308 (error
16309 (setq year (nth 5 org-defdecode))
16310 (setq org-read-date-analyze-forced-year t))))
16311 (setq org-read-date-analyze-futurep futurep)
16312 (list second minute hour day month year)))
16314 (defvar parse-time-weekdays)
16315 (defun org-read-date-get-relative (s today default)
16316 "Check string S for special relative date string.
16317 TODAY and DEFAULT are internal times, for today and for a default.
16318 Return shift list (N what def-flag)
16319 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16320 N is the number of WHATs to shift.
16321 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16322 the DEFAULT date rather than TODAY."
16323 (require 'parse-time)
16324 (when (and
16325 (string-match
16326 (concat
16327 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16328 "\\([0-9]+\\)?"
16329 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16330 "\\([ \t]\\|$\\)") s)
16331 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16332 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16333 (string-to-char (substring (match-string 1 s) -1))
16334 ?+))
16335 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16336 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16337 (what (if (match-end 3) (match-string 3 s) "d"))
16338 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16339 (date (if rel default today))
16340 (wday (nth 6 (decode-time date)))
16341 delta)
16342 (if wday1
16343 (progn
16344 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16345 (if (= dir ?-) (setq delta (- delta 7)))
16346 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16347 (list delta "d" rel))
16348 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16350 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16351 "Turn a user-specified date into the internal representation.
16352 The internal representation needed by the calendar is (month day year).
16353 This is a wrapper to handle the brain-dead convention in calendar that
16354 user function argument order change dependent on argument order."
16355 (if (boundp 'calendar-date-style)
16356 (cond
16357 ((eq calendar-date-style 'american)
16358 (list arg1 arg2 arg3))
16359 ((eq calendar-date-style 'european)
16360 (list arg2 arg1 arg3))
16361 ((eq calendar-date-style 'iso)
16362 (list arg2 arg3 arg1)))
16363 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16364 (if (org-bound-and-true-p european-calendar-style)
16365 (list arg2 arg1 arg3)
16366 (list arg1 arg2 arg3)))))
16368 (defun org-eval-in-calendar (form &optional keepdate)
16369 "Eval FORM in the calendar window and return to current window.
16370 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16371 otherwise stick to the current value of `org-ans2'."
16372 (let ((sf (selected-frame))
16373 (sw (selected-window)))
16374 (select-window (get-buffer-window "*Calendar*" t))
16375 (eval form)
16376 (when (and (not keepdate) (calendar-cursor-to-date))
16377 (let* ((date (calendar-cursor-to-date))
16378 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16379 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16380 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16381 (select-window sw)
16382 (org-select-frame-set-input-focus sf)))
16384 (defun org-calendar-select ()
16385 "Return to `org-read-date' with the date currently selected.
16386 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16387 (interactive)
16388 (when (calendar-cursor-to-date)
16389 (let* ((date (calendar-cursor-to-date))
16390 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16391 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16392 (if (active-minibuffer-window) (exit-minibuffer))))
16394 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16395 "Insert a date stamp for the date given by the internal TIME.
16396 WITH-HM means use the stamp format that includes the time of the day.
16397 INACTIVE means use square brackets instead of angular ones, so that the
16398 stamp will not contribute to the agenda.
16399 PRE and POST are optional strings to be inserted before and after the
16400 stamp.
16401 The command returns the inserted time stamp."
16402 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16403 stamp)
16404 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16405 (insert-before-markers (or pre ""))
16406 (when (listp extra)
16407 (setq extra (car extra))
16408 (if (and (stringp extra)
16409 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16410 (setq extra (format "-%02d:%02d"
16411 (string-to-number (match-string 1 extra))
16412 (string-to-number (match-string 2 extra))))
16413 (setq extra nil)))
16414 (when extra
16415 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16416 (insert-before-markers (setq stamp (format-time-string fmt time)))
16417 (insert-before-markers (or post ""))
16418 (setq org-last-inserted-timestamp stamp)))
16420 (defun org-toggle-time-stamp-overlays ()
16421 "Toggle the use of custom time stamp formats."
16422 (interactive)
16423 (setq org-display-custom-times (not org-display-custom-times))
16424 (unless org-display-custom-times
16425 (let ((p (point-min)) (bmp (buffer-modified-p)))
16426 (while (setq p (next-single-property-change p 'display))
16427 (if (and (get-text-property p 'display)
16428 (eq (get-text-property p 'face) 'org-date))
16429 (remove-text-properties
16430 p (setq p (next-single-property-change p 'display))
16431 '(display t))))
16432 (set-buffer-modified-p bmp)))
16433 (if (featurep 'xemacs)
16434 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16435 (org-restart-font-lock)
16436 (setq org-table-may-need-update t)
16437 (if org-display-custom-times
16438 (message "Time stamps are overlaid with custom format")
16439 (message "Time stamp overlays removed")))
16441 (defun org-display-custom-time (beg end)
16442 "Overlay modified time stamp format over timestamp between BEG and END."
16443 (let* ((ts (buffer-substring beg end))
16444 t1 w1 with-hm tf time str w2 (off 0))
16445 (save-match-data
16446 (setq t1 (org-parse-time-string ts t))
16447 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16448 (setq off (- (match-end 0) (match-beginning 0)))))
16449 (setq end (- end off))
16450 (setq w1 (- end beg)
16451 with-hm (and (nth 1 t1) (nth 2 t1))
16452 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16453 time (org-fix-decoded-time t1)
16454 str (org-add-props
16455 (format-time-string
16456 (substring tf 1 -1) (apply 'encode-time time))
16457 nil 'mouse-face 'highlight)
16458 w2 (length str))
16459 (if (not (= w2 w1))
16460 (add-text-properties (1+ beg) (+ 2 beg)
16461 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16462 (if (featurep 'xemacs)
16463 (progn
16464 (put-text-property beg end 'invisible t)
16465 (put-text-property beg end 'end-glyph (make-glyph str)))
16466 (put-text-property beg end 'display str))))
16468 (defun org-translate-time (string)
16469 "Translate all timestamps in STRING to custom format.
16470 But do this only if the variable `org-display-custom-times' is set."
16471 (when org-display-custom-times
16472 (save-match-data
16473 (let* ((start 0)
16474 (re org-ts-regexp-both)
16475 t1 with-hm inactive tf time str beg end)
16476 (while (setq start (string-match re string start))
16477 (setq beg (match-beginning 0)
16478 end (match-end 0)
16479 t1 (save-match-data
16480 (org-parse-time-string (substring string beg end) t))
16481 with-hm (and (nth 1 t1) (nth 2 t1))
16482 inactive (equal (substring string beg (1+ beg)) "[")
16483 tf (funcall (if with-hm 'cdr 'car)
16484 org-time-stamp-custom-formats)
16485 time (org-fix-decoded-time t1)
16486 str (format-time-string
16487 (concat
16488 (if inactive "[" "<") (substring tf 1 -1)
16489 (if inactive "]" ">"))
16490 (apply 'encode-time time))
16491 string (replace-match str t t string)
16492 start (+ start (length str)))))))
16493 string)
16495 (defun org-fix-decoded-time (time)
16496 "Set 0 instead of nil for the first 6 elements of time.
16497 Don't touch the rest."
16498 (let ((n 0))
16499 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16501 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16503 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16504 "Difference between TIMESTAMP-STRING and now in days.
16505 If SECONDS is non-nil, return the difference in seconds."
16506 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16507 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16508 (funcall fdiff (current-time)))))
16510 (defun org-deadline-close (timestamp-string &optional ndays)
16511 "Is the time in TIMESTAMP-STRING close to the current date?"
16512 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16513 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16514 (not (org-entry-is-done-p))))
16516 (defun org-get-wdays (ts &optional delay zero-delay)
16517 "Get the deadline lead time appropriate for timestring TS.
16518 When DELAY is non-nil, get the delay time for scheduled items
16519 instead of the deadline lead time. When ZERO-DELAY is non-nil
16520 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16521 don't try to find the delay cookie in the scheduled timestamp."
16522 (let ((tv (if delay org-scheduled-delay-days
16523 org-deadline-warning-days)))
16524 (cond
16525 ((or (and delay (< tv 0))
16526 (and delay zero-delay (<= tv 0))
16527 (and (not delay) (<= tv 0)))
16528 ;; Enforce this value no matter what
16529 (- tv))
16530 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16531 ;; lead time is specified.
16532 (floor (* (string-to-number (match-string 1 ts))
16533 (cdr (assoc (match-string 2 ts)
16534 '(("d" . 1) ("w" . 7)
16535 ("m" . 30.4) ("y" . 365.25)
16536 ("h" . 0.041667)))))))
16537 ;; go for the default.
16538 (t tv))))
16540 (defun org-calendar-select-mouse (ev)
16541 "Return to `org-read-date' with the date currently selected.
16542 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16543 (interactive "e")
16544 (mouse-set-point ev)
16545 (when (calendar-cursor-to-date)
16546 (let* ((date (calendar-cursor-to-date))
16547 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16548 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16549 (if (active-minibuffer-window) (exit-minibuffer))))
16551 (defun org-check-deadlines (ndays)
16552 "Check if there are any deadlines due or past due.
16553 A deadline is considered due if it happens within `org-deadline-warning-days'
16554 days from today's date. If the deadline appears in an entry marked DONE,
16555 it is not shown. The prefix arg NDAYS can be used to test that many
16556 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16557 (interactive "P")
16558 (let* ((org-warn-days
16559 (cond
16560 ((equal ndays '(4)) 100000)
16561 (ndays (prefix-numeric-value ndays))
16562 (t (abs org-deadline-warning-days))))
16563 (case-fold-search nil)
16564 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16565 (callback
16566 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16568 (message "%d deadlines past-due or due within %d days"
16569 (org-occur regexp nil callback)
16570 org-warn-days)))
16572 (defsubst org-re-timestamp (type)
16573 "Return a regexp for timestamp TYPE.
16574 Allowed values for TYPE are:
16576 all: all timestamps
16577 active: only active timestamps (<...>)
16578 inactive: only inactive timestamps ([...])
16579 scheduled: only scheduled timestamps
16580 deadline: only deadline timestamps
16582 When TYPE is nil, fall back on returning a regexp that matches
16583 both scheduled and deadline timestamps."
16584 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16585 ((eq type 'active) org-ts-regexp)
16586 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16587 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16588 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16589 ((eq type 'scheduled-or-deadline)
16590 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16592 (defun org-check-before-date (date)
16593 "Check if there are deadlines or scheduled entries before DATE."
16594 (interactive (list (org-read-date)))
16595 (let ((case-fold-search nil)
16596 (regexp (org-re-timestamp org-ts-type))
16597 (callback
16598 (lambda () (time-less-p
16599 (org-time-string-to-time (match-string 1))
16600 (org-time-string-to-time date)))))
16601 (message "%d entries before %s"
16602 (org-occur regexp nil callback) date)))
16604 (defun org-check-after-date (date)
16605 "Check if there are deadlines or scheduled entries after DATE."
16606 (interactive (list (org-read-date)))
16607 (let ((case-fold-search nil)
16608 (regexp (org-re-timestamp org-ts-type))
16609 (callback
16610 (lambda () (not
16611 (time-less-p
16612 (org-time-string-to-time (match-string 1))
16613 (org-time-string-to-time date))))))
16614 (message "%d entries after %s"
16615 (org-occur regexp nil callback) date)))
16617 (defun org-check-dates-range (start-date end-date)
16618 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16619 (interactive (list (org-read-date nil nil nil "Range starts")
16620 (org-read-date nil nil nil "Range end")))
16621 (let ((case-fold-search nil)
16622 (regexp (org-re-timestamp org-ts-type))
16623 (callback
16624 (lambda ()
16625 (let ((match (match-string 1)))
16626 (and
16627 (not (time-less-p
16628 (org-time-string-to-time match)
16629 (org-time-string-to-time start-date)))
16630 (time-less-p
16631 (org-time-string-to-time match)
16632 (org-time-string-to-time end-date)))))))
16633 (message "%d entries between %s and %s"
16634 (org-occur regexp nil callback) start-date end-date)))
16636 (defun org-evaluate-time-range (&optional to-buffer)
16637 "Evaluate a time range by computing the difference between start and end.
16638 Normally the result is just printed in the echo area, but with prefix arg
16639 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16640 If the time range is actually in a table, the result is inserted into the
16641 next column.
16642 For time difference computation, a year is assumed to be exactly 365
16643 days in order to avoid rounding problems."
16644 (interactive "P")
16646 (org-clock-update-time-maybe)
16647 (save-excursion
16648 (unless (org-at-date-range-p t)
16649 (goto-char (point-at-bol))
16650 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16651 (if (not (org-at-date-range-p t))
16652 (error "Not at a time-stamp range, and none found in current line")))
16653 (let* ((ts1 (match-string 1))
16654 (ts2 (match-string 2))
16655 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16656 (match-end (match-end 0))
16657 (time1 (org-time-string-to-time ts1))
16658 (time2 (org-time-string-to-time ts2))
16659 (t1 (org-float-time time1))
16660 (t2 (org-float-time time2))
16661 (diff (abs (- t2 t1)))
16662 (negative (< (- t2 t1) 0))
16663 ;; (ys (floor (* 365 24 60 60)))
16664 (ds (* 24 60 60))
16665 (hs (* 60 60))
16666 (fy "%dy %dd %02d:%02d")
16667 (fy1 "%dy %dd")
16668 (fd "%dd %02d:%02d")
16669 (fd1 "%dd")
16670 (fh "%02d:%02d")
16671 y d h m align)
16672 (if havetime
16673 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16675 d (floor (/ diff ds)) diff (mod diff ds)
16676 h (floor (/ diff hs)) diff (mod diff hs)
16677 m (floor (/ diff 60)))
16678 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16680 d (floor (+ (/ diff ds) 0.5))
16681 h 0 m 0))
16682 (if (not to-buffer)
16683 (message "%s" (org-make-tdiff-string y d h m))
16684 (if (org-at-table-p)
16685 (progn
16686 (goto-char match-end)
16687 (setq align t)
16688 (and (looking-at " *|") (goto-char (match-end 0))))
16689 (goto-char match-end))
16690 (if (looking-at
16691 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16692 (replace-match ""))
16693 (if negative (insert " -"))
16694 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16695 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16696 (insert " " (format fh h m))))
16697 (if align (org-table-align))
16698 (message "Time difference inserted")))))
16700 (defun org-make-tdiff-string (y d h m)
16701 (let ((fmt "")
16702 (l nil))
16703 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16704 l (push y l)))
16705 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16706 l (push d l)))
16707 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16708 l (push h l)))
16709 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16710 l (push m l)))
16711 (apply 'format fmt (nreverse l))))
16713 (defun org-time-string-to-time (s &optional buffer pos)
16714 "Convert a timestamp string into internal time."
16715 (condition-case errdata
16716 (apply 'encode-time (org-parse-time-string s))
16717 (error (error "Bad timestamp `%s'%s\nError was: %s"
16718 s (if (not (and buffer pos))
16720 (format " at %d in buffer `%s'" pos buffer))
16721 (cdr errdata)))))
16723 (defun org-time-string-to-seconds (s)
16724 "Convert a timestamp string to a number of seconds."
16725 (org-float-time (org-time-string-to-time s)))
16727 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16728 "Convert a time stamp to an absolute day number.
16729 If there is a specifier for a cyclic time stamp, get the closest
16730 date to DAYNR.
16731 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16732 The variable `date' is bound by the calendar when this is called."
16733 (cond
16734 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16735 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16736 daynr
16737 (+ daynr 1000)))
16738 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16739 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16740 (time-to-days (current-time))) (match-string 0 s)
16741 prefer show-all))
16742 (t (time-to-days
16743 (condition-case errdata
16744 (apply 'encode-time (org-parse-time-string s))
16745 (error (error "Bad timestamp `%s'%s\nError was: %s"
16746 s (if (not (and buffer pos))
16748 (format " at %d in buffer `%s'" pos buffer))
16749 (cdr errdata))))))))
16751 (defun org-days-to-iso-week (days)
16752 "Return the iso week number."
16753 (require 'cal-iso)
16754 (car (calendar-iso-from-absolute days)))
16756 (defun org-small-year-to-year (year)
16757 "Convert 2-digit years into 4-digit years.
16758 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16759 The year 2000 cannot be abbreviated. Any year larger than 99
16760 is returned unchanged."
16761 (if (< year 38)
16762 (setq year (+ 2000 year))
16763 (if (< year 100)
16764 (setq year (+ 1900 year))))
16765 year)
16767 (defun org-time-from-absolute (d)
16768 "Return the time corresponding to date D.
16769 D may be an absolute day number, or a calendar-type list (month day year)."
16770 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16771 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16773 (defun org-calendar-holiday ()
16774 "List of holidays, for Diary display in Org-mode."
16775 (require 'holidays)
16776 (let ((hl (funcall
16777 (if (fboundp 'calendar-check-holidays)
16778 'calendar-check-holidays 'check-calendar-holidays) date)))
16779 (if hl (mapconcat 'identity hl "; "))))
16781 (defun org-diary-sexp-entry (sexp entry date)
16782 "Process a SEXP diary ENTRY for DATE."
16783 (require 'diary-lib)
16784 (let ((result (if calendar-debug-sexp
16785 (let ((stack-trace-on-error t))
16786 (eval (car (read-from-string sexp))))
16787 (condition-case nil
16788 (eval (car (read-from-string sexp)))
16789 (error
16790 (beep)
16791 (message "Bad sexp at line %d in %s: %s"
16792 (org-current-line)
16793 (buffer-file-name) sexp)
16794 (sleep-for 2))))))
16795 (cond ((stringp result) (split-string result "; "))
16796 ((and (consp result)
16797 (not (consp (cdr result)))
16798 (stringp (cdr result))) (cdr result))
16799 ((and (consp result)
16800 (stringp (car result))) result)
16801 (result entry))))
16803 (defun org-diary-to-ical-string (frombuf)
16804 "Get iCalendar entries from diary entries in buffer FROMBUF.
16805 This uses the icalendar.el library."
16806 (let* ((tmpdir (if (featurep 'xemacs)
16807 (temp-directory)
16808 temporary-file-directory))
16809 (tmpfile (make-temp-name
16810 (expand-file-name "orgics" tmpdir)))
16811 buf rtn b e)
16812 (with-current-buffer frombuf
16813 (icalendar-export-region (point-min) (point-max) tmpfile)
16814 (setq buf (find-buffer-visiting tmpfile))
16815 (set-buffer buf)
16816 (goto-char (point-min))
16817 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16818 (setq b (match-beginning 0)))
16819 (goto-char (point-max))
16820 (if (re-search-backward "^END:VEVENT" nil t)
16821 (setq e (match-end 0)))
16822 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16823 (kill-buffer buf)
16824 (delete-file tmpfile)
16825 rtn))
16827 (defun org-closest-date (start current change prefer show-all)
16828 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16829 When PREFER is `past', return a date that is either CURRENT or past.
16830 When PREFER is `future', return a date that is either CURRENT or future.
16831 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16832 ;; Make the proper lists from the dates
16833 (catch 'exit
16834 (let ((a1 '(("h" . hour)
16835 ("d" . day)
16836 ("w" . week)
16837 ("m" . month)
16838 ("y" . year)))
16839 (shour (nth 2 (org-parse-time-string start)))
16840 dn dw sday cday n1 n2 n0
16841 d m y y1 y2 date1 date2 nmonths nm ny m2)
16843 (setq start (org-date-to-gregorian start)
16844 current (org-date-to-gregorian
16845 (if show-all
16846 current
16847 (time-to-days (current-time))))
16848 sday (calendar-absolute-from-gregorian start)
16849 cday (calendar-absolute-from-gregorian current))
16851 (if (<= cday sday) (throw 'exit sday))
16853 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16854 (setq dn (string-to-number (match-string 1 change))
16855 dw (cdr (assoc (match-string 2 change) a1)))
16856 (error "Invalid change specifier: %s" change))
16857 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16858 (cond
16859 ((eq dw 'hour)
16860 (let ((missing-hours
16861 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16862 dn)))
16863 (setq n1 (if (zerop missing-hours) cday
16864 (- cday (1+ (floor (/ missing-hours 24)))))
16865 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16866 ((eq dw 'day)
16867 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16868 n2 (+ n1 dn)))
16869 ((eq dw 'year)
16870 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16871 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16872 (setq date1 (list m d y1)
16873 n1 (calendar-absolute-from-gregorian date1)
16874 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16875 n2 (calendar-absolute-from-gregorian date2)))
16876 ((eq dw 'month)
16877 ;; approx number of month between the two dates
16878 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16879 ;; How often does dn fit in there?
16880 (setq d (nth 1 start) m (car start) y (nth 2 start)
16881 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16882 m (+ m nm)
16883 ny (floor (/ m 12))
16884 y (+ y ny)
16885 m (- m (* ny 12)))
16886 (while (> m 12) (setq m (- m 12) y (1+ y)))
16887 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16888 (setq m2 (+ m dn) y2 y)
16889 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16890 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16891 (while (<= n2 cday)
16892 (setq n1 n2 m m2 y y2)
16893 (setq m2 (+ m dn) y2 y)
16894 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16895 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16896 ;; Make sure n1 is the earlier date
16897 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16898 (if show-all
16899 (cond
16900 ((eq prefer 'past) (if (= cday n2) n2 n1))
16901 ((eq prefer 'future) (if (= cday n1) n1 n2))
16902 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16903 (cond
16904 ((eq prefer 'past) (if (= cday n2) n2 n1))
16905 ((eq prefer 'future) (if (= cday n1) n1 n2))
16906 (t (if (= cday n1) n1 n2)))))))
16908 (defun org-date-to-gregorian (date)
16909 "Turn any specification of DATE into a Gregorian date for the calendar."
16910 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16911 ((and (listp date) (= (length date) 3)) date)
16912 ((stringp date)
16913 (setq date (org-parse-time-string date))
16914 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16915 ((listp date)
16916 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16918 (defun org-parse-time-string (s &optional nodefault)
16919 "Parse the standard Org-mode time string.
16920 This should be a lot faster than the normal `parse-time-string'.
16921 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16922 hour and minute fields will be nil if not given."
16923 (cond ((string-match org-ts-regexp0 s)
16924 (list 0
16925 (if (or (match-beginning 8) (not nodefault))
16926 (string-to-number (or (match-string 8 s) "0")))
16927 (if (or (match-beginning 7) (not nodefault))
16928 (string-to-number (or (match-string 7 s) "0")))
16929 (string-to-number (match-string 4 s))
16930 (string-to-number (match-string 3 s))
16931 (string-to-number (match-string 2 s))
16932 nil nil nil))
16933 ((string-match "^<[^>]+>$" s)
16934 (decode-time (seconds-to-time (org-matcher-time s))))
16935 (t (error "Not a standard Org-mode time string: %s" s))))
16937 (defun org-timestamp-up (&optional arg)
16938 "Increase the date item at the cursor by one.
16939 If the cursor is on the year, change the year. If it is on the month,
16940 the day or the time, change that.
16941 With prefix ARG, change by that many units."
16942 (interactive "p")
16943 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16945 (defun org-timestamp-down (&optional arg)
16946 "Decrease the date item at the cursor by one.
16947 If the cursor is on the year, change the year. If it is on the month,
16948 the day or the time, change that.
16949 With prefix ARG, change by that many units."
16950 (interactive "p")
16951 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16953 (defun org-timestamp-up-day (&optional arg)
16954 "Increase the date in the time stamp by one day.
16955 With prefix ARG, change that many days."
16956 (interactive "p")
16957 (if (and (not (org-at-timestamp-p t))
16958 (org-at-heading-p))
16959 (org-todo 'up)
16960 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16962 (defun org-timestamp-down-day (&optional arg)
16963 "Decrease the date in the time stamp by one day.
16964 With prefix ARG, change that many days."
16965 (interactive "p")
16966 (if (and (not (org-at-timestamp-p t))
16967 (org-at-heading-p))
16968 (org-todo 'down)
16969 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16971 (defun org-at-timestamp-p (&optional inactive-ok)
16972 "Determine if the cursor is in or at a timestamp."
16973 (interactive)
16974 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16975 (pos (point))
16976 (ans (or (looking-at tsr)
16977 (save-excursion
16978 (skip-chars-backward "^[<\n\r\t")
16979 (if (> (point) (point-min)) (backward-char 1))
16980 (and (looking-at tsr)
16981 (> (- (match-end 0) pos) -1))))))
16982 (and ans
16983 (boundp 'org-ts-what)
16984 (setq org-ts-what
16985 (cond
16986 ((= pos (match-beginning 0)) 'bracket)
16987 ;; Point is considered to be "on the bracket" whether
16988 ;; it's really on it or right after it.
16989 ((= pos (1- (match-end 0))) 'bracket)
16990 ((= pos (match-end 0)) 'after)
16991 ((org-pos-in-match-range pos 2) 'year)
16992 ((org-pos-in-match-range pos 3) 'month)
16993 ((org-pos-in-match-range pos 7) 'hour)
16994 ((org-pos-in-match-range pos 8) 'minute)
16995 ((or (org-pos-in-match-range pos 4)
16996 (org-pos-in-match-range pos 5)) 'day)
16997 ((and (> pos (or (match-end 8) (match-end 5)))
16998 (< pos (match-end 0)))
16999 (- pos (or (match-end 8) (match-end 5))))
17000 (t 'day))))
17001 ans))
17003 (defun org-toggle-timestamp-type ()
17004 "Toggle the type (<active> or [inactive]) of a time stamp."
17005 (interactive)
17006 (when (org-at-timestamp-p t)
17007 (let ((beg (match-beginning 0)) (end (match-end 0))
17008 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17009 (save-excursion
17010 (goto-char beg)
17011 (while (re-search-forward "[][<>]" end t)
17012 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17013 t t)))
17014 (message "Timestamp is now %sactive"
17015 (if (equal (char-after beg) ?<) "" "in")))))
17017 (defun org-at-clock-log-p nil
17018 "Is the cursor on the clock log line?"
17019 (save-excursion
17020 (move-beginning-of-line 1)
17021 (looking-at "^[ \t]*CLOCK:")))
17023 (defvar org-clock-history) ; defined in org-clock.el
17024 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17025 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17026 "Change the date in the time stamp at point.
17027 The date will be changed by N times WHAT. WHAT can be `day', `month',
17028 `year', `minute', `second'. If WHAT is not given, the cursor position
17029 in the timestamp determines what will be changed.
17030 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17031 (let ((origin (point)) origin-cat
17032 with-hm inactive
17033 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17034 org-ts-what
17035 extra rem
17036 ts time time0 fixnext clrgx)
17037 (if (not (org-at-timestamp-p t))
17038 (error "Not at a timestamp"))
17039 (if (and (not what) (eq org-ts-what 'bracket))
17040 (org-toggle-timestamp-type)
17041 ;; Point isn't on brackets. Remember the part of the time-stamp
17042 ;; the point was in. Indeed, size of time-stamps may change,
17043 ;; but point must be kept in the same category nonetheless.
17044 (setq origin-cat org-ts-what)
17045 (if (and (not what) (not (eq org-ts-what 'day))
17046 org-display-custom-times
17047 (get-text-property (point) 'display)
17048 (not (get-text-property (1- (point)) 'display)))
17049 (setq org-ts-what 'day))
17050 (setq org-ts-what (or what org-ts-what)
17051 inactive (= (char-after (match-beginning 0)) ?\[)
17052 ts (match-string 0))
17053 (replace-match "")
17054 (when (string-match
17055 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17057 (setq extra (match-string 1 ts))
17058 (if suppress-tmp-delay
17059 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17060 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17061 (setq with-hm t))
17062 (setq time0 (org-parse-time-string ts))
17063 (when (and updown
17064 (eq org-ts-what 'minute)
17065 (not current-prefix-arg))
17066 ;; This looks like s-up and s-down. Change by one rounding step.
17067 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17068 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17069 (setcar (cdr time0) (+ (nth 1 time0)
17070 (if (> n 0) (- rem) (- dm rem))))))
17071 (setq time
17072 (encode-time (or (car time0) 0)
17073 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17074 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17075 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17076 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17077 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17078 (nthcdr 6 time0)))
17079 (when (and (member org-ts-what '(hour minute))
17080 extra
17081 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17082 (setq extra (org-modify-ts-extra
17083 extra
17084 (if (eq org-ts-what 'hour) 2 5)
17085 n dm)))
17086 (when (integerp org-ts-what)
17087 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17088 (if (eq what 'calendar)
17089 (let ((cal-date (org-get-date-from-calendar)))
17090 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17091 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17092 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17093 (setcar time0 (or (car time0) 0))
17094 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17095 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17096 (setq time (apply 'encode-time time0))))
17097 ;; Insert the new time-stamp, and ensure point stays in the same
17098 ;; category as before (i.e. not after the last position in that
17099 ;; category).
17100 (let ((pos (point)))
17101 ;; Stay before inserted string. `save-excursion' is of no use.
17102 (setq org-last-changed-timestamp
17103 (org-insert-time-stamp time with-hm inactive nil nil extra))
17104 (goto-char pos))
17105 (save-match-data
17106 (looking-at org-ts-regexp3)
17107 (goto-char (cond
17108 ;; `day' category ends before `hour' if any, or at
17109 ;; the end of the day name.
17110 ((eq origin-cat 'day)
17111 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17112 ((eq origin-cat 'hour) (min (match-end 7) origin))
17113 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17114 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17115 ;; `year' and `month' have both fixed size: point
17116 ;; couldn't have moved into another part.
17117 (t origin))))
17118 ;; Update clock if on a CLOCK line.
17119 (org-clock-update-time-maybe)
17120 ;; Maybe adjust the closest clock in `org-clock-history'
17121 (when org-clock-adjust-closest
17122 (if (not (and (org-at-clock-log-p)
17123 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17124 org-clock-history))))))
17125 (message "No clock to adjust")
17126 (cond ((save-excursion ; fix previous clock?
17127 (re-search-backward org-ts-regexp0 nil t)
17128 (org-looking-back (concat org-clock-string " \\[")))
17129 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17130 ((save-excursion ; fix next clock?
17131 (re-search-backward org-ts-regexp0 nil t)
17132 (looking-at (concat org-ts-regexp0 "\\] =>")))
17133 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17134 (save-window-excursion
17135 ;; Find closest clock to point, adjust the previous/next one in history
17136 (let* ((p (save-excursion (org-back-to-heading t)))
17137 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17138 (clfixnth
17139 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17140 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17141 (if (not clfixpos)
17142 (message "No clock to adjust")
17143 (save-excursion
17144 (org-goto-marker-or-bmk clfixpos)
17145 (org-show-subtree)
17146 (when (re-search-forward clrgx nil t)
17147 (goto-char (match-beginning 1))
17148 (let (org-clock-adjust-closest)
17149 (org-timestamp-change n org-ts-what updown))
17150 (message "Clock adjusted in %s for heading: %s"
17151 (file-name-nondirectory (buffer-file-name))
17152 (org-get-heading t t)))))))))
17153 ;; Try to recenter the calendar window, if any.
17154 (if (and org-calendar-follow-timestamp-change
17155 (get-buffer-window "*Calendar*" t)
17156 (memq org-ts-what '(day month year)))
17157 (org-recenter-calendar (time-to-days time))))))
17159 (defun org-modify-ts-extra (s pos n dm)
17160 "Change the different parts of the lead-time and repeat fields in timestamp."
17161 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17162 ng h m new rem)
17163 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17164 (cond
17165 ((or (org-pos-in-match-range pos 2)
17166 (org-pos-in-match-range pos 3))
17167 (setq m (string-to-number (match-string 3 s))
17168 h (string-to-number (match-string 2 s)))
17169 (if (org-pos-in-match-range pos 2)
17170 (setq h (+ h n))
17171 (setq n (* dm (org-no-warnings (signum n))))
17172 (when (not (= 0 (setq rem (% m dm))))
17173 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17174 (setq m (+ m n)))
17175 (if (< m 0) (setq m (+ m 60) h (1- h)))
17176 (if (> m 59) (setq m (- m 60) h (1+ h)))
17177 (setq h (min 24 (max 0 h)))
17178 (setq ng 1 new (format "-%02d:%02d" h m)))
17179 ((org-pos-in-match-range pos 6)
17180 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17181 ((org-pos-in-match-range pos 5)
17182 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17184 ((org-pos-in-match-range pos 9)
17185 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17186 ((org-pos-in-match-range pos 8)
17187 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17189 (when ng
17190 (setq s (concat
17191 (substring s 0 (match-beginning ng))
17193 (substring s (match-end ng))))))
17196 (defun org-recenter-calendar (date)
17197 "If the calendar is visible, recenter it to DATE."
17198 (let ((cwin (get-buffer-window "*Calendar*" t)))
17199 (when cwin
17200 (let ((calendar-move-hook nil))
17201 (with-selected-window cwin
17202 (calendar-goto-date (if (listp date) date
17203 (calendar-gregorian-from-absolute date))))))))
17205 (defun org-goto-calendar (&optional arg)
17206 "Go to the Emacs calendar at the current date.
17207 If there is a time stamp in the current line, go to that date.
17208 A prefix ARG can be used to force the current date."
17209 (interactive "P")
17210 (let ((tsr org-ts-regexp) diff
17211 (calendar-move-hook nil)
17212 (calendar-view-holidays-initially-flag nil)
17213 (calendar-view-diary-initially-flag nil))
17214 (if (or (org-at-timestamp-p)
17215 (save-excursion
17216 (beginning-of-line 1)
17217 (looking-at (concat ".*" tsr))))
17218 (let ((d1 (time-to-days (current-time)))
17219 (d2 (time-to-days
17220 (org-time-string-to-time (match-string 1)))))
17221 (setq diff (- d2 d1))))
17222 (calendar)
17223 (calendar-goto-today)
17224 (if (and diff (not arg)) (calendar-forward-day diff))))
17226 (defun org-get-date-from-calendar ()
17227 "Return a list (month day year) of date at point in calendar."
17228 (with-current-buffer "*Calendar*"
17229 (save-match-data
17230 (calendar-cursor-to-date))))
17232 (defun org-date-from-calendar ()
17233 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17234 If there is already a time stamp at the cursor position, update it."
17235 (interactive)
17236 (if (org-at-timestamp-p t)
17237 (org-timestamp-change 0 'calendar)
17238 (let ((cal-date (org-get-date-from-calendar)))
17239 (org-insert-time-stamp
17240 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17242 (defcustom org-effort-durations
17243 `(("h" . 60)
17244 ("d" . ,(* 60 8))
17245 ("w" . ,(* 60 8 5))
17246 ("m" . ,(* 60 8 5 4))
17247 ("y" . ,(* 60 8 5 40)))
17248 "Conversion factor to minutes for an effort modifier.
17250 Each entry has the form (MODIFIER . MINUTES).
17252 In an effort string, a number followed by MODIFIER is multiplied
17253 by the specified number of MINUTES to obtain an effort in
17254 minutes.
17256 For example, if the value of this variable is ((\"hours\" . 60)), then an
17257 effort string \"2hours\" is equivalent to 120 minutes."
17258 :group 'org-agenda
17259 :version "24.1"
17260 :type '(alist :key-type (string :tag "Modifier")
17261 :value-type (number :tag "Minutes")))
17263 (defun org-minutes-to-clocksum-string (m)
17264 "Format number of minutes as a clocksum string.
17265 The format is determined by `org-time-clocksum-format',
17266 `org-time-clocksum-use-fractional' and
17267 `org-time-clocksum-fractional-format' and
17268 `org-time-clocksum-use-effort-durations'."
17269 (let ((clocksum "") h d w mo y fmt n)
17270 (setq h (if org-time-clocksum-use-effort-durations
17271 (cdr (assoc "h" org-effort-durations)) 60)
17272 d (if org-time-clocksum-use-effort-durations
17273 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17274 w (if org-time-clocksum-use-effort-durations
17275 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17276 mo (if org-time-clocksum-use-effort-durations
17277 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17278 y (if org-time-clocksum-use-effort-durations
17279 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17280 ;; fractional format
17281 (if org-time-clocksum-use-fractional
17282 (cond
17283 ;; single format string
17284 ((stringp org-time-clocksum-fractional-format)
17285 (format org-time-clocksum-fractional-format (/ m (float h))))
17286 ;; choice of fractional formats for different time units
17287 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17288 (> (/ (truncate m) (* y d h)) 0))
17289 (format fmt (/ m (* y d (float h)))))
17290 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17291 (> (/ (truncate m) (* mo d h)) 0))
17292 (format fmt (/ m (* mo d (float h)))))
17293 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17294 (> (/ (truncate m) (* w d h)) 0))
17295 (format fmt (/ m (* w d (float h)))))
17296 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17297 (> (/ (truncate m) (* d h)) 0))
17298 (format fmt (/ m (* d (float h)))))
17299 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17300 (> (/ (truncate m) h) 0))
17301 (format fmt (/ m (float h))))
17302 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17303 (format fmt m))
17304 ;; fall back to smallest time unit with a format
17305 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17306 (format fmt (/ m (float h))))
17307 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17308 (format fmt (/ m (* d (float h)))))
17309 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17310 (format fmt (/ m (* w d (float h)))))
17311 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17312 (format fmt (/ m (* mo d (float h)))))
17313 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17314 (format fmt (/ m (* y d (float h))))))
17315 ;; standard (non-fractional) format, with single format string
17316 (if (stringp org-time-clocksum-format)
17317 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17318 ;; separate formats components
17319 (and (setq fmt (plist-get org-time-clocksum-format :years))
17320 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17321 (plist-get org-time-clocksum-format :require-years))
17322 (setq clocksum (concat clocksum (format fmt n))
17323 m (- m (* n y d h))))
17324 (and (setq fmt (plist-get org-time-clocksum-format :months))
17325 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17326 (plist-get org-time-clocksum-format :require-months))
17327 (setq clocksum (concat clocksum (format fmt n))
17328 m (- m (* n mo d h))))
17329 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17330 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17331 (plist-get org-time-clocksum-format :require-weeks))
17332 (setq clocksum (concat clocksum (format fmt n))
17333 m (- m (* n w d h))))
17334 (and (setq fmt (plist-get org-time-clocksum-format :days))
17335 (or (> (setq n (/ (truncate m) (* d h))) 0)
17336 (plist-get org-time-clocksum-format :require-days))
17337 (setq clocksum (concat clocksum (format fmt n))
17338 m (- m (* n d h))))
17339 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17340 (or (> (setq n (/ (truncate m) h)) 0)
17341 (plist-get org-time-clocksum-format :require-hours))
17342 (setq clocksum (concat clocksum (format fmt n))
17343 m (- m (* n h))))
17344 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17345 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17346 (setq clocksum (concat clocksum (format fmt m))))
17347 ;; return formatted time duration
17348 clocksum))))
17350 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17351 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17352 "Org mode version 8.0")
17354 (defun org-hours-to-clocksum-string (n)
17355 (org-minutes-to-clocksum-string (* n 60)))
17357 (defun org-hh:mm-string-to-minutes (s)
17358 "Convert a string H:MM to a number of minutes.
17359 If the string is just a number, interpret it as minutes.
17360 In fact, the first hh:mm or number in the string will be taken,
17361 there can be extra stuff in the string.
17362 If no number is found, the return value is 0."
17363 (cond
17364 ((integerp s) s)
17365 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17366 (+ (* (string-to-number (match-string 1 s)) 60)
17367 (string-to-number (match-string 2 s))))
17368 ((string-match "\\([0-9]+\\)" s)
17369 (string-to-number (match-string 1 s)))
17370 (t 0)))
17372 (defcustom org-image-actual-width t
17373 "Should we use the actual width of images when inlining them?
17375 When set to `t', always use the image width.
17377 When set to a number, use imagemagick (when available) to set
17378 the image's width to this value.
17380 When set to a number in a list, try to get the width from the
17381 #+ATTR.* keyword if it matches a width specification like
17382 width=\"[0-9]+\", and fall back on that number if none is found.
17384 When set to nil, try to get the width from an #+ATTR.* keyword
17385 and fall back on the original width if none is found.
17387 This requires Emacs >= 24.1, build with imagemagick support."
17388 :group 'org-appearance
17389 :version "24.4"
17390 :package-version '(Org . "8.0")
17391 :type '(choice
17392 (const :tag "Use the image width" t)
17393 (integer :tag "Use a number of pixels")
17394 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17395 (const :tag "Use #+ATTR* or don't resize" nil)))
17397 (defcustom org-agenda-inhibit-startup nil
17398 "Inhibit startup when preparing agenda buffers.
17399 When this variable is `t' (the default), the initialization of
17400 the Org agenda buffers is inhibited: e.g. the visibility state
17401 is not set, the tables are not re-aligned, etc."
17402 :type 'boolean
17403 :version "24.3"
17404 :group 'org-agenda)
17406 (defun org-duration-string-to-minutes (s &optional output-to-string)
17407 "Convert a duration string S to minutes.
17409 A bare number is interpreted as minutes, modifiers can be set by
17410 customizing `org-effort-durations' (which see).
17412 Entries containing a colon are interpreted as H:MM by
17413 `org-hh:mm-string-to-minutes'."
17414 (let ((result 0)
17415 (re (concat "\\([0-9.]+\\) *\\("
17416 (regexp-opt (mapcar 'car org-effort-durations))
17417 "\\)")))
17418 (while (string-match re s)
17419 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17420 (string-to-number (match-string 1 s))))
17421 (setq s (replace-match "" nil t s)))
17422 (setq result (floor result))
17423 (incf result (org-hh:mm-string-to-minutes s))
17424 (if output-to-string (number-to-string result) result)))
17426 ;;;; Files
17428 (defun org-save-all-org-buffers ()
17429 "Save all Org-mode buffers without user confirmation."
17430 (interactive)
17431 (message "Saving all Org-mode buffers...")
17432 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17433 (when (featurep 'org-id) (org-id-locations-save))
17434 (message "Saving all Org-mode buffers... done"))
17436 (defun org-revert-all-org-buffers ()
17437 "Revert all Org-mode buffers.
17438 Prompt for confirmation when there are unsaved changes.
17439 Be sure you know what you are doing before letting this function
17440 overwrite your changes.
17442 This function is useful in a setup where one tracks org files
17443 with a version control system, to revert on one machine after pulling
17444 changes from another. I believe the procedure must be like this:
17446 1. M-x org-save-all-org-buffers
17447 2. Pull changes from the other machine, resolve conflicts
17448 3. M-x org-revert-all-org-buffers"
17449 (interactive)
17450 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17451 (error "Abort"))
17452 (save-excursion
17453 (save-window-excursion
17454 (mapc
17455 (lambda (b)
17456 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17457 (with-current-buffer b buffer-file-name))
17458 (org-pop-to-buffer-same-window b)
17459 (revert-buffer t 'no-confirm)))
17460 (buffer-list))
17461 (when (and (featurep 'org-id) org-id-track-globally)
17462 (org-id-locations-load)))))
17464 ;;;; Agenda files
17466 ;;;###autoload
17467 (defun org-switchb (&optional arg)
17468 "Switch between Org buffers.
17469 With one prefix argument, restrict available buffers to files.
17470 With two prefix arguments, restrict available buffers to agenda files.
17472 Defaults to `iswitchb' for buffer name completion.
17473 Set `org-completion-use-ido' to make it use ido instead."
17474 (interactive "P")
17475 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17476 ((equal arg '(16)) (org-buffer-list 'agenda))
17477 (t (org-buffer-list))))
17478 (org-completion-use-iswitchb org-completion-use-iswitchb)
17479 (org-completion-use-ido org-completion-use-ido))
17480 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17481 (setq org-completion-use-iswitchb t))
17482 (org-pop-to-buffer-same-window
17483 (org-icompleting-read "Org buffer: "
17484 (mapcar 'list (mapcar 'buffer-name blist))
17485 nil t))))
17487 ;;; Define some older names previously used for this functionality
17488 ;;;###autoload
17489 (defalias 'org-ido-switchb 'org-switchb)
17490 ;;;###autoload
17491 (defalias 'org-iswitchb 'org-switchb)
17493 (defun org-buffer-list (&optional predicate exclude-tmp)
17494 "Return a list of Org buffers.
17495 PREDICATE can be `export', `files' or `agenda'.
17497 export restrict the list to Export buffers.
17498 files restrict the list to buffers visiting Org files.
17499 agenda restrict the list to buffers visiting agenda files.
17501 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17502 (let* ((bfn nil)
17503 (agenda-files (and (eq predicate 'agenda)
17504 (mapcar 'file-truename (org-agenda-files t))))
17505 (filter
17506 (cond
17507 ((eq predicate 'files)
17508 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17509 ((eq predicate 'export)
17510 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17511 ((eq predicate 'agenda)
17512 (lambda (b)
17513 (with-current-buffer b
17514 (and (derived-mode-p 'org-mode)
17515 (setq bfn (buffer-file-name b))
17516 (member (file-truename bfn) agenda-files)))))
17517 (t (lambda (b) (with-current-buffer b
17518 (or (derived-mode-p 'org-mode)
17519 (string-match "\*Org .*Export"
17520 (buffer-name b)))))))))
17521 (delq nil
17522 (mapcar
17523 (lambda(b)
17524 (if (and (funcall filter b)
17525 (or (not exclude-tmp)
17526 (not (string-match "tmp" (buffer-name b)))))
17528 nil))
17529 (buffer-list)))))
17531 (defun org-agenda-files (&optional unrestricted archives)
17532 "Get the list of agenda files.
17533 Optional UNRESTRICTED means return the full list even if a restriction
17534 is currently in place.
17535 When ARCHIVES is t, include all archive files that are really being
17536 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17537 `org-agenda-archives-mode' is t."
17538 (let ((files
17539 (cond
17540 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17541 ((stringp org-agenda-files) (org-read-agenda-file-list))
17542 ((listp org-agenda-files) org-agenda-files)
17543 (t (error "Invalid value of `org-agenda-files'")))))
17544 (setq files (apply 'append
17545 (mapcar (lambda (f)
17546 (if (file-directory-p f)
17547 (directory-files
17548 f t org-agenda-file-regexp)
17549 (list f)))
17550 files)))
17551 (when org-agenda-skip-unavailable-files
17552 (setq files (delq nil
17553 (mapcar (function
17554 (lambda (file)
17555 (and (file-readable-p file) file)))
17556 files))))
17557 (when (or (eq archives t)
17558 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17559 (setq files (org-add-archive-files files)))
17560 files))
17562 (defun org-agenda-file-p (&optional file)
17563 "Return non-nil, if FILE is an agenda file.
17564 If FILE is omitted, use the file associated with the current
17565 buffer."
17566 (member (or file (buffer-file-name))
17567 (org-agenda-files t)))
17569 (defun org-edit-agenda-file-list ()
17570 "Edit the list of agenda files.
17571 Depending on setup, this either uses customize to edit the variable
17572 `org-agenda-files', or it visits the file that is holding the list. In the
17573 latter case, the buffer is set up in a way that saving it automatically kills
17574 the buffer and restores the previous window configuration."
17575 (interactive)
17576 (if (stringp org-agenda-files)
17577 (let ((cw (current-window-configuration)))
17578 (find-file org-agenda-files)
17579 (org-set-local 'org-window-configuration cw)
17580 (org-add-hook 'after-save-hook
17581 (lambda ()
17582 (set-window-configuration
17583 (prog1 org-window-configuration
17584 (kill-buffer (current-buffer))))
17585 (org-install-agenda-files-menu)
17586 (message "New agenda file list installed"))
17587 nil 'local)
17588 (message "%s" (substitute-command-keys
17589 "Edit list and finish with \\[save-buffer]")))
17590 (customize-variable 'org-agenda-files)))
17592 (defun org-store-new-agenda-file-list (list)
17593 "Set new value for the agenda file list and save it correctly."
17594 (if (stringp org-agenda-files)
17595 (let ((fe (org-read-agenda-file-list t)) b u)
17596 (while (setq b (find-buffer-visiting org-agenda-files))
17597 (kill-buffer b))
17598 (with-temp-file org-agenda-files
17599 (insert
17600 (mapconcat
17601 (lambda (f) ;; Keep un-expanded entries.
17602 (if (setq u (assoc f fe))
17603 (cdr u)
17605 list "\n")
17606 "\n")))
17607 (let ((org-mode-hook nil) (org-inhibit-startup t)
17608 (org-insert-mode-line-in-empty-file nil))
17609 (setq org-agenda-files list)
17610 (customize-save-variable 'org-agenda-files org-agenda-files))))
17612 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17613 "Read the list of agenda files from a file.
17614 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17615 filenames, used by `org-store-new-agenda-file-list' to write back
17616 un-expanded file names."
17617 (when (file-directory-p org-agenda-files)
17618 (error "`org-agenda-files' cannot be a single directory"))
17619 (when (stringp org-agenda-files)
17620 (with-temp-buffer
17621 (insert-file-contents org-agenda-files)
17622 (mapcar
17623 (lambda (f)
17624 (let ((e (expand-file-name (substitute-in-file-name f)
17625 org-directory)))
17626 (if pair-with-expansion
17627 (cons e f)
17628 e)))
17629 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17631 ;;;###autoload
17632 (defun org-cycle-agenda-files ()
17633 "Cycle through the files in `org-agenda-files'.
17634 If the current buffer visits an agenda file, find the next one in the list.
17635 If the current buffer does not, find the first agenda file."
17636 (interactive)
17637 (let* ((fs (org-agenda-files t))
17638 (files (append fs (list (car fs))))
17639 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17640 file)
17641 (unless files (error "No agenda files"))
17642 (catch 'exit
17643 (while (setq file (pop files))
17644 (if (equal (file-truename file) tcf)
17645 (when (car files)
17646 (find-file (car files))
17647 (throw 'exit t))))
17648 (find-file (car fs)))
17649 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17651 (defun org-agenda-file-to-front (&optional to-end)
17652 "Move/add the current file to the top of the agenda file list.
17653 If the file is not present in the list, it is added to the front. If it is
17654 present, it is moved there. With optional argument TO-END, add/move to the
17655 end of the list."
17656 (interactive "P")
17657 (let ((org-agenda-skip-unavailable-files nil)
17658 (file-alist (mapcar (lambda (x)
17659 (cons (file-truename x) x))
17660 (org-agenda-files t)))
17661 (ctf (file-truename
17662 (or buffer-file-name
17663 (error "Please save the current buffer to a file"))))
17664 x had)
17665 (setq x (assoc ctf file-alist) had x)
17667 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17668 (if to-end
17669 (setq file-alist (append (delq x file-alist) (list x)))
17670 (setq file-alist (cons x (delq x file-alist))))
17671 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17672 (org-install-agenda-files-menu)
17673 (message "File %s to %s of agenda file list"
17674 (if had "moved" "added") (if to-end "end" "front"))))
17676 (defun org-remove-file (&optional file)
17677 "Remove current file from the list of files in variable `org-agenda-files'.
17678 These are the files which are being checked for agenda entries.
17679 Optional argument FILE means use this file instead of the current."
17680 (interactive)
17681 (let* ((org-agenda-skip-unavailable-files nil)
17682 (file (or file buffer-file-name
17683 (error "Current buffer does not visit a file")))
17684 (true-file (file-truename file))
17685 (afile (abbreviate-file-name file))
17686 (files (delq nil (mapcar
17687 (lambda (x)
17688 (if (equal true-file
17689 (file-truename x))
17690 nil x))
17691 (org-agenda-files t)))))
17692 (if (not (= (length files) (length (org-agenda-files t))))
17693 (progn
17694 (org-store-new-agenda-file-list files)
17695 (org-install-agenda-files-menu)
17696 (message "Removed file: %s" afile))
17697 (message "File was not in list: %s (not removed)" afile))))
17699 (defun org-file-menu-entry (file)
17700 (vector file (list 'find-file file) t))
17702 (defun org-check-agenda-file (file)
17703 "Make sure FILE exists. If not, ask user what to do."
17704 (when (not (file-exists-p file))
17705 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17706 (abbreviate-file-name file))
17707 (let ((r (downcase (read-char-exclusive))))
17708 (cond
17709 ((equal r ?r)
17710 (org-remove-file file)
17711 (throw 'nextfile t))
17712 (t (error "Abort"))))))
17714 (defun org-get-agenda-file-buffer (file)
17715 "Get a buffer visiting FILE. If the buffer needs to be created, add
17716 it to the list of buffers which might be released later."
17717 (let ((buf (org-find-base-buffer-visiting file)))
17718 (if buf
17719 buf ; just return it
17720 ;; Make a new buffer and remember it
17721 (setq buf (find-file-noselect file))
17722 (if buf (push buf org-agenda-new-buffers))
17723 buf)))
17725 (defun org-release-buffers (blist)
17726 "Release all buffers in list, asking the user for confirmation when needed.
17727 When a buffer is unmodified, it is just killed. When modified, it is saved
17728 \(if the user agrees) and then killed."
17729 (let (buf file)
17730 (while (setq buf (pop blist))
17731 (setq file (buffer-file-name buf))
17732 (when (and (buffer-modified-p buf)
17733 file
17734 (y-or-n-p (format "Save file %s? " file)))
17735 (with-current-buffer buf (save-buffer)))
17736 (kill-buffer buf))))
17738 (defun org-agenda-prepare-buffers (files)
17739 "Create buffers for all agenda files, protect archived trees and comments."
17740 (interactive)
17741 (let ((pa '(:org-archived t))
17742 (pc '(:org-comment t))
17743 (pall '(:org-archived t :org-comment t))
17744 (inhibit-read-only t)
17745 (org-inhibit-startup org-agenda-inhibit-startup)
17746 (rea (concat ":" org-archive-tag ":"))
17747 file re)
17748 (save-excursion
17749 (save-restriction
17750 (while (setq file (pop files))
17751 (catch 'nextfile
17752 (if (bufferp file)
17753 (set-buffer file)
17754 (org-check-agenda-file file)
17755 (set-buffer (org-get-agenda-file-buffer file)))
17756 (widen)
17757 (org-refresh-category-properties)
17758 (org-refresh-properties org-effort-property 'org-effort)
17759 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17760 (setq org-todo-keywords-for-agenda
17761 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17762 (setq org-done-keywords-for-agenda
17763 (append org-done-keywords-for-agenda org-done-keywords))
17764 (setq org-todo-keyword-alist-for-agenda
17765 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17766 (setq org-drawers-for-agenda
17767 (append org-drawers-for-agenda org-drawers))
17768 (setq org-tag-alist-for-agenda
17769 (append org-tag-alist-for-agenda org-tag-alist))
17770 (org-with-silent-modifications
17771 (save-excursion
17772 (remove-text-properties (point-min) (point-max) pall)
17773 (when org-agenda-skip-archived-trees
17774 (goto-char (point-min))
17775 (while (re-search-forward rea nil t)
17776 (if (org-at-heading-p t)
17777 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17778 (goto-char (point-min))
17779 (setq re (format org-heading-keyword-regexp-format
17780 org-comment-string))
17781 (while (re-search-forward re nil t)
17782 (add-text-properties
17783 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17784 (setq org-todo-keywords-for-agenda
17785 (org-uniquify org-todo-keywords-for-agenda))
17786 (setq org-todo-keyword-alist-for-agenda
17787 (org-uniquify org-todo-keyword-alist-for-agenda)
17788 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17791 ;;;; CDLaTeX minor mode
17793 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17794 "Keymap for the minor `org-cdlatex-mode'.")
17796 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17797 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17798 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17799 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17800 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17802 (defvar org-cdlatex-texmathp-advice-is-done nil
17803 "Flag remembering if we have applied the advice to texmathp already.")
17805 (define-minor-mode org-cdlatex-mode
17806 "Toggle the minor `org-cdlatex-mode'.
17807 This mode supports entering LaTeX environment and math in LaTeX fragments
17808 in Org-mode.
17809 \\{org-cdlatex-mode-map}"
17810 nil " OCDL" nil
17811 (when org-cdlatex-mode
17812 (require 'cdlatex)
17813 (run-hooks 'cdlatex-mode-hook)
17814 (cdlatex-compute-tables))
17815 (unless org-cdlatex-texmathp-advice-is-done
17816 (setq org-cdlatex-texmathp-advice-is-done t)
17817 (defadvice texmathp (around org-math-always-on activate)
17818 "Always return t in org-mode buffers.
17819 This is because we want to insert math symbols without dollars even outside
17820 the LaTeX math segments. If Orgmode thinks that point is actually inside
17821 an embedded LaTeX fragment, let texmathp do its job.
17822 \\[org-cdlatex-mode-map]"
17823 (interactive)
17824 (let (p)
17825 (cond
17826 ((not (derived-mode-p 'org-mode)) ad-do-it)
17827 ((eq this-command 'cdlatex-math-symbol)
17828 (setq ad-return-value t
17829 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17831 (let ((p (org-inside-LaTeX-fragment-p)))
17832 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17833 (setq ad-return-value t
17834 texmathp-why '("Org-mode embedded math" . 0))
17835 (if p ad-do-it)))))))))
17837 (defun turn-on-org-cdlatex ()
17838 "Unconditionally turn on `org-cdlatex-mode'."
17839 (org-cdlatex-mode 1))
17841 (defun org-try-cdlatex-tab ()
17842 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17843 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17844 - inside a LaTeX fragment, or
17845 - after the first word in a line, where an abbreviation expansion could
17846 insert a LaTeX environment."
17847 (when org-cdlatex-mode
17848 (cond
17849 ;; Before any word on the line: No expansion possible.
17850 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17851 ;; Just after first word on the line: Expand it. Make sure it
17852 ;; cannot happen on headlines, though.
17853 ((save-excursion
17854 (skip-chars-backward "a-zA-Z0-9*")
17855 (skip-chars-backward " \t")
17856 (and (bolp) (not (org-at-heading-p))))
17857 (cdlatex-tab) t)
17858 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17860 (defun org-cdlatex-underscore-caret (&optional arg)
17861 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17862 Revert to the normal definition outside of these fragments."
17863 (interactive "P")
17864 (if (org-inside-LaTeX-fragment-p)
17865 (call-interactively 'cdlatex-sub-superscript)
17866 (let (org-cdlatex-mode)
17867 (call-interactively (key-binding (vector last-input-event))))))
17869 (defun org-cdlatex-math-modify (&optional arg)
17870 "Execute `cdlatex-math-modify' in LaTeX fragments.
17871 Revert to the normal definition outside of these fragments."
17872 (interactive "P")
17873 (if (org-inside-LaTeX-fragment-p)
17874 (call-interactively 'cdlatex-math-modify)
17875 (let (org-cdlatex-mode)
17876 (call-interactively (key-binding (vector last-input-event))))))
17880 ;;;; LaTeX fragments
17882 (defvar org-latex-regexps
17883 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17884 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17885 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17886 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17887 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17888 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17889 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17890 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17891 "Regular expressions for matching embedded LaTeX.")
17893 (defun org-inside-LaTeX-fragment-p ()
17894 "Test if point is inside a LaTeX fragment.
17895 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17896 sequence appearing also before point.
17897 Even though the matchers for math are configurable, this function assumes
17898 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17899 delimiters are skipped when they have been removed by customization.
17900 The return value is nil, or a cons cell with the delimiter and the
17901 position of this delimiter.
17903 This function does a reasonably good job, but can locally be fooled by
17904 for example currency specifications. For example it will assume being in
17905 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17906 fragments that are properly closed, but during editing, we have to live
17907 with the uncertainty caused by missing closing delimiters. This function
17908 looks only before point, not after."
17909 (catch 'exit
17910 (let ((pos (point))
17911 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17912 (lim (progn
17913 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17914 (point)))
17915 dd-on str (start 0) m re)
17916 (goto-char pos)
17917 (when dodollar
17918 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17919 re (nth 1 (assoc "$" org-latex-regexps)))
17920 (while (string-match re str start)
17921 (cond
17922 ((= (match-end 0) (length str))
17923 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17924 ((= (match-end 0) (- (length str) 5))
17925 (throw 'exit nil))
17926 (t (setq start (match-end 0))))))
17927 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17928 (goto-char pos)
17929 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17930 (and (match-beginning 2) (throw 'exit nil))
17931 ;; count $$
17932 (while (re-search-backward "\\$\\$" lim t)
17933 (setq dd-on (not dd-on)))
17934 (goto-char pos)
17935 (if dd-on (cons "$$" m))))))
17937 (defun org-inside-latex-macro-p ()
17938 "Is point inside a LaTeX macro or its arguments?"
17939 (save-match-data
17940 (org-in-regexp
17941 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17943 (defvar org-latex-fragment-image-overlays nil
17944 "List of overlays carrying the images of latex fragments.")
17945 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17947 (defun org-remove-latex-fragment-image-overlays ()
17948 "Remove all overlays with LaTeX fragment images in current buffer."
17949 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17950 (setq org-latex-fragment-image-overlays nil))
17952 (defun org-preview-latex-fragment (&optional subtree)
17953 "Preview the LaTeX fragment at point, or all locally or globally.
17954 If the cursor is in a LaTeX fragment, create the image and overlay
17955 it over the source code. If there is no fragment at point, display
17956 all fragments in the current text, from one headline to the next. With
17957 prefix SUBTREE, display all fragments in the current subtree. With a
17958 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17959 the cursor is before the first headline,
17960 display all fragments in the buffer.
17961 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17962 (interactive "P")
17963 (unless buffer-file-name
17964 (error "Can't preview LaTeX fragment in a non-file buffer"))
17965 (org-remove-latex-fragment-image-overlays)
17966 (save-excursion
17967 (save-restriction
17968 (let (beg end at msg)
17969 (cond
17970 ((or (equal subtree '(16))
17971 (not (save-excursion
17972 (re-search-backward org-outline-regexp-bol nil t))))
17973 (setq beg (point-min) end (point-max)
17974 msg "Creating images for buffer...%s"))
17975 ((equal subtree '(4))
17976 (org-back-to-heading)
17977 (setq beg (point) end (org-end-of-subtree t)
17978 msg "Creating images for subtree...%s"))
17980 (if (setq at (org-inside-LaTeX-fragment-p))
17981 (goto-char (max (point-min) (- (cdr at) 2)))
17982 (org-back-to-heading))
17983 (setq beg (point) end (progn (outline-next-heading) (point))
17984 msg (if at "Creating image...%s"
17985 "Creating images for entry...%s"))))
17986 (message msg "")
17987 (narrow-to-region beg end)
17988 (goto-char beg)
17989 (org-format-latex
17990 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17991 (file-name-nondirectory
17992 buffer-file-name)))
17993 default-directory 'overlays msg at 'forbuffer
17994 org-latex-create-formula-image-program)
17995 (message msg "done. Use `C-c C-c' to remove images.")))))
17997 (defun org-format-latex (prefix &optional dir overlays msg at
17998 forbuffer processing-type)
17999 "Replace LaTeX fragments with links to an image, and produce images.
18000 Some of the options can be changed using the variable
18001 `org-format-latex-options'."
18002 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18003 (let* ((prefixnodir (file-name-nondirectory prefix))
18004 (absprefix (expand-file-name prefix dir))
18005 (todir (file-name-directory absprefix))
18006 (opt org-format-latex-options)
18007 (optnew org-format-latex-options)
18008 (matchers (plist-get opt :matchers))
18009 (re-list org-latex-regexps)
18010 (cnt 0) txt hash link beg end re e checkdir
18011 string
18012 m n block-type block linkfile movefile ov)
18013 ;; Check the different regular expressions
18014 (while (setq e (pop re-list))
18015 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18016 block (if block-type "\n\n" ""))
18017 (when (member m matchers)
18018 (goto-char (point-min))
18019 (while (re-search-forward re nil t)
18020 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18021 (or (not overlays)
18022 (not (eq (get-char-property (match-beginning n)
18023 'org-overlay-type)
18024 'org-latex-overlay))))
18025 (cond
18026 ((eq processing-type 'verbatim))
18027 ((eq processing-type 'mathjax)
18028 ;; Prepare for MathJax processing.
18029 (setq string (match-string n))
18030 (when (member m '("$" "$1"))
18031 (save-excursion
18032 (delete-region (match-beginning n) (match-end n))
18033 (goto-char (match-beginning n))
18034 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18035 ((or (eq processing-type 'dvipng)
18036 (eq processing-type 'imagemagick))
18037 ;; Process to an image.
18038 (setq txt (match-string n)
18039 beg (match-beginning n) end (match-end n)
18040 cnt (1+ cnt))
18041 (let ((face (face-at-point))
18042 (fg (plist-get opt :foreground))
18043 (bg (plist-get opt :background))
18044 ;; Ensure full list is printed.
18045 print-length print-level)
18046 (when forbuffer
18047 ;; Get the colors from the face at point.
18048 (goto-char beg)
18049 (when (eq fg 'auto)
18050 (setq fg (face-attribute face :foreground nil 'default)))
18051 (when (eq bg 'auto)
18052 (setq bg (face-attribute face :background nil 'default)))
18053 (setq optnew (copy-sequence opt))
18054 (plist-put optnew :foreground fg)
18055 (plist-put optnew :background bg))
18056 (setq hash (sha1 (prin1-to-string
18057 (list org-format-latex-header
18058 org-latex-default-packages-alist
18059 org-latex-packages-alist
18060 org-format-latex-options
18061 forbuffer txt fg bg)))
18062 linkfile (format "%s_%s.png" prefix hash)
18063 movefile (format "%s_%s.png" absprefix hash)))
18064 (setq link (concat block "[[file:" linkfile "]]" block))
18065 (if msg (message msg cnt))
18066 (goto-char beg)
18067 (unless checkdir ; Ensure the directory exists.
18068 (setq checkdir t)
18069 (or (file-directory-p todir) (make-directory todir t)))
18070 (unless (file-exists-p movefile)
18071 (org-create-formula-image
18072 txt movefile optnew forbuffer processing-type))
18073 (if overlays
18074 (progn
18075 (mapc (lambda (o)
18076 (if (eq (overlay-get o 'org-overlay-type)
18077 'org-latex-overlay)
18078 (delete-overlay o)))
18079 (overlays-in beg end))
18080 (setq ov (make-overlay beg end))
18081 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18082 (if (featurep 'xemacs)
18083 (progn
18084 (overlay-put ov 'invisible t)
18085 (overlay-put
18086 ov 'end-glyph
18087 (make-glyph (vector 'png :file movefile))))
18088 (overlay-put
18089 ov 'display
18090 (list 'image :type 'png :file movefile :ascent 'center)))
18091 (push ov org-latex-fragment-image-overlays)
18092 (goto-char end))
18093 (delete-region beg end)
18094 (insert (org-add-props link
18095 (list 'org-latex-src
18096 (replace-regexp-in-string
18097 "\"" "" txt)
18098 'org-latex-src-embed-type
18099 (if block-type 'paragraph 'character))))))
18100 ((eq processing-type 'mathml)
18101 ;; Process to MathML
18102 (unless (save-match-data (org-format-latex-mathml-available-p))
18103 (error "LaTeX to MathML converter not configured"))
18104 (setq txt (match-string n)
18105 beg (match-beginning n) end (match-end n)
18106 cnt (1+ cnt))
18107 (if msg (message msg cnt))
18108 (goto-char beg)
18109 (delete-region beg end)
18110 (insert (org-format-latex-as-mathml
18111 txt block-type prefix dir)))
18113 (error "Unknown conversion type %s for latex fragments"
18114 processing-type)))))))))
18116 (defun org-create-math-formula (latex-frag &optional mathml-file)
18117 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18118 Use `org-latex-to-mathml-convert-command'. If the conversion is
18119 sucessful, return the portion between \"<math...> </math>\"
18120 elements otherwise return nil. When MATHML-FILE is specified,
18121 write the results in to that file. When invoked as an
18122 interactive command, prompt for LATEX-FRAG, with initial value
18123 set to the current active region and echo the results for user
18124 inspection."
18125 (interactive (list (let ((frag (when (org-region-active-p)
18126 (buffer-substring-no-properties
18127 (region-beginning) (region-end)))))
18128 (read-string "LaTeX Fragment: " frag nil frag))))
18129 (unless latex-frag (error "Invalid latex-frag"))
18130 (let* ((tmp-in-file (file-relative-name
18131 (make-temp-name (expand-file-name "ltxmathml-in"))))
18132 (ignore (write-region latex-frag nil tmp-in-file))
18133 (tmp-out-file (file-relative-name
18134 (make-temp-name (expand-file-name "ltxmathml-out"))))
18135 (cmd (format-spec
18136 org-latex-to-mathml-convert-command
18137 `((?j . ,(shell-quote-argument
18138 (expand-file-name org-latex-to-mathml-jar-file)))
18139 (?I . ,(shell-quote-argument tmp-in-file))
18140 (?o . ,(shell-quote-argument tmp-out-file)))))
18141 mathml shell-command-output)
18142 (when (org-called-interactively-p 'any)
18143 (unless (org-format-latex-mathml-available-p)
18144 (error "LaTeX to MathML converter not configured")))
18145 (message "Running %s" cmd)
18146 (setq shell-command-output (shell-command-to-string cmd))
18147 (setq mathml
18148 (when (file-readable-p tmp-out-file)
18149 (with-current-buffer (find-file-noselect tmp-out-file t)
18150 (goto-char (point-min))
18151 (when (re-search-forward
18152 (concat
18153 (regexp-quote
18154 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18155 "\\(.\\|\n\\)*"
18156 (regexp-quote "</math>")) nil t)
18157 (prog1 (match-string 0) (kill-buffer))))))
18158 (cond
18159 (mathml
18160 (setq mathml
18161 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18162 (when mathml-file
18163 (write-region mathml nil mathml-file))
18164 (when (org-called-interactively-p 'any)
18165 (message mathml)))
18166 ((message "LaTeX to MathML conversion failed")
18167 (message shell-command-output)))
18168 (delete-file tmp-in-file)
18169 (when (file-exists-p tmp-out-file)
18170 (delete-file tmp-out-file))
18171 mathml))
18173 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18174 prefix &optional dir)
18175 "Use `org-create-math-formula' but check local cache first."
18176 (let* ((absprefix (expand-file-name prefix dir))
18177 (print-length nil) (print-level nil)
18178 (formula-id (concat
18179 "formula-"
18180 (sha1
18181 (prin1-to-string
18182 (list latex-frag
18183 org-latex-to-mathml-convert-command)))))
18184 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18185 (formula-cache-dir (file-name-directory formula-cache)))
18187 (unless (file-directory-p formula-cache-dir)
18188 (make-directory formula-cache-dir t))
18190 (unless (file-exists-p formula-cache)
18191 (org-create-math-formula latex-frag formula-cache))
18193 (if (file-exists-p formula-cache)
18194 ;; Successful conversion. Return the link to MathML file.
18195 (org-add-props
18196 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18197 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18198 'org-latex-src-embed-type (if latex-frag-type
18199 'paragraph 'character)))
18200 ;; Failed conversion. Return the LaTeX fragment verbatim
18201 latex-frag)))
18203 (defun org-create-formula-image (string tofile options buffer &optional type)
18204 "Create an image from LaTeX source using dvipng or convert.
18205 This function calls either `org-create-formula-image-with-dvipng'
18206 or `org-create-formula-image-with-imagemagick' depending on the
18207 value of `org-latex-create-formula-image-program' or on the value
18208 of the optional TYPE variable.
18210 Note: ultimately these two function should be combined as they
18211 share a good deal of logic."
18212 (org-check-external-command
18213 "latex" "needed to convert LaTeX fragments to images")
18214 (funcall
18215 (case (or type org-latex-create-formula-image-program)
18216 ('dvipng
18217 (org-check-external-command
18218 "dvipng" "needed to convert LaTeX fragments to images")
18219 #'org-create-formula-image-with-dvipng)
18220 ('imagemagick
18221 (org-check-external-command
18222 "convert" "you need to install imagemagick")
18223 #'org-create-formula-image-with-imagemagick)
18224 (t (error
18225 "invalid value of `org-latex-create-formula-image-program'")))
18226 string tofile options buffer))
18228 (declare-function org-export--get-global-options "ox" (&optional backend))
18229 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18230 (defun org-create-formula--latex-header ()
18231 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18232 (org-latex-guess-inputenc
18233 (org-splice-latex-header
18234 org-format-latex-header
18235 org-latex-default-packages-alist
18236 org-latex-packages-alist t
18237 (plist-get
18238 (org-combine-plists
18239 (org-export--get-global-options 'latex)
18240 (org-export--get-inbuffer-options 'latex))
18241 :latex-header))))
18243 ;; This function borrows from Ganesh Swami's latex2png.el
18244 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18245 "This calls dvipng."
18246 (require 'ox-latex)
18247 (let* ((tmpdir (if (featurep 'xemacs)
18248 (temp-directory)
18249 temporary-file-directory))
18250 (texfilebase (make-temp-name
18251 (expand-file-name "orgtex" tmpdir)))
18252 (texfile (concat texfilebase ".tex"))
18253 (dvifile (concat texfilebase ".dvi"))
18254 (pngfile (concat texfilebase ".png"))
18255 (fnh (if (featurep 'xemacs)
18256 (font-height (face-font 'default))
18257 (face-attribute 'default :height nil)))
18258 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18259 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18260 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18261 "Black"))
18262 (bg (or (plist-get options (if buffer :background :html-background))
18263 "Transparent")))
18264 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18265 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18266 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18267 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18268 (let ((latex-header (org-create-formula--latex-header)))
18269 (with-temp-file texfile
18270 (insert latex-header)
18271 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18272 (let ((dir default-directory))
18273 (condition-case nil
18274 (progn
18275 (cd tmpdir)
18276 (call-process "latex" nil nil nil texfile))
18277 (error nil))
18278 (cd dir))
18279 (if (not (file-exists-p dvifile))
18280 (progn (message "Failed to create dvi file from %s" texfile) nil)
18281 (condition-case nil
18282 (if (featurep 'xemacs)
18283 (call-process "dvipng" nil nil nil
18284 "-fg" fg "-bg" bg
18285 "-T" "tight"
18286 "-o" pngfile
18287 dvifile)
18288 (call-process "dvipng" nil nil nil
18289 "-fg" fg "-bg" bg
18290 "-D" dpi
18291 ;;"-x" scale "-y" scale
18292 "-T" "tight"
18293 "-o" pngfile
18294 dvifile))
18295 (error nil))
18296 (if (not (file-exists-p pngfile))
18297 (if org-format-latex-signal-error
18298 (error "Failed to create png file from %s" texfile)
18299 (message "Failed to create png file from %s" texfile)
18300 nil)
18301 ;; Use the requested file name and clean up
18302 (copy-file pngfile tofile 'replace)
18303 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18304 (if (file-exists-p (concat texfilebase e))
18305 (delete-file (concat texfilebase e))))
18306 pngfile))))
18308 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18309 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18310 "This calls convert, which is included into imagemagick."
18311 (require 'ox-latex)
18312 (let* ((tmpdir (if (featurep 'xemacs)
18313 (temp-directory)
18314 temporary-file-directory))
18315 (texfilebase (make-temp-name
18316 (expand-file-name "orgtex" tmpdir)))
18317 (texfile (concat texfilebase ".tex"))
18318 (pdffile (concat texfilebase ".pdf"))
18319 (pngfile (concat texfilebase ".png"))
18320 (fnh (if (featurep 'xemacs)
18321 (font-height (face-font 'default))
18322 (face-attribute 'default :height nil)))
18323 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18324 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18325 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18326 "black"))
18327 (bg (or (plist-get options (if buffer :background :html-background))
18328 "white")))
18329 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18330 (setq fg (org-latex-color-format fg)))
18331 (if (eq bg 'default) (setq bg (org-latex-color :background))
18332 (setq bg (org-latex-color-format
18333 (if (string= bg "Transparent") "white" bg))))
18334 (let ((latex-header (org-create-formula--latex-header)))
18335 (with-temp-file texfile
18336 (insert latex-header)
18337 (insert "\n\\begin{document}\n"
18338 "\\definecolor{fg}{rgb}{" fg "}\n"
18339 "\\definecolor{bg}{rgb}{" bg "}\n"
18340 "\n\\pagecolor{bg}\n"
18341 "\n{\\color{fg}\n"
18342 string
18343 "\n}\n"
18344 "\n\\end{document}\n")))
18345 (org-latex-compile texfile t)
18346 (if (not (file-exists-p pdffile))
18347 (progn (message "Failed to create pdf file from %s" texfile) nil)
18348 (condition-case nil
18349 (if (featurep 'xemacs)
18350 (call-process "convert" nil nil nil
18351 "-density" "96"
18352 "-trim"
18353 "-antialias"
18354 pdffile
18355 "-quality" "100"
18356 ;; "-sharpen" "0x1.0"
18357 pngfile)
18358 (call-process "convert" nil nil nil
18359 "-density" dpi
18360 "-trim"
18361 "-antialias"
18362 pdffile
18363 "-quality" "100"
18364 ;; "-sharpen" "0x1.0"
18365 pngfile))
18366 (error nil))
18367 (if (not (file-exists-p pngfile))
18368 (if org-format-latex-signal-error
18369 (error "Failed to create png file from %s" texfile)
18370 (message "Failed to create png file from %s" texfile)
18371 nil)
18372 ;; Use the requested file name and clean up
18373 (copy-file pngfile tofile 'replace)
18374 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18375 (if (file-exists-p (concat texfilebase e))
18376 (delete-file (concat texfilebase e))))
18377 pngfile))))
18379 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18380 "Fill a LaTeX header template TPL.
18381 In the template, the following place holders will be recognized:
18383 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18384 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18385 [PACKAGES] \\usepackage statements for PKG
18386 [NO-PACKAGES] do not include PKG
18387 [EXTRA] the string EXTRA
18388 [NO-EXTRA] do not include EXTRA
18390 For backward compatibility, if both the positive and the negative place
18391 holder is missing, the positive one (without the \"NO-\") will be
18392 assumed to be present at the end of the template.
18393 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18394 EXTRA is a string.
18395 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18396 (let (rpl (end ""))
18397 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18398 (setq rpl (if (or (match-end 1) (not def-pkg))
18399 "" (org-latex-packages-to-string def-pkg snippets-p t))
18400 tpl (replace-match rpl t t tpl))
18401 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18403 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18404 (setq rpl (if (or (match-end 1) (not pkg))
18405 "" (org-latex-packages-to-string pkg snippets-p t))
18406 tpl (replace-match rpl t t tpl))
18407 (if pkg (setq end
18408 (concat end "\n"
18409 (org-latex-packages-to-string pkg snippets-p)))))
18411 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18412 (setq rpl (if (or (match-end 1) (not extra))
18413 "" (concat extra "\n"))
18414 tpl (replace-match rpl t t tpl))
18415 (if (and extra (string-match "\\S-" extra))
18416 (setq end (concat end "\n" extra))))
18418 (if (string-match "\\S-" end)
18419 (concat tpl "\n" end)
18420 tpl)))
18422 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18423 "Turn an alist of packages into a string with the \\usepackage macros."
18424 (setq pkg (mapconcat (lambda(p)
18425 (cond
18426 ((stringp p) p)
18427 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18428 (format "%% Package %s omitted" (cadr p)))
18429 ((equal "" (car p))
18430 (format "\\usepackage{%s}" (cadr p)))
18432 (format "\\usepackage[%s]{%s}"
18433 (car p) (cadr p)))))
18435 "\n"))
18436 (if newline (concat pkg "\n") pkg))
18438 (defun org-dvipng-color (attr)
18439 "Return a RGB color specification for dvipng."
18440 (apply 'format "rgb %s %s %s"
18441 (mapcar 'org-normalize-color
18442 (if (featurep 'xemacs)
18443 (color-rgb-components
18444 (face-property 'default
18445 (cond ((eq attr :foreground) 'foreground)
18446 ((eq attr :background) 'background))))
18447 (color-values (face-attribute 'default attr nil))))))
18449 (defun org-dvipng-color-format (color-name)
18450 "Convert COLOR-NAME to a RGB color value for dvipng."
18451 (apply 'format "rgb %s %s %s"
18452 (mapcar 'org-normalize-color
18453 (color-values color-name))))
18455 (defun org-latex-color (attr)
18456 "Return a RGB color for the LaTeX color package."
18457 (apply 'format "%s,%s,%s"
18458 (mapcar 'org-normalize-color
18459 (if (featurep 'xemacs)
18460 (color-rgb-components
18461 (face-property 'default
18462 (cond ((eq attr :foreground) 'foreground)
18463 ((eq attr :background) 'background))))
18464 (color-values (face-attribute 'default attr nil))))))
18466 (defun org-latex-color-format (color-name)
18467 "Convert COLOR-NAME to a RGB color value."
18468 (apply 'format "%s,%s,%s"
18469 (mapcar 'org-normalize-color
18470 (color-values color-name))))
18472 (defun org-normalize-color (value)
18473 "Return string to be used as color value for an RGB component."
18474 (format "%g" (/ value 65535.0)))
18478 ;; Image display
18480 (defvar org-inline-image-overlays nil)
18481 (make-variable-buffer-local 'org-inline-image-overlays)
18483 (defun org-toggle-inline-images (&optional include-linked)
18484 "Toggle the display of inline images.
18485 INCLUDE-LINKED is passed to `org-display-inline-images'."
18486 (interactive "P")
18487 (if org-inline-image-overlays
18488 (progn
18489 (org-remove-inline-images)
18490 (message "Inline image display turned off"))
18491 (org-display-inline-images include-linked)
18492 (if (and (org-called-interactively-p)
18493 org-inline-image-overlays)
18494 (message "%d images displayed inline"
18495 (length org-inline-image-overlays))
18496 (message "No images to display inline"))))
18498 (defun org-redisplay-inline-images ()
18499 "Refresh the display of inline images."
18500 (interactive)
18501 (if (not org-inline-image-overlays)
18502 (org-toggle-inline-images)
18503 (org-toggle-inline-images)
18504 (org-toggle-inline-images)))
18506 (defun org-display-inline-images (&optional include-linked refresh beg end)
18507 "Display inline images.
18508 Normally only links without a description part are inlined, because this
18509 is how it will work for export. When INCLUDE-LINKED is set, also links
18510 with a description part will be inlined. This can be nice for a quick
18511 look at those images, but it does not reflect what exported files will look
18512 like.
18513 When REFRESH is set, refresh existing images between BEG and END.
18514 This will create new image displays only if necessary.
18515 BEG and END default to the buffer boundaries."
18516 (interactive "P")
18517 (unless refresh
18518 (org-remove-inline-images)
18519 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18520 (save-excursion
18521 (save-restriction
18522 (widen)
18523 (setq beg (or beg (point-min)) end (or end (point-max)))
18524 (goto-char beg)
18525 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18526 (substring (org-image-file-name-regexp) 0 -2)
18527 "\\)\\]" (if include-linked "" "\\]")))
18528 old file ov img type attrwidth width)
18529 (while (re-search-forward re end t)
18530 (setq old (get-char-property-and-overlay (match-beginning 1)
18531 'org-image-overlay)
18532 file (expand-file-name
18533 (concat (or (match-string 3) "") (match-string 4))))
18534 (when (image-type-available-p 'imagemagick)
18535 (setq attrwidth (if (or (listp org-image-actual-width)
18536 (null org-image-actual-width))
18537 (save-excursion
18538 (save-match-data
18539 (when (re-search-backward
18540 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18541 (save-excursion
18542 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18543 (string-to-number (match-string 1))))))
18544 width (cond ((eq org-image-actual-width t) nil)
18545 ((null org-image-actual-width) attrwidth)
18546 ((numberp org-image-actual-width)
18547 org-image-actual-width)
18548 ((listp org-image-actual-width)
18549 (or attrwidth (car org-image-actual-width))))
18550 type (if width 'imagemagick)))
18551 (when (file-exists-p file)
18552 (if (and (car-safe old) refresh)
18553 (image-refresh (overlay-get (cdr old) 'display))
18554 (setq img (save-match-data (create-image file type nil :width width)))
18555 (when img
18556 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18557 (overlay-put ov 'display img)
18558 (overlay-put ov 'face 'default)
18559 (overlay-put ov 'org-image-overlay t)
18560 (overlay-put ov 'modification-hooks
18561 (list 'org-display-inline-remove-overlay))
18562 (push ov org-inline-image-overlays)))))))))
18564 (define-obsolete-function-alias
18565 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18567 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18568 "Remove inline-display overlay if a corresponding region is modified."
18569 (let ((inhibit-modification-hooks t))
18570 (when (and ov after)
18571 (delete ov org-inline-image-overlays)
18572 (delete-overlay ov))))
18574 (defun org-remove-inline-images ()
18575 "Remove inline display of images."
18576 (interactive)
18577 (mapc 'delete-overlay org-inline-image-overlays)
18578 (setq org-inline-image-overlays nil))
18580 ;;;; Key bindings
18582 ;; Outline functions from `outline-mode-prefix-map'
18583 ;; that can be remapped in Org:
18584 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18585 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18586 (define-key org-mode-map [remap outline-forward-same-level]
18587 'org-forward-heading-same-level)
18588 (define-key org-mode-map [remap outline-backward-same-level]
18589 'org-backward-heading-same-level)
18590 (define-key org-mode-map [remap show-branches]
18591 'org-kill-note-or-show-branches)
18592 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18593 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18594 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18596 ;; Outline functions from `outline-mode-prefix-map' that can not
18597 ;; be remapped in Org:
18599 ;; - the column "key binding" shows whether the Outline function is still
18600 ;; available in Org mode on the same key that it has been bound to in
18601 ;; Outline mode:
18602 ;; - "overridden": key used for a different functionality in Org mode
18603 ;; - else: key still bound to the same Outline function in Org mode
18605 ;; | Outline function | key binding | Org replacement |
18606 ;; |------------------------------------+-------------+-----------------------|
18607 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18608 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18609 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18610 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18611 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18612 ;; | `show-entry' | overridden | no replacement |
18613 ;; | `show-children' | `C-c C-i' | visibility cycling |
18614 ;; | `show-branches' | `C-c C-k' | still same function |
18615 ;; | `show-subtree' | overridden | visibility cycling |
18616 ;; | `show-all' | overridden | no replacement |
18617 ;; | `hide-subtree' | overridden | visibility cycling |
18618 ;; | `hide-body' | overridden | no replacement |
18619 ;; | `hide-entry' | overridden | visibility cycling |
18620 ;; | `hide-leaves' | overridden | no replacement |
18621 ;; | `hide-sublevels' | overridden | no replacement |
18622 ;; | `hide-other' | overridden | no replacement |
18624 ;; Make `C-c C-x' a prefix key
18625 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18627 ;; TAB key with modifiers
18628 (org-defkey org-mode-map "\C-i" 'org-cycle)
18629 (org-defkey org-mode-map [(tab)] 'org-cycle)
18630 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18631 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18632 ;; The following line is necessary under Suse GNU/Linux
18633 (unless (featurep 'xemacs)
18634 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18635 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18636 (define-key org-mode-map [backtab] 'org-shifttab)
18638 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18639 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18640 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18642 ;; Cursor keys with modifiers
18643 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18644 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18645 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18646 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18648 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18649 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18650 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18651 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18653 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18654 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18655 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18656 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18658 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18659 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18660 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18661 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18663 ;; Babel keys
18664 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18665 (mapc (lambda (pair)
18666 (define-key org-babel-map (car pair) (cdr pair)))
18667 org-babel-key-bindings)
18669 ;;; Extra keys for tty access.
18670 ;; We only set them when really needed because otherwise the
18671 ;; menus don't show the simple keys
18673 (when (or org-use-extra-keys
18674 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18675 (not window-system))
18676 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18677 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18678 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18679 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18680 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18681 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18682 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18683 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18684 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18685 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18686 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18687 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18688 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18689 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18690 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18691 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18692 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18693 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18694 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18695 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18696 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18697 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18698 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18699 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18700 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18701 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18702 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18703 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18705 ;; All the other keys
18707 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18708 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18709 (if (boundp 'narrow-map)
18710 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18711 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18712 (if (boundp 'narrow-map)
18713 (org-defkey narrow-map "b" 'org-narrow-to-block)
18714 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18715 (if (boundp 'narrow-map)
18716 (org-defkey narrow-map "e" 'org-narrow-to-element)
18717 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18718 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18719 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18720 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18721 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18722 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18723 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18724 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18725 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18726 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18727 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18728 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18729 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18730 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18731 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18732 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18733 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18734 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18735 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18736 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18737 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18738 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18739 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18740 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18741 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18742 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18743 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18744 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18745 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18746 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18747 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18748 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18749 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18750 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18751 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18752 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18753 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18754 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18755 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18756 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18757 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18758 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18759 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18760 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18761 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18762 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18763 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18764 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18765 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18766 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18767 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18768 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18769 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18770 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18771 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18772 (org-defkey org-mode-map "\C-c^" 'org-sort)
18773 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18774 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18775 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18776 (org-defkey org-mode-map "\C-m" 'org-return)
18777 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18778 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18779 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18780 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18781 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18782 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18783 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18784 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18785 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18786 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18787 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18788 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18789 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18790 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18791 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18792 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18793 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18794 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18795 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18796 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18797 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18798 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18799 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18801 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18802 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18803 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18805 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18806 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18807 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18808 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18809 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18810 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18811 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18812 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18813 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18814 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18815 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18816 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18817 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18818 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18819 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18820 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18821 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18822 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18823 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18824 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18825 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18826 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18827 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18829 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18830 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18831 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18832 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18833 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18835 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18837 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18839 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18840 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18842 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18845 (when (featurep 'xemacs)
18846 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18849 (defconst org-speed-commands-default
18851 ("Outline Navigation")
18852 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18853 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18854 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18855 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18856 ("F" . org-next-block)
18857 ("B" . org-previous-block)
18858 ("u" . (org-speed-move-safe 'outline-up-heading))
18859 ("j" . org-goto)
18860 ("g" . (org-refile t))
18861 ("Outline Visibility")
18862 ("c" . org-cycle)
18863 ("C" . org-shifttab)
18864 (" " . org-display-outline-path)
18865 ("=" . org-columns)
18866 ("Outline Structure Editing")
18867 ("U" . org-shiftmetaup)
18868 ("D" . org-shiftmetadown)
18869 ("r" . org-metaright)
18870 ("l" . org-metaleft)
18871 ("R" . org-shiftmetaright)
18872 ("L" . org-shiftmetaleft)
18873 ("i" . (progn (forward-char 1) (call-interactively
18874 'org-insert-heading-respect-content)))
18875 ("^" . org-sort)
18876 ("w" . org-refile)
18877 ("a" . org-archive-subtree-default-with-confirmation)
18878 ("@" . org-mark-subtree)
18879 ("#" . org-toggle-comment)
18880 ("Clock Commands")
18881 ("I" . org-clock-in)
18882 ("O" . org-clock-out)
18883 ("Meta Data Editing")
18884 ("t" . org-todo)
18885 ("," . (org-priority))
18886 ("0" . (org-priority ?\ ))
18887 ("1" . (org-priority ?A))
18888 ("2" . (org-priority ?B))
18889 ("3" . (org-priority ?C))
18890 (":" . org-set-tags-command)
18891 ("e" . org-set-effort)
18892 ("E" . org-inc-effort)
18893 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18894 (org-entry-put (point) "APPT_WARNTIME" m)))
18895 ("Agenda Views etc")
18896 ("v" . org-agenda)
18897 ("/" . org-sparse-tree)
18898 ("Misc")
18899 ("o" . org-open-at-point)
18900 ("?" . org-speed-command-help)
18901 ("<" . (org-agenda-set-restriction-lock 'subtree))
18902 (">" . (org-agenda-remove-restriction-lock))
18904 "The default speed commands.")
18906 (defun org-print-speed-command (e)
18907 (if (> (length (car e)) 1)
18908 (progn
18909 (princ "\n")
18910 (princ (car e))
18911 (princ "\n")
18912 (princ (make-string (length (car e)) ?-))
18913 (princ "\n"))
18914 (princ (car e))
18915 (princ " ")
18916 (if (symbolp (cdr e))
18917 (princ (symbol-name (cdr e)))
18918 (prin1 (cdr e)))
18919 (princ "\n")))
18921 (defun org-speed-command-help ()
18922 "Show the available speed commands."
18923 (interactive)
18924 (if (not org-use-speed-commands)
18925 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18926 (with-output-to-temp-buffer "*Help*"
18927 (princ "User-defined Speed commands\n===========================\n")
18928 (mapc 'org-print-speed-command org-speed-commands-user)
18929 (princ "\n")
18930 (princ "Built-in Speed commands\n=======================\n")
18931 (mapc 'org-print-speed-command org-speed-commands-default))
18932 (with-current-buffer "*Help*"
18933 (setq truncate-lines t))))
18935 (defun org-speed-move-safe (cmd)
18936 "Execute CMD, but make sure that the cursor always ends up in a headline.
18937 If not, return to the original position and throw an error."
18938 (interactive)
18939 (let ((pos (point)))
18940 (call-interactively cmd)
18941 (unless (and (bolp) (org-at-heading-p))
18942 (goto-char pos)
18943 (error "Boundary reached while executing %s" cmd))))
18945 (defvar org-self-insert-command-undo-counter 0)
18947 (defvar org-table-auto-blank-field) ; defined in org-table.el
18948 (defvar org-speed-command nil)
18950 (define-obsolete-function-alias
18951 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18953 (defun org-speed-command-activate (keys)
18954 "Hook for activating single-letter speed commands.
18955 `org-speed-commands-default' specifies a minimal command set.
18956 Use `org-speed-commands-user' for further customization."
18957 (when (or (and (bolp) (looking-at org-outline-regexp))
18958 (and (functionp org-use-speed-commands)
18959 (funcall org-use-speed-commands)))
18960 (cdr (assoc keys (append org-speed-commands-user
18961 org-speed-commands-default)))))
18963 (define-obsolete-function-alias
18964 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18966 (defun org-babel-speed-command-activate (keys)
18967 "Hook for activating single-letter code block commands."
18968 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18969 (cdr (assoc keys org-babel-key-bindings))))
18971 (defcustom org-speed-command-hook
18972 '(org-speed-command-default-hook org-babel-speed-command-hook)
18973 "Hook for activating speed commands at strategic locations.
18974 Hook functions are called in sequence until a valid handler is
18975 found.
18977 Each hook takes a single argument, a user-pressed command key
18978 which is also a `self-insert-command' from the global map.
18980 Within the hook, examine the cursor position and the command key
18981 and return nil or a valid handler as appropriate. Handler could
18982 be one of an interactive command, a function, or a form.
18984 Set `org-use-speed-commands' to non-nil value to enable this
18985 hook. The default setting is `org-speed-command-activate'."
18986 :group 'org-structure
18987 :version "24.1"
18988 :type 'hook)
18990 (defun org-self-insert-command (N)
18991 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18992 If the cursor is in a table looking at whitespace, the whitespace is
18993 overwritten, and the table is not marked as requiring realignment."
18994 (interactive "p")
18995 (org-check-before-invisible-edit 'insert)
18996 (cond
18997 ((and org-use-speed-commands
18998 (setq org-speed-command
18999 (run-hook-with-args-until-success
19000 'org-speed-command-hook (this-command-keys))))
19001 (cond
19002 ((commandp org-speed-command)
19003 (setq this-command org-speed-command)
19004 (call-interactively org-speed-command))
19005 ((functionp org-speed-command)
19006 (funcall org-speed-command))
19007 ((and org-speed-command (listp org-speed-command))
19008 (eval org-speed-command))
19009 (t (let (org-use-speed-commands)
19010 (call-interactively 'org-self-insert-command)))))
19011 ((and
19012 (org-table-p)
19013 (progn
19014 ;; check if we blank the field, and if that triggers align
19015 (and (featurep 'org-table) org-table-auto-blank-field
19016 (member last-command
19017 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19018 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19019 ;; got extra space, this field does not determine column width
19020 (let (org-table-may-need-update) (org-table-blank-field))
19021 ;; no extra space, this field may determine column width
19022 (org-table-blank-field)))
19024 (eq N 1)
19025 (looking-at "[^|\n]* |"))
19026 (let (org-table-may-need-update)
19027 (goto-char (1- (match-end 0)))
19028 (backward-delete-char 1)
19029 (goto-char (match-beginning 0))
19030 (self-insert-command N)))
19032 (setq org-table-may-need-update t)
19033 (self-insert-command N)
19034 (org-fix-tags-on-the-fly)
19035 (if org-self-insert-cluster-for-undo
19036 (if (not (eq last-command 'org-self-insert-command))
19037 (setq org-self-insert-command-undo-counter 1)
19038 (if (>= org-self-insert-command-undo-counter 20)
19039 (setq org-self-insert-command-undo-counter 1)
19040 (and (> org-self-insert-command-undo-counter 0)
19041 buffer-undo-list (listp buffer-undo-list)
19042 (not (cadr buffer-undo-list)) ; remove nil entry
19043 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19044 (setq org-self-insert-command-undo-counter
19045 (1+ org-self-insert-command-undo-counter))))))))
19047 (defun org-check-before-invisible-edit (kind)
19048 "Check is editing if kind KIND would be dangerous with invisible text around.
19049 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19050 ;; First, try to get out of here as quickly as possible, to reduce overhead
19051 (if (and org-catch-invisible-edits
19052 (or (not (boundp 'visible-mode)) (not visible-mode))
19053 (or (get-char-property (point) 'invisible)
19054 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19055 ;; OK, we need to take a closer look
19056 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19057 (invisible-before-point (if (bobp) nil (get-char-property
19058 (1- (point)) 'invisible)))
19059 (border-and-ok-direction
19061 ;; Check if we are acting predictably before invisible text
19062 (and invisible-at-point (not invisible-before-point)
19063 (memq kind '(insert delete-backward)))
19064 ;; Check if we are acting predictably after invisible text
19065 ;; This works not well, and I have turned it off. It seems
19066 ;; better to always show and stop after invisible text.
19067 ;; (and (not invisible-at-point) invisible-before-point
19068 ;; (memq kind '(insert delete)))
19070 (when (or (memq invisible-at-point '(outline org-hide-block t))
19071 (memq invisible-before-point '(outline org-hide-block t)))
19072 (if (eq org-catch-invisible-edits 'error)
19073 (error "Editing in invisible areas is prohibited - make visible first"))
19074 (if (and org-custom-properties-overlays
19075 (y-or-n-p "Display invisible properties in this buffer? "))
19076 (org-toggle-custom-properties-visibility)
19077 ;; Make the area visible
19078 (save-excursion
19079 (if invisible-before-point
19080 (goto-char (previous-single-char-property-change
19081 (point) 'invisible)))
19082 (org-cycle))
19083 (cond
19084 ((eq org-catch-invisible-edits 'show)
19085 ;; That's it, we do the edit after showing
19086 (message
19087 "Unfolding invisible region around point before editing")
19088 (sit-for 1))
19089 ((and (eq org-catch-invisible-edits 'smart)
19090 border-and-ok-direction)
19091 (message "Unfolding invisible region around point before editing"))
19093 ;; Don't do the edit, make the user repeat it in full visibility
19094 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19096 (defun org-fix-tags-on-the-fly ()
19097 (when (and (equal (char-after (point-at-bol)) ?*)
19098 (org-at-heading-p))
19099 (org-align-tags-here org-tags-column)))
19101 (defun org-delete-backward-char (N)
19102 "Like `delete-backward-char', insert whitespace at field end in tables.
19103 When deleting backwards, in tables this function will insert whitespace in
19104 front of the next \"|\" separator, to keep the table aligned. The table will
19105 still be marked for re-alignment if the field did fill the entire column,
19106 because, in this case the deletion might narrow the column."
19107 (interactive "p")
19108 (save-match-data
19109 (org-check-before-invisible-edit 'delete-backward)
19110 (if (and (org-table-p)
19111 (eq N 1)
19112 (string-match "|" (buffer-substring (point-at-bol) (point)))
19113 (looking-at ".*?|"))
19114 (let ((pos (point))
19115 (noalign (looking-at "[^|\n\r]* |"))
19116 (c org-table-may-need-update))
19117 (backward-delete-char N)
19118 (if (not overwrite-mode)
19119 (progn
19120 (skip-chars-forward "^|")
19121 (insert " ")
19122 (goto-char (1- pos))))
19123 ;; noalign: if there were two spaces at the end, this field
19124 ;; does not determine the width of the column.
19125 (if noalign (setq org-table-may-need-update c)))
19126 (backward-delete-char N)
19127 (org-fix-tags-on-the-fly))))
19129 (defun org-delete-char (N)
19130 "Like `delete-char', but insert whitespace at field end in tables.
19131 When deleting characters, in tables this function will insert whitespace in
19132 front of the next \"|\" separator, to keep the table aligned. The table will
19133 still be marked for re-alignment if the field did fill the entire column,
19134 because, in this case the deletion might narrow the column."
19135 (interactive "p")
19136 (save-match-data
19137 (org-check-before-invisible-edit 'delete)
19138 (if (and (org-table-p)
19139 (not (bolp))
19140 (not (= (char-after) ?|))
19141 (eq N 1))
19142 (if (looking-at ".*?|")
19143 (let ((pos (point))
19144 (noalign (looking-at "[^|\n\r]* |"))
19145 (c org-table-may-need-update))
19146 (replace-match
19147 (concat (substring (match-string 0) 1 -1) " |") nil t)
19148 (goto-char pos)
19149 ;; noalign: if there were two spaces at the end, this field
19150 ;; does not determine the width of the column.
19151 (if noalign (setq org-table-may-need-update c)))
19152 (delete-char N))
19153 (delete-char N)
19154 (org-fix-tags-on-the-fly))))
19156 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19157 (put 'org-self-insert-command 'delete-selection t)
19158 (put 'orgtbl-self-insert-command 'delete-selection t)
19159 (put 'org-delete-char 'delete-selection 'supersede)
19160 (put 'org-delete-backward-char 'delete-selection 'supersede)
19161 (put 'org-yank 'delete-selection 'yank)
19163 ;; Make `flyspell-mode' delay after some commands
19164 (put 'org-self-insert-command 'flyspell-delayed t)
19165 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19166 (put 'org-delete-char 'flyspell-delayed t)
19167 (put 'org-delete-backward-char 'flyspell-delayed t)
19169 ;; Make pabbrev-mode expand after org-mode commands
19170 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19171 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19173 ;; How to do this: Measure non-white length of current string
19174 ;; If equal to column width, we should realign.
19176 (defun org-remap (map &rest commands)
19177 "In MAP, remap the functions given in COMMANDS.
19178 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19179 (let (new old)
19180 (while commands
19181 (setq old (pop commands) new (pop commands))
19182 (if (fboundp 'command-remapping)
19183 (org-defkey map (vector 'remap old) new)
19184 (substitute-key-definition old new map global-map)))))
19186 (defun org-transpose-words ()
19187 "Transpose words for Org.
19188 This uses the `org-mode-transpose-word-syntax-table' syntax
19189 table, which interprets characters in `org-emphasis-alist' as
19190 word constituants."
19191 (interactive)
19192 (with-syntax-table org-mode-transpose-word-syntax-table
19193 (call-interactively 'transpose-words)))
19194 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19196 (when (eq org-enable-table-editor 'optimized)
19197 ;; If the user wants maximum table support, we need to hijack
19198 ;; some standard editing functions
19199 (org-remap org-mode-map
19200 'self-insert-command 'org-self-insert-command
19201 'delete-char 'org-delete-char
19202 'delete-backward-char 'org-delete-backward-char)
19203 (org-defkey org-mode-map "|" 'org-force-self-insert))
19205 (defvar org-ctrl-c-ctrl-c-hook nil
19206 "Hook for functions attaching themselves to `C-c C-c'.
19208 This can be used to add additional functionality to the C-c C-c
19209 key which executes context-dependent commands. This hook is run
19210 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19211 run after the last test.
19213 Each function will be called with no arguments. The function
19214 must check if the context is appropriate for it to act. If yes,
19215 it should do its thing and then return a non-nil value. If the
19216 context is wrong, just do nothing and return nil.")
19218 (defvar org-ctrl-c-ctrl-c-final-hook nil
19219 "Hook for functions attaching themselves to `C-c C-c'.
19221 This can be used to add additional functionality to the C-c C-c
19222 key which executes context-dependent commands. This hook is run
19223 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19224 before the first test.
19226 Each function will be called with no arguments. The function
19227 must check if the context is appropriate for it to act. If yes,
19228 it should do its thing and then return a non-nil value. If the
19229 context is wrong, just do nothing and return nil.")
19231 (defvar org-tab-first-hook nil
19232 "Hook for functions to attach themselves to TAB.
19233 See `org-ctrl-c-ctrl-c-hook' for more information.
19234 This hook runs as the first action when TAB is pressed, even before
19235 `org-cycle' messes around with the `outline-regexp' to cater for
19236 inline tasks and plain list item folding.
19237 If any function in this hook returns t, any other actions that
19238 would have been caused by TAB (such as table field motion or visibility
19239 cycling) will not occur.")
19241 (defvar org-tab-after-check-for-table-hook nil
19242 "Hook for functions to attach themselves to TAB.
19243 See `org-ctrl-c-ctrl-c-hook' for more information.
19244 This hook runs after it has been established that the cursor is not in a
19245 table, but before checking if the cursor is in a headline or if global cycling
19246 should be done.
19247 If any function in this hook returns t, not other actions like visibility
19248 cycling will be done.")
19250 (defvar org-tab-after-check-for-cycling-hook nil
19251 "Hook for functions to attach themselves to TAB.
19252 See `org-ctrl-c-ctrl-c-hook' for more information.
19253 This hook runs after it has been established that not table field motion and
19254 not visibility should be done because of current context. This is probably
19255 the place where a package like yasnippets can hook in.")
19257 (defvar org-tab-before-tab-emulation-hook nil
19258 "Hook for functions to attach themselves to TAB.
19259 See `org-ctrl-c-ctrl-c-hook' for more information.
19260 This hook runs after every other options for TAB have been exhausted, but
19261 before indentation and \t insertion takes place.")
19263 (defvar org-metaleft-hook nil
19264 "Hook for functions attaching themselves to `M-left'.
19265 See `org-ctrl-c-ctrl-c-hook' for more information.")
19266 (defvar org-metaright-hook nil
19267 "Hook for functions attaching themselves to `M-right'.
19268 See `org-ctrl-c-ctrl-c-hook' for more information.")
19269 (defvar org-metaup-hook nil
19270 "Hook for functions attaching themselves to `M-up'.
19271 See `org-ctrl-c-ctrl-c-hook' for more information.")
19272 (defvar org-metadown-hook nil
19273 "Hook for functions attaching themselves to `M-down'.
19274 See `org-ctrl-c-ctrl-c-hook' for more information.")
19275 (defvar org-shiftmetaleft-hook nil
19276 "Hook for functions attaching themselves to `M-S-left'.
19277 See `org-ctrl-c-ctrl-c-hook' for more information.")
19278 (defvar org-shiftmetaright-hook nil
19279 "Hook for functions attaching themselves to `M-S-right'.
19280 See `org-ctrl-c-ctrl-c-hook' for more information.")
19281 (defvar org-shiftmetaup-hook nil
19282 "Hook for functions attaching themselves to `M-S-up'.
19283 See `org-ctrl-c-ctrl-c-hook' for more information.")
19284 (defvar org-shiftmetadown-hook nil
19285 "Hook for functions attaching themselves to `M-S-down'.
19286 See `org-ctrl-c-ctrl-c-hook' for more information.")
19287 (defvar org-metareturn-hook nil
19288 "Hook for functions attaching themselves to `M-RET'.
19289 See `org-ctrl-c-ctrl-c-hook' for more information.")
19290 (defvar org-shiftup-hook nil
19291 "Hook for functions attaching themselves to `S-up'.
19292 See `org-ctrl-c-ctrl-c-hook' for more information.")
19293 (defvar org-shiftup-final-hook nil
19294 "Hook for functions attaching themselves to `S-up'.
19295 This one runs after all other options except shift-select have been excluded.
19296 See `org-ctrl-c-ctrl-c-hook' for more information.")
19297 (defvar org-shiftdown-hook nil
19298 "Hook for functions attaching themselves to `S-down'.
19299 See `org-ctrl-c-ctrl-c-hook' for more information.")
19300 (defvar org-shiftdown-final-hook nil
19301 "Hook for functions attaching themselves to `S-down'.
19302 This one runs after all other options except shift-select have been excluded.
19303 See `org-ctrl-c-ctrl-c-hook' for more information.")
19304 (defvar org-shiftleft-hook nil
19305 "Hook for functions attaching themselves to `S-left'.
19306 See `org-ctrl-c-ctrl-c-hook' for more information.")
19307 (defvar org-shiftleft-final-hook nil
19308 "Hook for functions attaching themselves to `S-left'.
19309 This one runs after all other options except shift-select have been excluded.
19310 See `org-ctrl-c-ctrl-c-hook' for more information.")
19311 (defvar org-shiftright-hook nil
19312 "Hook for functions attaching themselves to `S-right'.
19313 See `org-ctrl-c-ctrl-c-hook' for more information.")
19314 (defvar org-shiftright-final-hook nil
19315 "Hook for functions attaching themselves to `S-right'.
19316 This one runs after all other options except shift-select have been excluded.
19317 See `org-ctrl-c-ctrl-c-hook' for more information.")
19319 (defun org-modifier-cursor-error ()
19320 "Throw an error, a modified cursor command was applied in wrong context."
19321 (error "This command is active in special context like tables, headlines or items"))
19323 (defun org-shiftselect-error ()
19324 "Throw an error because Shift-Cursor command was applied in wrong context."
19325 (if (and (boundp 'shift-select-mode) shift-select-mode)
19326 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19327 (error "This command works only in special context like headlines or timestamps")))
19329 (defun org-call-for-shift-select (cmd)
19330 (let ((this-command-keys-shift-translated t))
19331 (call-interactively cmd)))
19333 (defun org-shifttab (&optional arg)
19334 "Global visibility cycling or move to previous table field.
19335 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19336 on context.
19337 See the individual commands for more information."
19338 (interactive "P")
19339 (cond
19340 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19341 ((integerp arg)
19342 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19343 (message "Content view to level: %d" arg)
19344 (org-content (prefix-numeric-value arg2))
19345 (setq org-cycle-global-status 'overview)))
19346 (t (call-interactively 'org-global-cycle))))
19348 (defun org-shiftmetaleft ()
19349 "Promote subtree or delete table column.
19350 Calls `org-promote-subtree', `org-outdent-item-tree', or
19351 `org-table-delete-column', depending on context. See the
19352 individual commands for more information."
19353 (interactive)
19354 (cond
19355 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19356 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19357 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19358 ((if (not (org-region-active-p)) (org-at-item-p)
19359 (save-excursion (goto-char (region-beginning))
19360 (org-at-item-p)))
19361 (call-interactively 'org-outdent-item-tree))
19362 (t (org-modifier-cursor-error))))
19364 (defun org-shiftmetaright ()
19365 "Demote subtree or insert table column.
19366 Calls `org-demote-subtree', `org-indent-item-tree', or
19367 `org-table-insert-column', depending on context. See the
19368 individual commands for more information."
19369 (interactive)
19370 (cond
19371 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19372 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19373 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19374 ((if (not (org-region-active-p)) (org-at-item-p)
19375 (save-excursion (goto-char (region-beginning))
19376 (org-at-item-p)))
19377 (call-interactively 'org-indent-item-tree))
19378 (t (org-modifier-cursor-error))))
19380 (defun org-shiftmetaup (&optional arg)
19381 "Move subtree up or kill table row.
19382 Calls `org-move-subtree-up' or `org-table-kill-row' or
19383 `org-move-item-up' or `org-timestamp-up', depending on context.
19384 See the individual commands for more information."
19385 (interactive "P")
19386 (cond
19387 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19388 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19389 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19390 ((org-at-item-p) (call-interactively 'org-move-item-up))
19391 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19392 (call-interactively 'org-timestamp-up)))
19393 (t (call-interactively 'org-drag-line-backward))))
19395 (defun org-shiftmetadown (&optional arg)
19396 "Move subtree down or insert table row.
19397 Calls `org-move-subtree-down' or `org-table-insert-row' or
19398 `org-move-item-down' or `org-timestamp-up', depending on context.
19399 See the individual commands for more information."
19400 (interactive "P")
19401 (cond
19402 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19403 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19404 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19405 ((org-at-item-p) (call-interactively 'org-move-item-down))
19406 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19407 (call-interactively 'org-timestamp-down)))
19408 (t (call-interactively 'org-drag-line-forward))))
19410 (defsubst org-hidden-tree-error ()
19411 (error
19412 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19414 (defun org-metaleft (&optional arg)
19415 "Promote heading or move table column to left.
19416 Calls `org-do-promote' or `org-table-move-column', depending on context.
19417 With no specific context, calls the Emacs default `backward-word'.
19418 See the individual commands for more information."
19419 (interactive "P")
19420 (cond
19421 ((run-hook-with-args-until-success 'org-metaleft-hook))
19422 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19423 ((org-with-limited-levels
19424 (or (org-at-heading-p)
19425 (and (org-region-active-p)
19426 (save-excursion
19427 (goto-char (region-beginning))
19428 (org-at-heading-p)))))
19429 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19430 (call-interactively 'org-do-promote))
19431 ;; At an inline task.
19432 ((org-at-heading-p)
19433 (call-interactively 'org-inlinetask-promote))
19434 ((or (org-at-item-p)
19435 (and (org-region-active-p)
19436 (save-excursion
19437 (goto-char (region-beginning))
19438 (org-at-item-p))))
19439 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19440 (call-interactively 'org-outdent-item))
19441 (t (call-interactively 'backward-word))))
19443 (defun org-metaright (&optional arg)
19444 "Demote a subtree, a list item or move table column to right.
19445 In front of a drawer or a block keyword, indent it correctly.
19446 With no specific context, calls the Emacs default `forward-word'.
19447 See the individual commands for more information."
19448 (interactive "P")
19449 (cond
19450 ((run-hook-with-args-until-success 'org-metaright-hook))
19451 ((org-at-table-p) (call-interactively 'org-table-move-column))
19452 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19453 ((org-at-block-p) (call-interactively 'org-indent-block))
19454 ((org-with-limited-levels
19455 (or (org-at-heading-p)
19456 (and (org-region-active-p)
19457 (save-excursion
19458 (goto-char (region-beginning))
19459 (org-at-heading-p)))))
19460 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19461 (call-interactively 'org-do-demote))
19462 ;; At an inline task.
19463 ((org-at-heading-p)
19464 (call-interactively 'org-inlinetask-demote))
19465 ((or (org-at-item-p)
19466 (and (org-region-active-p)
19467 (save-excursion
19468 (goto-char (region-beginning))
19469 (org-at-item-p))))
19470 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19471 (call-interactively 'org-indent-item))
19472 (t (call-interactively 'forward-word))))
19474 (defun org-check-for-hidden (what)
19475 "Check if there are hidden headlines/items in the current visual line.
19476 WHAT can be either `headlines' or `items'. If the current line is
19477 an outline or item heading and it has a folded subtree below it,
19478 this function returns t, nil otherwise."
19479 (let ((re (cond
19480 ((eq what 'headlines) org-outline-regexp-bol)
19481 ((eq what 'items) (org-item-beginning-re))
19482 (t (error "This should not happen"))))
19483 beg end)
19484 (save-excursion
19485 (catch 'exit
19486 (unless (org-region-active-p)
19487 (setq beg (point-at-bol))
19488 (beginning-of-line 2)
19489 (while (and (not (eobp)) ;; this is like `next-line'
19490 (get-char-property (1- (point)) 'invisible))
19491 (beginning-of-line 2))
19492 (setq end (point))
19493 (goto-char beg)
19494 (goto-char (point-at-eol))
19495 (setq end (max end (point)))
19496 (while (re-search-forward re end t)
19497 (if (get-char-property (match-beginning 0) 'invisible)
19498 (throw 'exit t))))
19499 nil))))
19501 (defun org-metaup (&optional arg)
19502 "Move subtree up or move table row up.
19503 Calls `org-move-subtree-up' or `org-table-move-row' or
19504 `org-move-item-up', depending on context. See the individual commands
19505 for more information."
19506 (interactive "P")
19507 (cond
19508 ((run-hook-with-args-until-success 'org-metaup-hook))
19509 ((org-region-active-p)
19510 (let* ((a (min (region-beginning) (region-end)))
19511 (b (1- (max (region-beginning) (region-end))))
19512 (c (save-excursion (goto-char a)
19513 (move-beginning-of-line 0)))
19514 (d (save-excursion (goto-char a)
19515 (move-end-of-line 0) (point))))
19516 (transpose-regions a b c d)
19517 (goto-char c)))
19518 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19519 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19520 ((org-at-item-p) (call-interactively 'org-move-item-up))
19521 (t (org-drag-element-backward))))
19523 (defun org-metadown (&optional arg)
19524 "Move subtree down or move table row down.
19525 Calls `org-move-subtree-down' or `org-table-move-row' or
19526 `org-move-item-down', depending on context. See the individual
19527 commands for more information."
19528 (interactive "P")
19529 (cond
19530 ((run-hook-with-args-until-success 'org-metadown-hook))
19531 ((org-region-active-p)
19532 (let* ((a (min (region-beginning) (region-end)))
19533 (b (max (region-beginning) (region-end)))
19534 (c (save-excursion (goto-char b)
19535 (move-beginning-of-line 1)))
19536 (d (save-excursion (goto-char b)
19537 (move-end-of-line 1) (1+ (point)))))
19538 (transpose-regions a b c d)
19539 (goto-char d)))
19540 ((org-at-table-p) (call-interactively 'org-table-move-row))
19541 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19542 ((org-at-item-p) (call-interactively 'org-move-item-down))
19543 (t (org-drag-element-forward))))
19545 (defun org-shiftup (&optional arg)
19546 "Increase item in timestamp or increase priority of current headline.
19547 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19548 depending on context. See the individual commands for more information."
19549 (interactive "P")
19550 (cond
19551 ((run-hook-with-args-until-success 'org-shiftup-hook))
19552 ((and org-support-shift-select (org-region-active-p))
19553 (org-call-for-shift-select 'previous-line))
19554 ((org-at-timestamp-p t)
19555 (call-interactively (if org-edit-timestamp-down-means-later
19556 'org-timestamp-down 'org-timestamp-up)))
19557 ((and (not (eq org-support-shift-select 'always))
19558 org-enable-priority-commands
19559 (org-at-heading-p))
19560 (call-interactively 'org-priority-up))
19561 ((and (not org-support-shift-select) (org-at-item-p))
19562 (call-interactively 'org-previous-item))
19563 ((org-clocktable-try-shift 'up arg))
19564 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19565 (org-support-shift-select
19566 (org-call-for-shift-select 'previous-line))
19567 (t (org-shiftselect-error))))
19569 (defun org-shiftdown (&optional arg)
19570 "Decrease item in timestamp or decrease priority of current headline.
19571 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19572 depending on context. See the individual commands for more information."
19573 (interactive "P")
19574 (cond
19575 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19576 ((and org-support-shift-select (org-region-active-p))
19577 (org-call-for-shift-select 'next-line))
19578 ((org-at-timestamp-p t)
19579 (call-interactively (if org-edit-timestamp-down-means-later
19580 'org-timestamp-up 'org-timestamp-down)))
19581 ((and (not (eq org-support-shift-select 'always))
19582 org-enable-priority-commands
19583 (org-at-heading-p))
19584 (call-interactively 'org-priority-down))
19585 ((and (not org-support-shift-select) (org-at-item-p))
19586 (call-interactively 'org-next-item))
19587 ((org-clocktable-try-shift 'down arg))
19588 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19589 (org-support-shift-select
19590 (org-call-for-shift-select 'next-line))
19591 (t (org-shiftselect-error))))
19593 (defun org-shiftright (&optional arg)
19594 "Cycle the thing at point or in the current line, depending on context.
19595 Depending on context, this does one of the following:
19597 - switch a timestamp at point one day into the future
19598 - on a headline, switch to the next TODO keyword.
19599 - on an item, switch entire list to the next bullet type
19600 - on a property line, switch to the next allowed value
19601 - on a clocktable definition line, move time block into the future"
19602 (interactive "P")
19603 (cond
19604 ((run-hook-with-args-until-success 'org-shiftright-hook))
19605 ((and org-support-shift-select (org-region-active-p))
19606 (org-call-for-shift-select 'forward-char))
19607 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19608 ((and (not (eq org-support-shift-select 'always))
19609 (org-at-heading-p))
19610 (let ((org-inhibit-logging
19611 (not org-treat-S-cursor-todo-selection-as-state-change))
19612 (org-inhibit-blocking
19613 (not org-treat-S-cursor-todo-selection-as-state-change)))
19614 (org-call-with-arg 'org-todo 'right)))
19615 ((or (and org-support-shift-select
19616 (not (eq org-support-shift-select 'always))
19617 (org-at-item-bullet-p))
19618 (and (not org-support-shift-select) (org-at-item-p)))
19619 (org-call-with-arg 'org-cycle-list-bullet nil))
19620 ((and (not (eq org-support-shift-select 'always))
19621 (org-at-property-p))
19622 (call-interactively 'org-property-next-allowed-value))
19623 ((org-clocktable-try-shift 'right arg))
19624 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19625 (org-support-shift-select
19626 (org-call-for-shift-select 'forward-char))
19627 (t (org-shiftselect-error))))
19629 (defun org-shiftleft (&optional arg)
19630 "Cycle the thing at point or in the current line, depending on context.
19631 Depending on context, this does one of the following:
19633 - switch a timestamp at point one day into the past
19634 - on a headline, switch to the previous TODO keyword.
19635 - on an item, switch entire list to the previous bullet type
19636 - on a property line, switch to the previous allowed value
19637 - on a clocktable definition line, move time block into the past"
19638 (interactive "P")
19639 (cond
19640 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19641 ((and org-support-shift-select (org-region-active-p))
19642 (org-call-for-shift-select 'backward-char))
19643 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19644 ((and (not (eq org-support-shift-select 'always))
19645 (org-at-heading-p))
19646 (let ((org-inhibit-logging
19647 (not org-treat-S-cursor-todo-selection-as-state-change))
19648 (org-inhibit-blocking
19649 (not org-treat-S-cursor-todo-selection-as-state-change)))
19650 (org-call-with-arg 'org-todo 'left)))
19651 ((or (and org-support-shift-select
19652 (not (eq org-support-shift-select 'always))
19653 (org-at-item-bullet-p))
19654 (and (not org-support-shift-select) (org-at-item-p)))
19655 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19656 ((and (not (eq org-support-shift-select 'always))
19657 (org-at-property-p))
19658 (call-interactively 'org-property-previous-allowed-value))
19659 ((org-clocktable-try-shift 'left arg))
19660 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19661 (org-support-shift-select
19662 (org-call-for-shift-select 'backward-char))
19663 (t (org-shiftselect-error))))
19665 (defun org-shiftcontrolright ()
19666 "Switch to next TODO set."
19667 (interactive)
19668 (cond
19669 ((and org-support-shift-select (org-region-active-p))
19670 (org-call-for-shift-select 'forward-word))
19671 ((and (not (eq org-support-shift-select 'always))
19672 (org-at-heading-p))
19673 (org-call-with-arg 'org-todo 'nextset))
19674 (org-support-shift-select
19675 (org-call-for-shift-select 'forward-word))
19676 (t (org-shiftselect-error))))
19678 (defun org-shiftcontrolleft ()
19679 "Switch to previous TODO set."
19680 (interactive)
19681 (cond
19682 ((and org-support-shift-select (org-region-active-p))
19683 (org-call-for-shift-select 'backward-word))
19684 ((and (not (eq org-support-shift-select 'always))
19685 (org-at-heading-p))
19686 (org-call-with-arg 'org-todo 'previousset))
19687 (org-support-shift-select
19688 (org-call-for-shift-select 'backward-word))
19689 (t (org-shiftselect-error))))
19691 (defun org-shiftcontrolup (&optional n)
19692 "Change timestamps synchronously up in CLOCK log lines.
19693 Optional argument N tells to change by that many units."
19694 (interactive "P")
19695 (cond ((and (not org-support-shift-select)
19696 (org-at-clock-log-p)
19697 (org-at-timestamp-p t))
19698 (org-clock-timestamps-up n))
19699 (t (org-shiftselect-error))))
19701 (defun org-shiftcontroldown (&optional n)
19702 "Change timestamps synchronously down in CLOCK log lines.
19703 Optional argument N tells to change by that many units."
19704 (interactive "P")
19705 (cond ((and (not org-support-shift-select)
19706 (org-at-clock-log-p)
19707 (org-at-timestamp-p t))
19708 (org-clock-timestamps-down n))
19709 (t (org-shiftselect-error))))
19711 (defun org-ctrl-c-ret ()
19712 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19713 (interactive)
19714 (cond
19715 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19716 (t (call-interactively 'org-insert-heading))))
19718 (defun org-find-visible ()
19719 (let ((s (point)))
19720 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19721 (get-char-property s 'invisible)))
19723 (defun org-find-invisible ()
19724 (let ((s (point)))
19725 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19726 (not (get-char-property s 'invisible))))
19729 (defun org-copy-visible (beg end)
19730 "Copy the visible parts of the region."
19731 (interactive "r")
19732 (let (snippets s)
19733 (save-excursion
19734 (save-restriction
19735 (narrow-to-region beg end)
19736 (setq s (goto-char (point-min)))
19737 (while (not (= (point) (point-max)))
19738 (goto-char (org-find-invisible))
19739 (push (buffer-substring s (point)) snippets)
19740 (setq s (goto-char (org-find-visible))))))
19741 (kill-new (apply 'concat (nreverse snippets)))))
19743 (defun org-copy-special ()
19744 "Copy region in table or copy current subtree.
19745 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19746 See the individual commands for more information."
19747 (interactive)
19748 (call-interactively
19749 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19751 (defun org-cut-special ()
19752 "Cut region in table or cut current subtree.
19753 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19754 See the individual commands for more information."
19755 (interactive)
19756 (call-interactively
19757 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19759 (defun org-paste-special (arg)
19760 "Paste rectangular region into table, or past subtree relative to level.
19761 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19762 See the individual commands for more information."
19763 (interactive "P")
19764 (if (org-at-table-p)
19765 (org-table-paste-rectangle)
19766 (org-paste-subtree arg)))
19768 (defsubst org-in-fixed-width-region-p ()
19769 "Is point in a fixed-width region?"
19770 (save-match-data
19771 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19773 (defun org-edit-special (&optional arg)
19774 "Call a special editor for the element at point.
19775 When at a table, call the formula editor with `org-table-edit-formulas'.
19776 When in a source code block, call `org-edit-src-code'.
19777 When in a fixed-width region, call `org-edit-fixed-width-region'.
19778 When at an #+INCLUDE keyword, visit the included file.
19779 On a link, call `ffap' to visit the link at point.
19780 Otherwise, return a user error."
19781 (interactive)
19782 (let ((element (org-element-at-point)))
19783 (assert (not buffer-read-only) nil
19784 "Buffer is read-only: %s" (buffer-name))
19785 (case (org-element-type element)
19786 (src-block
19787 (if (not arg) (org-edit-src-code)
19788 (let* ((info (org-babel-get-src-block-info))
19789 (lang (nth 0 info))
19790 (params (nth 2 info))
19791 (session (cdr (assq :session params))))
19792 (if (not session) (org-edit-src-code)
19793 ;; At a src-block with a session and function called with
19794 ;; an ARG: switch to the buffer related to the inferior
19795 ;; process.
19796 (funcall (intern (concat "org-babel-prep-session:" lang))
19797 session params)))))
19798 (keyword
19799 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19800 (find-file
19801 (org-remove-double-quotes
19802 (car (org-split-string (org-element-property :value element)))))
19803 (user-error "No special environment to edit here")))
19804 (table
19805 (if (eq (org-element-property :type element) 'table.el)
19806 (org-edit-src-code)
19807 (call-interactively 'org-table-edit-formulas)))
19808 ;; Only Org tables contain `table-row' type elements.
19809 (table-row (call-interactively 'org-table-edit-formulas))
19810 ((example-block export-block) (org-edit-src-code))
19811 (fixed-width (org-edit-fixed-width-region))
19812 (otherwise
19813 ;; No notable element at point. Though, we may be at a link,
19814 ;; which is an object. Thus, scan deeper.
19815 (if (eq (org-element-type (org-element-context element)) 'link)
19816 (call-interactively 'ffap)
19817 (user-error "No special environment to edit here"))))))
19819 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19820 (defun org-ctrl-c-ctrl-c (&optional arg)
19821 "Set tags in headline, or update according to changed information at point.
19823 This command does many different things, depending on context:
19825 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19826 this is what we do.
19828 - If the cursor is on a statistics cookie, update it.
19830 - If the cursor is in a headline, prompt for tags and insert them
19831 into the current line, aligned to `org-tags-column'. When called
19832 with prefix arg, realign all tags in the current buffer.
19834 - If the cursor is in one of the special #+KEYWORD lines, this
19835 triggers scanning the buffer for these lines and updating the
19836 information.
19838 - If the cursor is inside a table, realign the table. This command
19839 works even if the automatic table editor has been turned off.
19841 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19842 the entire table.
19844 - If the cursor is at a footnote reference or definition, jump to
19845 the corresponding definition or references, respectively.
19847 - If the cursor is a the beginning of a dynamic block, update it.
19849 - If the current buffer is a capture buffer, close note and file it.
19851 - If the cursor is on a <<<target>>>, update radio targets and
19852 corresponding links in this buffer.
19854 - If the cursor is on a numbered item in a plain list, renumber the
19855 ordered list.
19857 - If the cursor is on a checkbox, toggle it.
19859 - If the cursor is on a code block, evaluate it. The variable
19860 `org-confirm-babel-evaluate' can be used to control prompting
19861 before code block evaluation, by default every code block
19862 evaluation requires confirmation. Code block evaluation can be
19863 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19864 (interactive "P")
19865 (cond
19866 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19867 org-occur-highlights
19868 org-latex-fragment-image-overlays)
19869 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19870 (org-remove-occur-highlights)
19871 (org-remove-latex-fragment-image-overlays)
19872 (message "Temporary highlights/overlays removed from current buffer"))
19873 ((and (local-variable-p 'org-finish-function (current-buffer))
19874 (fboundp org-finish-function))
19875 (funcall org-finish-function))
19876 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19878 (let* ((context (org-element-context)) (type (org-element-type context)))
19879 ;; Test if point is within a blank line.
19880 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19881 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19882 (user-error "C-c C-c can do nothing useful at this location"))
19883 ;; For convenience: at the first line of a paragraph on the
19884 ;; same line as an item, apply function on that item instead.
19885 (when (eq type 'paragraph)
19886 (let ((parent (org-element-property :parent context)))
19887 (when (and (eq (org-element-type parent) 'item)
19888 (= (point-at-bol) (org-element-property :begin parent)))
19889 (setq context parent type 'item))))
19890 ;; Act according to type of element or object at point.
19891 (case type
19892 (clock (org-clock-update-time-maybe))
19893 (dynamic-block
19894 (save-excursion
19895 (goto-char (org-element-property :post-affiliated context))
19896 (org-update-dblock)))
19897 (footnote-definition
19898 (goto-char (org-element-property :post-affiliated context))
19899 (call-interactively 'org-footnote-action))
19900 (footnote-reference (call-interactively 'org-footnote-action))
19901 ((headline inlinetask)
19902 (save-excursion (goto-char (org-element-property :begin context))
19903 (call-interactively 'org-set-tags)))
19904 (item
19905 ;; At an item: a double C-u set checkbox to "[-]"
19906 ;; unconditionally, whereas a single one will toggle its
19907 ;; presence. Without an universal argument, if the item
19908 ;; has a checkbox, toggle it. Otherwise repair the list.
19909 (let* ((box (org-element-property :checkbox context))
19910 (struct (org-element-property :structure context))
19911 (old-struct (copy-tree struct))
19912 (parents (org-list-parents-alist struct))
19913 (prevs (org-list-prevs-alist struct))
19914 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19915 (org-list-set-checkbox
19916 (org-element-property :begin context) struct
19917 (cond ((equal arg '(16)) "[-]")
19918 ((and (not box) (equal arg '(4))) "[ ]")
19919 ((or (not box) (equal arg '(4))) nil)
19920 ((eq box 'on) "[ ]")
19921 (t "[X]")))
19922 ;; Mimic `org-list-write-struct' but with grabbing
19923 ;; a return value from `org-list-struct-fix-box'.
19924 (org-list-struct-fix-ind struct parents 2)
19925 (org-list-struct-fix-item-end struct)
19926 (org-list-struct-fix-bul struct prevs)
19927 (org-list-struct-fix-ind struct parents)
19928 (let ((block-item
19929 (org-list-struct-fix-box struct parents prevs orderedp)))
19930 (if (and box (equal struct old-struct))
19931 (if (equal arg '(16))
19932 (message "Checkboxes already reset")
19933 (user-error "Cannot toggle this checkbox: %s"
19934 (if (eq box 'on)
19935 "all subitems checked"
19936 "unchecked subitems")))
19937 (org-list-struct-apply-struct struct old-struct)
19938 (org-update-checkbox-count-maybe))
19939 (when block-item
19940 (message "Checkboxes were removed due to empty box at line %d"
19941 (org-current-line block-item))))))
19942 (keyword
19943 (let ((org-inhibit-startup-visibility-stuff t)
19944 (org-startup-align-all-tables nil))
19945 (when (boundp 'org-table-coordinate-overlays)
19946 (mapc 'delete-overlay org-table-coordinate-overlays)
19947 (setq org-table-coordinate-overlays nil))
19948 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19949 (message "Local setup has been refreshed"))
19950 (plain-list
19951 ;; At a plain list, with a double C-u argument, set
19952 ;; checkboxes of each item to "[-]", whereas a single one
19953 ;; will toggle their presence according to the state of the
19954 ;; first item in the list. Without an argument, repair the
19955 ;; list.
19956 (let* ((begin (org-element-property :contents-begin context))
19957 (struct (org-element-property :structure context))
19958 (old-struct (copy-tree struct))
19959 (first-box (save-excursion
19960 (goto-char begin)
19961 (looking-at org-list-full-item-re)
19962 (match-string-no-properties 3)))
19963 (new-box (cond ((equal arg '(16)) "[-]")
19964 ((equal arg '(4)) (unless first-box "[ ]"))
19965 ((equal first-box "[X]") "[ ]")
19966 (t "[X]"))))
19967 (cond
19968 (arg
19969 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19970 (org-list-get-all-items
19971 begin struct (org-list-prevs-alist struct))))
19972 ((and first-box (eq (point) begin))
19973 ;; For convenience, when point is at bol on the first
19974 ;; item of the list and no argument is provided, simply
19975 ;; toggle checkbox of that item, if any.
19976 (org-list-set-checkbox begin struct new-box)))
19977 (org-list-write-struct
19978 struct (org-list-parents-alist struct) old-struct)
19979 (org-update-checkbox-count-maybe)
19980 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19981 ((property-drawer node-property)
19982 (call-interactively 'org-property-action))
19983 ((radio-target target)
19984 (call-interactively 'org-update-radio-target-regexp))
19985 (statistics-cookie
19986 (call-interactively 'org-update-statistics-cookies))
19987 ((table table-cell table-row)
19988 ;; At a table, recalculate every field and align it. Also
19989 ;; send the table if necessary. If the table has
19990 ;; a `table.el' type, just give up. At a table row or
19991 ;; cell, maybe recalculate line but always align table.
19992 (if (eq (org-element-property :type context) 'table.el)
19993 (message "Use C-c ' to edit table.el tables")
19994 (let ((org-enable-table-editor t))
19995 (if (or (eq type 'table)
19996 ;; Check if point is at a TBLFM line.
19997 (and (eq type 'table-row)
19998 (= (point) (org-element-property :end context))))
19999 (save-excursion
20000 (goto-char (org-element-property :contents-begin context))
20001 (org-call-with-arg 'org-table-recalculate (or arg t))
20002 (orgtbl-send-table 'maybe))
20003 (org-table-maybe-eval-formula)
20004 (cond (arg (call-interactively 'org-table-recalculate))
20005 ((org-table-maybe-recalculate-line))
20006 (t (org-table-align)))))))
20007 (timestamp (org-timestamp-change 0 'day))
20008 (otherwise
20009 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20010 (user-error
20011 "C-c C-c can do nothing useful at this location")))))))))
20013 (defun org-mode-restart ()
20014 "Restart Org-mode, to scan again for special lines.
20015 Also updates the keyword regular expressions."
20016 (interactive)
20017 (org-mode)
20018 (message "Org-mode restarted"))
20020 (defun org-kill-note-or-show-branches ()
20021 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20022 (interactive)
20023 (if (not org-finish-function)
20024 (progn
20025 (hide-subtree)
20026 (call-interactively 'show-branches))
20027 (let ((org-note-abort t))
20028 (funcall org-finish-function))))
20030 (defun org-return (&optional indent)
20031 "Goto next table row or insert a newline.
20032 Calls `org-table-next-row' or `newline', depending on context.
20033 See the individual commands for more information."
20034 (interactive)
20035 (let (org-ts-what)
20036 (cond
20037 ((or (bobp) (org-in-src-block-p))
20038 (if indent (newline-and-indent) (newline)))
20039 ((org-at-table-p)
20040 (org-table-justify-field-maybe)
20041 (call-interactively 'org-table-next-row))
20042 ;; when `newline-and-indent' is called within a list, make sure
20043 ;; text moved stays inside the item.
20044 ((and (org-in-item-p) indent)
20045 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20046 (progn
20047 (save-match-data (newline))
20048 (org-indent-line-to (length (match-string 0))))
20049 (let ((ind (org-get-indentation)))
20050 (newline)
20051 (if (org-looking-back org-list-end-re)
20052 (org-indent-line)
20053 (org-indent-line-to ind)))))
20054 ((and org-return-follows-link
20055 (org-at-timestamp-p t)
20056 (not (eq org-ts-what 'after)))
20057 (org-follow-timestamp-link))
20058 ((and org-return-follows-link
20059 (let ((tprop (get-text-property (point) 'face)))
20060 (or (eq tprop 'org-link)
20061 (and (listp tprop) (memq 'org-link tprop)))))
20062 (call-interactively 'org-open-at-point))
20063 ((and (org-at-heading-p)
20064 (looking-at
20065 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20066 (org-show-entry)
20067 (end-of-line 1)
20068 (newline))
20069 (t (if indent (newline-and-indent) (newline))))))
20071 (defun org-return-indent ()
20072 "Goto next table row or insert a newline and indent.
20073 Calls `org-table-next-row' or `newline-and-indent', depending on
20074 context. See the individual commands for more information."
20075 (interactive)
20076 (org-return t))
20078 (defun org-ctrl-c-star ()
20079 "Compute table, or change heading status of lines.
20080 Calls `org-table-recalculate' or `org-toggle-heading',
20081 depending on context."
20082 (interactive)
20083 (cond
20084 ((org-at-table-p)
20085 (call-interactively 'org-table-recalculate))
20087 ;; Convert all lines in region to list items
20088 (call-interactively 'org-toggle-heading))))
20090 (defun org-ctrl-c-minus ()
20091 "Insert separator line in table or modify bullet status of line.
20092 Also turns a plain line or a region of lines into list items.
20093 Calls `org-table-insert-hline', `org-toggle-item', or
20094 `org-cycle-list-bullet', depending on context."
20095 (interactive)
20096 (cond
20097 ((org-at-table-p)
20098 (call-interactively 'org-table-insert-hline))
20099 ((org-region-active-p)
20100 (call-interactively 'org-toggle-item))
20101 ((org-in-item-p)
20102 (call-interactively 'org-cycle-list-bullet))
20104 (call-interactively 'org-toggle-item))))
20106 (defun org-toggle-item (arg)
20107 "Convert headings or normal lines to items, items to normal lines.
20108 If there is no active region, only the current line is considered.
20110 If the first non blank line in the region is a headline, convert
20111 all headlines to items, shifting text accordingly.
20113 If it is an item, convert all items to normal lines.
20115 If it is normal text, change region into a list of items.
20116 With a prefix argument ARG, change the region in a single item."
20117 (interactive "P")
20118 (let ((shift-text
20119 (function
20120 ;; Shift text in current section to IND, from point to END.
20121 ;; The function leaves point to END line.
20122 (lambda (ind end)
20123 (let ((min-i 1000) (end (copy-marker end)))
20124 ;; First determine the minimum indentation (MIN-I) of
20125 ;; the text.
20126 (save-excursion
20127 (catch 'exit
20128 (while (< (point) end)
20129 (let ((i (org-get-indentation)))
20130 (cond
20131 ;; Skip blank lines and inline tasks.
20132 ((looking-at "^[ \t]*$"))
20133 ((looking-at org-outline-regexp-bol))
20134 ;; We can't find less than 0 indentation.
20135 ((zerop i) (throw 'exit (setq min-i 0)))
20136 ((< i min-i) (setq min-i i))))
20137 (forward-line))))
20138 ;; Then indent each line so that a line indented to
20139 ;; MIN-I becomes indented to IND. Ignore blank lines
20140 ;; and inline tasks in the process.
20141 (let ((delta (- ind min-i)))
20142 (while (< (point) end)
20143 (unless (or (looking-at "^[ \t]*$")
20144 (looking-at org-outline-regexp-bol))
20145 (org-indent-line-to (+ (org-get-indentation) delta)))
20146 (forward-line)))))))
20147 (skip-blanks
20148 (function
20149 ;; Return beginning of first non-blank line, starting from
20150 ;; line at POS.
20151 (lambda (pos)
20152 (save-excursion
20153 (goto-char pos)
20154 (skip-chars-forward " \r\t\n")
20155 (point-at-bol)))))
20156 beg end)
20157 ;; Determine boundaries of changes.
20158 (if (org-region-active-p)
20159 (setq beg (funcall skip-blanks (region-beginning))
20160 end (copy-marker (region-end)))
20161 (setq beg (funcall skip-blanks (point-at-bol))
20162 end (copy-marker (point-at-eol))))
20163 ;; Depending on the starting line, choose an action on the text
20164 ;; between BEG and END.
20165 (org-with-limited-levels
20166 (save-excursion
20167 (goto-char beg)
20168 (cond
20169 ;; Case 1. Start at an item: de-itemize. Note that it only
20170 ;; happens when a region is active: `org-ctrl-c-minus'
20171 ;; would call `org-cycle-list-bullet' otherwise.
20172 ((org-at-item-p)
20173 (while (< (point) end)
20174 (when (org-at-item-p)
20175 (skip-chars-forward " \t")
20176 (delete-region (point) (match-end 0)))
20177 (forward-line)))
20178 ;; Case 2. Start at an heading: convert to items.
20179 ((org-at-heading-p)
20180 (let* ((bul (org-list-bullet-string "-"))
20181 (bul-len (length bul))
20182 ;; Indentation of the first heading. It should be
20183 ;; relative to the indentation of its parent, if any.
20184 (start-ind (save-excursion
20185 (cond
20186 ((not org-adapt-indentation) 0)
20187 ((not (outline-previous-heading)) 0)
20188 (t (length (match-string 0))))))
20189 ;; Level of first heading. Further headings will be
20190 ;; compared to it to determine hierarchy in the list.
20191 (ref-level (org-reduced-level (org-outline-level))))
20192 (while (< (point) end)
20193 (let* ((level (org-reduced-level (org-outline-level)))
20194 (delta (max 0 (- level ref-level))))
20195 ;; If current headline is less indented than the first
20196 ;; one, set it as reference, in order to preserve
20197 ;; subtrees.
20198 (when (< level ref-level) (setq ref-level level))
20199 (replace-match bul t t)
20200 (org-indent-line-to (+ start-ind (* delta bul-len)))
20201 ;; Ensure all text down to END (or SECTION-END) belongs
20202 ;; to the newly created item.
20203 (let ((section-end (save-excursion
20204 (or (outline-next-heading) (point)))))
20205 (forward-line)
20206 (funcall shift-text
20207 (+ start-ind (* (1+ delta) bul-len))
20208 (min end section-end)))))))
20209 ;; Case 3. Normal line with ARG: make the first line of region
20210 ;; an item, and shift indentation of others lines to
20211 ;; set them as item's body.
20212 (arg (let* ((bul (org-list-bullet-string "-"))
20213 (bul-len (length bul))
20214 (ref-ind (org-get-indentation)))
20215 (skip-chars-forward " \t")
20216 (insert bul)
20217 (forward-line)
20218 (while (< (point) end)
20219 ;; Ensure that lines less indented than first one
20220 ;; still get included in item body.
20221 (funcall shift-text
20222 (+ ref-ind bul-len)
20223 (min end (save-excursion (or (outline-next-heading)
20224 (point)))))
20225 (forward-line))))
20226 ;; Case 4. Normal line without ARG: turn each non-item line
20227 ;; into an item.
20229 (while (< (point) end)
20230 (unless (or (org-at-heading-p) (org-at-item-p))
20231 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20232 (replace-match
20233 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20234 (forward-line))))))))
20236 (defun org-toggle-heading (&optional nstars)
20237 "Convert headings to normal text, or items or text to headings.
20238 If there is no active region, only convert the current line.
20240 With a \\[universal-argument] prefix, convert the whole list at
20241 point into heading.
20243 In a region:
20245 - If the first non blank line is a headline, remove the stars
20246 from all headlines in the region.
20248 - If it is a normal line, turn each and every normal line (i.e.,
20249 not an heading or an item) in the region into headings. If you
20250 want to convert only the first line of this region, use one
20251 universal prefix argument.
20253 - If it is a plain list item, turn all plain list items into headings.
20255 When converting a line into a heading, the number of stars is chosen
20256 such that the lines become children of the current entry. However,
20257 when a numeric prefix argument is given, its value determines the
20258 number of stars to add."
20259 (interactive "P")
20260 (let ((skip-blanks
20261 (function
20262 ;; Return beginning of first non-blank line, starting from
20263 ;; line at POS.
20264 (lambda (pos)
20265 (save-excursion
20266 (goto-char pos)
20267 (while (org-at-comment-p) (forward-line))
20268 (skip-chars-forward " \r\t\n")
20269 (point-at-bol)))))
20270 beg end toggled)
20271 ;; Determine boundaries of changes. If a universal prefix has
20272 ;; been given, put the list in a region. If region ends at a bol,
20273 ;; do not consider the last line to be in the region.
20275 (when (and current-prefix-arg (org-at-item-p))
20276 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20277 (org-mark-element))
20279 (if (org-region-active-p)
20280 (setq beg (funcall skip-blanks (region-beginning))
20281 end (copy-marker (save-excursion
20282 (goto-char (region-end))
20283 (if (bolp) (point) (point-at-eol)))))
20284 (setq beg (funcall skip-blanks (point-at-bol))
20285 end (copy-marker (point-at-eol))))
20286 ;; Ensure inline tasks don't count as headings.
20287 (org-with-limited-levels
20288 (save-excursion
20289 (goto-char beg)
20290 (cond
20291 ;; Case 1. Started at an heading: de-star headings.
20292 ((org-at-heading-p)
20293 (while (< (point) end)
20294 (when (org-at-heading-p t)
20295 (looking-at org-outline-regexp) (replace-match "")
20296 (setq toggled t))
20297 (forward-line)))
20298 ;; Case 2. Started at an item: change items into headlines.
20299 ;; One star will be added by `org-list-to-subtree'.
20300 ((org-at-item-p)
20301 (let* ((stars (make-string
20302 ;; subtract the star that will be added again by
20303 ;; `org-list-to-subtree'
20304 (if (numberp nstars) (1- nstars)
20305 (or (org-current-level) 0))
20306 ?*))
20307 (add-stars
20308 (cond (nstars "") ; stars from prefix only
20309 ((equal stars "") "") ; before first heading
20310 (org-odd-levels-only "*") ; inside heading, odd
20311 (t "")))) ; inside heading, oddeven
20312 (while (< (point) end)
20313 (when (org-at-item-p)
20314 ;; Pay attention to cases when region ends before list.
20315 (let* ((struct (org-list-struct))
20316 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20317 (save-restriction
20318 (narrow-to-region (point) list-end)
20319 (insert
20320 (org-list-to-subtree
20321 (org-list-parse-list t)
20322 '(:istart (concat stars add-stars (funcall get-stars depth))
20323 :icount (concat stars add-stars (funcall get-stars depth)))))))
20324 (setq toggled t))
20325 (forward-line))))
20326 ;; Case 3. Started at normal text: make every line an heading,
20327 ;; skipping headlines and items.
20328 (t (let* ((stars
20329 (make-string
20330 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20331 (add-stars
20332 (cond (nstars "") ; stars from prefix only
20333 ((equal stars "") "*") ; before first heading
20334 (org-odd-levels-only "**") ; inside heading, odd
20335 (t "*"))) ; inside heading, oddeven
20336 (rpl (concat stars add-stars " "))
20337 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20338 (while (< (point) (if (equal nstars '(4)) lend end))
20339 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20340 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20341 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20342 (forward-line)))))))
20343 (unless toggled (message "Cannot toggle heading from here"))))
20345 (defun org-meta-return (&optional arg)
20346 "Insert a new heading or wrap a region in a table.
20347 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20348 See the individual commands for more information."
20349 (interactive "P")
20350 (cond
20351 ((run-hook-with-args-until-success 'org-metareturn-hook))
20352 ((or (org-at-drawer-p) (org-at-property-p))
20353 (newline-and-indent))
20354 ((org-at-table-p)
20355 (call-interactively 'org-table-wrap-region))
20356 (t (call-interactively 'org-insert-heading))))
20358 ;;; Menu entries
20360 (defsubst org-in-subtree-not-table-p ()
20361 "Are we in a subtree and not in a table?"
20362 (and (not (org-before-first-heading-p))
20363 (not (org-at-table-p))))
20365 ;; Define the Org-mode menus
20366 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20367 '("Tbl"
20368 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20369 ["Next Field" org-cycle (org-at-table-p)]
20370 ["Previous Field" org-shifttab (org-at-table-p)]
20371 ["Next Row" org-return (org-at-table-p)]
20372 "--"
20373 ["Blank Field" org-table-blank-field (org-at-table-p)]
20374 ["Edit Field" org-table-edit-field (org-at-table-p)]
20375 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20376 "--"
20377 ("Column"
20378 ["Move Column Left" org-metaleft (org-at-table-p)]
20379 ["Move Column Right" org-metaright (org-at-table-p)]
20380 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20381 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20382 ("Row"
20383 ["Move Row Up" org-metaup (org-at-table-p)]
20384 ["Move Row Down" org-metadown (org-at-table-p)]
20385 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20386 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20387 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20388 "--"
20389 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20390 ("Rectangle"
20391 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20392 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20393 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20394 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20395 "--"
20396 ("Calculate"
20397 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20398 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20399 ["Edit Formulas" org-edit-special (org-at-table-p)]
20400 "--"
20401 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20402 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20403 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20404 "--"
20405 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20406 "--"
20407 ["Sum Column/Rectangle" org-table-sum
20408 (or (org-at-table-p) (org-region-active-p))]
20409 ["Which Column?" org-table-current-column (org-at-table-p)])
20410 ["Debug Formulas"
20411 org-table-toggle-formula-debugger
20412 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20413 ["Show Col/Row Numbers"
20414 org-table-toggle-coordinate-overlays
20415 :style toggle
20416 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20417 "--"
20418 ["Create" org-table-create (and (not (org-at-table-p))
20419 org-enable-table-editor)]
20420 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20421 ["Import from File" org-table-import (not (org-at-table-p))]
20422 ["Export to File" org-table-export (org-at-table-p)]
20423 "--"
20424 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20426 (easy-menu-define org-org-menu org-mode-map "Org menu"
20427 '("Org"
20428 ("Show/Hide"
20429 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20430 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20431 ["Sparse Tree..." org-sparse-tree t]
20432 ["Reveal Context" org-reveal t]
20433 ["Show All" show-all t]
20434 "--"
20435 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20436 "--"
20437 ["New Heading" org-insert-heading t]
20438 ("Navigate Headings"
20439 ["Up" outline-up-heading t]
20440 ["Next" outline-next-visible-heading t]
20441 ["Previous" outline-previous-visible-heading t]
20442 ["Next Same Level" outline-forward-same-level t]
20443 ["Previous Same Level" outline-backward-same-level t]
20444 "--"
20445 ["Jump" org-goto t])
20446 ("Edit Structure"
20447 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20448 "--"
20449 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20450 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20451 "--"
20452 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20453 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20454 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20455 "--"
20456 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20457 "--"
20458 ["Copy visible text" org-copy-visible t]
20459 "--"
20460 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20461 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20462 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20463 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20464 "--"
20465 ["Sort Region/Children" org-sort t]
20466 "--"
20467 ["Convert to odd levels" org-convert-to-odd-levels t]
20468 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20469 ("Editing"
20470 ["Emphasis..." org-emphasize t]
20471 ["Edit Source Example" org-edit-special t]
20472 "--"
20473 ["Footnote new/jump" org-footnote-action t]
20474 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20475 ("Archive"
20476 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20477 "--"
20478 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20479 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20480 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20482 "--"
20483 ("Hyperlinks"
20484 ["Store Link (Global)" org-store-link t]
20485 ["Find existing link to here" org-occur-link-in-agenda-files t]
20486 ["Insert Link" org-insert-link t]
20487 ["Follow Link" org-open-at-point t]
20488 "--"
20489 ["Next link" org-next-link t]
20490 ["Previous link" org-previous-link t]
20491 "--"
20492 ["Descriptive Links"
20493 org-toggle-link-display
20494 :style radio
20495 :selected org-descriptive-links
20497 ["Literal Links"
20498 org-toggle-link-display
20499 :style radio
20500 :selected (not org-descriptive-links)])
20501 "--"
20502 ("TODO Lists"
20503 ["TODO/DONE/-" org-todo t]
20504 ("Select keyword"
20505 ["Next keyword" org-shiftright (org-at-heading-p)]
20506 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20507 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20508 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20509 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20510 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20511 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20512 "--"
20513 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20514 :selected org-enforce-todo-dependencies :style toggle :active t]
20515 "Settings for tree at point"
20516 ["Do Children sequentially" org-toggle-ordered-property :style radio
20517 :selected (org-entry-get nil "ORDERED")
20518 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20519 ["Do Children parallel" org-toggle-ordered-property :style radio
20520 :selected (not (org-entry-get nil "ORDERED"))
20521 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20522 "--"
20523 ["Set Priority" org-priority t]
20524 ["Priority Up" org-shiftup t]
20525 ["Priority Down" org-shiftdown t]
20526 "--"
20527 ["Get news from all feeds" org-feed-update-all t]
20528 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20529 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20530 ("TAGS and Properties"
20531 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20532 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20533 "--"
20534 ["Set property" org-set-property (not (org-before-first-heading-p))]
20535 ["Column view of properties" org-columns t]
20536 ["Insert Column View DBlock" org-insert-columns-dblock t])
20537 ("Dates and Scheduling"
20538 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20539 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20540 ("Change Date"
20541 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20542 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20543 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20544 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20545 ["Compute Time Range" org-evaluate-time-range t]
20546 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20547 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20548 "--"
20549 ["Custom time format" org-toggle-time-stamp-overlays
20550 :style radio :selected org-display-custom-times]
20551 "--"
20552 ["Goto Calendar" org-goto-calendar t]
20553 ["Date from Calendar" org-date-from-calendar t]
20554 "--"
20555 ["Start/Restart Timer" org-timer-start t]
20556 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20557 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20558 ["Insert Timer String" org-timer t]
20559 ["Insert Timer Item" org-timer-item t])
20560 ("Logging work"
20561 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20562 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20563 ["Clock out" org-clock-out t]
20564 ["Clock cancel" org-clock-cancel t]
20565 "--"
20566 ["Mark as default task" org-clock-mark-default-task t]
20567 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20568 ["Goto running clock" org-clock-goto t]
20569 "--"
20570 ["Display times" org-clock-display t]
20571 ["Create clock table" org-clock-report t]
20572 "--"
20573 ["Record DONE time"
20574 (progn (setq org-log-done (not org-log-done))
20575 (message "Switching to %s will %s record a timestamp"
20576 (car org-done-keywords)
20577 (if org-log-done "automatically" "not")))
20578 :style toggle :selected org-log-done])
20579 "--"
20580 ["Agenda Command..." org-agenda t]
20581 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20582 ("File List for Agenda")
20583 ("Special views current file"
20584 ["TODO Tree" org-show-todo-tree t]
20585 ["Check Deadlines" org-check-deadlines t]
20586 ["Timeline" org-timeline t]
20587 ["Tags/Property tree" org-match-sparse-tree t])
20588 "--"
20589 ["Export/Publish..." org-export-dispatch t]
20590 ("LaTeX"
20591 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20592 :selected org-cdlatex-mode]
20593 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20594 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20595 ["Modify math symbol" org-cdlatex-math-modify
20596 (org-inside-LaTeX-fragment-p)]
20597 ["Insert citation" org-reftex-citation t]
20598 "--"
20599 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20600 "--"
20601 ("MobileOrg"
20602 ["Push Files and Views" org-mobile-push t]
20603 ["Get Captured and Flagged" org-mobile-pull t]
20604 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20605 "--"
20606 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20607 "--"
20608 ("Documentation"
20609 ["Show Version" org-version t]
20610 ["Info Documentation" org-info t])
20611 ("Customize"
20612 ["Browse Org Group" org-customize t]
20613 "--"
20614 ["Expand This Menu" org-create-customize-menu
20615 (fboundp 'customize-menu-create)])
20616 ["Send bug report" org-submit-bug-report t]
20617 "--"
20618 ("Refresh/Reload"
20619 ["Refresh setup current buffer" org-mode-restart t]
20620 ["Reload Org (after update)" org-reload t]
20621 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20624 (defun org-info (&optional node)
20625 "Read documentation for Org-mode in the info system.
20626 With optional NODE, go directly to that node."
20627 (interactive)
20628 (info (format "(org)%s" (or node ""))))
20630 ;;;###autoload
20631 (defun org-submit-bug-report ()
20632 "Submit a bug report on Org-mode via mail.
20634 Don't hesitate to report any problems or inaccurate documentation.
20636 If you don't have setup sending mail from (X)Emacs, please copy the
20637 output buffer into your mail program, as it gives us important
20638 information about your Org-mode version and configuration."
20639 (interactive)
20640 (require 'reporter)
20641 (org-load-modules-maybe)
20642 (org-require-autoloaded-modules)
20643 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20644 (reporter-submit-bug-report
20645 "emacs-orgmode@gnu.org"
20646 (org-version nil 'full)
20647 (let (list)
20648 (save-window-excursion
20649 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20650 (delete-other-windows)
20651 (erase-buffer)
20652 (insert "You are about to submit a bug report to the Org-mode mailing list.
20654 We would like to add your full Org-mode and Outline configuration to the
20655 bug report. This greatly simplifies the work of the maintainer and
20656 other experts on the mailing list.
20658 HOWEVER, some variables you have customized may contain private
20659 information. The names of customers, colleagues, or friends, might
20660 appear in the form of file names, tags, todo states, or search strings.
20661 If you answer yes to the prompt, you might want to check and remove
20662 such private information before sending the email.")
20663 (add-text-properties (point-min) (point-max) '(face org-warning))
20664 (when (yes-or-no-p "Include your Org-mode configuration ")
20665 (mapatoms
20666 (lambda (v)
20667 (and (boundp v)
20668 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20669 (or (and (symbol-value v)
20670 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20671 (and
20672 (get v 'custom-type) (get v 'standard-value)
20673 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20674 (push v list)))))
20675 (kill-buffer (get-buffer "*Warn about privacy*"))
20676 list))
20677 nil nil
20678 "Remember to cover the basics, that is, what you expected to happen and
20679 what in fact did happen. You don't know how to make a good report? See
20681 http://orgmode.org/manual/Feedback.html#Feedback
20683 Your bug report will be posted to the Org-mode mailing list.
20684 ------------------------------------------------------------------------")
20685 (save-excursion
20686 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20687 (replace-match "\\1Bug: \\3 [\\2]")))))
20690 (defun org-install-agenda-files-menu ()
20691 (let ((bl (buffer-list)))
20692 (save-excursion
20693 (while bl
20694 (set-buffer (pop bl))
20695 (if (derived-mode-p 'org-mode) (setq bl nil)))
20696 (when (derived-mode-p 'org-mode)
20697 (easy-menu-change
20698 '("Org") "File List for Agenda"
20699 (append
20700 (list
20701 ["Edit File List" (org-edit-agenda-file-list) t]
20702 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20703 ["Remove Current File from List" org-remove-file t]
20704 ["Cycle through agenda files" org-cycle-agenda-files t]
20705 ["Occur in all agenda files" org-occur-in-agenda-files t]
20706 "--")
20707 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20709 ;;;; Documentation
20711 (defun org-require-autoloaded-modules ()
20712 (interactive)
20713 (mapc 'require
20714 '(org-agenda org-archive org-attach org-clock org-colview org-id
20715 org-remember org-table org-timer)))
20717 ;;;###autoload
20718 (defun org-reload (&optional uncompiled)
20719 "Reload all org lisp files.
20720 With prefix arg UNCOMPILED, load the uncompiled versions."
20721 (interactive "P")
20722 (require 'loadhist)
20723 (let* ((org-dir (org-find-library-dir "org"))
20724 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20725 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20726 (remove-re (mapconcat 'identity
20727 (mapcar (lambda (f) (concat "^" f "$"))
20728 (list (if (featurep 'xemacs)
20729 "org-colview"
20730 "org-colview-xemacs")
20731 "org" "org-loaddefs" "org-version"))
20732 "\\|"))
20733 (feats (delete-dups
20734 (mapcar 'file-name-sans-extension
20735 (mapcar 'file-name-nondirectory
20736 (delq nil
20737 (mapcar 'feature-file
20738 features))))))
20739 (lfeat (append
20740 (sort
20741 (setq feats
20742 (delq nil (mapcar
20743 (lambda (f)
20744 (if (and (string-match feature-re f)
20745 (not (string-match remove-re f)))
20746 f nil))
20747 feats)))
20748 'string-lessp)
20749 (list "org-version" "org")))
20750 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20751 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20752 load-uncore load-misses)
20753 (setq load-misses
20754 (delq 't
20755 (mapcar (lambda (f)
20756 (or (org-load-noerror-mustsuffix (concat org-dir f))
20757 (and (string= org-dir contrib-dir)
20758 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20759 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20760 (add-to-list 'load-uncore f 'append)
20763 lfeat)))
20764 (if load-uncore
20765 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20766 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20767 (if load-misses
20768 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20769 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20770 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20772 ;;;###autoload
20773 (defun org-customize ()
20774 "Call the customize function with org as argument."
20775 (interactive)
20776 (org-load-modules-maybe)
20777 (org-require-autoloaded-modules)
20778 (customize-browse 'org))
20780 (defun org-create-customize-menu ()
20781 "Create a full customization menu for Org-mode, insert it into the menu."
20782 (interactive)
20783 (org-load-modules-maybe)
20784 (org-require-autoloaded-modules)
20785 (if (fboundp 'customize-menu-create)
20786 (progn
20787 (easy-menu-change
20788 '("Org") "Customize"
20789 `(["Browse Org group" org-customize t]
20790 "--"
20791 ,(customize-menu-create 'org)
20792 ["Set" Custom-set t]
20793 ["Save" Custom-save t]
20794 ["Reset to Current" Custom-reset-current t]
20795 ["Reset to Saved" Custom-reset-saved t]
20796 ["Reset to Standard Settings" Custom-reset-standard t]))
20797 (message "\"Org\"-menu now contains full customization menu"))
20798 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20800 ;;;; Miscellaneous stuff
20802 ;;; Generally useful functions
20804 (defun org-get-at-bol (property)
20805 "Get text property PROPERTY at beginning of line."
20806 (get-text-property (point-at-bol) property))
20808 (defun org-find-text-property-in-string (prop s)
20809 "Return the first non-nil value of property PROP in string S."
20810 (or (get-text-property 0 prop s)
20811 (get-text-property (or (next-single-property-change 0 prop s) 0)
20812 prop s)))
20814 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20815 "Display the given MESSAGE as a warning."
20816 (if (fboundp 'display-warning)
20817 (display-warning 'org message
20818 (if (featurep 'xemacs) 'warning :warning))
20819 (let ((buf (get-buffer-create "*Org warnings*")))
20820 (with-current-buffer buf
20821 (goto-char (point-max))
20822 (insert "Warning (Org): " message)
20823 (unless (bolp)
20824 (newline)))
20825 (display-buffer buf)
20826 (sit-for 0))))
20828 (defun org-eval (form)
20829 "Eval FORM and return result."
20830 (condition-case error
20831 (eval form)
20832 (error (format "%%![Error: %s]" error))))
20834 (defun org-in-clocktable-p ()
20835 "Check if the cursor is in a clocktable."
20836 (let ((pos (point)) start)
20837 (save-excursion
20838 (end-of-line 1)
20839 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20840 (setq start (match-beginning 0))
20841 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20842 (>= (match-end 0) pos)
20843 start))))
20845 (defun org-in-commented-line ()
20846 "Is point in a line starting with `#'?"
20847 (equal (char-after (point-at-bol)) ?#))
20849 (defun org-in-indented-comment-line ()
20850 "Is point in a line starting with `#' after some white space?"
20851 (save-excursion
20852 (save-match-data
20853 (goto-char (point-at-bol))
20854 (looking-at "[ \t]*#"))))
20856 (defun org-in-verbatim-emphasis ()
20857 (save-match-data
20858 (and (org-in-regexp org-emph-re 2)
20859 (>= (point) (match-beginning 3))
20860 (<= (point) (match-end 4))
20861 (member (match-string 3) '("=" "~")))))
20863 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20864 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20865 (if (and marker (marker-buffer marker)
20866 (buffer-live-p (marker-buffer marker)))
20867 (progn
20868 (org-pop-to-buffer-same-window (marker-buffer marker))
20869 (if (or (> marker (point-max)) (< marker (point-min)))
20870 (widen))
20871 (goto-char marker)
20872 (org-show-context 'org-goto))
20873 (if bookmark
20874 (bookmark-jump bookmark)
20875 (error "Cannot find location"))))
20877 (defun org-quote-csv-field (s)
20878 "Quote field for inclusion in CSV material."
20879 (if (string-match "[\",]" s)
20880 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20883 (defun org-force-self-insert (N)
20884 "Needed to enforce self-insert under remapping."
20885 (interactive "p")
20886 (self-insert-command N))
20888 (defun org-string-width (s)
20889 "Compute width of string, ignoring invisible characters.
20890 This ignores character with invisibility property `org-link', and also
20891 characters with property `org-cwidth', because these will become invisible
20892 upon the next fontification round."
20893 (let (b l)
20894 (when (or (eq t buffer-invisibility-spec)
20895 (assq 'org-link buffer-invisibility-spec))
20896 (while (setq b (text-property-any 0 (length s)
20897 'invisible 'org-link s))
20898 (setq s (concat (substring s 0 b)
20899 (substring s (or (next-single-property-change
20900 b 'invisible s) (length s)))))))
20901 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20902 (setq s (concat (substring s 0 b)
20903 (substring s (or (next-single-property-change
20904 b 'org-cwidth s) (length s))))))
20905 (setq l (string-width s) b -1)
20906 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20907 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20910 (defun org-shorten-string (s maxlength)
20911 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20912 If the string is shorter or has length MAXLENGTH, just return the
20913 original string. If it is longer, the functions finds a space in the
20914 string, breaks this string off at that locations and adds three dots
20915 as ellipsis. Including the ellipsis, the string will not be longer
20916 than MAXLENGTH. If finding a good breaking point in the string does
20917 not work, the string is just chopped off in the middle of a word
20918 if necessary."
20919 (if (<= (length s) maxlength)
20921 (let* ((n (max (- maxlength 4) 1))
20922 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20923 (if (string-match re s)
20924 (concat (match-string 1 s) "...")
20925 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20927 (defun org-get-indentation (&optional line)
20928 "Get the indentation of the current line, interpreting tabs.
20929 When LINE is given, assume it represents a line and compute its indentation."
20930 (if line
20931 (if (string-match "^ *" (org-remove-tabs line))
20932 (match-end 0))
20933 (save-excursion
20934 (beginning-of-line 1)
20935 (skip-chars-forward " \t")
20936 (current-column))))
20938 (defun org-get-string-indentation (s)
20939 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20940 (let ((n -1) (i 0) (w tab-width) c)
20941 (catch 'exit
20942 (while (< (setq n (1+ n)) (length s))
20943 (setq c (aref s n))
20944 (cond ((= c ?\ ) (setq i (1+ i)))
20945 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20946 (t (throw 'exit t)))))
20949 (defun org-remove-tabs (s &optional width)
20950 "Replace tabulators in S with spaces.
20951 Assumes that s is a single line, starting in column 0."
20952 (setq width (or width tab-width))
20953 (while (string-match "\t" s)
20954 (setq s (replace-match
20955 (make-string
20956 (- (* width (/ (+ (match-beginning 0) width) width))
20957 (match-beginning 0)) ?\ )
20958 t t s)))
20961 (defun org-fix-indentation (line ind)
20962 "Fix indentation in LINE.
20963 IND is a cons cell with target and minimum indentation.
20964 If the current indentation in LINE is smaller than the minimum,
20965 leave it alone. If it is larger than ind, set it to the target."
20966 (let* ((l (org-remove-tabs line))
20967 (i (org-get-indentation l))
20968 (i1 (car ind)) (i2 (cdr ind)))
20969 (if (>= i i2) (setq l (substring line i2)))
20970 (if (> i1 0)
20971 (concat (make-string i1 ?\ ) l)
20972 l)))
20974 (defun org-remove-indentation (code &optional n)
20975 "Remove the maximum common indentation from the lines in CODE.
20976 N may optionally be the number of spaces to remove."
20977 (with-temp-buffer
20978 (insert code)
20979 (org-do-remove-indentation n)
20980 (buffer-string)))
20982 (defun org-do-remove-indentation (&optional n)
20983 "Remove the maximum common indentation from the buffer."
20984 (untabify (point-min) (point-max))
20985 (let ((min 10000) re)
20986 (if n
20987 (setq min n)
20988 (goto-char (point-min))
20989 (while (re-search-forward "^ *[^ \n]" nil t)
20990 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20991 (unless (or (= min 0) (= min 10000))
20992 (setq re (format "^ \\{%d\\}" min))
20993 (goto-char (point-min))
20994 (while (re-search-forward re nil t)
20995 (replace-match "")
20996 (end-of-line 1))
20997 min)))
20999 (defun org-fill-template (template alist)
21000 "Find each %key of ALIST in TEMPLATE and replace it."
21001 (let ((case-fold-search nil)
21002 entry key value)
21003 (setq alist (sort (copy-sequence alist)
21004 (lambda (a b) (< (length (car a)) (length (car b))))))
21005 (while (setq entry (pop alist))
21006 (setq template
21007 (replace-regexp-in-string
21008 (concat "%" (regexp-quote (car entry)))
21009 (or (cdr entry) "") template t t)))
21010 template))
21012 (defun org-base-buffer (buffer)
21013 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21014 (if (not buffer)
21015 buffer
21016 (or (buffer-base-buffer buffer)
21017 buffer)))
21019 (defun org-trim (s)
21020 "Remove whitespace at beginning and end of string."
21021 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21022 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21025 (defun org-wrap (string &optional width lines)
21026 "Wrap string to either a number of lines, or a width in characters.
21027 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21028 that costs. If there is a word longer than WIDTH, the text is actually
21029 wrapped to the length of that word.
21030 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21031 many lines, whatever width that takes.
21032 The return value is a list of lines, without newlines at the end."
21033 (let* ((words (org-split-string string "[ \t\n]+"))
21034 (maxword (apply 'max (mapcar 'org-string-width words)))
21035 w ll)
21036 (cond (width
21037 (org-do-wrap words (max maxword width)))
21038 (lines
21039 (setq w maxword)
21040 (setq ll (org-do-wrap words maxword))
21041 (if (<= (length ll) lines)
21043 (setq ll words)
21044 (while (> (length ll) lines)
21045 (setq w (1+ w))
21046 (setq ll (org-do-wrap words w)))
21047 ll))
21048 (t (error "Cannot wrap this")))))
21050 (defun org-do-wrap (words width)
21051 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21052 (let (lines line)
21053 (while words
21054 (setq line (pop words))
21055 (while (and words (< (+ (length line) (length (car words))) width))
21056 (setq line (concat line " " (pop words))))
21057 (setq lines (push line lines)))
21058 (nreverse lines)))
21060 (defun org-split-string (string &optional separators)
21061 "Splits STRING into substrings at SEPARATORS.
21062 No empty strings are returned if there are matches at the beginning
21063 and end of string."
21064 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21065 (start 0)
21066 notfirst
21067 (list nil))
21068 (while (and (string-match rexp string
21069 (if (and notfirst
21070 (= start (match-beginning 0))
21071 (< start (length string)))
21072 (1+ start) start))
21073 (< (match-beginning 0) (length string)))
21074 (setq notfirst t)
21075 (or (eq (match-beginning 0) 0)
21076 (and (eq (match-beginning 0) (match-end 0))
21077 (eq (match-beginning 0) start))
21078 (setq list
21079 (cons (substring string start (match-beginning 0))
21080 list)))
21081 (setq start (match-end 0)))
21082 (or (eq start (length string))
21083 (setq list
21084 (cons (substring string start)
21085 list)))
21086 (nreverse list)))
21088 (defun org-quote-vert (s)
21089 "Replace \"|\" with \"\\vert\"."
21090 (while (string-match "|" s)
21091 (setq s (replace-match "\\vert" t t s)))
21094 (defun org-uuidgen-p (s)
21095 "Is S an ID created by UUIDGEN?"
21096 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21098 (defun org-in-src-block-p (&optional inside)
21099 "Whether point is in a code source block.
21100 When INSIDE is non-nil, don't consider we are within a src block
21101 when point is at #+BEGIN_SRC or #+END_SRC."
21102 (let ((case-fold-search t) ov)
21103 (or (and (setq ov (overlays-at (point)))
21104 (memq 'org-block-background
21105 (overlay-properties (car ov))))
21106 (and (not inside)
21107 (save-match-data
21108 (save-excursion
21109 (beginning-of-line)
21110 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21112 (defun org-context ()
21113 "Return a list of contexts of the current cursor position.
21114 If several contexts apply, all are returned.
21115 Each context entry is a list with a symbol naming the context, and
21116 two positions indicating start and end of the context. Possible
21117 contexts are:
21119 :headline anywhere in a headline
21120 :headline-stars on the leading stars in a headline
21121 :todo-keyword on a TODO keyword (including DONE) in a headline
21122 :tags on the TAGS in a headline
21123 :priority on the priority cookie in a headline
21124 :item on the first line of a plain list item
21125 :item-bullet on the bullet/number of a plain list item
21126 :checkbox on the checkbox in a plain list item
21127 :table in an org-mode table
21128 :table-special on a special filed in a table
21129 :table-table in a table.el table
21130 :clocktable in a clocktable
21131 :src-block in a source block
21132 :link on a hyperlink
21133 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21134 :target on a <<target>>
21135 :radio-target on a <<<radio-target>>>
21136 :latex-fragment on a LaTeX fragment
21137 :latex-preview on a LaTeX fragment with overlaid preview image
21139 This function expects the position to be visible because it uses font-lock
21140 faces as a help to recognize the following contexts: :table-special, :link,
21141 and :keyword."
21142 (let* ((f (get-text-property (point) 'face))
21143 (faces (if (listp f) f (list f)))
21144 (case-fold-search t)
21145 (p (point)) clist o)
21146 ;; First the large context
21147 (cond
21148 ((org-at-heading-p t)
21149 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21150 (when (progn
21151 (beginning-of-line 1)
21152 (looking-at org-todo-line-tags-regexp))
21153 (push (org-point-in-group p 1 :headline-stars) clist)
21154 (push (org-point-in-group p 2 :todo-keyword) clist)
21155 (push (org-point-in-group p 4 :tags) clist))
21156 (goto-char p)
21157 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21158 (if (looking-at "\\[#[A-Z0-9]\\]")
21159 (push (org-point-in-group p 0 :priority) clist)))
21161 ((org-at-item-p)
21162 (push (org-point-in-group p 2 :item-bullet) clist)
21163 (push (list :item (point-at-bol)
21164 (save-excursion (org-end-of-item) (point)))
21165 clist)
21166 (and (org-at-item-checkbox-p)
21167 (push (org-point-in-group p 0 :checkbox) clist)))
21169 ((org-at-table-p)
21170 (push (list :table (org-table-begin) (org-table-end)) clist)
21171 (if (memq 'org-formula faces)
21172 (push (list :table-special
21173 (previous-single-property-change p 'face)
21174 (next-single-property-change p 'face)) clist)))
21175 ((org-at-table-p 'any)
21176 (push (list :table-table) clist)))
21177 (goto-char p)
21179 (let ((case-fold-search t))
21180 ;; New the "medium" contexts: clocktables, source blocks
21181 (cond ((org-in-clocktable-p)
21182 (push (list :clocktable
21183 (and (or (looking-at "#\\+BEGIN: clocktable")
21184 (search-backward "#+BEGIN: clocktable" nil t))
21185 (match-beginning 0))
21186 (and (re-search-forward "#\\+END:?" nil t)
21187 (match-end 0))) clist))
21188 ((org-in-src-block-p)
21189 (push (list :src-block
21190 (and (or (looking-at "#\\+BEGIN_SRC")
21191 (search-backward "#+BEGIN_SRC" nil t))
21192 (match-beginning 0))
21193 (and (search-forward "#+END_SRC" nil t)
21194 (match-beginning 0))) clist))))
21195 (goto-char p)
21197 ;; Now the small context
21198 (cond
21199 ((org-at-timestamp-p)
21200 (push (org-point-in-group p 0 :timestamp) clist))
21201 ((memq 'org-link faces)
21202 (push (list :link
21203 (previous-single-property-change p 'face)
21204 (next-single-property-change p 'face)) clist))
21205 ((memq 'org-special-keyword faces)
21206 (push (list :keyword
21207 (previous-single-property-change p 'face)
21208 (next-single-property-change p 'face)) clist))
21209 ((org-at-target-p)
21210 (push (org-point-in-group p 0 :target) clist)
21211 (goto-char (1- (match-beginning 0)))
21212 (if (looking-at org-radio-target-regexp)
21213 (push (org-point-in-group p 0 :radio-target) clist))
21214 (goto-char p))
21215 ((setq o (car (delq nil
21216 (mapcar
21217 (lambda (x)
21218 (if (memq x org-latex-fragment-image-overlays) x))
21219 (overlays-at (point))))))
21220 (push (list :latex-fragment
21221 (overlay-start o) (overlay-end o)) clist)
21222 (push (list :latex-preview
21223 (overlay-start o) (overlay-end o)) clist))
21224 ((org-inside-LaTeX-fragment-p)
21225 ;; FIXME: positions wrong.
21226 (push (list :latex-fragment (point) (point)) clist)))
21228 (setq clist (nreverse (delq nil clist)))
21229 clist))
21231 ;; FIXME: Compare with at-regexp-p Do we need both?
21232 (defun org-in-regexp (re &optional nlines visually)
21233 "Check if point is inside a match of regexp.
21234 Normally only the current line is checked, but you can include NLINES extra
21235 lines both before and after point into the search.
21236 If VISUALLY is set, require that the cursor is not after the match but
21237 really on, so that the block visually is on the match."
21238 (catch 'exit
21239 (let ((pos (point))
21240 (eol (point-at-eol (+ 1 (or nlines 0))))
21241 (inc (if visually 1 0)))
21242 (save-excursion
21243 (beginning-of-line (- 1 (or nlines 0)))
21244 (while (re-search-forward re eol t)
21245 (if (and (<= (match-beginning 0) pos)
21246 (>= (+ inc (match-end 0)) pos))
21247 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21249 (defun org-at-regexp-p (regexp)
21250 "Is point inside a match of REGEXP in the current line?"
21251 (catch 'exit
21252 (save-excursion
21253 (let ((pos (point)) (end (point-at-eol)))
21254 (beginning-of-line 1)
21255 (while (re-search-forward regexp end t)
21256 (if (and (<= (match-beginning 0) pos)
21257 (>= (match-end 0) pos))
21258 (throw 'exit t)))
21259 nil))))
21261 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21262 "Non-nil when point is between matches of START-RE and END-RE.
21264 Also return a non-nil value when point is on one of the matches.
21266 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21267 buffer positions. Default values are the positions of headlines
21268 surrounding the point.
21270 The functions returns a cons cell whose car (resp. cdr) is the
21271 position before START-RE (resp. after END-RE)."
21272 (save-match-data
21273 (let ((pos (point))
21274 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21275 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21276 beg end)
21277 (save-excursion
21278 ;; Point is on a block when on START-RE or if START-RE can be
21279 ;; found before it...
21280 (and (or (org-at-regexp-p start-re)
21281 (re-search-backward start-re limit-up t))
21282 (setq beg (match-beginning 0))
21283 ;; ... and END-RE after it...
21284 (goto-char (match-end 0))
21285 (re-search-forward end-re limit-down t)
21286 (> (setq end (match-end 0)) pos)
21287 ;; ... without another START-RE in-between.
21288 (goto-char (match-beginning 0))
21289 (not (re-search-backward start-re (1+ beg) t))
21290 ;; Return value.
21291 (cons beg end))))))
21293 (defun org-in-block-p (names)
21294 "Non-nil when point belongs to a block whose name belongs to NAMES.
21296 NAMES is a list of strings containing names of blocks.
21298 Return first block name matched, or nil. Beware that in case of
21299 nested blocks, the returned name may not belong to the closest
21300 block from point."
21301 (save-match-data
21302 (catch 'exit
21303 (let ((case-fold-search t)
21304 (lim-up (save-excursion (outline-previous-heading)))
21305 (lim-down (save-excursion (outline-next-heading))))
21306 (mapc (lambda (name)
21307 (let ((n (regexp-quote name)))
21308 (when (org-between-regexps-p
21309 (concat "^[ \t]*#\\+begin_" n)
21310 (concat "^[ \t]*#\\+end_" n)
21311 lim-up lim-down)
21312 (throw 'exit n))))
21313 names))
21314 nil)))
21316 (defun org-occur-in-agenda-files (regexp &optional nlines)
21317 "Call `multi-occur' with buffers for all agenda files."
21318 (interactive "sOrg-files matching: \np")
21319 (let* ((files (org-agenda-files))
21320 (tnames (mapcar 'file-truename files))
21321 (extra org-agenda-text-search-extra-files)
21323 (when (eq (car extra) 'agenda-archives)
21324 (setq extra (cdr extra))
21325 (setq files (org-add-archive-files files)))
21326 (while (setq f (pop extra))
21327 (unless (member (file-truename f) tnames)
21328 (add-to-list 'files f 'append)
21329 (add-to-list 'tnames (file-truename f) 'append)))
21330 (multi-occur
21331 (mapcar (lambda (x)
21332 (with-current-buffer
21333 (or (get-file-buffer x) (find-file-noselect x))
21334 (widen)
21335 (current-buffer)))
21336 files)
21337 regexp)))
21339 (if (boundp 'occur-mode-find-occurrence-hook)
21340 ;; Emacs 23
21341 (add-hook 'occur-mode-find-occurrence-hook
21342 (lambda ()
21343 (when (derived-mode-p 'org-mode)
21344 (org-reveal))))
21345 ;; Emacs 22
21346 (defadvice occur-mode-goto-occurrence
21347 (after org-occur-reveal activate)
21348 (and (derived-mode-p 'org-mode) (org-reveal)))
21349 (defadvice occur-mode-goto-occurrence-other-window
21350 (after org-occur-reveal activate)
21351 (and (derived-mode-p 'org-mode) (org-reveal)))
21352 (defadvice occur-mode-display-occurrence
21353 (after org-occur-reveal activate)
21354 (when (derived-mode-p 'org-mode)
21355 (let ((pos (occur-mode-find-occurrence)))
21356 (with-current-buffer (marker-buffer pos)
21357 (save-excursion
21358 (goto-char pos)
21359 (org-reveal)))))))
21361 (defun org-occur-link-in-agenda-files ()
21362 "Create a link and search for it in the agendas.
21363 The link is not stored in `org-stored-links', it is just created
21364 for the search purpose."
21365 (interactive)
21366 (let ((link (condition-case nil
21367 (org-store-link nil)
21368 (error "Unable to create a link to here"))))
21369 (org-occur-in-agenda-files (regexp-quote link))))
21371 (defun org-reverse-string (string)
21372 "Return the reverse of STRING."
21373 (apply 'string (reverse (string-to-list string))))
21375 (defun org-uniquify (list)
21376 "Remove duplicate elements from LIST."
21377 (let (res)
21378 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21379 res))
21381 (defun org-delete-all (elts list)
21382 "Remove all elements in ELTS from LIST."
21383 (while elts
21384 (setq list (delete (pop elts) list)))
21385 list)
21387 (defun org-count (cl-item cl-seq)
21388 "Count the number of occurrences of ITEM in SEQ.
21389 Taken from `count' in cl-seq.el with all keyword arguments removed."
21390 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21391 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21392 (while (< cl-start cl-end)
21393 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21394 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21395 (setq cl-start (1+ cl-start)))
21396 cl-count))
21398 (defun org-remove-if (predicate seq)
21399 "Remove everything from SEQ that fulfills PREDICATE."
21400 (let (res e)
21401 (while seq
21402 (setq e (pop seq))
21403 (if (not (funcall predicate e)) (push e res)))
21404 (nreverse res)))
21406 (defun org-remove-if-not (predicate seq)
21407 "Remove everything from SEQ that does not fulfill PREDICATE."
21408 (let (res e)
21409 (while seq
21410 (setq e (pop seq))
21411 (if (funcall predicate e) (push e res)))
21412 (nreverse res)))
21414 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21415 "Reduce two-argument FUNCTION across SEQ.
21416 Taken from `reduce' in cl-seq.el with all keyword arguments but
21417 \":initial-value\" removed."
21418 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21419 (cadr (memq :initial-value cl-keys)))
21420 (cl-seq (pop cl-seq))
21421 (t (funcall cl-func)))))
21422 (while cl-seq
21423 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21424 cl-accum))
21426 (defun org-back-over-empty-lines ()
21427 "Move backwards over whitespace, to the beginning of the first empty line.
21428 Returns the number of empty lines passed."
21429 (let ((pos (point)))
21430 (if (cdr (assoc 'heading org-blank-before-new-entry))
21431 (skip-chars-backward " \t\n\r")
21432 (unless (eobp)
21433 (forward-line -1)))
21434 (beginning-of-line 2)
21435 (goto-char (min (point) pos))
21436 (count-lines (point) pos)))
21438 (defun org-skip-whitespace ()
21439 (skip-chars-forward " \t\n\r"))
21441 (defun org-point-in-group (point group &optional context)
21442 "Check if POINT is in match-group GROUP.
21443 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21444 match. If the match group does not exist or point is not inside it,
21445 return nil."
21446 (and (match-beginning group)
21447 (>= point (match-beginning group))
21448 (<= point (match-end group))
21449 (if context
21450 (list context (match-beginning group) (match-end group))
21451 t)))
21453 (defun org-switch-to-buffer-other-window (&rest args)
21454 "Switch to buffer in a second window on the current frame.
21455 In particular, do not allow pop-up frames.
21456 Returns the newly created buffer."
21457 (org-no-popups
21458 (apply 'switch-to-buffer-other-window args)))
21460 (defun org-combine-plists (&rest plists)
21461 "Create a single property list from all plists in PLISTS.
21462 The process starts by copying the first list, and then setting properties
21463 from the other lists. Settings in the last list are the most significant
21464 ones and overrule settings in the other lists."
21465 (let ((rtn (copy-sequence (pop plists)))
21466 p v ls)
21467 (while plists
21468 (setq ls (pop plists))
21469 (while ls
21470 (setq p (pop ls) v (pop ls))
21471 (setq rtn (plist-put rtn p v))))
21472 rtn))
21474 (defun org-replace-escapes (string table)
21475 "Replace %-escapes in STRING with values in TABLE.
21476 TABLE is an association list with keys like \"%a\" and string values.
21477 The sequences in STRING may contain normal field width and padding information,
21478 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21479 so values can contain further %-escapes if they are define later in TABLE."
21480 (let ((tbl (copy-alist table))
21481 (case-fold-search nil)
21482 (pchg 0)
21483 e re rpl)
21484 (while (setq e (pop tbl))
21485 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21486 (when (and (cdr e) (string-match re (cdr e)))
21487 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21488 (safe "SREF"))
21489 (add-text-properties 0 3 (list 'sref sref) safe)
21490 (setcdr e (replace-match safe t t (cdr e)))))
21491 (while (string-match re string)
21492 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21493 (cdr e)))
21494 (setq string (replace-match rpl t t string))))
21495 (while (setq pchg (next-property-change pchg string))
21496 (let ((sref (get-text-property pchg 'sref string)))
21497 (when (and sref (string-match "SREF" string pchg))
21498 (setq string (replace-match sref t t string)))))
21499 string))
21501 (defun org-sublist (list start end)
21502 "Return a section of LIST, from START to END.
21503 Counting starts at 1."
21504 (let (rtn (c start))
21505 (setq list (nthcdr (1- start) list))
21506 (while (and list (<= c end))
21507 (push (pop list) rtn)
21508 (setq c (1+ c)))
21509 (nreverse rtn)))
21511 (defun org-find-base-buffer-visiting (file)
21512 "Like `find-buffer-visiting' but always return the base buffer and
21513 not an indirect buffer."
21514 (let ((buf (or (get-file-buffer file)
21515 (find-buffer-visiting file))))
21516 (if buf
21517 (or (buffer-base-buffer buf) buf)
21518 nil)))
21520 (defun org-image-file-name-regexp (&optional extensions)
21521 "Return regexp matching the file names of images.
21522 If EXTENSIONS is given, only match these."
21523 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21524 (image-file-name-regexp)
21525 (let ((image-file-name-extensions
21526 (or extensions
21527 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21528 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21529 (concat "\\."
21530 (regexp-opt (nconc (mapcar 'upcase
21531 image-file-name-extensions)
21532 image-file-name-extensions)
21534 "\\'"))))
21536 (defun org-file-image-p (file &optional extensions)
21537 "Return non-nil if FILE is an image."
21538 (save-match-data
21539 (string-match (org-image-file-name-regexp extensions) file)))
21541 (defun org-get-cursor-date (&optional with-time)
21542 "Return the date at cursor in as a time.
21543 This works in the calendar and in the agenda, anywhere else it just
21544 returns the current time.
21545 If WITH-TIME is non-nil, returns the time of the event at point (in
21546 the agenda) or the current time of the day."
21547 (let (date day defd tp tm hod mod)
21548 (when with-time
21549 (setq tp (get-text-property (point) 'time))
21550 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21551 (setq hod (string-to-number (match-string 1 tp))
21552 mod (string-to-number (match-string 2 tp))))
21553 (or tp (setq hod (nth 2 (decode-time (current-time)))
21554 mod (nth 1 (decode-time (current-time))))))
21555 (cond
21556 ((eq major-mode 'calendar-mode)
21557 (setq date (calendar-cursor-to-date)
21558 defd (encode-time 0 (or mod 0) (or hod 0)
21559 (nth 1 date) (nth 0 date) (nth 2 date))))
21560 ((eq major-mode 'org-agenda-mode)
21561 (setq day (get-text-property (point) 'day))
21562 (if day
21563 (setq date (calendar-gregorian-from-absolute day)
21564 defd (encode-time 0 (or mod 0) (or hod 0)
21565 (nth 1 date) (nth 0 date) (nth 2 date))))))
21566 (or defd (current-time))))
21568 (defun org-mark-subtree (&optional up)
21569 "Mark the current subtree.
21570 This puts point at the start of the current subtree, and mark at
21571 the end. If a numeric prefix UP is given, move up into the
21572 hierarchy of headlines by UP levels before marking the subtree."
21573 (interactive "P")
21574 (org-with-limited-levels
21575 (cond ((org-at-heading-p) (beginning-of-line))
21576 ((org-before-first-heading-p) (error "Not in a subtree"))
21577 (t (outline-previous-visible-heading 1))))
21578 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21579 (if (org-called-interactively-p 'any)
21580 (call-interactively 'org-mark-element)
21581 (org-mark-element)))
21584 ;;; Indentation
21586 (defun org-indent-line ()
21587 "Indent line depending on context."
21588 (interactive)
21589 (let* ((pos (point))
21590 (itemp (org-at-item-p))
21591 (case-fold-search t)
21592 (org-drawer-regexp (or org-drawer-regexp "\000"))
21593 (inline-task-p (and (featurep 'org-inlinetask)
21594 (org-inlinetask-in-task-p)))
21595 (inline-re (and inline-task-p
21596 (org-inlinetask-outline-regexp)))
21597 column)
21598 (if (and orgstruct-is-++ (eq pos (point)))
21599 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21600 (indent-according-to-mode))
21601 (beginning-of-line 1)
21602 (cond
21603 ;; Headings
21604 ((looking-at org-outline-regexp) (setq column 0))
21605 ;; Footnote definition
21606 ((looking-at org-footnote-definition-re) (setq column 0))
21607 ;; Literal examples
21608 ((looking-at "[ \t]*:\\( \\|$\\)")
21609 (setq column (org-get-indentation))) ; do nothing
21610 ;; Lists
21611 ((ignore-errors (goto-char (org-in-item-p)))
21612 (setq column (if itemp
21613 (org-get-indentation)
21614 (org-list-item-body-column (point))))
21615 (goto-char pos))
21616 ;; Drawers
21617 ((and (looking-at "[ \t]*:END:")
21618 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21619 (save-excursion
21620 (goto-char (1- (match-beginning 1)))
21621 (setq column (current-column))))
21622 ;; Special blocks
21623 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21624 (save-excursion
21625 (re-search-backward
21626 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21627 (setq column (org-get-indentation (match-string 0))))
21628 ((and (not (looking-at "[ \t]*#\\+begin_"))
21629 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21630 (save-excursion
21631 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21632 (setq column
21633 (cond ((equal (downcase (match-string 1)) "src")
21634 ;; src blocks: let `org-edit-src-exit' handle them
21635 (org-get-indentation))
21636 ((equal (downcase (match-string 1)) "example")
21637 (max (org-get-indentation)
21638 (org-get-indentation (match-string 0))))
21640 (org-get-indentation (match-string 0))))))
21641 ;; This line has nothing special, look at the previous relevant
21642 ;; line to compute indentation
21644 (beginning-of-line 0)
21645 (while (and (not (bobp))
21646 (not (looking-at org-table-line-regexp))
21647 (not (looking-at org-drawer-regexp))
21648 ;; When point started in an inline task, do not move
21649 ;; above task starting line.
21650 (not (and inline-task-p (looking-at inline-re)))
21651 ;; Skip drawers, blocks, empty lines, verbatim,
21652 ;; comments, tables, footnotes definitions, lists,
21653 ;; inline tasks.
21654 (or (and (looking-at "[ \t]*:END:")
21655 (re-search-backward org-drawer-regexp nil t))
21656 (and (looking-at "[ \t]*#\\+end_")
21657 (re-search-backward "[ \t]*#\\+begin_"nil t))
21658 (looking-at "[ \t]*[\n:#|]")
21659 (looking-at org-footnote-definition-re)
21660 (and (ignore-errors (goto-char (org-in-item-p)))
21661 (goto-char
21662 (org-list-get-top-point (org-list-struct))))
21663 (and (not inline-task-p)
21664 (featurep 'org-inlinetask)
21665 (org-inlinetask-in-task-p)
21666 (or (org-inlinetask-goto-beginning) t))))
21667 (beginning-of-line 0))
21668 (cond
21669 ;; There was an heading above.
21670 ((looking-at "\\*+[ \t]+")
21671 (if (not org-adapt-indentation)
21672 (setq column 0)
21673 (goto-char (match-end 0))
21674 (setq column (current-column))))
21675 ;; A drawer had started and is unfinished
21676 ((looking-at org-drawer-regexp)
21677 (goto-char (1- (match-beginning 1)))
21678 (setq column (current-column)))
21679 ;; Else, nothing noticeable found: get indentation and go on.
21680 (t (setq column (org-get-indentation))))))
21681 ;; Now apply indentation and move cursor accordingly
21682 (goto-char pos)
21683 (if (<= (current-column) (current-indentation))
21684 (org-indent-line-to column)
21685 (save-excursion (org-indent-line-to column)))
21686 ;; Special polishing for properties, see `org-property-format'
21687 (setq column (current-column))
21688 (beginning-of-line 1)
21689 (if (looking-at
21690 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21691 (replace-match (concat (match-string 1)
21692 (format org-property-format
21693 (match-string 2) (match-string 3)))
21694 t t))
21695 (org-move-to-column column))))
21697 (defun org-indent-drawer ()
21698 "Indent the drawer at point."
21699 (interactive)
21700 (let ((p (point))
21701 (e (and (save-excursion (re-search-forward ":END:" nil t))
21702 (match-end 0)))
21703 (folded
21704 (save-excursion
21705 (end-of-line)
21706 (when (overlays-at (point))
21707 (member 'invisible (overlay-properties
21708 (car (overlays-at (point)))))))))
21709 (when folded (org-cycle))
21710 (indent-for-tab-command)
21711 (while (and (move-beginning-of-line 2) (< (point) e))
21712 (indent-for-tab-command))
21713 (goto-char p)
21714 (when folded (org-cycle)))
21715 (message "Drawer at point indented"))
21717 (defun org-indent-block ()
21718 "Indent the block at point."
21719 (interactive)
21720 (let ((p (point))
21721 (case-fold-search t)
21722 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21723 (match-end 0)))
21724 (folded
21725 (save-excursion
21726 (end-of-line)
21727 (when (overlays-at (point))
21728 (member 'invisible (overlay-properties
21729 (car (overlays-at (point)))))))))
21730 (when folded (org-cycle))
21731 (indent-for-tab-command)
21732 (while (and (move-beginning-of-line 2) (< (point) e))
21733 (indent-for-tab-command))
21734 (goto-char p)
21735 (when folded (org-cycle)))
21736 (message "Block at point indented"))
21738 (defun org-indent-region (start end)
21739 "Indent region."
21740 (interactive "r")
21741 (save-excursion
21742 (let ((line-end (org-current-line end)))
21743 (goto-char start)
21744 (while (< (org-current-line) line-end)
21745 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21746 (t (call-interactively 'org-indent-line)))
21747 (move-beginning-of-line 2)))))
21750 ;;; Filling
21752 ;; We use our own fill-paragraph and auto-fill functions.
21754 ;; `org-fill-paragraph' relies on adaptive filling and context
21755 ;; checking. Appropriate `fill-prefix' is computed with
21756 ;; `org-adaptive-fill-function'.
21758 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21759 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21760 ;; `org-adaptive-fill-function' value. Internally,
21761 ;; `org-comment-line-break-function' breaks the line.
21763 ;; `org-setup-filling' installs filling and auto-filling related
21764 ;; variables during `org-mode' initialization.
21766 (defun org-setup-filling ()
21767 (interactive)
21768 ;; Prevent auto-fill from inserting unwanted new items.
21769 (when (boundp 'fill-nobreak-predicate)
21770 (org-set-local
21771 'fill-nobreak-predicate
21772 (org-uniquify
21773 (append fill-nobreak-predicate
21774 '(org-fill-paragraph-separate-nobreak-p
21775 org-fill-line-break-nobreak-p
21776 org-fill-paragraph-with-timestamp-nobreak-p)))))
21777 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21778 (org-set-local 'auto-fill-inhibit-regexp nil)
21779 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21780 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21781 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21783 (defvar org-element-paragraph-separate) ; org-element.el
21784 (defun org-fill-paragraph-separate-nobreak-p ()
21785 "Non-nil when a line break at point would insert a new item."
21786 (looking-at (substring org-element-paragraph-separate 1)))
21788 (defun org-fill-line-break-nobreak-p ()
21789 "Non-nil when a line break at point would create an Org line break."
21790 (save-excursion
21791 (skip-chars-backward "[ \t]")
21792 (skip-chars-backward "\\\\")
21793 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21795 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21796 "Non-nil when a line break at point would insert a new item."
21797 (and (org-at-timestamp-p t)
21798 (not (looking-at org-ts-regexp-both))))
21800 (declare-function message-in-body-p "message" ())
21801 (defvar orgtbl-line-start-regexp) ; From org-table.el
21802 (defun org-adaptive-fill-function ()
21803 "Compute a fill prefix for the current line.
21804 Return fill prefix, as a string, or nil if current line isn't
21805 meant to be filled."
21806 (let (prefix)
21807 (catch 'exit
21808 (when (derived-mode-p 'message-mode)
21809 (save-excursion
21810 (beginning-of-line)
21811 (cond ((or (not (message-in-body-p))
21812 (looking-at orgtbl-line-start-regexp))
21813 (throw 'exit nil))
21814 ((looking-at message-cite-prefix-regexp)
21815 (throw 'exit (match-string-no-properties 0)))
21816 ((looking-at org-outline-regexp)
21817 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21818 (org-with-wide-buffer
21819 (let* ((p (line-beginning-position))
21820 (element (save-excursion (beginning-of-line)
21821 (org-element-at-point)))
21822 (type (org-element-type element))
21823 (post-affiliated (org-element-property :post-affiliated element)))
21824 (unless (and post-affiliated (< p post-affiliated))
21825 (case type
21826 (comment (looking-at "[ \t]*# ?") (match-string 0))
21827 (footnote-definition "")
21828 ((item plain-list)
21829 (make-string (org-list-item-body-column
21830 (or post-affiliated
21831 (org-element-property :begin element)))
21832 ? ))
21833 (paragraph
21834 ;; Fill prefix is usually the same as the current line,
21835 ;; except if the paragraph is at the beginning of an item.
21836 (let ((parent (org-element-property :parent element)))
21837 (cond ((eq (org-element-type parent) 'item)
21838 (make-string (org-list-item-body-column
21839 (org-element-property :begin parent))
21840 ? ))
21841 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21842 (match-string 0))
21843 (t ""))))
21844 (comment-block
21845 ;; Only fill contents if P is within block boundaries.
21846 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21847 (forward-line)
21848 (point)))
21849 (cend (save-excursion
21850 (goto-char (org-element-property :end element))
21851 (skip-chars-backward " \r\t\n")
21852 (line-beginning-position))))
21853 (when (and (>= p cbeg) (< p cend))
21854 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21855 (match-string 0)
21856 "")))))))))))
21858 (declare-function message-goto-body "message" ())
21859 (defvar message-cite-prefix-regexp) ; From message.el
21860 (defun org-fill-paragraph (&optional justify)
21861 "Fill element at point, when applicable.
21863 This function only applies to comment blocks, comments, example
21864 blocks and paragraphs. Also, as a special case, re-align table
21865 when point is at one.
21867 If JUSTIFY is non-nil (interactively, with prefix argument),
21868 justify as well. If `sentence-end-double-space' is non-nil, then
21869 period followed by one space does not end a sentence, so don't
21870 break a line there. The variable `fill-column' controls the
21871 width for filling.
21873 For convenience, when point is at a plain list, an item or
21874 a footnote definition, try to fill the first paragraph within."
21875 (interactive)
21876 (if (and (derived-mode-p 'message-mode)
21877 (or (not (message-in-body-p))
21878 (save-excursion (move-beginning-of-line 1)
21879 (looking-at message-cite-prefix-regexp))))
21880 ;; First ensure filling is correct in message-mode.
21881 (let ((fill-paragraph-function
21882 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21883 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21884 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21885 (paragraph-separate
21886 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21887 (fill-paragraph nil))
21888 (with-syntax-table org-mode-transpose-word-syntax-table
21889 ;; Move to end of line in order to get the first paragraph
21890 ;; within a plain list or a footnote definition.
21891 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21892 ;; First check if point is in a blank line at the beginning of
21893 ;; the buffer. In that case, ignore filling.
21894 (case (org-element-type element)
21895 ;; Use major mode filling function is src blocks.
21896 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21897 ;; Align Org tables, leave table.el tables as-is.
21898 (table-row (org-table-align) t)
21899 (table
21900 (when (eq (org-element-property :type element) 'org)
21901 (org-table-align))
21903 (paragraph
21904 ;; Paragraphs may contain `line-break' type objects.
21905 (let ((beg (max (point-min)
21906 (org-element-property :contents-begin element)))
21907 (end (min (point-max)
21908 (org-element-property :contents-end element))))
21909 ;; Do nothing if point is at an affiliated keyword.
21910 (if (< (line-end-position) beg) t
21911 (when (derived-mode-p 'message-mode)
21912 ;; In `message-mode', do not fill following citation
21913 ;; in current paragraph nor text before message body.
21914 (let ((body-start (save-excursion (message-goto-body))))
21915 (when body-start (setq beg (max body-start beg))))
21916 (when (save-excursion
21917 (re-search-forward
21918 (concat "^" message-cite-prefix-regexp) end t))
21919 (setq end (match-beginning 0))))
21920 ;; Fill paragraph, taking line breaks into account.
21921 ;; For that, slice the paragraph using line breaks as
21922 ;; separators, and fill the parts in reverse order to
21923 ;; avoid messing with markers.
21924 (save-excursion
21925 (goto-char end)
21926 (mapc
21927 (lambda (pos)
21928 (fill-region-as-paragraph pos (point) justify)
21929 (goto-char pos))
21930 ;; Find the list of ending positions for line breaks
21931 ;; in the current paragraph. Add paragraph
21932 ;; beginning to include first slice.
21933 (nreverse
21934 (cons beg
21935 (org-element-map
21936 (org-element--parse-objects
21937 beg end nil (org-element-restriction 'paragraph))
21938 'line-break
21939 (lambda (lb) (org-element-property :end lb)))))))
21940 t)))
21941 ;; Contents of `comment-block' type elements should be
21942 ;; filled as plain text, but only if point is within block
21943 ;; markers.
21944 (comment-block
21945 (let* ((case-fold-search t)
21946 (beg (save-excursion
21947 (goto-char (org-element-property :begin element))
21948 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21949 (forward-line)
21950 (point)))
21951 (end (save-excursion
21952 (goto-char (org-element-property :end element))
21953 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21954 (line-beginning-position))))
21955 (when (and (>= (point) beg) (< (point) end))
21956 (fill-region-as-paragraph
21957 (save-excursion
21958 (end-of-line)
21959 (re-search-backward "^[ \t]*$" beg 'move)
21960 (line-beginning-position))
21961 (save-excursion
21962 (beginning-of-line)
21963 (re-search-forward "^[ \t]*$" end 'move)
21964 (line-beginning-position))
21965 justify)))
21967 ;; Fill comments.
21968 (comment (fill-comment-paragraph justify))
21969 ;; Ignore every other element.
21970 (otherwise t))))))
21972 (defun org-auto-fill-function ()
21973 "Auto-fill function."
21974 ;; Check if auto-filling is meaningful.
21975 (let ((fc (current-fill-column)))
21976 (when (and fc (> (current-column) fc))
21977 (let* ((fill-prefix (org-adaptive-fill-function))
21978 ;; Enforce empty fill prefix, if required. Otherwise, it
21979 ;; will be computed again.
21980 (adaptive-fill-mode (not (equal fill-prefix ""))))
21981 (when fill-prefix (do-auto-fill))))))
21983 (defun org-comment-line-break-function (&optional soft)
21984 "Break line at point and indent, continuing comment if within one.
21985 The inserted newline is marked hard if variable
21986 `use-hard-newlines' is true, unless optional argument SOFT is
21987 non-nil."
21988 (if soft (insert-and-inherit ?\n) (newline 1))
21989 (save-excursion (forward-char -1) (delete-horizontal-space))
21990 (delete-horizontal-space)
21991 (indent-to-left-margin)
21992 (insert-before-markers-and-inherit fill-prefix))
21995 ;;; Comments
21997 ;; Org comments syntax is quite complex. It requires the entire line
21998 ;; to be just a comment. Also, even with the right syntax at the
21999 ;; beginning of line, some some elements (i.e. verse-block or
22000 ;; example-block) don't accept comments. Usual Emacs comment commands
22001 ;; cannot cope with those requirements. Therefore, Org replaces them.
22003 ;; Org still relies on `comment-dwim', but cannot trust
22004 ;; `comment-only-p'. So, `comment-region-function' and
22005 ;; `uncomment-region-function' both point
22006 ;; to`org-comment-or-uncomment-region'. Eventually,
22007 ;; `org-insert-comment' takes care of insertion of comments at the
22008 ;; beginning of line.
22010 ;; `org-setup-comments-handling' install comments related variables
22011 ;; during `org-mode' initialization.
22013 (defun org-setup-comments-handling ()
22014 (interactive)
22015 (org-set-local 'comment-use-syntax nil)
22016 (org-set-local 'comment-start "# ")
22017 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22018 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22019 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22020 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22022 (defun org-insert-comment ()
22023 "Insert an empty comment above current line.
22024 If the line is empty, insert comment at its beginning."
22025 (beginning-of-line)
22026 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22027 (org-indent-line)
22028 (insert "# "))
22030 (defvar comment-empty-lines) ; From newcomment.el.
22031 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22032 "Comment or uncomment each non-blank line in the region.
22033 Uncomment each non-blank line between BEG and END if it only
22034 contains commented lines. Otherwise, comment them."
22035 (save-restriction
22036 ;; Restrict region
22037 (narrow-to-region (save-excursion (goto-char beg)
22038 (skip-chars-forward " \r\t\n" end)
22039 (line-beginning-position))
22040 (save-excursion (goto-char end)
22041 (skip-chars-backward " \r\t\n" beg)
22042 (line-end-position)))
22043 (let ((uncommentp
22044 ;; UNCOMMENTP is non-nil when every non blank line between
22045 ;; BEG and END is a comment.
22046 (save-excursion
22047 (goto-char (point-min))
22048 (while (and (not (eobp))
22049 (let ((element (org-element-at-point)))
22050 (and (eq (org-element-type element) 'comment)
22051 (goto-char (min (point-max)
22052 (org-element-property
22053 :end element)))))))
22054 (eobp))))
22055 (if uncommentp
22056 ;; Only blank lines and comments in region: uncomment it.
22057 (save-excursion
22058 (goto-char (point-min))
22059 (while (not (eobp))
22060 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22061 (replace-match "" nil nil nil 1))
22062 (forward-line)))
22063 ;; Comment each line in region.
22064 (let ((min-indent (point-max)))
22065 ;; First find the minimum indentation across all lines.
22066 (save-excursion
22067 (goto-char (point-min))
22068 (while (and (not (eobp)) (not (zerop min-indent)))
22069 (unless (looking-at "[ \t]*$")
22070 (setq min-indent (min min-indent (current-indentation))))
22071 (forward-line)))
22072 ;; Then loop over all lines.
22073 (save-excursion
22074 (goto-char (point-min))
22075 (while (not (eobp))
22076 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22077 ;; Don't get fooled by invisible text (e.g. link path)
22078 ;; when moving to column MIN-INDENT.
22079 (let ((buffer-invisibility-spec nil))
22080 (org-move-to-column min-indent t))
22081 (insert comment-start))
22082 (forward-line))))))))
22085 ;;; Planning
22087 ;; This section contains tools to operate on timestamp objects, as
22088 ;; returned by, e.g. `org-element-context'.
22090 (defun org-timestamp-has-time-p (timestamp)
22091 "Non-nil when TIMESTAMP has a time specified."
22092 (org-element-property :hour-start timestamp))
22094 (defun org-timestamp-format (timestamp format &optional end utc)
22095 "Format a TIMESTAMP element into a string.
22097 FORMAT is a format specifier to be passed to
22098 `format-time-string'.
22100 When optional argument END is non-nil, use end of date-range or
22101 time-range, if possible.
22103 When optional argument UTC is non-nil, time will be expressed as
22104 Universal Time."
22105 (format-time-string
22106 format
22107 (apply 'encode-time
22108 (cons 0
22109 (mapcar
22110 (lambda (prop) (or (org-element-property prop timestamp) 0))
22111 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22112 '(:minute-start :hour-start :day-start :month-start
22113 :year-start)))))
22114 utc))
22116 (defun org-timestamp-split-range (timestamp &optional end)
22117 "Extract a timestamp object from a date or time range.
22119 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22120 the end of the range. Otherwise, extract its start.
22122 Return a new timestamp object sharing the same parent as
22123 TIMESTAMP."
22124 (let ((type (org-element-property :type timestamp)))
22125 (if (memq type '(active inactive diary)) timestamp
22126 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22127 ;; Set new type.
22128 (org-element-put-property
22129 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22130 ;; Copy start properties over end properties if END is
22131 ;; non-nil. Otherwise, copy end properties over `start' ones.
22132 (let ((p-alist '((:minute-start . :minute-end)
22133 (:hour-start . :hour-end)
22134 (:day-start . :day-end)
22135 (:month-start . :month-end)
22136 (:year-start . :year-end))))
22137 (dolist (p-cell p-alist)
22138 (org-element-put-property
22139 split-ts
22140 (funcall (if end 'car 'cdr) p-cell)
22141 (org-element-property
22142 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22143 ;; Eventually refresh `:raw-value'.
22144 (org-element-put-property split-ts :raw-value nil)
22145 (org-element-put-property
22146 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22148 (defun org-timestamp-translate (timestamp &optional boundary)
22149 "Apply `org-translate-time' on a TIMESTAMP object.
22150 When optional argument BOUNDARY is non-nil, it is either the
22151 symbol `start' or `end'. In this case, only translate the
22152 starting or ending part of TIMESTAMP if it is a date or time
22153 range. Otherwise, translate both parts."
22154 (if (and (not boundary)
22155 (memq (org-element-property :type timestamp)
22156 '(active-range inactive-range)))
22157 (concat
22158 (org-translate-time
22159 (org-element-property :raw-value
22160 (org-timestamp-split-range timestamp)))
22161 "--"
22162 (org-translate-time
22163 (org-element-property :raw-value
22164 (org-timestamp-split-range timestamp t))))
22165 (org-translate-time
22166 (org-element-property
22167 :raw-value
22168 (if (not boundary) timestamp
22169 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22173 ;;; Other stuff.
22175 (defun org-toggle-fixed-width-section (arg)
22176 "Toggle the fixed-width export.
22177 If there is no active region, the QUOTE keyword at the current headline is
22178 inserted or removed. When present, it causes the text between this headline
22179 and the next to be exported as fixed-width text, and unmodified.
22180 If there is an active region, this command adds or removes a colon as the
22181 first character of this line. If the first character of a line is a colon,
22182 this line is also exported in fixed-width font."
22183 (interactive "P")
22184 (let* ((cc 0)
22185 (regionp (org-region-active-p))
22186 (beg (if regionp (region-beginning) (point)))
22187 (end (if regionp (region-end)))
22188 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22189 (case-fold-search nil)
22190 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22191 off)
22192 (if regionp
22193 (save-excursion
22194 (goto-char beg)
22195 (setq cc (current-column))
22196 (beginning-of-line 1)
22197 (setq off (looking-at re))
22198 (while (> nlines 0)
22199 (setq nlines (1- nlines))
22200 (beginning-of-line 1)
22201 (cond
22202 (arg
22203 (org-move-to-column cc t)
22204 (insert ": \n")
22205 (forward-line -1))
22206 ((and off (looking-at re))
22207 (replace-match "" t t nil 1))
22208 ((not off) (org-move-to-column cc t) (insert ": ")))
22209 (forward-line 1)))
22210 (save-excursion
22211 (org-back-to-heading)
22212 (cond
22213 ((looking-at (format org-heading-keyword-regexp-format
22214 org-quote-string))
22215 (goto-char (match-end 1))
22216 (looking-at (concat " +" org-quote-string))
22217 (replace-match "" t t)
22218 (when (eolp) (insert " ")))
22219 ((looking-at org-outline-regexp)
22220 (goto-char (match-end 0))
22221 (insert org-quote-string " ")))))))
22223 (defun org-reftex-citation ()
22224 "Use reftex-citation to insert a citation into the buffer.
22225 This looks for a line like
22227 #+BIBLIOGRAPHY: foo plain option:-d
22229 and derives from it that foo.bib is the bibliography file relevant
22230 for this document. It then installs the necessary environment for RefTeX
22231 to work in this buffer and calls `reftex-citation' to insert a citation
22232 into the buffer.
22234 Export of such citations to both LaTeX and HTML is handled by the contributed
22235 package org-exp-bibtex by Taru Karttunen."
22236 (interactive)
22237 (let ((reftex-docstruct-symbol 'rds)
22238 (reftex-cite-format "\\cite{%l}")
22239 rds bib)
22240 (save-excursion
22241 (save-restriction
22242 (widen)
22243 (let ((case-fold-search t)
22244 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22245 (if (not (save-excursion
22246 (or (re-search-forward re nil t)
22247 (re-search-backward re nil t))))
22248 (error "No bibliography defined in file")
22249 (setq bib (concat (match-string 1) ".bib")
22250 rds (list (list 'bib bib)))))))
22251 (call-interactively 'reftex-citation)))
22253 ;;;; Functions extending outline functionality
22255 (defun org-beginning-of-line (&optional arg)
22256 "Go to the beginning of the current line. If that is invisible, continue
22257 to a visible line beginning. This makes the function of C-a more intuitive.
22258 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22259 first attempt, and only move to after the tags when the cursor is already
22260 beyond the end of the headline."
22261 (interactive "P")
22262 (let ((pos (point))
22263 (special (if (consp org-special-ctrl-a/e)
22264 (car org-special-ctrl-a/e)
22265 org-special-ctrl-a/e))
22266 refpos)
22267 (if (org-bound-and-true-p visual-line-mode)
22268 (beginning-of-visual-line 1)
22269 (beginning-of-line 1))
22270 (if (and arg (fboundp 'move-beginning-of-line))
22271 (call-interactively 'move-beginning-of-line)
22272 (if (bobp)
22274 (backward-char 1)
22275 (if (org-truely-invisible-p)
22276 (while (and (not (bobp)) (org-truely-invisible-p))
22277 (backward-char 1)
22278 (beginning-of-line 1))
22279 (forward-char 1))))
22280 (when special
22281 (cond
22282 ((and (looking-at org-complex-heading-regexp)
22283 (= (char-after (match-end 1)) ?\ ))
22284 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22285 (point-at-eol)))
22286 (goto-char
22287 (if (eq special t)
22288 (cond ((> pos refpos) refpos)
22289 ((= pos (point)) refpos)
22290 (t (point)))
22291 (cond ((> pos (point)) (point))
22292 ((not (eq last-command this-command)) (point))
22293 (t refpos)))))
22294 ((org-at-item-p)
22295 ;; Being at an item and not looking at an the item means point
22296 ;; was previously moved to beginning of a visual line, which
22297 ;; doesn't contain the item. Therefore, do nothing special,
22298 ;; just stay here.
22299 (when (looking-at org-list-full-item-re)
22300 ;; Set special position at first white space character after
22301 ;; bullet, and check-box, if any.
22302 (let ((after-bullet
22303 (let ((box (match-end 3)))
22304 (if (not box) (match-end 1)
22305 (let ((after (char-after box)))
22306 (if (and after (= after ? )) (1+ box) box))))))
22307 ;; Special case: Move point to special position when
22308 ;; currently after it or at beginning of line.
22309 (if (eq special t)
22310 (when (or (> pos after-bullet) (= (point) pos))
22311 (goto-char after-bullet))
22312 ;; Reversed case: Move point to special position when
22313 ;; point was already at beginning of line and command is
22314 ;; repeated.
22315 (when (and (= (point) pos) (eq last-command this-command))
22316 (goto-char after-bullet))))))))
22317 (org-no-warnings
22318 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22320 (defun org-end-of-line (&optional arg)
22321 "Go to the end of the line.
22322 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22323 tags on the first attempt, and only move to after the tags when
22324 the cursor is already beyond the end of the headline."
22325 (interactive "P")
22326 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22327 org-special-ctrl-a/e))
22328 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22329 'end-of-visual-line)
22330 ((fboundp 'move-end-of-line) 'move-end-of-line)
22331 (t 'end-of-line))))
22332 (if (or (not special) arg) (call-interactively move-fun)
22333 (let* ((element (save-excursion (beginning-of-line)
22334 (org-element-at-point)))
22335 (type (org-element-type element)))
22336 (cond
22337 ((memq type '(headline inlinetask))
22338 (let ((pos (point)))
22339 (beginning-of-line 1)
22340 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22341 (if (eq special t)
22342 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22343 (goto-char (match-beginning 1))
22344 (goto-char (match-end 0)))
22345 (if (or (< pos (match-end 0))
22346 (not (eq this-command last-command)))
22347 (goto-char (match-end 0))
22348 (goto-char (match-beginning 1))))
22349 (call-interactively move-fun))))
22350 ((org-element-property :hiddenp element)
22351 ;; If element is hidden, `move-end-of-line' would put point
22352 ;; after it. Use `end-of-line' to stay on current line.
22353 (call-interactively 'end-of-line))
22354 (t (call-interactively move-fun)))))
22355 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22357 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22358 (define-key org-mode-map "\C-e" 'org-end-of-line)
22360 (defun org-backward-sentence (&optional arg)
22361 "Go to beginning of sentence, or beginning of table field.
22362 This will call `backward-sentence' or `org-table-beginning-of-field',
22363 depending on context."
22364 (interactive "P")
22365 (cond
22366 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22367 (t (call-interactively 'backward-sentence))))
22369 (defun org-forward-sentence (&optional arg)
22370 "Go to end of sentence, or end of table field.
22371 This will call `forward-sentence' or `org-table-end-of-field',
22372 depending on context."
22373 (interactive "P")
22374 (cond
22375 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22376 (t (call-interactively 'forward-sentence))))
22378 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22379 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22381 (defun org-kill-line (&optional arg)
22382 "Kill line, to tags or end of line."
22383 (interactive "P")
22384 (cond
22385 ((or (not org-special-ctrl-k)
22386 (bolp)
22387 (not (org-at-heading-p)))
22388 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22389 org-ctrl-k-protect-subtree)
22390 (if (or (eq org-ctrl-k-protect-subtree 'error)
22391 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22392 (error "C-k aborted - would kill hidden subtree")))
22393 (call-interactively
22394 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22395 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22396 (kill-region (point) (match-beginning 1))
22397 (org-set-tags nil t))
22398 (t (kill-region (point) (point-at-eol)))))
22400 (define-key org-mode-map "\C-k" 'org-kill-line)
22402 (defun org-yank (&optional arg)
22403 "Yank. If the kill is a subtree, treat it specially.
22404 This command will look at the current kill and check if is a single
22405 subtree, or a series of subtrees[1]. If it passes the test, and if the
22406 cursor is at the beginning of a line or after the stars of a currently
22407 empty headline, then the yank is handled specially. How exactly depends
22408 on the value of the following variables, both set by default.
22410 org-yank-folded-subtrees
22411 When set, the subtree(s) will be folded after insertion, but only
22412 if doing so would now swallow text after the yanked text.
22414 org-yank-adjusted-subtrees
22415 When set, the subtree will be promoted or demoted in order to
22416 fit into the local outline tree structure, which means that the level
22417 will be adjusted so that it becomes the smaller one of the two
22418 *visible* surrounding headings.
22420 Any prefix to this command will cause `yank' to be called directly with
22421 no special treatment. In particular, a simple \\[universal-argument] prefix \
22422 will just
22423 plainly yank the text as it is.
22425 \[1] The test checks if the first non-white line is a heading
22426 and if there are no other headings with fewer stars."
22427 (interactive "P")
22428 (org-yank-generic 'yank arg))
22430 (defun org-yank-generic (command arg)
22431 "Perform some yank-like command.
22433 This function implements the behavior described in the `org-yank'
22434 documentation. However, it has been generalized to work for any
22435 interactive command with similar behavior."
22437 ;; pretend to be command COMMAND
22438 (setq this-command command)
22440 (if arg
22441 (call-interactively command)
22443 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22444 (and (org-kill-is-subtree-p)
22445 (or (bolp)
22446 (and (looking-at "[ \t]*$")
22447 (string-match
22448 "\\`\\*+\\'"
22449 (buffer-substring (point-at-bol) (point)))))))
22450 swallowp)
22451 (cond
22452 ((and subtreep org-yank-folded-subtrees)
22453 (let ((beg (point))
22454 end)
22455 (if (and subtreep org-yank-adjusted-subtrees)
22456 (org-paste-subtree nil nil 'for-yank)
22457 (call-interactively command))
22459 (setq end (point))
22460 (goto-char beg)
22461 (when (and (bolp) subtreep
22462 (not (setq swallowp
22463 (org-yank-folding-would-swallow-text beg end))))
22464 (org-with-limited-levels
22465 (or (looking-at org-outline-regexp)
22466 (re-search-forward org-outline-regexp-bol end t))
22467 (while (and (< (point) end) (looking-at org-outline-regexp))
22468 (hide-subtree)
22469 (org-cycle-show-empty-lines 'folded)
22470 (condition-case nil
22471 (outline-forward-same-level 1)
22472 (error (goto-char end))))))
22473 (when swallowp
22474 (message
22475 "Inserted text not folded because that would swallow text"))
22477 (goto-char end)
22478 (skip-chars-forward " \t\n\r")
22479 (beginning-of-line 1)
22480 (push-mark beg 'nomsg)))
22481 ((and subtreep org-yank-adjusted-subtrees)
22482 (let ((beg (point-at-bol)))
22483 (org-paste-subtree nil nil 'for-yank)
22484 (push-mark beg 'nomsg)))
22486 (call-interactively command))))))
22488 (defun org-yank-folding-would-swallow-text (beg end)
22489 "Would hide-subtree at BEG swallow any text after END?"
22490 (let (level)
22491 (org-with-limited-levels
22492 (save-excursion
22493 (goto-char beg)
22494 (when (or (looking-at org-outline-regexp)
22495 (re-search-forward org-outline-regexp-bol end t))
22496 (setq level (org-outline-level)))
22497 (goto-char end)
22498 (skip-chars-forward " \t\r\n\v\f")
22499 (if (or (eobp)
22500 (and (bolp) (looking-at org-outline-regexp)
22501 (<= (org-outline-level) level)))
22502 nil ; Nothing would be swallowed
22503 t))))) ; something would swallow
22505 (define-key org-mode-map "\C-y" 'org-yank)
22507 (defun org-truely-invisible-p ()
22508 "Check if point is at a character currently not visible.
22509 This version does not only check the character property, but also
22510 `visible-mode'."
22511 ;; Early versions of noutline don't have `outline-invisible-p'.
22512 (if (org-bound-and-true-p visible-mode)
22514 (outline-invisible-p)))
22516 (defun org-invisible-p2 ()
22517 "Check if point is at a character currently not visible."
22518 (save-excursion
22519 (if (and (eolp) (not (bobp))) (backward-char 1))
22520 ;; Early versions of noutline don't have `outline-invisible-p'.
22521 (outline-invisible-p)))
22523 (defun org-back-to-heading (&optional invisible-ok)
22524 "Call `outline-back-to-heading', but provide a better error message."
22525 (condition-case nil
22526 (outline-back-to-heading invisible-ok)
22527 (error (error "Before first headline at position %d in buffer %s"
22528 (point) (current-buffer)))))
22530 (defun org-before-first-heading-p ()
22531 "Before first heading?"
22532 (save-excursion
22533 (end-of-line)
22534 (null (re-search-backward org-outline-regexp-bol nil t))))
22536 (defun org-at-heading-p (&optional ignored)
22537 (outline-on-heading-p t))
22538 ;; Compatibility alias with Org versions < 7.8.03
22539 (defalias 'org-on-heading-p 'org-at-heading-p)
22541 (defun org-at-comment-p nil
22542 "Is cursor in a line starting with a # character?"
22543 (save-excursion
22544 (beginning-of-line)
22545 (looking-at "^#")))
22547 (defun org-at-drawer-p nil
22548 "Is cursor at a drawer keyword?"
22549 (save-excursion
22550 (move-beginning-of-line 1)
22551 (looking-at org-drawer-regexp)))
22553 (defun org-at-block-p nil
22554 "Is cursor at a block keyword?"
22555 (save-excursion
22556 (move-beginning-of-line 1)
22557 (looking-at org-block-regexp)))
22559 (defun org-point-at-end-of-empty-headline ()
22560 "If point is at the end of an empty headline, return t, else nil.
22561 If the heading only contains a TODO keyword, it is still still considered
22562 empty."
22563 (and (looking-at "[ \t]*$")
22564 (when org-todo-line-regexp
22565 (save-excursion
22566 (beginning-of-line 1)
22567 (let ((case-fold-search nil))
22568 (looking-at org-todo-line-regexp)
22569 (string= (match-string 3) ""))))))
22571 (defun org-at-heading-or-item-p ()
22572 (or (org-at-heading-p) (org-at-item-p)))
22574 (defun org-at-target-p ()
22575 (or (org-in-regexp org-radio-target-regexp)
22576 (org-in-regexp org-target-regexp)))
22577 ;; Compatibility alias with Org versions < 7.8.03
22578 (defalias 'org-on-target-p 'org-at-target-p)
22580 (defun org-up-heading-all (arg)
22581 "Move to the heading line of which the present line is a subheading.
22582 This function considers both visible and invisible heading lines.
22583 With argument, move up ARG levels."
22584 (if (fboundp 'outline-up-heading-all)
22585 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22586 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22588 (defun org-up-heading-safe ()
22589 "Move to the heading line of which the present line is a subheading.
22590 This version will not throw an error. It will return the level of the
22591 headline found, or nil if no higher level is found.
22593 Also, this function will be a lot faster than `outline-up-heading',
22594 because it relies on stars being the outline starters. This can really
22595 make a significant difference in outlines with very many siblings."
22596 (let (start-level re)
22597 (org-back-to-heading t)
22598 (setq start-level (funcall outline-level))
22599 (if (equal start-level 1)
22601 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22602 (if (re-search-backward re nil t)
22603 (funcall outline-level)))))
22605 (defun org-first-sibling-p ()
22606 "Is this heading the first child of its parents?"
22607 (interactive)
22608 (let ((re org-outline-regexp-bol)
22609 level l)
22610 (unless (org-at-heading-p t)
22611 (error "Not at a heading"))
22612 (setq level (funcall outline-level))
22613 (save-excursion
22614 (if (not (re-search-backward re nil t))
22616 (setq l (funcall outline-level))
22617 (< l level)))))
22619 (defun org-goto-sibling (&optional previous)
22620 "Goto the next sibling, even if it is invisible.
22621 When PREVIOUS is set, go to the previous sibling instead. Returns t
22622 when a sibling was found. When none is found, return nil and don't
22623 move point."
22624 (let ((fun (if previous 're-search-backward 're-search-forward))
22625 (pos (point))
22626 (re org-outline-regexp-bol)
22627 level l)
22628 (when (condition-case nil (org-back-to-heading t) (error nil))
22629 (setq level (funcall outline-level))
22630 (catch 'exit
22631 (or previous (forward-char 1))
22632 (while (funcall fun re nil t)
22633 (setq l (funcall outline-level))
22634 (when (< l level) (goto-char pos) (throw 'exit nil))
22635 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22636 (goto-char pos)
22637 nil))))
22639 (defun org-show-siblings ()
22640 "Show all siblings of the current headline."
22641 (save-excursion
22642 (while (org-goto-sibling) (org-flag-heading nil)))
22643 (save-excursion
22644 (while (org-goto-sibling 'previous)
22645 (org-flag-heading nil))))
22647 (defun org-goto-first-child ()
22648 "Goto the first child, even if it is invisible.
22649 Return t when a child was found. Otherwise don't move point and
22650 return nil."
22651 (let (level (pos (point)) (re org-outline-regexp-bol))
22652 (when (condition-case nil (org-back-to-heading t) (error nil))
22653 (setq level (outline-level))
22654 (forward-char 1)
22655 (if (and (re-search-forward re nil t) (> (outline-level) level))
22656 (progn (goto-char (match-beginning 0)) t)
22657 (goto-char pos) nil))))
22659 (defun org-show-hidden-entry ()
22660 "Show an entry where even the heading is hidden."
22661 (save-excursion
22662 (org-show-entry)))
22664 (defun org-flag-heading (flag &optional entry)
22665 "Flag the current heading. FLAG non-nil means make invisible.
22666 When ENTRY is non-nil, show the entire entry."
22667 (save-excursion
22668 (org-back-to-heading t)
22669 ;; Check if we should show the entire entry
22670 (if entry
22671 (progn
22672 (org-show-entry)
22673 (save-excursion
22674 (and (outline-next-heading)
22675 (org-flag-heading nil))))
22676 (outline-flag-region (max (point-min) (1- (point)))
22677 (save-excursion (outline-end-of-heading) (point))
22678 flag))))
22680 (defun org-get-next-sibling ()
22681 "Move to next heading of the same level, and return point.
22682 If there is no such heading, return nil.
22683 This is like outline-next-sibling, but invisible headings are ok."
22684 (let ((level (funcall outline-level)))
22685 (outline-next-heading)
22686 (while (and (not (eobp)) (> (funcall outline-level) level))
22687 (outline-next-heading))
22688 (if (or (eobp) (< (funcall outline-level) level))
22690 (point))))
22692 (defun org-get-last-sibling ()
22693 "Move to previous heading of the same level, and return point.
22694 If there is no such heading, return nil."
22695 (let ((opoint (point))
22696 (level (funcall outline-level)))
22697 (outline-previous-heading)
22698 (when (and (/= (point) opoint) (outline-on-heading-p t))
22699 (while (and (> (funcall outline-level) level)
22700 (not (bobp)))
22701 (outline-previous-heading))
22702 (if (< (funcall outline-level) level)
22704 (point)))))
22706 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22707 "Goto to the end of a subtree."
22708 ;; This contains an exact copy of the original function, but it uses
22709 ;; `org-back-to-heading', to make it work also in invisible
22710 ;; trees. And is uses an invisible-ok argument.
22711 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22712 ;; Furthermore, when used inside Org, finding the end of a large subtree
22713 ;; with many children and grandchildren etc, this can be much faster
22714 ;; than the outline version.
22715 (org-back-to-heading invisible-ok)
22716 (let ((first t)
22717 (level (funcall outline-level)))
22718 (if (and (derived-mode-p 'org-mode) (< level 1000))
22719 ;; A true heading (not a plain list item), in Org-mode
22720 ;; This means we can easily find the end by looking
22721 ;; only for the right number of stars. Using a regexp to do
22722 ;; this is so much faster than using a Lisp loop.
22723 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22724 (forward-char 1)
22725 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22726 ;; something else, do it the slow way
22727 (while (and (not (eobp))
22728 (or first (> (funcall outline-level) level)))
22729 (setq first nil)
22730 (outline-next-heading)))
22731 (unless to-heading
22732 (if (memq (preceding-char) '(?\n ?\^M))
22733 (progn
22734 ;; Go to end of line before heading
22735 (forward-char -1)
22736 (if (memq (preceding-char) '(?\n ?\^M))
22737 ;; leave blank line before heading
22738 (forward-char -1))))))
22739 (point))
22741 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22742 "Use Org version in org-mode, for dramatic speed-up."
22743 (if (derived-mode-p 'org-mode)
22744 (progn
22745 (org-end-of-subtree nil t)
22746 (unless (eobp) (backward-char 1)))
22747 ad-do-it))
22749 (defun org-end-of-meta-data-and-drawers ()
22750 "Jump to the first text after meta data and drawers in the current entry.
22751 This will move over empty lines, lines with planning time stamps,
22752 clocking lines, and drawers."
22753 (org-back-to-heading t)
22754 (let ((end (save-excursion (outline-next-heading) (point)))
22755 (re (concat "\\(" org-drawer-regexp "\\)"
22756 "\\|" "[ \t]*" org-keyword-time-regexp)))
22757 (forward-line 1)
22758 (while (re-search-forward re end t)
22759 (if (not (match-end 1))
22760 ;; empty or planning line
22761 (forward-line 1)
22762 ;; a drawer, find the end
22763 (re-search-forward "^[ \t]*:END:" end 'move)
22764 (forward-line 1)))
22765 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22766 (point)))
22768 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22769 "Move forward to the ARG'th subheading at same level as this one.
22770 Stop at the first and last subheadings of a superior heading.
22771 Normally this only looks at visible headings, but when INVISIBLE-OK is
22772 non-nil it will also look at invisible ones."
22773 (interactive "p")
22774 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22775 (if (and arg (< arg 0))
22776 (goto-char (point-min))
22777 (outline-next-heading))
22778 (org-at-heading-p)
22779 (let ((level (- (match-end 0) (match-beginning 0) 1))
22780 (f (if (and arg (< arg 0))
22781 're-search-backward
22782 're-search-forward))
22783 (count (if arg (abs arg) 1))
22784 (result (point)))
22785 (forward-char (if (and arg (< arg 0)) -1 1))
22786 (while (and (> count 0)
22787 (funcall f org-outline-regexp-bol nil 'move))
22788 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22789 (cond ((< l level) (setq count 0))
22790 ((and (= l level)
22791 (or invisible-ok
22792 (progn
22793 (goto-char (line-beginning-position))
22794 (not (outline-invisible-p)))))
22795 (setq count (1- count))
22796 (when (eq l level)
22797 (setq result (point)))))))
22798 (goto-char result))
22799 (beginning-of-line 1)))
22801 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22802 "Move backward to the ARG'th subheading at same level as this one.
22803 Stop at the first and last subheadings of a superior heading."
22804 (interactive "p")
22805 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22807 (defun org-next-block (arg &optional backward block-regexp)
22808 "Jump to the next block.
22809 With a prefix argument ARG, jump forward ARG many source blocks.
22810 When BACKWARD is non-nil, jump to the previous block.
22811 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22812 (interactive "p")
22813 (let ((re (or block-regexp org-block-regexp))
22814 (re-search-fn (or (and backward 're-search-backward)
22815 're-search-forward)))
22816 (if (looking-at re) (forward-char 1))
22817 (condition-case nil
22818 (funcall re-search-fn re nil nil arg)
22819 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22820 (goto-char (match-beginning 0)) (org-show-context)))
22822 (defun org-previous-block (arg &optional block-regexp)
22823 "Jump to the previous block.
22824 With a prefix argument ARG, jump backward ARG many source blocks.
22825 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22826 (interactive "p")
22827 (org-next-block arg t block-regexp))
22829 (defun org-forward-element ()
22830 "Move forward by one element.
22831 Move to the next element at the same level, when possible."
22832 (interactive)
22833 (cond ((eobp) (user-error "Cannot move further down"))
22834 ((org-with-limited-levels (org-at-heading-p))
22835 (let ((origin (point)))
22836 (goto-char (org-end-of-subtree nil t))
22837 (unless (org-with-limited-levels (org-at-heading-p))
22838 (goto-char origin)
22839 (user-error "Cannot move further down"))))
22841 (let* ((elem (org-element-at-point))
22842 (end (org-element-property :end elem))
22843 (parent (org-element-property :parent elem)))
22844 (if (and parent (= (org-element-property :contents-end parent) end))
22845 (goto-char (org-element-property :end parent))
22846 (goto-char end))))))
22848 (defun org-backward-element ()
22849 "Move backward by one element.
22850 Move to the previous element at the same level, when possible."
22851 (interactive)
22852 (cond ((bobp) (user-error "Cannot move further up"))
22853 ((org-with-limited-levels (org-at-heading-p))
22854 ;; At a headline, move to the previous one, if any, or stay
22855 ;; here.
22856 (let ((origin (point)))
22857 (org-with-limited-levels (org-backward-heading-same-level 1))
22858 ;; When current headline has no sibling above, move to its
22859 ;; parent.
22860 (when (= (point) origin)
22861 (or (org-with-limited-levels (org-up-heading-safe))
22862 (progn (goto-char origin)
22863 (user-error "Cannot move further up"))))))
22865 (let* ((trail (org-element-at-point 'keep-trail))
22866 (elem (car trail))
22867 (prev-elem (nth 1 trail))
22868 (beg (org-element-property :begin elem)))
22869 (cond
22870 ;; Move to beginning of current element if point isn't
22871 ;; there already.
22872 ((/= (point) beg) (goto-char beg))
22873 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22874 ((org-before-first-heading-p) (goto-char (point-min)))
22875 (t (org-back-to-heading)))))))
22877 (defun org-up-element ()
22878 "Move to upper element."
22879 (interactive)
22880 (if (org-with-limited-levels (org-at-heading-p))
22881 (unless (org-up-heading-safe) (error "No surrounding element"))
22882 (let* ((elem (org-element-at-point))
22883 (parent (org-element-property :parent elem)))
22884 (if parent (goto-char (org-element-property :begin parent))
22885 (if (org-with-limited-levels (org-before-first-heading-p))
22886 (error "No surrounding element")
22887 (org-with-limited-levels (org-back-to-heading)))))))
22889 (defvar org-element-greater-elements)
22890 (defun org-down-element ()
22891 "Move to inner element."
22892 (interactive)
22893 (let ((element (org-element-at-point)))
22894 (cond
22895 ((memq (org-element-type element) '(plain-list table))
22896 (goto-char (org-element-property :contents-begin element))
22897 (forward-char))
22898 ((memq (org-element-type element) org-element-greater-elements)
22899 ;; If contents are hidden, first disclose them.
22900 (when (org-element-property :hiddenp element) (org-cycle))
22901 (goto-char (or (org-element-property :contents-begin element)
22902 (error "No content for this element"))))
22903 (t (error "No inner element")))))
22905 (defun org-drag-element-backward ()
22906 "Move backward element at point."
22907 (interactive)
22908 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22909 (let* ((trail (org-element-at-point 'keep-trail))
22910 (elem (car trail))
22911 (prev-elem (nth 1 trail)))
22912 ;; Error out if no previous element or previous element is
22913 ;; a parent of the current one.
22914 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22915 (error "Cannot drag element backward")
22916 (let ((pos (point)))
22917 (org-element-swap-A-B prev-elem elem)
22918 (goto-char (+ (org-element-property :begin prev-elem)
22919 (- pos (org-element-property :begin elem)))))))))
22921 (defun org-drag-element-forward ()
22922 "Move forward element at point."
22923 (interactive)
22924 (let* ((pos (point))
22925 (elem (org-element-at-point)))
22926 (when (= (point-max) (org-element-property :end elem))
22927 (error "Cannot drag element forward"))
22928 (goto-char (org-element-property :end elem))
22929 (let ((next-elem (org-element-at-point)))
22930 (when (or (org-element-nested-p elem next-elem)
22931 (and (eq (org-element-type next-elem) 'headline)
22932 (not (eq (org-element-type elem) 'headline))))
22933 (goto-char pos)
22934 (error "Cannot drag element forward"))
22935 ;; Compute new position of point: it's shifted by NEXT-ELEM
22936 ;; body's length (without final blanks) and by the length of
22937 ;; blanks between ELEM and NEXT-ELEM.
22938 (let ((size-next (- (save-excursion
22939 (goto-char (org-element-property :end next-elem))
22940 (skip-chars-backward " \r\t\n")
22941 (forward-line)
22942 ;; Small correction if buffer doesn't end
22943 ;; with a newline character.
22944 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22945 (org-element-property :begin next-elem)))
22946 (size-blank (- (org-element-property :end elem)
22947 (save-excursion
22948 (goto-char (org-element-property :end elem))
22949 (skip-chars-backward " \r\t\n")
22950 (forward-line)
22951 (point)))))
22952 (org-element-swap-A-B elem next-elem)
22953 (goto-char (+ pos size-next size-blank))))))
22955 (defun org-drag-line-forward (arg)
22956 "Drag the line at point ARG lines forward."
22957 (interactive "p")
22958 (dotimes (n (abs arg))
22959 (let ((c (current-column)))
22960 (if (< 0 arg)
22961 (progn
22962 (beginning-of-line 2)
22963 (transpose-lines 1)
22964 (beginning-of-line 0))
22965 (transpose-lines 1)
22966 (beginning-of-line -1))
22967 (org-move-to-column c))))
22969 (defun org-drag-line-backward (arg)
22970 "Drag the line at point ARG lines backward."
22971 (interactive "p")
22972 (org-drag-line-forward (- arg)))
22974 (defun org-mark-element ()
22975 "Put point at beginning of this element, mark at end.
22977 Interactively, if this command is repeated or (in Transient Mark
22978 mode) if the mark is active, it marks the next element after the
22979 ones already marked."
22980 (interactive)
22981 (let (deactivate-mark)
22982 (if (and (org-called-interactively-p 'any)
22983 (or (and (eq last-command this-command) (mark t))
22984 (and transient-mark-mode mark-active)))
22985 (set-mark
22986 (save-excursion
22987 (goto-char (mark))
22988 (goto-char (org-element-property :end (org-element-at-point)))))
22989 (let ((element (org-element-at-point)))
22990 (end-of-line)
22991 (push-mark (org-element-property :end element) t t)
22992 (goto-char (org-element-property :begin element))))))
22994 (defun org-narrow-to-element ()
22995 "Narrow buffer to current element."
22996 (interactive)
22997 (let ((elem (org-element-at-point)))
22998 (cond
22999 ((eq (car elem) 'headline)
23000 (narrow-to-region
23001 (org-element-property :begin elem)
23002 (org-element-property :end elem)))
23003 ((memq (car elem) org-element-greater-elements)
23004 (narrow-to-region
23005 (org-element-property :contents-begin elem)
23006 (org-element-property :contents-end elem)))
23008 (narrow-to-region
23009 (org-element-property :begin elem)
23010 (org-element-property :end elem))))))
23012 (defun org-transpose-element ()
23013 "Transpose current and previous elements, keeping blank lines between.
23014 Point is moved after both elements."
23015 (interactive)
23016 (org-skip-whitespace)
23017 (let ((end (org-element-property :end (org-element-at-point))))
23018 (org-drag-element-backward)
23019 (goto-char end)))
23021 (defun org-unindent-buffer ()
23022 "Un-indent the visible part of the buffer.
23023 Relative indentation (between items, inside blocks, etc.) isn't
23024 modified."
23025 (interactive)
23026 (unless (eq major-mode 'org-mode)
23027 (error "Cannot un-indent a buffer not in Org mode"))
23028 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23029 unindent-tree ; For byte-compiler.
23030 (unindent-tree
23031 (function
23032 (lambda (contents)
23033 (mapc
23034 (lambda (element)
23035 (if (memq (org-element-type element) '(headline section))
23036 (funcall unindent-tree (org-element-contents element))
23037 (save-excursion
23038 (save-restriction
23039 (narrow-to-region
23040 (org-element-property :begin element)
23041 (org-element-property :end element))
23042 (org-do-remove-indentation)))))
23043 (reverse contents))))))
23044 (funcall unindent-tree (org-element-contents parse-tree))))
23046 (defun org-show-subtree ()
23047 "Show everything after this heading at deeper levels."
23048 (interactive)
23049 (outline-flag-region
23050 (point)
23051 (save-excursion
23052 (org-end-of-subtree t t))
23053 nil))
23055 (defun org-show-entry ()
23056 "Show the body directly following this heading.
23057 Show the heading too, if it is currently invisible."
23058 (interactive)
23059 (save-excursion
23060 (condition-case nil
23061 (progn
23062 (org-back-to-heading t)
23063 (outline-flag-region
23064 (max (point-min) (1- (point)))
23065 (save-excursion
23066 (if (re-search-forward
23067 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23068 (match-beginning 1)
23069 (point-max)))
23070 nil)
23071 (org-cycle-hide-drawers 'children))
23072 (error nil))))
23074 (defun org-make-options-regexp (kwds &optional extra)
23075 "Make a regular expression for keyword lines."
23076 (concat
23077 "^#\\+\\("
23078 (mapconcat 'regexp-quote kwds "\\|")
23079 (if extra (concat "\\|" extra))
23080 "\\):[ \t]*\\(.*\\)"))
23082 ;; Make isearch reveal the necessary context
23083 (defun org-isearch-end ()
23084 "Reveal context after isearch exits."
23085 (when isearch-success ; only if search was successful
23086 (if (featurep 'xemacs)
23087 ;; Under XEmacs, the hook is run in the correct place,
23088 ;; we directly show the context.
23089 (org-show-context 'isearch)
23090 ;; In Emacs the hook runs *before* restoring the overlays.
23091 ;; So we have to use a one-time post-command-hook to do this.
23092 ;; (Emacs 22 has a special variable, see function `org-mode')
23093 (unless (and (boundp 'isearch-mode-end-hook-quit)
23094 isearch-mode-end-hook-quit)
23095 ;; Only when the isearch was not quitted.
23096 (org-add-hook 'post-command-hook 'org-isearch-post-command
23097 'append 'local)))
23098 (org-fix-ellipsis-at-bol)))
23100 (defun org-isearch-post-command ()
23101 "Remove self from hook, and show context."
23102 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23103 (org-show-context 'isearch))
23106 ;;;; Integration with and fixes for other packages
23108 ;;; Imenu support
23110 (defvar org-imenu-markers nil
23111 "All markers currently used by Imenu.")
23112 (make-variable-buffer-local 'org-imenu-markers)
23114 (defun org-imenu-new-marker (&optional pos)
23115 "Return a new marker for use by Imenu, and remember the marker."
23116 (let ((m (make-marker)))
23117 (move-marker m (or pos (point)))
23118 (push m org-imenu-markers)
23121 (defun org-imenu-get-tree ()
23122 "Produce the index for Imenu."
23123 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23124 (setq org-imenu-markers nil)
23125 (let* ((n org-imenu-depth)
23126 (re (concat "^" (org-get-limited-outline-regexp)))
23127 (subs (make-vector (1+ n) nil))
23128 (last-level 0)
23129 m level head0 head)
23130 (save-excursion
23131 (save-restriction
23132 (widen)
23133 (goto-char (point-max))
23134 (while (re-search-backward re nil t)
23135 (setq level (org-reduced-level (funcall outline-level)))
23136 (when (and (<= level n)
23137 (looking-at org-complex-heading-regexp)
23138 (setq head0 (org-match-string-no-properties 4)))
23139 (setq head (org-link-display-format head0)
23140 m (org-imenu-new-marker))
23141 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23142 (if (>= level last-level)
23143 (push (cons head m) (aref subs level))
23144 (push (cons head (aref subs (1+ level))) (aref subs level))
23145 (loop for i from (1+ level) to n do (aset subs i nil)))
23146 (setq last-level level)))))
23147 (aref subs 1)))
23149 (eval-after-load "imenu"
23150 '(progn
23151 (add-hook 'imenu-after-jump-hook
23152 (lambda ()
23153 (if (derived-mode-p 'org-mode)
23154 (org-show-context 'org-goto))))))
23156 (defun org-link-display-format (link)
23157 "Replace a link with its the description.
23158 If there is no description, use the link target."
23159 (save-match-data
23160 (if (string-match org-bracket-link-analytic-regexp link)
23161 (replace-match (if (match-end 5)
23162 (match-string 5 link)
23163 (concat (match-string 1 link)
23164 (match-string 3 link)))
23165 nil t link)
23166 link)))
23168 (defun org-toggle-link-display ()
23169 "Toggle the literal or descriptive display of links."
23170 (interactive)
23171 (if org-descriptive-links
23172 (progn (org-remove-from-invisibility-spec '(org-link))
23173 (org-restart-font-lock)
23174 (setq org-descriptive-links nil))
23175 (progn (add-to-invisibility-spec '(org-link))
23176 (org-restart-font-lock)
23177 (setq org-descriptive-links t))))
23179 ;; Speedbar support
23181 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23182 "Overlay marking the agenda restriction line in speedbar.")
23183 (overlay-put org-speedbar-restriction-lock-overlay
23184 'face 'org-agenda-restriction-lock)
23185 (overlay-put org-speedbar-restriction-lock-overlay
23186 'help-echo "Agendas are currently limited to this item.")
23187 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23189 (defun org-speedbar-set-agenda-restriction ()
23190 "Restrict future agenda commands to the location at point in speedbar.
23191 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23192 (interactive)
23193 (require 'org-agenda)
23194 (let (p m tp np dir txt)
23195 (cond
23196 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23197 'org-imenu t))
23198 (setq m (get-text-property p 'org-imenu-marker))
23199 (with-current-buffer (marker-buffer m)
23200 (goto-char m)
23201 (org-agenda-set-restriction-lock 'subtree)))
23202 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23203 'speedbar-function 'speedbar-find-file))
23204 (setq tp (previous-single-property-change
23205 (1+ p) 'speedbar-function)
23206 np (next-single-property-change
23207 tp 'speedbar-function)
23208 dir (speedbar-line-directory)
23209 txt (buffer-substring-no-properties (or tp (point-min))
23210 (or np (point-max))))
23211 (with-current-buffer (find-file-noselect
23212 (let ((default-directory dir))
23213 (expand-file-name txt)))
23214 (unless (derived-mode-p 'org-mode)
23215 (error "Cannot restrict to non-Org-mode file"))
23216 (org-agenda-set-restriction-lock 'file)))
23217 (t (error "Don't know how to restrict Org-mode's agenda")))
23218 (move-overlay org-speedbar-restriction-lock-overlay
23219 (point-at-bol) (point-at-eol))
23220 (setq current-prefix-arg nil)
23221 (org-agenda-maybe-redo)))
23223 (eval-after-load "speedbar"
23224 '(progn
23225 (speedbar-add-supported-extension ".org")
23226 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23227 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23228 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23229 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23230 (add-hook 'speedbar-visiting-tag-hook
23231 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23233 ;;; Fixes and Hacks for problems with other packages
23235 ;; Make flyspell not check words in links, to not mess up our keymap
23236 (defvar org-element-affiliated-keywords) ; From org-element.el
23237 (defvar org-element-block-name-alist) ; From org-element.el
23238 (defun org-mode-flyspell-verify ()
23239 "Don't let flyspell put overlays at active buttons, or on
23240 {todo,all-time,additional-option-like}-keywords."
23241 (let ((pos (max (1- (point)) (point-min)))
23242 (word (thing-at-point 'word)))
23243 (and (not (get-text-property pos 'keymap))
23244 (not (get-text-property pos 'org-no-flyspell))
23245 (not (member word org-todo-keywords-1))
23246 (not (member word org-all-time-keywords))
23247 (not (member word org-options-keywords))
23248 (not (member word (mapcar 'car org-startup-options)))
23249 (not (member-ignore-case word org-element-affiliated-keywords))
23250 (not (member-ignore-case word (org-get-export-keywords)))
23251 (not (member-ignore-case
23252 word (mapcar 'car org-element-block-name-alist)))
23253 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23255 (defun org-remove-flyspell-overlays-in (beg end)
23256 "Remove flyspell overlays in region."
23257 (and (org-bound-and-true-p flyspell-mode)
23258 (fboundp 'flyspell-delete-region-overlays)
23259 (flyspell-delete-region-overlays beg end))
23260 (add-text-properties beg end '(org-no-flyspell t)))
23262 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23263 (eval-after-load "bookmark"
23264 '(if (boundp 'bookmark-after-jump-hook)
23265 ;; We can use the hook
23266 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23267 ;; Hook not available, use advice
23268 (defadvice bookmark-jump (after org-make-visible activate)
23269 "Make the position visible."
23270 (org-bookmark-jump-unhide))))
23272 ;; Make sure saveplace shows the location if it was hidden
23273 (eval-after-load "saveplace"
23274 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23275 "Make the position visible."
23276 (org-bookmark-jump-unhide)))
23278 ;; Make sure ecb shows the location if it was hidden
23279 (eval-after-load "ecb"
23280 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23281 "Make hierarchy visible when jumping into location from ECB tree buffer."
23282 (if (derived-mode-p 'org-mode)
23283 (org-show-context))))
23285 (defun org-bookmark-jump-unhide ()
23286 "Unhide the current position, to show the bookmark location."
23287 (and (derived-mode-p 'org-mode)
23288 (or (outline-invisible-p)
23289 (save-excursion (goto-char (max (point-min) (1- (point))))
23290 (outline-invisible-p)))
23291 (org-show-context 'bookmark-jump)))
23293 ;; Make session.el ignore our circular variable
23294 (eval-after-load "session"
23295 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23297 ;;;; Experimental code
23299 (defun org-closed-in-range ()
23300 "Sparse tree of items closed in a certain time range.
23301 Still experimental, may disappear in the future."
23302 (interactive)
23303 ;; Get the time interval from the user.
23304 (let* ((time1 (org-float-time
23305 (org-read-date nil 'to-time nil "Starting date: ")))
23306 (time2 (org-float-time
23307 (org-read-date nil 'to-time nil "End date:")))
23308 ;; callback function
23309 (callback (lambda ()
23310 (let ((time
23311 (org-float-time
23312 (apply 'encode-time
23313 (org-parse-time-string
23314 (match-string 1))))))
23315 ;; check if time in interval
23316 (and (>= time time1) (<= time time2))))))
23317 ;; make tree, check each match with the callback
23318 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23320 ;;;; Finish up
23322 (provide 'org)
23324 (run-hooks 'org-load-hook)
23326 ;;; org.el ends here