Add :version and :package-version
[org-mode.git] / lisp / org.el
bloba42b6b023db6d55efb226b95499247cb2e0b43a3
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 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function orgtbl-mode "org-table" (&optional arg))
126 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
127 (declare-function org-beamer-mode "ox-beamer" ())
128 (declare-function org-table-edit-field "org-table" (arg))
129 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-table-align "org-table" ())
135 (declare-function org-table-paste-rectangle "org-table" ())
136 (declare-function org-table-maybe-eval-formula "org-table" ())
137 (declare-function org-table-maybe-recalculate-line "org-table" ())
139 (declare-function org-element--parse-objects "org-element"
140 (beg end acc restriction))
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-interpret-data "org-element"
145 (data &optional parent))
146 (declare-function org-element-map "org-element"
147 (data types fun &optional info first-match no-recursion))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element"
150 (&optional granularity visible-only))
151 (declare-function org-element-property "org-element" (property element))
152 (declare-function org-element-put-property "org-element"
153 (element property value))
154 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
155 (declare-function org-element--parse-objects "org-element"
156 (beg end acc restriction))
157 (declare-function org-element-parse-buffer "org-element"
158 (&optional granularity visible-only))
159 (declare-function org-element-restriction "org-element" (element))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :version "24.4"
351 :package-version '(Org . "8.0")
352 :type
353 '(set :greedy t
354 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
355 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
356 (const :tag " crypt: Encryption of subtrees" org-crypt)
357 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
358 (const :tag " docview: Links to doc-view buffers" org-docview)
359 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
360 (const :tag " id: Global IDs for identifying entries" org-id)
361 (const :tag " info: Links to Info nodes" org-info)
362 (const :tag " habit: Track your consistency with habits" org-habit)
363 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
364 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
365 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
366 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
367 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
368 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
369 (const :tag " mouse: Additional mouse support" org-mouse)
371 (const :tag "C vm: Links to VM folders/messages" org-vm)
372 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
373 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
374 (const :tag "C mew: Links to Mew folders/messages" org-mew)
375 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
376 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
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 exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
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 org2rem: Convert org appointments into reminders" org2rem)
404 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
405 (const :tag "C secretary: Team management with org-mode" org-secretary)
406 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
407 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
408 (const :tag "C track: Keep up with Org-mode development" org-track)
409 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
410 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
411 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
413 (defvar org-export-registered-backends) ; From ox.el
414 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
415 (defcustom org-export-backends '(ascii html icalendar latex)
416 "List of export back-ends that should be always available.
418 If a description starts with <C>, the file is not part of Emacs
419 and loading it will require that you have downloaded and properly
420 installed the Org mode distribution.
422 Unlike to `org-modules', libraries in this list will not be
423 loaded along with Org, but only once the export framework is
424 needed.
426 This variable needs to be set before org.el is loaded. If you
427 need to make a change while Emacs is running, use the customize
428 interface or run the following code, where VALUE stands for the
429 new value of the variable, after updating it:
431 \(progn
432 \(setq org-export-registered-backends
433 \(org-remove-if-not
434 \(lambda (backend)
435 \(or (memq backend val)
436 \(catch 'parentp
437 \(mapc
438 \(lambda (b)
439 \(and (org-export-derived-backend-p b (car backend))
440 \(throw 'parentp t)))
441 val)
442 nil)))
443 org-export-registered-backends))
444 \(let ((new-list (mapcar 'car org-export-registered-backends)))
445 \(dolist (backend val)
446 \(cond
447 \((not (load (format \"ox-%s\" backend) t t))
448 \(message \"Problems while trying to load export back-end `%s'\"
449 backend))
450 \((not (memq backend new-list)) (push backend new-list))))
451 \(set-default var new-list)))
453 Adding a back-end to this list will also pull the back-end it
454 depends on, if any."
455 :group 'org
456 :group 'org-export
457 :version "24.4"
458 :package-version '(Org . "8.0")
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 freemind Export buffer to Freemind mindmap format" freemind)
499 (const :tag "C groff Export buffer to Groff format" groff)
500 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
501 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
503 (eval-after-load 'ox
504 '(mapc
505 (lambda (backend)
506 (condition-case nil (require (intern (format "ox-%s" backend)))
507 (error (message "Problems while trying to load export back-end `%s'"
508 backend))))
509 org-export-backends))
511 (defcustom org-support-shift-select nil
512 "Non-nil means make shift-cursor commands select text when possible.
514 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
515 start selecting a region, or enlarge regions started in this way.
516 In Org-mode, in special contexts, these same keys are used for
517 other purposes, important enough to compete with shift selection.
518 Org tries to balance these needs by supporting `shift-select-mode'
519 outside these special contexts, under control of this variable.
521 The default of this variable is nil, to avoid confusing behavior. Shifted
522 cursor keys will then execute Org commands in the following contexts:
523 - on a headline, changing TODO state (left/right) and priority (up/down)
524 - on a time stamp, changing the time
525 - in a plain list item, changing the bullet type
526 - in a property definition line, switching between allowed values
527 - in the BEGIN line of a clock table (changing the time block).
528 Outside these contexts, the commands will throw an error.
530 When this variable is t and the cursor is not in a special
531 context, Org-mode will support shift-selection for making and
532 enlarging regions. To make this more effective, the bullet
533 cycling will no longer happen anywhere in an item line, but only
534 if the cursor is exactly on the bullet.
536 If you set this variable to the symbol `always', then the keys
537 will not be special in headlines, property lines, and item lines,
538 to make shift selection work there as well. If this is what you
539 want, you can use the following alternative commands: `C-c C-t'
540 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
541 can be used to switch TODO sets, `C-c -' to cycle item bullet
542 types, and properties can be edited by hand or in column view.
544 However, when the cursor is on a timestamp, shift-cursor commands
545 will still edit the time stamp - this is just too good to give up.
547 XEmacs user should have this variable set to nil, because
548 `shift-select-mode' is in Emacs 23 or later only."
549 :group 'org
550 :type '(choice
551 (const :tag "Never" nil)
552 (const :tag "When outside special context" t)
553 (const :tag "Everywhere except timestamps" always)))
555 (defcustom org-loop-over-headlines-in-active-region nil
556 "Shall some commands act upon headlines in the active region?
558 When set to `t', some commands will be performed in all headlines
559 within the active region.
561 When set to `start-level', some commands will be performed in all
562 headlines within the active region, provided that these headlines
563 are of the same level than the first one.
565 When set to a string, those commands will be performed on the
566 matching headlines within the active region. Such string must be
567 a tags/property/todo match as it is used in the agenda tags view.
569 The list of commands is: `org-schedule', `org-deadline',
570 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
571 `org-archive-to-archive-sibling'. The archiving commands skip
572 already archived entries."
573 :type '(choice (const :tag "Don't loop" nil)
574 (const :tag "All headlines in active region" t)
575 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
576 (string :tag "Tags/Property/Todo matcher"))
577 :version "24.1"
578 :group 'org-todo
579 :group 'org-archive)
581 (defgroup org-startup nil
582 "Options concerning startup of Org-mode."
583 :tag "Org Startup"
584 :group 'org)
586 (defcustom org-startup-folded t
587 "Non-nil means entering Org-mode will switch to OVERVIEW.
588 This can also be configured on a per-file basis by adding one of
589 the following lines anywhere in the buffer:
591 #+STARTUP: fold (or `overview', this is equivalent)
592 #+STARTUP: nofold (or `showall', this is equivalent)
593 #+STARTUP: content
594 #+STARTUP: showeverything
596 By default, this option is ignored when Org opens agenda files
597 for the first time. If you want the agenda to honor the startup
598 option, set `org-agenda-inhibit-startup' to nil."
599 :group 'org-startup
600 :type '(choice
601 (const :tag "nofold: show all" nil)
602 (const :tag "fold: overview" t)
603 (const :tag "content: all headlines" content)
604 (const :tag "show everything, even drawers" showeverything)))
606 (defcustom org-startup-truncated t
607 "Non-nil means entering Org-mode will set `truncate-lines'.
608 This is useful since some lines containing links can be very long and
609 uninteresting. Also tables look terrible when wrapped."
610 :group 'org-startup
611 :type 'boolean)
613 (defcustom org-startup-indented nil
614 "Non-nil means turn on `org-indent-mode' on startup.
615 This can also be configured on a per-file basis by adding one of
616 the following lines anywhere in the buffer:
618 #+STARTUP: indent
619 #+STARTUP: noindent"
620 :group 'org-structure
621 :type '(choice
622 (const :tag "Not" nil)
623 (const :tag "Globally (slow on startup in large files)" t)))
625 (defcustom org-use-sub-superscripts t
626 "Non-nil means interpret \"_\" and \"^\" for display.
627 When this option is turned on, you can use TeX-like syntax for sub- and
628 superscripts. Several characters after \"_\" or \"^\" will be
629 considered as a single item - so grouping with {} is normally not
630 needed. For example, the following things will be parsed as single
631 sub- or superscripts.
633 10^24 or 10^tau several digits will be considered 1 item.
634 10^-12 or 10^-tau a leading sign with digits or a word
635 x^2-y^3 will be read as x^2 - y^3, because items are
636 terminated by almost any nonword/nondigit char.
637 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
639 Still, ambiguity is possible - so when in doubt use {} to enclose
640 the sub/superscript. If you set this variable to the symbol
641 `{}', the braces are *required* in order to trigger
642 interpretations as sub/superscript. This can be helpful in
643 documents that need \"_\" frequently in plain text."
644 :group 'org-startup
645 :version "24.1"
646 :type '(choice
647 (const :tag "Always interpret" t)
648 (const :tag "Only with braces" {})
649 (const :tag "Never interpret" nil)))
651 (defcustom org-startup-with-beamer-mode nil
652 "Non-nil means turn on `org-beamer-mode' on startup.
653 This can also be configured on a per-file basis by adding one of
654 the following lines anywhere in the buffer:
656 #+STARTUP: beamer"
657 :group 'org-startup
658 :version "24.1"
659 :type 'boolean)
661 (defcustom org-startup-align-all-tables nil
662 "Non-nil means align all tables when visiting a file.
663 This is useful when the column width in tables is forced with <N> cookies
664 in table fields. Such tables will look correct only after the first re-align.
665 This can also be configured on a per-file basis by adding one of
666 the following lines anywhere in the buffer:
667 #+STARTUP: align
668 #+STARTUP: noalign"
669 :group 'org-startup
670 :type 'boolean)
672 (defcustom org-startup-with-inline-images nil
673 "Non-nil means show inline images when loading a new Org file.
674 This can also be configured on a per-file basis by adding one of
675 the following lines anywhere in the buffer:
676 #+STARTUP: inlineimages
677 #+STARTUP: noinlineimages"
678 :group 'org-startup
679 :version "24.1"
680 :type 'boolean)
682 (defcustom org-startup-with-latex-preview nil
683 "Non-nil means preview LaTeX fragments when loading a new Org file.
685 This can also be configured on a per-file basis by adding one of
686 the followinglines anywhere in the buffer:
687 #+STARTUP: latexpreview
688 #+STARTUP: nolatexpreview"
689 :group 'org-startup
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type 'boolean)
694 (defcustom org-insert-mode-line-in-empty-file nil
695 "Non-nil means insert the first line setting Org-mode in empty files.
696 When the function `org-mode' is called interactively in an empty file, this
697 normally means that the file name does not automatically trigger Org-mode.
698 To ensure that the file will always be in Org-mode in the future, a
699 line enforcing Org-mode will be inserted into the buffer, if this option
700 has been set."
701 :group 'org-startup
702 :type 'boolean)
704 (defcustom org-replace-disputed-keys nil
705 "Non-nil means use alternative key bindings for some keys.
706 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
707 These keys are also used by other packages like shift-selection-mode'
708 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
709 If you want to use Org-mode together with one of these other modes,
710 or more generally if you would like to move some Org-mode commands to
711 other keys, set this variable and configure the keys with the variable
712 `org-disputed-keys'.
714 This option is only relevant at load-time of Org-mode, and must be set
715 *before* org.el is loaded. Changing it requires a restart of Emacs to
716 become effective."
717 :group 'org-startup
718 :type 'boolean)
720 (defcustom org-use-extra-keys nil
721 "Non-nil means use extra key sequence definitions for certain commands.
722 This happens automatically if you run XEmacs or if `window-system'
723 is nil. This variable lets you do the same manually. You must
724 set it before loading org.
726 Example: on Carbon Emacs 22 running graphically, with an external
727 keyboard on a Powerbook, the default way of setting M-left might
728 not work for either Alt or ESC. Setting this variable will make
729 it work for ESC."
730 :group 'org-startup
731 :type 'boolean)
733 (if (fboundp 'defvaralias)
734 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
736 (defcustom org-disputed-keys
737 '(([(shift up)] . [(meta p)])
738 ([(shift down)] . [(meta n)])
739 ([(shift left)] . [(meta -)])
740 ([(shift right)] . [(meta +)])
741 ([(control shift right)] . [(meta shift +)])
742 ([(control shift left)] . [(meta shift -)]))
743 "Keys for which Org-mode and other modes compete.
744 This is an alist, cars are the default keys, second element specifies
745 the alternative to use when `org-replace-disputed-keys' is t.
747 Keys can be specified in any syntax supported by `define-key'.
748 The value of this option takes effect only at Org-mode's startup,
749 therefore you'll have to restart Emacs to apply it after changing."
750 :group 'org-startup
751 :type 'alist)
753 (defun org-key (key)
754 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
755 Or return the original if not disputed.
756 Also apply the translations defined in `org-xemacs-key-equivalents'."
757 (when org-replace-disputed-keys
758 (let* ((nkey (key-description key))
759 (x (org-find-if (lambda (x)
760 (equal (key-description (car x)) nkey))
761 org-disputed-keys)))
762 (setq key (if x (cdr x) key))))
763 (when (featurep 'xemacs)
764 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
765 key)
767 (defun org-find-if (predicate seq)
768 (catch 'exit
769 (while seq
770 (if (funcall predicate (car seq))
771 (throw 'exit (car seq))
772 (pop seq)))))
774 (defun org-defkey (keymap key def)
775 "Define a key, possibly translated, as returned by `org-key'."
776 (define-key keymap (org-key key) def))
778 (defcustom org-ellipsis nil
779 "The ellipsis to use in the Org-mode outline.
780 When nil, just use the standard three dots. When a string, use that instead,
781 When a face, use the standard 3 dots, but with the specified face.
782 The change affects only Org-mode (which will then use its own display table).
783 Changing this requires executing `M-x org-mode' in a buffer to become
784 effective."
785 :group 'org-startup
786 :type '(choice (const :tag "Default" nil)
787 (face :tag "Face" :value org-warning)
788 (string :tag "String" :value "...#")))
790 (defvar org-display-table nil
791 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
793 (defgroup org-keywords nil
794 "Keywords in Org-mode."
795 :tag "Org Keywords"
796 :group 'org)
798 (defcustom org-deadline-string "DEADLINE:"
799 "String to mark deadline entries.
800 A deadline is this string, followed by a time stamp. Should be a word,
801 terminated by a colon. You can insert a schedule keyword and
802 a timestamp with \\[org-deadline].
803 Changes become only effective after restarting Emacs."
804 :group 'org-keywords
805 :type 'string)
807 (defcustom org-scheduled-string "SCHEDULED:"
808 "String to mark scheduled TODO entries.
809 A schedule is this string, followed by a time stamp. Should be a word,
810 terminated by a colon. You can insert a schedule keyword and
811 a timestamp with \\[org-schedule].
812 Changes become only effective after restarting Emacs."
813 :group 'org-keywords
814 :type 'string)
816 (defcustom org-closed-string "CLOSED:"
817 "String used as the prefix for timestamps logging closing a TODO entry."
818 :group 'org-keywords
819 :type 'string)
821 (defcustom org-clock-string "CLOCK:"
822 "String used as prefix for timestamps clocking work hours on an item."
823 :group 'org-keywords
824 :type 'string)
826 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
827 org-scheduled-string "\\|"
828 org-deadline-string "\\|"
829 org-closed-string "\\|"
830 org-clock-string "\\)")
831 "Matches a line with planning or clock info.")
833 (defcustom org-comment-string "COMMENT"
834 "Entries starting with this keyword will never be exported.
835 An entry can be toggled between COMMENT and normal with
836 \\[org-toggle-comment].
837 Changes become only effective after restarting Emacs."
838 :group 'org-keywords
839 :type 'string)
841 (defcustom org-quote-string "QUOTE"
842 "Entries starting with this keyword will be exported in fixed-width font.
843 Quoting applies only to the text in the entry following the headline, and does
844 not extend beyond the next headline, even if that is lower level.
845 An entry can be toggled between QUOTE and normal with
846 \\[org-toggle-fixed-width-section]."
847 :group 'org-keywords
848 :type 'string)
850 (defconst org-repeat-re
851 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
852 "Regular expression for specifying repeated events.
853 After a match, group 1 contains the repeat expression.")
855 (defgroup org-structure nil
856 "Options concerning the general structure of Org-mode files."
857 :tag "Org Structure"
858 :group 'org)
860 (defgroup org-reveal-location nil
861 "Options about how to make context of a location visible."
862 :tag "Org Reveal Location"
863 :group 'org-structure)
865 (defconst org-context-choice
866 '(choice
867 (const :tag "Always" t)
868 (const :tag "Never" nil)
869 (repeat :greedy t :tag "Individual contexts"
870 (cons
871 (choice :tag "Context"
872 (const agenda)
873 (const org-goto)
874 (const occur-tree)
875 (const tags-tree)
876 (const link-search)
877 (const mark-goto)
878 (const bookmark-jump)
879 (const isearch)
880 (const default))
881 (boolean))))
882 "Contexts for the reveal options.")
884 (defcustom org-show-hierarchy-above '((default . t))
885 "Non-nil means show full hierarchy when revealing a location.
886 Org-mode often shows locations in an org-mode file which might have
887 been invisible before. When this is set, the hierarchy of headings
888 above the exposed location is shown.
889 Turning this off for example for sparse trees makes them very compact.
890 Instead of t, this can also be an alist specifying this option for different
891 contexts. Valid contexts are
892 agenda when exposing an entry from the agenda
893 org-goto when using the command `org-goto' on key C-c C-j
894 occur-tree when using the command `org-occur' on key C-c /
895 tags-tree when constructing a sparse tree based on tags matches
896 link-search when exposing search matches associated with a link
897 mark-goto when exposing the jump goal of a mark
898 bookmark-jump when exposing a bookmark location
899 isearch when exiting from an incremental search
900 default default for all contexts not set explicitly"
901 :group 'org-reveal-location
902 :type org-context-choice)
904 (defcustom org-show-following-heading '((default . nil))
905 "Non-nil means show following heading when revealing a location.
906 Org-mode often shows locations in an org-mode file which might have
907 been invisible before. When this is set, the heading following the
908 match is shown.
909 Turning this off for example for sparse trees makes them very compact,
910 but makes it harder to edit the location of the match. In such a case,
911 use the command \\[org-reveal] to show more context.
912 Instead of t, this can also be an alist specifying this option for different
913 contexts. See `org-show-hierarchy-above' for valid contexts."
914 :group 'org-reveal-location
915 :type org-context-choice)
917 (defcustom org-show-siblings '((default . nil) (isearch t))
918 "Non-nil means show all sibling heading when revealing a location.
919 Org-mode often shows locations in an org-mode file which might have
920 been invisible before. When this is set, the sibling of the current entry
921 heading are all made visible. If `org-show-hierarchy-above' is t,
922 the same happens on each level of the hierarchy above the current entry.
924 By default this is on for the isearch context, off for all other contexts.
925 Turning this off for example for sparse trees makes them very compact,
926 but makes it harder to edit the location of the match. In such a case,
927 use the command \\[org-reveal] to show more context.
928 Instead of t, this can also be an alist specifying this option for different
929 contexts. See `org-show-hierarchy-above' for valid contexts."
930 :group 'org-reveal-location
931 :type org-context-choice)
933 (defcustom org-show-entry-below '((default . nil))
934 "Non-nil means show the entry below a headline when revealing a location.
935 Org-mode often shows locations in an org-mode file which might have
936 been invisible before. When this is set, the text below the headline that is
937 exposed is also shown.
939 By default this is off for all contexts.
940 Instead of t, this can also be an alist specifying this option for different
941 contexts. See `org-show-hierarchy-above' for valid contexts."
942 :group 'org-reveal-location
943 :type org-context-choice)
945 (defcustom org-indirect-buffer-display 'other-window
946 "How should indirect tree buffers be displayed?
947 This applies to indirect buffers created with the commands
948 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
949 Valid values are:
950 current-window Display in the current window
951 other-window Just display in another window.
952 dedicated-frame Create one new frame, and re-use it each time.
953 new-frame Make a new frame each time. Note that in this case
954 previously-made indirect buffers are kept, and you need to
955 kill these buffers yourself."
956 :group 'org-structure
957 :group 'org-agenda-windows
958 :type '(choice
959 (const :tag "In current window" current-window)
960 (const :tag "In current frame, other window" other-window)
961 (const :tag "Each time a new frame" new-frame)
962 (const :tag "One dedicated frame" dedicated-frame)))
964 (defcustom org-use-speed-commands nil
965 "Non-nil means activate single letter commands at beginning of a headline.
966 This may also be a function to test for appropriate locations where speed
967 commands should be active."
968 :group 'org-structure
969 :type '(choice
970 (const :tag "Never" nil)
971 (const :tag "At beginning of headline stars" t)
972 (function)))
974 (defcustom org-speed-commands-user nil
975 "Alist of additional speed commands.
976 This list will be checked before `org-speed-commands-default'
977 when the variable `org-use-speed-commands' is non-nil
978 and when the cursor is at the beginning of a headline.
979 The car if each entry is a string with a single letter, which must
980 be assigned to `self-insert-command' in the global map.
981 The cdr is either a command to be called interactively, a function
982 to be called, or a form to be evaluated.
983 An entry that is just a list with a single string will be interpreted
984 as a descriptive headline that will be added when listing the speed
985 commands in the Help buffer using the `?' speed command."
986 :group 'org-structure
987 :type '(repeat :value ("k" . ignore)
988 (choice :value ("k" . ignore)
989 (list :tag "Descriptive Headline" (string :tag "Headline"))
990 (cons :tag "Letter and Command"
991 (string :tag "Command letter")
992 (choice
993 (function)
994 (sexp))))))
996 (defgroup org-cycle nil
997 "Options concerning visibility cycling in Org-mode."
998 :tag "Org Cycle"
999 :group 'org-structure)
1001 (defcustom org-cycle-skip-children-state-if-no-children t
1002 "Non-nil means skip CHILDREN state in entries that don't have any."
1003 :group 'org-cycle
1004 :type 'boolean)
1006 (defcustom org-cycle-max-level nil
1007 "Maximum level which should still be subject to visibility cycling.
1008 Levels higher than this will, for cycling, be treated as text, not a headline.
1009 When `org-odd-levels-only' is set, a value of N in this variable actually
1010 means 2N-1 stars as the limiting headline.
1011 When nil, cycle all levels.
1012 Note that the limiting level of cycling is also influenced by
1013 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1014 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1015 than its value."
1016 :group 'org-cycle
1017 :type '(choice
1018 (const :tag "No limit" nil)
1019 (integer :tag "Maximum level")))
1021 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1022 "Names of drawers. Drawers are not opened by cycling on the headline above.
1023 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1024 this:
1025 :DRAWERNAME:
1026 .....
1027 :END:
1028 The drawer \"PROPERTIES\" is special for capturing properties through
1029 the property API.
1031 Drawers can be defined on the per-file basis with a line like:
1033 #+DRAWERS: HIDDEN STATE PROPERTIES"
1034 :group 'org-structure
1035 :group 'org-cycle
1036 :type '(repeat (string :tag "Drawer Name")))
1038 (defcustom org-hide-block-startup nil
1039 "Non-nil means entering Org-mode will fold all blocks.
1040 This can also be set in on a per-file basis with
1042 #+STARTUP: hideblocks
1043 #+STARTUP: showblocks"
1044 :group 'org-startup
1045 :group 'org-cycle
1046 :type 'boolean)
1048 (defcustom org-cycle-global-at-bob nil
1049 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1050 This makes it possible to do global cycling without having to use S-TAB or
1051 \\[universal-argument] TAB. For this special case to work, the first line
1052 of the buffer must not be a headline -- it may be empty or some other text.
1053 When used in this way, `org-cycle-hook' is disabled temporarily to make
1054 sure the cursor stays at the beginning of the buffer. When this option is
1055 nil, don't do anything special at the beginning of the buffer."
1056 :group 'org-cycle
1057 :type 'boolean)
1059 (defcustom org-cycle-level-after-item/entry-creation t
1060 "Non-nil means cycle entry level or item indentation in new empty entries.
1062 When the cursor is at the end of an empty headline, i.e., with only stars
1063 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1064 and then all possible ancestor states, before returning to the original state.
1065 This makes data entry extremely fast: M-RET to create a new headline,
1066 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1068 When the cursor is at the end of an empty plain list item, one TAB will
1069 make it a subitem, two or more tabs will back up to make this an item
1070 higher up in the item hierarchy."
1071 :group 'org-cycle
1072 :type 'boolean)
1074 (defcustom org-cycle-emulate-tab t
1075 "Where should `org-cycle' emulate TAB.
1076 nil Never
1077 white Only in completely white lines
1078 whitestart Only at the beginning of lines, before the first non-white char
1079 t Everywhere except in headlines
1080 exc-hl-bol Everywhere except at the start of a headline
1081 If TAB is used in a place where it does not emulate TAB, the current subtree
1082 visibility is cycled."
1083 :group 'org-cycle
1084 :type '(choice (const :tag "Never" nil)
1085 (const :tag "Only in completely white lines" white)
1086 (const :tag "Before first char in a line" whitestart)
1087 (const :tag "Everywhere except in headlines" t)
1088 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1091 (defcustom org-cycle-separator-lines 2
1092 "Number of empty lines needed to keep an empty line between collapsed trees.
1093 If you leave an empty line between the end of a subtree and the following
1094 headline, this empty line is hidden when the subtree is folded.
1095 Org-mode will leave (exactly) one empty line visible if the number of
1096 empty lines is equal or larger to the number given in this variable.
1097 So the default 2 means at least 2 empty lines after the end of a subtree
1098 are needed to produce free space between a collapsed subtree and the
1099 following headline.
1101 If the number is negative, and the number of empty lines is at least -N,
1102 all empty lines are shown.
1104 Special case: when 0, never leave empty lines in collapsed view."
1105 :group 'org-cycle
1106 :type 'integer)
1107 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1109 (defcustom org-pre-cycle-hook nil
1110 "Hook that is run before visibility cycling is happening.
1111 The function(s) in this hook must accept a single argument which indicates
1112 the new state that will be set right after running this hook. The
1113 argument is a symbol. Before a global state change, it can have the values
1114 `overview', `content', or `all'. Before a local state change, it can have
1115 the values `folded', `children', or `subtree'."
1116 :group 'org-cycle
1117 :type 'hook)
1119 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1120 org-cycle-hide-drawers
1121 org-cycle-hide-inline-tasks
1122 org-cycle-show-empty-lines
1123 org-optimize-window-after-visibility-change)
1124 "Hook that is run after `org-cycle' has changed the buffer visibility.
1125 The function(s) in this hook must accept a single argument which indicates
1126 the new state that was set by the most recent `org-cycle' command. The
1127 argument is a symbol. After a global state change, it can have the values
1128 `overview', `contents', or `all'. After a local state change, it can have
1129 the values `folded', `children', or `subtree'."
1130 :group 'org-cycle
1131 :type 'hook)
1133 (defgroup org-edit-structure nil
1134 "Options concerning structure editing in Org-mode."
1135 :tag "Org Edit Structure"
1136 :group 'org-structure)
1138 (defcustom org-odd-levels-only nil
1139 "Non-nil means skip even levels and only use odd levels for the outline.
1140 This has the effect that two stars are being added/taken away in
1141 promotion/demotion commands. It also influences how levels are
1142 handled by the exporters.
1143 Changing it requires restart of `font-lock-mode' to become effective
1144 for fontification also in regions already fontified.
1145 You may also set this on a per-file basis by adding one of the following
1146 lines to the buffer:
1148 #+STARTUP: odd
1149 #+STARTUP: oddeven"
1150 :group 'org-edit-structure
1151 :group 'org-appearance
1152 :type 'boolean)
1154 (defcustom org-adapt-indentation t
1155 "Non-nil means adapt indentation to outline node level.
1157 When this variable is set, Org assumes that you write outlines by
1158 indenting text in each node to align with the headline (after the stars).
1159 The following issues are influenced by this variable:
1161 - When this is set and the *entire* text in an entry is indented, the
1162 indentation is increased by one space in a demotion command, and
1163 decreased by one in a promotion command. If any line in the entry
1164 body starts with text at column 0, indentation is not changed at all.
1166 - Property drawers and planning information is inserted indented when
1167 this variable s set. When nil, they will not be indented.
1169 - TAB indents a line relative to context. The lines below a headline
1170 will be indented when this variable is set.
1172 Note that this is all about true indentation, by adding and removing
1173 space characters. See also `org-indent.el' which does level-dependent
1174 indentation in a virtual way, i.e. at display time in Emacs."
1175 :group 'org-edit-structure
1176 :type 'boolean)
1178 (defcustom org-special-ctrl-a/e nil
1179 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1181 When t, `C-a' will bring back the cursor to the beginning of the
1182 headline text, i.e. after the stars and after a possible TODO
1183 keyword. In an item, this will be the position after bullet and
1184 check-box, if any. When the cursor is already at that position,
1185 another `C-a' will bring it to the beginning of the line.
1187 `C-e' will jump to the end of the headline, ignoring the presence
1188 of tags in the headline. A second `C-e' will then jump to the
1189 true end of the line, after any tags. This also means that, when
1190 this variable is non-nil, `C-e' also will never jump beyond the
1191 end of the heading of a folded section, i.e. not after the
1192 ellipses.
1194 When set to the symbol `reversed', the first `C-a' or `C-e' works
1195 normally, going to the true line boundary first. Only a directly
1196 following, identical keypress will bring the cursor to the
1197 special positions.
1199 This may also be a cons cell where the behavior for `C-a' and
1200 `C-e' is set separately."
1201 :group 'org-edit-structure
1202 :type '(choice
1203 (const :tag "off" nil)
1204 (const :tag "on: after stars/bullet and before tags first" t)
1205 (const :tag "reversed: true line boundary first" reversed)
1206 (cons :tag "Set C-a and C-e separately"
1207 (choice :tag "Special C-a"
1208 (const :tag "off" nil)
1209 (const :tag "on: after stars/bullet first" t)
1210 (const :tag "reversed: before stars/bullet first" reversed))
1211 (choice :tag "Special C-e"
1212 (const :tag "off" nil)
1213 (const :tag "on: before tags first" t)
1214 (const :tag "reversed: after tags first" reversed)))))
1215 (if (fboundp 'defvaralias)
1216 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1218 (defcustom org-special-ctrl-k nil
1219 "Non-nil means `C-k' will behave specially in headlines.
1220 When nil, `C-k' will call the default `kill-line' command.
1221 When t, the following will happen while the cursor is in the headline:
1223 - When the cursor is at the beginning of a headline, kill the entire
1224 line and possible the folded subtree below the line.
1225 - When in the middle of the headline text, kill the headline up to the tags.
1226 - When after the headline text, kill the tags."
1227 :group 'org-edit-structure
1228 :type 'boolean)
1230 (defcustom org-ctrl-k-protect-subtree nil
1231 "Non-nil means, do not delete a hidden subtree with C-k.
1232 When set to the symbol `error', simply throw an error when C-k is
1233 used to kill (part-of) a headline that has hidden text behind it.
1234 Any other non-nil value will result in a query to the user, if it is
1235 OK to kill that hidden subtree. When nil, kill without remorse."
1236 :group 'org-edit-structure
1237 :version "24.1"
1238 :type '(choice
1239 (const :tag "Do not protect hidden subtrees" nil)
1240 (const :tag "Protect hidden subtrees with a security query" t)
1241 (const :tag "Never kill a hidden subtree with C-k" error)))
1243 (defcustom org-catch-invisible-edits nil
1244 "Check if in invisible region before inserting or deleting a character.
1245 Valid values are:
1247 nil Do not check, so just do invisible edits.
1248 error Throw an error and do nothing.
1249 show Make point visible, and do the requested edit.
1250 show-and-error Make point visible, then throw an error and abort the edit.
1251 smart Make point visible, and do insertion/deletion if it is
1252 adjacent to visible text and the change feels predictable.
1253 Never delete a previously invisible character or add in the
1254 middle or right after an invisible region. Basically, this
1255 allows insertion and backward-delete right before ellipses.
1256 FIXME: maybe in this case we should not even show?"
1257 :group 'org-edit-structure
1258 :version "24.1"
1259 :type '(choice
1260 (const :tag "Do not check" nil)
1261 (const :tag "Throw error when trying to edit" error)
1262 (const :tag "Unhide, but do not do the edit" show-and-error)
1263 (const :tag "Show invisible part and do the edit" show)
1264 (const :tag "Be smart and do the right thing" smart)))
1266 (defcustom org-yank-folded-subtrees t
1267 "Non-nil means when yanking subtrees, fold them.
1268 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1269 it starts with a heading and all other headings in it are either children
1270 or siblings, then fold all the subtrees. However, do this only if no
1271 text after the yank would be swallowed into a folded tree by this action."
1272 :group 'org-edit-structure
1273 :type 'boolean)
1275 (defcustom org-yank-adjusted-subtrees nil
1276 "Non-nil means when yanking subtrees, adjust the level.
1277 With this setting, `org-paste-subtree' is used to insert the subtree, see
1278 this function for details."
1279 :group 'org-edit-structure
1280 :type 'boolean)
1282 (defcustom org-M-RET-may-split-line '((default . t))
1283 "Non-nil means M-RET will split the line at the cursor position.
1284 When nil, it will go to the end of the line before making a
1285 new line.
1286 You may also set this option in a different way for different
1287 contexts. Valid contexts are:
1289 headline when creating a new headline
1290 item when creating a new item
1291 table in a table field
1292 default the value to be used for all contexts not explicitly
1293 customized"
1294 :group 'org-structure
1295 :group 'org-table
1296 :type '(choice
1297 (const :tag "Always" t)
1298 (const :tag "Never" nil)
1299 (repeat :greedy t :tag "Individual contexts"
1300 (cons
1301 (choice :tag "Context"
1302 (const headline)
1303 (const item)
1304 (const table)
1305 (const default))
1306 (boolean)))))
1309 (defcustom org-insert-heading-respect-content nil
1310 "Non-nil means insert new headings after the current subtree.
1311 When nil, the new heading is created directly after the current line.
1312 The commands \\[org-insert-heading-respect-content] and
1313 \\[org-insert-todo-heading-respect-content] turn this variable on
1314 for the duration of the command."
1315 :group 'org-structure
1316 :type 'boolean)
1318 (defcustom org-blank-before-new-entry '((heading . auto)
1319 (plain-list-item . auto))
1320 "Should `org-insert-heading' leave a blank line before new heading/item?
1321 The value is an alist, with `heading' and `plain-list-item' as CAR,
1322 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1323 which case Org will look at the surrounding headings/items and try to
1324 make an intelligent decision whether to insert a blank line or not.
1326 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1327 set, the setting here is ignored and no empty line is inserted, to avoid
1328 breaking the list structure."
1329 :group 'org-edit-structure
1330 :type '(list
1331 (cons (const heading)
1332 (choice (const :tag "Never" nil)
1333 (const :tag "Always" t)
1334 (const :tag "Auto" auto)))
1335 (cons (const plain-list-item)
1336 (choice (const :tag "Never" nil)
1337 (const :tag "Always" t)
1338 (const :tag "Auto" auto)))))
1340 (defcustom org-insert-heading-hook nil
1341 "Hook being run after inserting a new heading."
1342 :group 'org-edit-structure
1343 :type 'hook)
1345 (defcustom org-enable-fixed-width-editor t
1346 "Non-nil means lines starting with \":\" are treated as fixed-width.
1347 This currently only means they are never auto-wrapped.
1348 When nil, such lines will be treated like ordinary lines.
1349 See also the QUOTE keyword."
1350 :group 'org-edit-structure
1351 :type 'boolean)
1353 (defcustom org-goto-auto-isearch t
1354 "Non-nil means typing characters in `org-goto' starts incremental search.
1355 When nil, you can use these keybindings to navigate the buffer:
1357 q Quit the org-goto interface
1358 n Go to the next visible heading
1359 p Go to the previous visible heading
1360 f Go one heading forward on same level
1361 b Go one heading backward on same level
1362 u Go one heading up"
1363 :group 'org-edit-structure
1364 :type 'boolean)
1366 (defgroup org-sparse-trees nil
1367 "Options concerning sparse trees in Org-mode."
1368 :tag "Org Sparse Trees"
1369 :group 'org-structure)
1371 (defcustom org-highlight-sparse-tree-matches t
1372 "Non-nil means highlight all matches that define a sparse tree.
1373 The highlights will automatically disappear the next time the buffer is
1374 changed by an edit command."
1375 :group 'org-sparse-trees
1376 :type 'boolean)
1378 (defcustom org-remove-highlights-with-change t
1379 "Non-nil means any change to the buffer will remove temporary highlights.
1380 Such highlights are created by `org-occur' and `org-clock-display'.
1381 When nil, `C-c C-c needs to be used to get rid of the highlights.
1382 The highlights created by `org-preview-latex-fragment' always need
1383 `C-c C-c' to be removed."
1384 :group 'org-sparse-trees
1385 :group 'org-time
1386 :type 'boolean)
1389 (defcustom org-occur-hook '(org-first-headline-recenter)
1390 "Hook that is run after `org-occur' has constructed a sparse tree.
1391 This can be used to recenter the window to show as much of the structure
1392 as possible."
1393 :group 'org-sparse-trees
1394 :type 'hook)
1396 (defgroup org-imenu-and-speedbar nil
1397 "Options concerning imenu and speedbar in Org-mode."
1398 :tag "Org Imenu and Speedbar"
1399 :group 'org-structure)
1401 (defcustom org-imenu-depth 2
1402 "The maximum level for Imenu access to Org-mode headlines.
1403 This also applied for speedbar access."
1404 :group 'org-imenu-and-speedbar
1405 :type 'integer)
1407 (defgroup org-table nil
1408 "Options concerning tables in Org-mode."
1409 :tag "Org Table"
1410 :group 'org)
1412 (defcustom org-enable-table-editor 'optimized
1413 "Non-nil means lines starting with \"|\" are handled by the table editor.
1414 When nil, such lines will be treated like ordinary lines.
1416 When equal to the symbol `optimized', the table editor will be optimized to
1417 do the following:
1418 - Automatic overwrite mode in front of whitespace in table fields.
1419 This makes the structure of the table stay in tact as long as the edited
1420 field does not exceed the column width.
1421 - Minimize the number of realigns. Normally, the table is aligned each time
1422 TAB or RET are pressed to move to another field. With optimization this
1423 happens only if changes to a field might have changed the column width.
1424 Optimization requires replacing the functions `self-insert-command',
1425 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1426 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1427 very good at guessing when a re-align will be necessary, but you can always
1428 force one with \\[org-ctrl-c-ctrl-c].
1430 If you would like to use the optimized version in Org-mode, but the
1431 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1433 This variable can be used to turn on and off the table editor during a session,
1434 but in order to toggle optimization, a restart is required.
1436 See also the variable `org-table-auto-blank-field'."
1437 :group 'org-table
1438 :type '(choice
1439 (const :tag "off" nil)
1440 (const :tag "on" t)
1441 (const :tag "on, optimized" optimized)))
1443 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1444 (version<= emacs-version "24.1"))
1445 "Non-nil means cluster self-insert commands for undo when possible.
1446 If this is set, then, like in the Emacs command loop, 20 consecutive
1447 characters will be undone together.
1448 This is configurable, because there is some impact on typing performance."
1449 :group 'org-table
1450 :type 'boolean)
1452 (defcustom org-table-tab-recognizes-table.el t
1453 "Non-nil means TAB will automatically notice a table.el table.
1454 When it sees such a table, it moves point into it and - if necessary -
1455 calls `table-recognize-table'."
1456 :group 'org-table-editing
1457 :type 'boolean)
1459 (defgroup org-link nil
1460 "Options concerning links in Org-mode."
1461 :tag "Org Link"
1462 :group 'org)
1464 (defvar org-link-abbrev-alist-local nil
1465 "Buffer-local version of `org-link-abbrev-alist', which see.
1466 The value of this is taken from the #+LINK lines.")
1467 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1469 (defcustom org-link-abbrev-alist nil
1470 "Alist of link abbreviations.
1471 The car of each element is a string, to be replaced at the start of a link.
1472 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1473 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1475 [[linkkey:tag][description]]
1477 The 'linkkey' must be a word word, starting with a letter, followed
1478 by letters, numbers, '-' or '_'.
1480 If REPLACE is a string, the tag will simply be appended to create the link.
1481 If the string contains \"%s\", the tag will be inserted there. If the string
1482 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1483 at that point (see the function `url-hexify-string'). If the string contains
1484 the specifier \"%(my-function)\", then the custom function `my-function' will
1485 be invoked: this function takes the tag as its only argument and must return
1486 a string.
1488 REPLACE may also be a function that will be called with the tag as the
1489 only argument to create the link, which should be returned as a string.
1491 See the manual for examples."
1492 :group 'org-link
1493 :type '(repeat
1494 (cons
1495 (string :tag "Protocol")
1496 (choice
1497 (string :tag "Format")
1498 (function)))))
1500 (defcustom org-descriptive-links t
1501 "Non-nil means Org will display descriptive links.
1502 E.g. [[http://orgmode.org][Org website]] will be displayed as
1503 \"Org Website\", hiding the link itself and just displaying its
1504 description. When set to `nil', Org will display the full links
1505 literally.
1507 You can interactively set the value of this variable by calling
1508 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1509 :group 'org-link
1510 :type 'boolean)
1512 (defcustom org-link-file-path-type 'adaptive
1513 "How the path name in file links should be stored.
1514 Valid values are:
1516 relative Relative to the current directory, i.e. the directory of the file
1517 into which the link is being inserted.
1518 absolute Absolute path, if possible with ~ for home directory.
1519 noabbrev Absolute path, no abbreviation of home directory.
1520 adaptive Use relative path for files in the current directory and sub-
1521 directories of it. For other files, use an absolute path."
1522 :group 'org-link
1523 :type '(choice
1524 (const relative)
1525 (const absolute)
1526 (const noabbrev)
1527 (const adaptive)))
1529 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1530 "Types of links that should be activated in Org-mode files.
1531 This is a list of symbols, each leading to the activation of a certain link
1532 type. In principle, it does not hurt to turn on most link types - there may
1533 be a small gain when turning off unused link types. The types are:
1535 bracket The recommended [[link][description]] or [[link]] links with hiding.
1536 angle Links in angular brackets that may contain whitespace like
1537 <bbdb:Carsten Dominik>.
1538 plain Plain links in normal text, no whitespace, like http://google.com.
1539 radio Text that is matched by a radio target, see manual for details.
1540 tag Tag settings in a headline (link to tag search).
1541 date Time stamps (link to calendar).
1542 footnote Footnote labels.
1544 Changing this variable requires a restart of Emacs to become effective."
1545 :group 'org-link
1546 :type '(set :greedy t
1547 (const :tag "Double bracket links" bracket)
1548 (const :tag "Angular bracket links" angle)
1549 (const :tag "Plain text links" plain)
1550 (const :tag "Radio target matches" radio)
1551 (const :tag "Tags" tag)
1552 (const :tag "Timestamps" date)
1553 (const :tag "Footnotes" footnote)))
1555 (defcustom org-make-link-description-function nil
1556 "Function to use for generating link descriptions from links.
1557 When nil, the link location will be used. This function must take
1558 two parameters: the first one is the link, the second one is the
1559 description generated by `org-insert-link'. The function should
1560 return the description to use."
1561 :group 'org-link
1562 :type 'function)
1564 (defgroup org-link-store nil
1565 "Options concerning storing links in Org-mode."
1566 :tag "Org Store Link"
1567 :group 'org-link)
1569 (defcustom org-url-hexify-p t
1570 "When non-nil, hexify URL when creating a link."
1571 :type 'boolean
1572 :version "24.3"
1573 :group 'org-link-store)
1575 (defcustom org-email-link-description-format "Email %c: %.30s"
1576 "Format of the description part of a link to an email or usenet message.
1577 The following %-escapes will be replaced by corresponding information:
1579 %F full \"From\" field
1580 %f name, taken from \"From\" field, address if no name
1581 %T full \"To\" field
1582 %t first name in \"To\" field, address if no name
1583 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1584 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1585 %s subject
1586 %d date
1587 %m message-id.
1589 You may use normal field width specification between the % and the letter.
1590 This is for example useful to limit the length of the subject.
1592 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1593 :group 'org-link-store
1594 :type 'string)
1596 (defcustom org-from-is-user-regexp
1597 (let (r1 r2)
1598 (when (and user-mail-address (not (string= user-mail-address "")))
1599 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1600 (when (and user-full-name (not (string= user-full-name "")))
1601 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1602 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1603 "Regexp matched against the \"From:\" header of an email or usenet message.
1604 It should match if the message is from the user him/herself."
1605 :group 'org-link-store
1606 :type 'regexp)
1608 (defcustom org-context-in-file-links t
1609 "Non-nil means file links from `org-store-link' contain context.
1610 A search string will be added to the file name with :: as separator and
1611 used to find the context when the link is activated by the command
1612 `org-open-at-point'. When this option is t, the entire active region
1613 will be placed in the search string of the file link. If set to a
1614 positive integer, only the first n lines of context will be stored.
1616 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1617 negates this setting for the duration of the command."
1618 :group 'org-link-store
1619 :type '(choice boolean integer))
1621 (defcustom org-keep-stored-link-after-insertion nil
1622 "Non-nil means keep link in list for entire session.
1624 The command `org-store-link' adds a link pointing to the current
1625 location to an internal list. These links accumulate during a session.
1626 The command `org-insert-link' can be used to insert links into any
1627 Org-mode file (offering completion for all stored links). When this
1628 option is nil, every link which has been inserted once using \\[org-insert-link]
1629 will be removed from the list, to make completing the unused links
1630 more efficient."
1631 :group 'org-link-store
1632 :type 'boolean)
1634 (defgroup org-link-follow nil
1635 "Options concerning following links in Org-mode."
1636 :tag "Org Follow Link"
1637 :group 'org-link)
1639 (defcustom org-link-translation-function nil
1640 "Function to translate links with different syntax to Org syntax.
1641 This can be used to translate links created for example by the Planner
1642 or emacs-wiki packages to Org syntax.
1643 The function must accept two parameters, a TYPE containing the link
1644 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1645 which is everything after the link protocol. It should return a cons
1646 with possibly modified values of type and path.
1647 Org contains a function for this, so if you set this variable to
1648 `org-translate-link-from-planner', you should be able follow many
1649 links created by planner."
1650 :group 'org-link-follow
1651 :type 'function)
1653 (defcustom org-follow-link-hook nil
1654 "Hook that is run after a link has been followed."
1655 :group 'org-link-follow
1656 :type 'hook)
1658 (defcustom org-tab-follows-link nil
1659 "Non-nil means on links TAB will follow the link.
1660 Needs to be set before org.el is loaded.
1661 This really should not be used, it does not make sense, and the
1662 implementation is bad."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-return-follows-link nil
1667 "Non-nil means on links RET will follow the link.
1668 In tables, the special behavior of RET has precedence."
1669 :group 'org-link-follow
1670 :type 'boolean)
1672 (defcustom org-mouse-1-follows-link
1673 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1674 "Non-nil means mouse-1 on a link will follow the link.
1675 A longer mouse click will still set point. Does not work on XEmacs.
1676 Needs to be set before org.el is loaded."
1677 :group 'org-link-follow
1678 :type 'boolean)
1680 (defcustom org-mark-ring-length 4
1681 "Number of different positions to be recorded in the ring.
1682 Changing this requires a restart of Emacs to work correctly."
1683 :group 'org-link-follow
1684 :type 'integer)
1686 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1687 "Non-nil means internal links in Org files must exactly match a headline.
1688 When nil, the link search tries to match a phrase with all words
1689 in the search text."
1690 :group 'org-link-follow
1691 :version "24.1"
1692 :type '(choice
1693 (const :tag "Use fuzzy text search" nil)
1694 (const :tag "Match only exact headline" t)
1695 (const :tag "Match exact headline or query to create it"
1696 query-to-create)))
1698 (defcustom org-link-frame-setup
1699 '((vm . vm-visit-folder-other-frame)
1700 (vm-imap . vm-visit-imap-folder-other-frame)
1701 (gnus . org-gnus-no-new-news)
1702 (file . find-file-other-window)
1703 (wl . wl-other-frame))
1704 "Setup the frame configuration for following links.
1705 When following a link with Emacs, it may often be useful to display
1706 this link in another window or frame. This variable can be used to
1707 set this up for the different types of links.
1708 For VM, use any of
1709 `vm-visit-folder'
1710 `vm-visit-folder-other-window'
1711 `vm-visit-folder-other-frame'
1712 For Gnus, use any of
1713 `gnus'
1714 `gnus-other-frame'
1715 `org-gnus-no-new-news'
1716 For FILE, use any of
1717 `find-file'
1718 `find-file-other-window'
1719 `find-file-other-frame'
1720 For Wanderlust use any of
1721 `wl'
1722 `wl-other-frame'
1723 For the calendar, use the variable `calendar-setup'.
1724 For BBDB, it is currently only possible to display the matches in
1725 another window."
1726 :group 'org-link-follow
1727 :type '(list
1728 (cons (const vm)
1729 (choice
1730 (const vm-visit-folder)
1731 (const vm-visit-folder-other-window)
1732 (const vm-visit-folder-other-frame)))
1733 (cons (const gnus)
1734 (choice
1735 (const gnus)
1736 (const gnus-other-frame)
1737 (const org-gnus-no-new-news)))
1738 (cons (const file)
1739 (choice
1740 (const find-file)
1741 (const find-file-other-window)
1742 (const find-file-other-frame)))
1743 (cons (const wl)
1744 (choice
1745 (const wl)
1746 (const wl-other-frame)))))
1748 (defcustom org-display-internal-link-with-indirect-buffer nil
1749 "Non-nil means use indirect buffer to display infile links.
1750 Activating internal links (from one location in a file to another location
1751 in the same file) normally just jumps to the location. When the link is
1752 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1753 is displayed in
1754 another window. When this option is set, the other window actually displays
1755 an indirect buffer clone of the current buffer, to avoid any visibility
1756 changes to the current buffer."
1757 :group 'org-link-follow
1758 :type 'boolean)
1760 (defcustom org-open-non-existing-files nil
1761 "Non-nil means `org-open-file' will open non-existing files.
1762 When nil, an error will be generated.
1763 This variable applies only to external applications because they
1764 might choke on non-existing files. If the link is to a file that
1765 will be opened in Emacs, the variable is ignored."
1766 :group 'org-link-follow
1767 :type 'boolean)
1769 (defcustom org-open-directory-means-index-dot-org nil
1770 "Non-nil means a link to a directory really means to index.org.
1771 When nil, following a directory link will run dired or open a finder/explorer
1772 window on that directory."
1773 :group 'org-link-follow
1774 :type 'boolean)
1776 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1777 "Function and arguments to call for following mailto links.
1778 This is a list with the first element being a Lisp function, and the
1779 remaining elements being arguments to the function. In string arguments,
1780 %a will be replaced by the address, and %s will be replaced by the subject
1781 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1782 :group 'org-link-follow
1783 :type '(choice
1784 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1785 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1786 (const :tag "message-mail" (message-mail "%a" "%s"))
1787 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1789 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1790 "Non-nil means ask for confirmation before executing shell links.
1791 Shell links can be dangerous: just think about a link
1793 [[shell:rm -rf ~/*][Google Search]]
1795 This link would show up in your Org-mode document as \"Google Search\",
1796 but really it would remove your entire home directory.
1797 Therefore we advise against setting this variable to nil.
1798 Just change it to `y-or-n-p' if you want to confirm with a
1799 single keystroke rather than having to type \"yes\"."
1800 :group 'org-link-follow
1801 :type '(choice
1802 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1803 (const :tag "with y-or-n (faster)" y-or-n-p)
1804 (const :tag "no confirmation (dangerous)" nil)))
1805 (put 'org-confirm-shell-link-function
1806 'safe-local-variable
1807 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1809 (defcustom org-confirm-shell-link-not-regexp ""
1810 "A regexp to skip confirmation for shell links."
1811 :group 'org-link-follow
1812 :version "24.1"
1813 :type 'regexp)
1815 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1816 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1817 Elisp links can be dangerous: just think about a link
1819 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1821 This link would show up in your Org-mode document as \"Google Search\",
1822 but really it would remove your entire home directory.
1823 Therefore we advise against setting this variable to nil.
1824 Just change it to `y-or-n-p' if you want to confirm with a
1825 single keystroke rather than having to type \"yes\"."
1826 :group 'org-link-follow
1827 :type '(choice
1828 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1829 (const :tag "with y-or-n (faster)" y-or-n-p)
1830 (const :tag "no confirmation (dangerous)" nil)))
1831 (put 'org-confirm-shell-link-function
1832 'safe-local-variable
1833 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1835 (defcustom org-confirm-elisp-link-not-regexp ""
1836 "A regexp to skip confirmation for Elisp links."
1837 :group 'org-link-follow
1838 :version "24.1"
1839 :type 'regexp)
1841 (defconst org-file-apps-defaults-gnu
1842 '((remote . emacs)
1843 (system . mailcap)
1844 (t . mailcap))
1845 "Default file applications on a UNIX or GNU/Linux system.
1846 See `org-file-apps'.")
1848 (defconst org-file-apps-defaults-macosx
1849 '((remote . emacs)
1850 (t . "open %s")
1851 (system . "open %s")
1852 ("ps.gz" . "gv %s")
1853 ("eps.gz" . "gv %s")
1854 ("dvi" . "xdvi %s")
1855 ("fig" . "xfig %s"))
1856 "Default file applications on a MacOS X system.
1857 The system \"open\" is known as a default, but we use X11 applications
1858 for some files for which the OS does not have a good default.
1859 See `org-file-apps'.")
1861 (defconst org-file-apps-defaults-windowsnt
1862 (list
1863 '(remote . emacs)
1864 (cons t
1865 (list (if (featurep 'xemacs)
1866 'mswindows-shell-execute
1867 'w32-shell-execute)
1868 "open" 'file))
1869 (cons 'system
1870 (list (if (featurep 'xemacs)
1871 'mswindows-shell-execute
1872 'w32-shell-execute)
1873 "open" 'file)))
1874 "Default file applications on a Windows NT system.
1875 The system \"open\" is used for most files.
1876 See `org-file-apps'.")
1878 (defcustom org-file-apps
1880 (auto-mode . emacs)
1881 ("\\.mm\\'" . default)
1882 ("\\.x?html?\\'" . default)
1883 ("\\.pdf\\'" . default)
1885 "External applications for opening `file:path' items in a document.
1886 Org-mode uses system defaults for different file types, but
1887 you can use this variable to set the application for a given file
1888 extension. The entries in this list are cons cells where the car identifies
1889 files and the cdr the corresponding command. Possible values for the
1890 file identifier are
1891 \"string\" A string as a file identifier can be interpreted in different
1892 ways, depending on its contents:
1894 - Alphanumeric characters only:
1895 Match links with this file extension.
1896 Example: (\"pdf\" . \"evince %s\")
1897 to open PDFs with evince.
1899 - Regular expression: Match links where the
1900 filename matches the regexp. If you want to
1901 use groups here, use shy groups.
1903 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1904 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1905 to open *.html and *.xhtml with firefox.
1907 - Regular expression which contains (non-shy) groups:
1908 Match links where the whole link, including \"::\", and
1909 anything after that, matches the regexp.
1910 In a custom command string, %1, %2, etc. are replaced with
1911 the parts of the link that were matched by the groups.
1912 For backwards compatibility, if a command string is given
1913 that does not use any of the group matches, this case is
1914 handled identically to the second one (i.e. match against
1915 file name only).
1916 In a custom lisp form, you can access the group matches with
1917 (match-string n link).
1919 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1920 to open [[file:document.pdf::5]] with evince at page 5.
1922 `directory' Matches a directory
1923 `remote' Matches a remote file, accessible through tramp or efs.
1924 Remote files most likely should be visited through Emacs
1925 because external applications cannot handle such paths.
1926 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1927 so all files Emacs knows how to handle. Using this with
1928 command `emacs' will open most files in Emacs. Beware that this
1929 will also open html files inside Emacs, unless you add
1930 (\"html\" . default) to the list as well.
1931 t Default for files not matched by any of the other options.
1932 `system' The system command to open files, like `open' on Windows
1933 and Mac OS X, and mailcap under GNU/Linux. This is the command
1934 that will be selected if you call `C-c C-o' with a double
1935 \\[universal-argument] \\[universal-argument] prefix.
1937 Possible values for the command are:
1938 `emacs' The file will be visited by the current Emacs process.
1939 `default' Use the default application for this file type, which is the
1940 association for t in the list, most likely in the system-specific
1941 part.
1942 This can be used to overrule an unwanted setting in the
1943 system-specific variable.
1944 `system' Use the system command for opening files, like \"open\".
1945 This command is specified by the entry whose car is `system'.
1946 Most likely, the system-specific version of this variable
1947 does define this command, but you can overrule/replace it
1948 here.
1949 string A command to be executed by a shell; %s will be replaced
1950 by the path to the file.
1951 sexp A Lisp form which will be evaluated. The file path will
1952 be available in the Lisp variable `file'.
1953 For more examples, see the system specific constants
1954 `org-file-apps-defaults-macosx'
1955 `org-file-apps-defaults-windowsnt'
1956 `org-file-apps-defaults-gnu'."
1957 :group 'org-link-follow
1958 :type '(repeat
1959 (cons (choice :value ""
1960 (string :tag "Extension")
1961 (const :tag "System command to open files" system)
1962 (const :tag "Default for unrecognized files" t)
1963 (const :tag "Remote file" remote)
1964 (const :tag "Links to a directory" directory)
1965 (const :tag "Any files that have Emacs modes"
1966 auto-mode))
1967 (choice :value ""
1968 (const :tag "Visit with Emacs" emacs)
1969 (const :tag "Use default" default)
1970 (const :tag "Use the system command" system)
1971 (string :tag "Command")
1972 (sexp :tag "Lisp form")))))
1974 (defcustom org-doi-server-url "http://dx.doi.org/"
1975 "The URL of the DOI server."
1976 :type 'string
1977 :version "24.3"
1978 :group 'org-link-follow)
1980 (defgroup org-refile nil
1981 "Options concerning refiling entries in Org-mode."
1982 :tag "Org Refile"
1983 :group 'org)
1985 (defcustom org-directory "~/org"
1986 "Directory with org files.
1987 This is just a default location to look for Org files. There is no need
1988 at all to put your files into this directory. It is only used in the
1989 following situations:
1991 1. When a capture template specifies a target file that is not an
1992 absolute path. The path will then be interpreted relative to
1993 `org-directory'
1994 2. When a capture note is filed away in an interactive way (when exiting the
1995 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1996 with `org-directory' as the default path."
1997 :group 'org-refile
1998 :group 'org-remember
1999 :group 'org-capture
2000 :type 'directory)
2002 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2003 "Default target for storing notes.
2004 Used as a fall back file for org-remember.el and org-capture.el, for
2005 templates that do not specify a target file."
2006 :group 'org-refile
2007 :group 'org-remember
2008 :group 'org-capture
2009 :type '(choice
2010 (const :tag "Default from remember-data-file" nil)
2011 file))
2013 (defcustom org-goto-interface 'outline
2014 "The default interface to be used for `org-goto'.
2015 Allowed values are:
2016 outline The interface shows an outline of the relevant file
2017 and the correct heading is found by moving through
2018 the outline or by searching with incremental search.
2019 outline-path-completion Headlines in the current buffer are offered via
2020 completion. This is the interface also used by
2021 the refile command."
2022 :group 'org-refile
2023 :type '(choice
2024 (const :tag "Outline" outline)
2025 (const :tag "Outline-path-completion" outline-path-completion)))
2027 (defcustom org-goto-max-level 5
2028 "Maximum target level when running `org-goto' with refile interface."
2029 :group 'org-refile
2030 :type 'integer)
2032 (defcustom org-reverse-note-order nil
2033 "Non-nil means store new notes at the beginning of a file or entry.
2034 When nil, new notes will be filed to the end of a file or entry.
2035 This can also be a list with cons cells of regular expressions that
2036 are matched against file names, and values."
2037 :group 'org-remember
2038 :group 'org-capture
2039 :group 'org-refile
2040 :type '(choice
2041 (const :tag "Reverse always" t)
2042 (const :tag "Reverse never" nil)
2043 (repeat :tag "By file name regexp"
2044 (cons regexp boolean))))
2046 (defcustom org-log-refile nil
2047 "Information to record when a task is refiled.
2049 Possible values are:
2051 nil Don't add anything
2052 time Add a time stamp to the task
2053 note Prompt for a note and add it with template `org-log-note-headings'
2055 This option can also be set with on a per-file-basis with
2057 #+STARTUP: nologrefile
2058 #+STARTUP: logrefile
2059 #+STARTUP: lognoterefile
2061 You can have local logging settings for a subtree by setting the LOGGING
2062 property to one or more of these keywords.
2064 When bulk-refiling from the agenda, the value `note' is forbidden and
2065 will temporarily be changed to `time'."
2066 :group 'org-refile
2067 :group 'org-progress
2068 :version "24.1"
2069 :type '(choice
2070 (const :tag "No logging" nil)
2071 (const :tag "Record timestamp" time)
2072 (const :tag "Record timestamp with note." note)))
2074 (defcustom org-refile-targets nil
2075 "Targets for refiling entries with \\[org-refile].
2076 This is a list of cons cells. Each cell contains:
2077 - a specification of the files to be considered, either a list of files,
2078 or a symbol whose function or variable value will be used to retrieve
2079 a file name or a list of file names. If you use `org-agenda-files' for
2080 that, all agenda files will be scanned for targets. Nil means consider
2081 headings in the current buffer.
2082 - A specification of how to find candidate refile targets. This may be
2083 any of:
2084 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2085 This tag has to be present in all target headlines, inheritance will
2086 not be considered.
2087 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2088 todo keyword.
2089 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2090 headlines that are refiling targets.
2091 - a cons cell (:level . N). Any headline of level N is considered a target.
2092 Note that, when `org-odd-levels-only' is set, level corresponds to
2093 order in hierarchy, not to the number of stars.
2094 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2095 Note that, when `org-odd-levels-only' is set, level corresponds to
2096 order in hierarchy, not to the number of stars.
2098 Each element of this list generates a set of possible targets.
2099 The union of these sets is presented (with completion) to
2100 the user by `org-refile'.
2102 You can set the variable `org-refile-target-verify-function' to a function
2103 to verify each headline found by the simple criteria above.
2105 When this variable is nil, all top-level headlines in the current buffer
2106 are used, equivalent to the value `((nil . (:level . 1))'."
2107 :group 'org-refile
2108 :type '(repeat
2109 (cons
2110 (choice :value org-agenda-files
2111 (const :tag "All agenda files" org-agenda-files)
2112 (const :tag "Current buffer" nil)
2113 (function) (variable) (file))
2114 (choice :tag "Identify target headline by"
2115 (cons :tag "Specific tag" (const :value :tag) (string))
2116 (cons :tag "TODO keyword" (const :value :todo) (string))
2117 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2118 (cons :tag "Level number" (const :value :level) (integer))
2119 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2121 (defcustom org-refile-target-verify-function nil
2122 "Function to verify if the headline at point should be a refile target.
2123 The function will be called without arguments, with point at the
2124 beginning of the headline. It should return t and leave point
2125 where it is if the headline is a valid target for refiling.
2127 If the target should not be selected, the function must return nil.
2128 In addition to this, it may move point to a place from where the search
2129 should be continued. For example, the function may decide that the entire
2130 subtree of the current entry should be excluded and move point to the end
2131 of the subtree."
2132 :group 'org-refile
2133 :type 'function)
2135 (defcustom org-refile-use-cache nil
2136 "Non-nil means cache refile targets to speed up the process.
2137 The cache for a particular file will be updated automatically when
2138 the buffer has been killed, or when any of the marker used for flagging
2139 refile targets no longer points at a live buffer.
2140 If you have added new entries to a buffer that might themselves be targets,
2141 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2142 find that easier, `C-u C-u C-u C-c C-w'."
2143 :group 'org-refile
2144 :version "24.1"
2145 :type 'boolean)
2147 (defcustom org-refile-use-outline-path nil
2148 "Non-nil means provide refile targets as paths.
2149 So a level 3 headline will be available as level1/level2/level3.
2151 When the value is `file', also include the file name (without directory)
2152 into the path. In this case, you can also stop the completion after
2153 the file name, to get entries inserted as top level in the file.
2155 When `full-file-path', include the full file path."
2156 :group 'org-refile
2157 :type '(choice
2158 (const :tag "Not" nil)
2159 (const :tag "Yes" t)
2160 (const :tag "Start with file name" file)
2161 (const :tag "Start with full file path" full-file-path)))
2163 (defcustom org-outline-path-complete-in-steps t
2164 "Non-nil means complete the outline path in hierarchical steps.
2165 When Org-mode uses the refile interface to select an outline path
2166 \(see variable `org-refile-use-outline-path'), the completion of
2167 the path can be done is a single go, or if can be done in steps down
2168 the headline hierarchy. Going in steps is probably the best if you
2169 do not use a special completion package like `ido' or `icicles'.
2170 However, when using these packages, going in one step can be very
2171 fast, while still showing the whole path to the entry."
2172 :group 'org-refile
2173 :type 'boolean)
2175 (defcustom org-refile-allow-creating-parent-nodes nil
2176 "Non-nil means allow to create new nodes as refile targets.
2177 New nodes are then created by adding \"/new node name\" to the completion
2178 of an existing node. When the value of this variable is `confirm',
2179 new node creation must be confirmed by the user (recommended)
2180 When nil, the completion must match an existing entry.
2182 Note that, if the new heading is not seen by the criteria
2183 listed in `org-refile-targets', multiple instances of the same
2184 heading would be created by trying again to file under the new
2185 heading."
2186 :group 'org-refile
2187 :type '(choice
2188 (const :tag "Never" nil)
2189 (const :tag "Always" t)
2190 (const :tag "Prompt for confirmation" confirm)))
2192 (defcustom org-refile-active-region-within-subtree nil
2193 "Non-nil means also refile active region within a subtree.
2195 By default `org-refile' doesn't allow refiling regions if they
2196 don't contain a set of subtrees, but it might be convenient to
2197 do so sometimes: in that case, the first line of the region is
2198 converted to a headline before refiling."
2199 :group 'org-refile
2200 :version "24.1"
2201 :type 'boolean)
2203 (defgroup org-todo nil
2204 "Options concerning TODO items in Org-mode."
2205 :tag "Org TODO"
2206 :group 'org)
2208 (defgroup org-progress nil
2209 "Options concerning Progress logging in Org-mode."
2210 :tag "Org Progress"
2211 :group 'org-time)
2213 (defvar org-todo-interpretation-widgets
2214 '((:tag "Sequence (cycling hits every state)" sequence)
2215 (:tag "Type (cycling directly to DONE)" type))
2216 "The available interpretation symbols for customizing `org-todo-keywords'.
2217 Interested libraries should add to this list.")
2219 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2220 "List of TODO entry keyword sequences and their interpretation.
2221 \\<org-mode-map>This is a list of sequences.
2223 Each sequence starts with a symbol, either `sequence' or `type',
2224 indicating if the keywords should be interpreted as a sequence of
2225 action steps, or as different types of TODO items. The first
2226 keywords are states requiring action - these states will select a headline
2227 for inclusion into the global TODO list Org-mode produces. If one of
2228 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2229 signify that no further action is necessary. If \"|\" is not found,
2230 the last keyword is treated as the only DONE state of the sequence.
2232 The command \\[org-todo] cycles an entry through these states, and one
2233 additional state where no keyword is present. For details about this
2234 cycling, see the manual.
2236 TODO keywords and interpretation can also be set on a per-file basis with
2237 the special #+SEQ_TODO and #+TYP_TODO lines.
2239 Each keyword can optionally specify a character for fast state selection
2240 \(in combination with the variable `org-use-fast-todo-selection')
2241 and specifiers for state change logging, using the same syntax that
2242 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2243 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2244 indicates to record a time stamp each time this state is selected.
2246 Each keyword may also specify if a timestamp or a note should be
2247 recorded when entering or leaving the state, by adding additional
2248 characters in the parenthesis after the keyword. This looks like this:
2249 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2250 record only the time of the state change. With X and Y being either
2251 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2252 Y when leaving the state if and only if the *target* state does not
2253 define X. You may omit any of the fast-selection key or X or /Y,
2254 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2256 For backward compatibility, this variable may also be just a list
2257 of keywords. In this case the interpretation (sequence or type) will be
2258 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2259 :group 'org-todo
2260 :group 'org-keywords
2261 :type '(choice
2262 (repeat :tag "Old syntax, just keywords"
2263 (string :tag "Keyword"))
2264 (repeat :tag "New syntax"
2265 (cons
2266 (choice
2267 :tag "Interpretation"
2268 ;;Quick and dirty way to see
2269 ;;`org-todo-interpretations'. This takes the
2270 ;;place of item arguments
2271 :convert-widget
2272 (lambda (widget)
2273 (widget-put widget
2274 :args (mapcar
2275 #'(lambda (x)
2276 (widget-convert
2277 (cons 'const x)))
2278 org-todo-interpretation-widgets))
2279 widget))
2280 (repeat
2281 (string :tag "Keyword"))))))
2283 (defvar org-todo-keywords-1 nil
2284 "All TODO and DONE keywords active in a buffer.")
2285 (make-variable-buffer-local 'org-todo-keywords-1)
2286 (defvar org-todo-keywords-for-agenda nil)
2287 (defvar org-done-keywords-for-agenda nil)
2288 (defvar org-drawers-for-agenda nil)
2289 (defvar org-todo-keyword-alist-for-agenda nil)
2290 (defvar org-tag-alist-for-agenda nil)
2291 (defvar org-agenda-contributing-files nil)
2292 (defvar org-not-done-keywords nil)
2293 (make-variable-buffer-local 'org-not-done-keywords)
2294 (defvar org-done-keywords nil)
2295 (make-variable-buffer-local 'org-done-keywords)
2296 (defvar org-todo-heads nil)
2297 (make-variable-buffer-local 'org-todo-heads)
2298 (defvar org-todo-sets nil)
2299 (make-variable-buffer-local 'org-todo-sets)
2300 (defvar org-todo-log-states nil)
2301 (make-variable-buffer-local 'org-todo-log-states)
2302 (defvar org-todo-kwd-alist nil)
2303 (make-variable-buffer-local 'org-todo-kwd-alist)
2304 (defvar org-todo-key-alist nil)
2305 (make-variable-buffer-local 'org-todo-key-alist)
2306 (defvar org-todo-key-trigger nil)
2307 (make-variable-buffer-local 'org-todo-key-trigger)
2309 (defcustom org-todo-interpretation 'sequence
2310 "Controls how TODO keywords are interpreted.
2311 This variable is in principle obsolete and is only used for
2312 backward compatibility, if the interpretation of todo keywords is
2313 not given already in `org-todo-keywords'. See that variable for
2314 more information."
2315 :group 'org-todo
2316 :group 'org-keywords
2317 :type '(choice (const sequence)
2318 (const type)))
2320 (defcustom org-use-fast-todo-selection t
2321 "Non-nil means use the fast todo selection scheme with C-c C-t.
2322 This variable describes if and under what circumstances the cycling
2323 mechanism for TODO keywords will be replaced by a single-key, direct
2324 selection scheme.
2326 When nil, fast selection is never used.
2328 When the symbol `prefix', it will be used when `org-todo' is called
2329 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2330 `C-u t' in an agenda buffer.
2332 When t, fast selection is used by default. In this case, the prefix
2333 argument forces cycling instead.
2335 In all cases, the special interface is only used if access keys have
2336 actually been assigned by the user, i.e. if keywords in the configuration
2337 are followed by a letter in parenthesis, like TODO(t)."
2338 :group 'org-todo
2339 :type '(choice
2340 (const :tag "Never" nil)
2341 (const :tag "By default" t)
2342 (const :tag "Only with C-u C-c C-t" prefix)))
2344 (defcustom org-provide-todo-statistics t
2345 "Non-nil means update todo statistics after insert and toggle.
2346 ALL-HEADLINES means update todo statistics by including headlines
2347 with no TODO keyword as well, counting them as not done.
2348 A list of TODO keywords means the same, but skip keywords that are
2349 not in this list.
2351 When this is set, todo statistics is updated in the parent of the
2352 current entry each time a todo state is changed."
2353 :group 'org-todo
2354 :type '(choice
2355 (const :tag "Yes, only for TODO entries" t)
2356 (const :tag "Yes, including all entries" 'all-headlines)
2357 (repeat :tag "Yes, for TODOs in this list"
2358 (string :tag "TODO keyword"))
2359 (other :tag "No TODO statistics" nil)))
2361 (defcustom org-hierarchical-todo-statistics t
2362 "Non-nil means TODO statistics covers just direct children.
2363 When nil, all entries in the subtree are considered.
2364 This has only an effect if `org-provide-todo-statistics' is set.
2365 To set this to nil for only a single subtree, use a COOKIE_DATA
2366 property and include the word \"recursive\" into the value."
2367 :group 'org-todo
2368 :type 'boolean)
2370 (defcustom org-after-todo-state-change-hook nil
2371 "Hook which is run after the state of a TODO item was changed.
2372 The new state (a string with a TODO keyword, or nil) is available in the
2373 Lisp variable `org-state'."
2374 :group 'org-todo
2375 :type 'hook)
2377 (defvar org-blocker-hook nil
2378 "Hook for functions that are allowed to block a state change.
2380 Functions in this hook should not modify the buffer.
2381 Each function gets as its single argument a property list,
2382 see `org-trigger-hook' for more information about this list.
2384 If any of the functions in this hook returns nil, the state change
2385 is blocked.")
2387 (defvar org-trigger-hook nil
2388 "Hook for functions that are triggered by a state change.
2390 Each function gets as its single argument a property list with at
2391 least the following elements:
2393 (:type type-of-change :position pos-at-entry-start
2394 :from old-state :to new-state)
2396 Depending on the type, more properties may be present.
2398 This mechanism is currently implemented for:
2400 TODO state changes
2401 ------------------
2402 :type todo-state-change
2403 :from previous state (keyword as a string), or nil, or a symbol
2404 'todo' or 'done', to indicate the general type of state.
2405 :to new state, like in :from")
2407 (defcustom org-enforce-todo-dependencies nil
2408 "Non-nil means undone TODO entries will block switching the parent to DONE.
2409 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2410 be blocked if any prior sibling is not yet done.
2411 Finally, if the parent is blocked because of ordered siblings of its own,
2412 the child will also be blocked."
2413 :set (lambda (var val)
2414 (set var val)
2415 (if val
2416 (add-hook 'org-blocker-hook
2417 'org-block-todo-from-children-or-siblings-or-parent)
2418 (remove-hook 'org-blocker-hook
2419 'org-block-todo-from-children-or-siblings-or-parent)))
2420 :group 'org-todo
2421 :type 'boolean)
2423 (defcustom org-enforce-todo-checkbox-dependencies nil
2424 "Non-nil means unchecked boxes will block switching the parent to DONE.
2425 When this is nil, checkboxes have no influence on switching TODO states.
2426 When non-nil, you first need to check off all check boxes before the TODO
2427 entry can be switched to DONE.
2428 This variable needs to be set before org.el is loaded, and you need to
2429 restart Emacs after a change to make the change effective. The only way
2430 to change is while Emacs is running is through the customize interface."
2431 :set (lambda (var val)
2432 (set var val)
2433 (if val
2434 (add-hook 'org-blocker-hook
2435 'org-block-todo-from-checkboxes)
2436 (remove-hook 'org-blocker-hook
2437 'org-block-todo-from-checkboxes)))
2438 :group 'org-todo
2439 :type 'boolean)
2441 (defcustom org-treat-insert-todo-heading-as-state-change nil
2442 "Non-nil means inserting a TODO heading is treated as state change.
2443 So when the command \\[org-insert-todo-heading] is used, state change
2444 logging will apply if appropriate. When nil, the new TODO item will
2445 be inserted directly, and no logging will take place."
2446 :group 'org-todo
2447 :type 'boolean)
2449 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2450 "Non-nil means switching TODO states with S-cursor counts as state change.
2451 This is the default behavior. However, setting this to nil allows a
2452 convenient way to select a TODO state and bypass any logging associated
2453 with that."
2454 :group 'org-todo
2455 :type 'boolean)
2457 (defcustom org-todo-state-tags-triggers nil
2458 "Tag changes that should be triggered by TODO state changes.
2459 This is a list. Each entry is
2461 (state-change (tag . flag) .......)
2463 State-change can be a string with a state, and empty string to indicate the
2464 state that has no TODO keyword, or it can be one of the symbols `todo'
2465 or `done', meaning any not-done or done state, respectively."
2466 :group 'org-todo
2467 :group 'org-tags
2468 :type '(repeat
2469 (cons (choice :tag "When changing to"
2470 (const :tag "Not-done state" todo)
2471 (const :tag "Done state" done)
2472 (string :tag "State"))
2473 (repeat
2474 (cons :tag "Tag action"
2475 (string :tag "Tag")
2476 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2478 (defcustom org-log-done nil
2479 "Information to record when a task moves to the DONE state.
2481 Possible values are:
2483 nil Don't add anything, just change the keyword
2484 time Add a time stamp to the task
2485 note Prompt for a note and add it with template `org-log-note-headings'
2487 This option can also be set with on a per-file-basis with
2489 #+STARTUP: nologdone
2490 #+STARTUP: logdone
2491 #+STARTUP: lognotedone
2493 You can have local logging settings for a subtree by setting the LOGGING
2494 property to one or more of these keywords."
2495 :group 'org-todo
2496 :group 'org-progress
2497 :type '(choice
2498 (const :tag "No logging" nil)
2499 (const :tag "Record CLOSED timestamp" time)
2500 (const :tag "Record CLOSED timestamp with note." note)))
2502 ;; Normalize old uses of org-log-done.
2503 (cond
2504 ((eq org-log-done t) (setq org-log-done 'time))
2505 ((and (listp org-log-done) (memq 'done org-log-done))
2506 (setq org-log-done 'note)))
2508 (defcustom org-log-reschedule nil
2509 "Information to record when the scheduling date of a tasks is modified.
2511 Possible values are:
2513 nil Don't add anything, just change the date
2514 time Add a time stamp to the task
2515 note Prompt for a note and add it with template `org-log-note-headings'
2517 This option can also be set with on a per-file-basis with
2519 #+STARTUP: nologreschedule
2520 #+STARTUP: logreschedule
2521 #+STARTUP: lognotereschedule"
2522 :group 'org-todo
2523 :group 'org-progress
2524 :type '(choice
2525 (const :tag "No logging" nil)
2526 (const :tag "Record timestamp" time)
2527 (const :tag "Record timestamp with note." note)))
2529 (defcustom org-log-redeadline nil
2530 "Information to record when the deadline date of a tasks is modified.
2532 Possible values are:
2534 nil Don't add anything, just change the date
2535 time Add a time stamp to the task
2536 note Prompt for a note and add it with template `org-log-note-headings'
2538 This option can also be set with on a per-file-basis with
2540 #+STARTUP: nologredeadline
2541 #+STARTUP: logredeadline
2542 #+STARTUP: lognoteredeadline
2544 You can have local logging settings for a subtree by setting the LOGGING
2545 property to one or more of these keywords."
2546 :group 'org-todo
2547 :group 'org-progress
2548 :type '(choice
2549 (const :tag "No logging" nil)
2550 (const :tag "Record timestamp" time)
2551 (const :tag "Record timestamp with note." note)))
2553 (defcustom org-log-note-clock-out nil
2554 "Non-nil means record a note when clocking out of an item.
2555 This can also be configured on a per-file basis by adding one of
2556 the following lines anywhere in the buffer:
2558 #+STARTUP: lognoteclock-out
2559 #+STARTUP: nolognoteclock-out"
2560 :group 'org-todo
2561 :group 'org-progress
2562 :type 'boolean)
2564 (defcustom org-log-done-with-time t
2565 "Non-nil means the CLOSED time stamp will contain date and time.
2566 When nil, only the date will be recorded."
2567 :group 'org-progress
2568 :type 'boolean)
2570 (defcustom org-log-note-headings
2571 '((done . "CLOSING NOTE %t")
2572 (state . "State %-12s from %-12S %t")
2573 (note . "Note taken on %t")
2574 (reschedule . "Rescheduled from %S on %t")
2575 (delschedule . "Not scheduled, was %S on %t")
2576 (redeadline . "New deadline from %S on %t")
2577 (deldeadline . "Removed deadline, was %S on %t")
2578 (refile . "Refiled on %t")
2579 (clock-out . ""))
2580 "Headings for notes added to entries.
2581 The value is an alist, with the car being a symbol indicating the note
2582 context, and the cdr is the heading to be used. The heading may also be the
2583 empty string.
2584 %t in the heading will be replaced by a time stamp.
2585 %T will be an active time stamp instead the default inactive one
2586 %d will be replaced by a short-format time stamp.
2587 %D will be replaced by an active short-format time stamp.
2588 %s will be replaced by the new TODO state, in double quotes.
2589 %S will be replaced by the old TODO state, in double quotes.
2590 %u will be replaced by the user name.
2591 %U will be replaced by the full user name.
2593 In fact, it is not a good idea to change the `state' entry, because
2594 agenda log mode depends on the format of these entries."
2595 :group 'org-todo
2596 :group 'org-progress
2597 :type '(list :greedy t
2598 (cons (const :tag "Heading when closing an item" done) string)
2599 (cons (const :tag
2600 "Heading when changing todo state (todo sequence only)"
2601 state) string)
2602 (cons (const :tag "Heading when just taking a note" note) string)
2603 (cons (const :tag "Heading when clocking out" clock-out) string)
2604 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2605 (cons (const :tag "Heading when rescheduling" reschedule) string)
2606 (cons (const :tag "Heading when changing deadline" redeadline) string)
2607 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2608 (cons (const :tag "Heading when refiling" refile) string)))
2610 (unless (assq 'note org-log-note-headings)
2611 (push '(note . "%t") org-log-note-headings))
2613 (defcustom org-log-into-drawer nil
2614 "Non-nil means insert state change notes and time stamps into a drawer.
2615 When nil, state changes notes will be inserted after the headline and
2616 any scheduling and clock lines, but not inside a drawer.
2618 The value of this variable should be the name of the drawer to use.
2619 LOGBOOK is proposed as the default drawer for this purpose, you can
2620 also set this to a string to define the drawer of your choice.
2622 A value of t is also allowed, representing \"LOGBOOK\".
2624 A value of t or nil can also be set with on a per-file-basis with
2626 #+STARTUP: logdrawer
2627 #+STARTUP: nologdrawer
2629 If this variable is set, `org-log-state-notes-insert-after-drawers'
2630 will be ignored.
2632 You can set the property LOG_INTO_DRAWER to overrule this setting for
2633 a subtree."
2634 :group 'org-todo
2635 :group 'org-progress
2636 :type '(choice
2637 (const :tag "Not into a drawer" nil)
2638 (const :tag "LOGBOOK" t)
2639 (string :tag "Other")))
2641 (if (fboundp 'defvaralias)
2642 (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 t
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 (if (fboundp 'defvaralias)
3091 (defvaralias 'org-popup-calendar-for-date-prompt
3092 'org-read-date-popup-calendar))
3094 (make-obsolete-variable
3095 'org-read-date-minibuffer-setup-hook
3096 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3097 (defcustom org-read-date-minibuffer-setup-hook nil
3098 "Hook to be used to set up keys for the date/time interface.
3099 Add key definitions to `minibuffer-local-map', which will be a
3100 temporary copy.
3102 WARNING: This option is obsolete, you should use
3103 `org-read-date-minibuffer-local-map' to set up keys."
3104 :group 'org-time
3105 :type 'hook)
3107 (defcustom org-extend-today-until 0
3108 "The hour when your day really ends. Must be an integer.
3109 This has influence for the following applications:
3110 - When switching the agenda to \"today\". It it is still earlier than
3111 the time given here, the day recognized as TODAY is actually yesterday.
3112 - When a date is read from the user and it is still before the time given
3113 here, the current date and time will be assumed to be yesterday, 23:59.
3114 Also, timestamps inserted in capture templates follow this rule.
3116 IMPORTANT: This is a feature whose implementation is and likely will
3117 remain incomplete. Really, it is only here because past midnight seems to
3118 be the favorite working time of John Wiegley :-)"
3119 :group 'org-time
3120 :type 'integer)
3122 (defcustom org-use-effective-time nil
3123 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3124 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3125 \"effective time\" of any timestamps between midnight and 8am will be
3126 23:59 of the previous day."
3127 :group 'org-time
3128 :version "24.1"
3129 :type 'boolean)
3131 (defcustom org-use-last-clock-out-time-as-effective-time nil
3132 "When non-nil, use the last clock out time for `org-todo'.
3133 Note that this option has precedence over the combined use of
3134 `org-use-effective-time' and `org-extend-today-until'."
3135 :group 'org-time
3136 :version "24.4"
3137 :package-version '(Org . "8.0")
3138 :type 'boolean)
3140 (defcustom org-edit-timestamp-down-means-later nil
3141 "Non-nil means S-down will increase the time in a time stamp.
3142 When nil, S-up will increase."
3143 :group 'org-time
3144 :type 'boolean)
3146 (defcustom org-calendar-follow-timestamp-change t
3147 "Non-nil means make the calendar window follow timestamp changes.
3148 When a timestamp is modified and the calendar window is visible, it will be
3149 moved to the new date."
3150 :group 'org-time
3151 :type 'boolean)
3153 (defgroup org-tags nil
3154 "Options concerning tags in Org-mode."
3155 :tag "Org Tags"
3156 :group 'org)
3158 (defcustom org-tag-alist nil
3159 "List of tags allowed in Org-mode files.
3160 When this list is nil, Org-mode will base TAG input on what is already in the
3161 buffer.
3162 The value of this variable is an alist, the car of each entry must be a
3163 keyword as a string, the cdr may be a character that is used to select
3164 that tag through the fast-tag-selection interface.
3165 See the manual for details."
3166 :group 'org-tags
3167 :type '(repeat
3168 (choice
3169 (cons (string :tag "Tag name")
3170 (character :tag "Access char"))
3171 (list :tag "Start radio group"
3172 (const :startgroup)
3173 (option (string :tag "Group description")))
3174 (list :tag "End radio group"
3175 (const :endgroup)
3176 (option (string :tag "Group description")))
3177 (const :tag "New line" (:newline)))))
3179 (defcustom org-tag-persistent-alist nil
3180 "List of tags that will always appear in all Org-mode files.
3181 This is in addition to any in buffer settings or customizations
3182 of `org-tag-alist'.
3183 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3184 The value of this variable is an alist, the car of each entry must be a
3185 keyword as a string, the cdr may be a character that is used to select
3186 that tag through the fast-tag-selection interface.
3187 See the manual for details.
3188 To disable these tags on a per-file basis, insert anywhere in the file:
3189 #+STARTUP: noptag"
3190 :group 'org-tags
3191 :type '(repeat
3192 (choice
3193 (cons (string :tag "Tag name")
3194 (character :tag "Access char"))
3195 (const :tag "Start radio group" (:startgroup))
3196 (const :tag "End radio group" (:endgroup))
3197 (const :tag "New line" (:newline)))))
3199 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3200 "If non-nil, always offer completion for all tags of all agenda files.
3201 Instead of customizing this variable directly, you might want to
3202 set it locally for capture buffers, because there no list of
3203 tags in that file can be created dynamically (there are none).
3205 (add-hook 'org-capture-mode-hook
3206 (lambda ()
3207 (set (make-local-variable
3208 'org-complete-tags-always-offer-all-agenda-tags)
3209 t)))"
3210 :group 'org-tags
3211 :version "24.1"
3212 :type 'boolean)
3214 (defvar org-file-tags nil
3215 "List of tags that can be inherited by all entries in the file.
3216 The tags will be inherited if the variable `org-use-tag-inheritance'
3217 says they should be.
3218 This variable is populated from #+FILETAGS lines.")
3220 (defcustom org-use-fast-tag-selection 'auto
3221 "Non-nil means use fast tag selection scheme.
3222 This is a special interface to select and deselect tags with single keys.
3223 When nil, fast selection is never used.
3224 When the symbol `auto', fast selection is used if and only if selection
3225 characters for tags have been configured, either through the variable
3226 `org-tag-alist' or through a #+TAGS line in the buffer.
3227 When t, fast selection is always used and selection keys are assigned
3228 automatically if necessary."
3229 :group 'org-tags
3230 :type '(choice
3231 (const :tag "Always" t)
3232 (const :tag "Never" nil)
3233 (const :tag "When selection characters are configured" 'auto)))
3235 (defcustom org-fast-tag-selection-single-key nil
3236 "Non-nil means fast tag selection exits after first change.
3237 When nil, you have to press RET to exit it.
3238 During fast tag selection, you can toggle this flag with `C-c'.
3239 This variable can also have the value `expert'. In this case, the window
3240 displaying the tags menu is not even shown, until you press C-c again."
3241 :group 'org-tags
3242 :type '(choice
3243 (const :tag "No" nil)
3244 (const :tag "Yes" t)
3245 (const :tag "Expert" expert)))
3247 (defvar org-fast-tag-selection-include-todo nil
3248 "Non-nil means fast tags selection interface will also offer TODO states.
3249 This is an undocumented feature, you should not rely on it.")
3251 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3252 "The column to which tags should be indented in a headline.
3253 If this number is positive, it specifies the column. If it is negative,
3254 it means that the tags should be flushright to that column. For example,
3255 -80 works well for a normal 80 character screen.
3256 When 0, place tags directly after headline text, with only one space in
3257 between."
3258 :group 'org-tags
3259 :type 'integer)
3261 (defcustom org-auto-align-tags t
3262 "Non-nil keeps tags aligned when modifying headlines.
3263 Some operations (i.e. demoting) change the length of a headline and
3264 therefore shift the tags around. With this option turned on, after
3265 each such operation the tags are again aligned to `org-tags-column'."
3266 :group 'org-tags
3267 :type 'boolean)
3269 (defcustom org-use-tag-inheritance t
3270 "Non-nil means tags in levels apply also for sublevels.
3271 When nil, only the tags directly given in a specific line apply there.
3272 This may also be a list of tags that should be inherited, or a regexp that
3273 matches tags that should be inherited. Additional control is possible
3274 with the variable `org-tags-exclude-from-inheritance' which gives an
3275 explicit list of tags to be excluded from inheritance, even if the value of
3276 `org-use-tag-inheritance' would select it for inheritance.
3278 If this option is t, a match early-on in a tree can lead to a large
3279 number of matches in the subtree when constructing the agenda or creating
3280 a sparse tree. If you only want to see the first match in a tree during
3281 a search, check out the variable `org-tags-match-list-sublevels'."
3282 :group 'org-tags
3283 :type '(choice
3284 (const :tag "Not" nil)
3285 (const :tag "Always" t)
3286 (repeat :tag "Specific tags" (string :tag "Tag"))
3287 (regexp :tag "Tags matched by regexp")))
3289 (defcustom org-tags-exclude-from-inheritance nil
3290 "List of tags that should never be inherited.
3291 This is a way to exclude a few tags from inheritance. For way to do
3292 the opposite, to actively allow inheritance for selected tags,
3293 see the variable `org-use-tag-inheritance'."
3294 :group 'org-tags
3295 :type '(repeat (string :tag "Tag")))
3297 (defun org-tag-inherit-p (tag)
3298 "Check if TAG is one that should be inherited."
3299 (cond
3300 ((member tag org-tags-exclude-from-inheritance) nil)
3301 ((eq org-use-tag-inheritance t) t)
3302 ((not org-use-tag-inheritance) nil)
3303 ((stringp org-use-tag-inheritance)
3304 (string-match org-use-tag-inheritance tag))
3305 ((listp org-use-tag-inheritance)
3306 (member tag org-use-tag-inheritance))
3307 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3309 (defcustom org-tags-match-list-sublevels t
3310 "Non-nil means list also sublevels of headlines matching a search.
3311 This variable applies to tags/property searches, and also to stuck
3312 projects because this search is based on a tags match as well.
3314 When set to the symbol `indented', sublevels are indented with
3315 leading dots.
3317 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3318 the sublevels of a headline matching a tag search often also match
3319 the same search. Listing all of them can create very long lists.
3320 Setting this variable to nil causes subtrees of a match to be skipped.
3322 This variable is semi-obsolete and probably should always be true. It
3323 is better to limit inheritance to certain tags using the variables
3324 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3325 :group 'org-tags
3326 :type '(choice
3327 (const :tag "No, don't list them" nil)
3328 (const :tag "Yes, do list them" t)
3329 (const :tag "List them, indented with leading dots" indented)))
3331 (defcustom org-tags-sort-function nil
3332 "When set, tags are sorted using this function as a comparator."
3333 :group 'org-tags
3334 :type '(choice
3335 (const :tag "No sorting" nil)
3336 (const :tag "Alphabetical" string<)
3337 (const :tag "Reverse alphabetical" string>)
3338 (function :tag "Custom function" nil)))
3340 (defvar org-tags-history nil
3341 "History of minibuffer reads for tags.")
3342 (defvar org-last-tags-completion-table nil
3343 "The last used completion table for tags.")
3344 (defvar org-after-tags-change-hook nil
3345 "Hook that is run after the tags in a line have changed.")
3347 (defgroup org-properties nil
3348 "Options concerning properties in Org-mode."
3349 :tag "Org Properties"
3350 :group 'org)
3352 (defcustom org-property-format "%-10s %s"
3353 "How property key/value pairs should be formatted by `indent-line'.
3354 When `indent-line' hits a property definition, it will format the line
3355 according to this format, mainly to make sure that the values are
3356 lined-up with respect to each other."
3357 :group 'org-properties
3358 :type 'string)
3360 (defcustom org-properties-postprocess-alist nil
3361 "Alist of properties and functions to adjust inserted values.
3362 Elements of this alist must be of the form
3364 ([string] [function])
3366 where [string] must be a property name and [function] must be a
3367 lambda expression: this lambda expression must take one argument,
3368 the value to adjust, and return the new value as a string.
3370 For example, this element will allow the property \"Remaining\"
3371 to be updated wrt the relation between the \"Effort\" property
3372 and the clock summary:
3374 ((\"Remaining\" (lambda(value)
3375 (let ((clocksum (org-clock-sum-current-item))
3376 (effort (org-duration-string-to-minutes
3377 (org-entry-get (point) \"Effort\"))))
3378 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3379 :group 'org-properties
3380 :version "24.1"
3381 :type '(alist :key-type (string :tag "Property")
3382 :value-type (function :tag "Function")))
3384 (defcustom org-use-property-inheritance nil
3385 "Non-nil means properties apply also for sublevels.
3387 This setting is chiefly used during property searches. Turning it on can
3388 cause significant overhead when doing a search, which is why it is not
3389 on by default.
3391 When nil, only the properties directly given in the current entry count.
3392 When t, every property is inherited. The value may also be a list of
3393 properties that should have inheritance, or a regular expression matching
3394 properties that should be inherited.
3396 However, note that some special properties use inheritance under special
3397 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3398 and the properties ending in \"_ALL\" when they are used as descriptor
3399 for valid values of a property.
3401 Note for programmers:
3402 When querying an entry with `org-entry-get', you can control if inheritance
3403 should be used. By default, `org-entry-get' looks only at the local
3404 properties. You can request inheritance by setting the inherit argument
3405 to t (to force inheritance) or to `selective' (to respect the setting
3406 in this variable)."
3407 :group 'org-properties
3408 :type '(choice
3409 (const :tag "Not" nil)
3410 (const :tag "Always" t)
3411 (repeat :tag "Specific properties" (string :tag "Property"))
3412 (regexp :tag "Properties matched by regexp")))
3414 (defun org-property-inherit-p (property)
3415 "Check if PROPERTY is one that should be inherited."
3416 (cond
3417 ((eq org-use-property-inheritance t) t)
3418 ((not org-use-property-inheritance) nil)
3419 ((stringp org-use-property-inheritance)
3420 (string-match org-use-property-inheritance property))
3421 ((listp org-use-property-inheritance)
3422 (member property org-use-property-inheritance))
3423 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3425 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3426 "The default column format, if no other format has been defined.
3427 This variable can be set on the per-file basis by inserting a line
3429 #+COLUMNS: %25ITEM ....."
3430 :group 'org-properties
3431 :type 'string)
3433 (defcustom org-columns-ellipses ".."
3434 "The ellipses to be used when a field in column view is truncated.
3435 When this is the empty string, as many characters as possible are shown,
3436 but then there will be no visual indication that the field has been truncated.
3437 When this is a string of length N, the last N characters of a truncated
3438 field are replaced by this string. If the column is narrower than the
3439 ellipses string, only part of the ellipses string will be shown."
3440 :group 'org-properties
3441 :type 'string)
3443 (defcustom org-columns-modify-value-for-display-function nil
3444 "Function that modifies values for display in column view.
3445 For example, it can be used to cut out a certain part from a time stamp.
3446 The function must take 2 arguments:
3448 column-title The title of the column (*not* the property name)
3449 value The value that should be modified.
3451 The function should return the value that should be displayed,
3452 or nil if the normal value should be used."
3453 :group 'org-properties
3454 :type 'function)
3456 (defcustom org-effort-property "Effort"
3457 "The property that is being used to keep track of effort estimates.
3458 Effort estimates given in this property need to have the format H:MM."
3459 :group 'org-properties
3460 :group 'org-progress
3461 :type '(string :tag "Property"))
3463 (defconst org-global-properties-fixed
3464 '(("VISIBILITY_ALL" . "folded children content all")
3465 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3466 "List of property/value pairs that can be inherited by any entry.
3468 These are fixed values, for the preset properties. The user variable
3469 that can be used to add to this list is `org-global-properties'.
3471 The entries in this list are cons cells where the car is a property
3472 name and cdr is a string with the value. If the value represents
3473 multiple items like an \"_ALL\" property, separate the items by
3474 spaces.")
3476 (defcustom org-global-properties nil
3477 "List of property/value pairs that can be inherited by any entry.
3479 This list will be combined with the constant `org-global-properties-fixed'.
3481 The entries in this list are cons cells where the car is a property
3482 name and cdr is a string with the value.
3484 You can set buffer-local values for the same purpose in the variable
3485 `org-file-properties' this by adding lines like
3487 #+PROPERTY: NAME VALUE"
3488 :group 'org-properties
3489 :type '(repeat
3490 (cons (string :tag "Property")
3491 (string :tag "Value"))))
3493 (defvar org-file-properties nil
3494 "List of property/value pairs that can be inherited by any entry.
3495 Valid for the current buffer.
3496 This variable is populated from #+PROPERTY lines.")
3497 (make-variable-buffer-local 'org-file-properties)
3499 (defgroup org-agenda nil
3500 "Options concerning agenda views in Org-mode."
3501 :tag "Org Agenda"
3502 :group 'org)
3504 (defvar org-category nil
3505 "Variable used by org files to set a category for agenda display.
3506 Such files should use a file variable to set it, for example
3508 # -*- mode: org; org-category: \"ELisp\"
3510 or contain a special line
3512 #+CATEGORY: ELisp
3514 If the file does not specify a category, then file's base name
3515 is used instead.")
3516 (make-variable-buffer-local 'org-category)
3517 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3519 (defcustom org-agenda-files nil
3520 "The files to be used for agenda display.
3521 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3522 \\[org-remove-file]. You can also use customize to edit the list.
3524 If an entry is a directory, all files in that directory that are matched by
3525 `org-agenda-file-regexp' will be part of the file list.
3527 If the value of the variable is not a list but a single file name, then
3528 the list of agenda files is actually stored and maintained in that file, one
3529 agenda file per line. In this file paths can be given relative to
3530 `org-directory'. Tilde expansion and environment variable substitution
3531 are also made."
3532 :group 'org-agenda
3533 :type '(choice
3534 (repeat :tag "List of files and directories" file)
3535 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3537 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3538 "Regular expression to match files for `org-agenda-files'.
3539 If any element in the list in that variable contains a directory instead
3540 of a normal file, all files in that directory that are matched by this
3541 regular expression will be included."
3542 :group 'org-agenda
3543 :type 'regexp)
3545 (defcustom org-agenda-text-search-extra-files nil
3546 "List of extra files to be searched by text search commands.
3547 These files will be search in addition to the agenda files by the
3548 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3549 Note that these files will only be searched for text search commands,
3550 not for the other agenda views like todo lists, tag searches or the weekly
3551 agenda. This variable is intended to list notes and possibly archive files
3552 that should also be searched by these two commands.
3553 In fact, if the first element in the list is the symbol `agenda-archives',
3554 than all archive files of all agenda files will be added to the search
3555 scope."
3556 :group 'org-agenda
3557 :type '(set :greedy t
3558 (const :tag "Agenda Archives" agenda-archives)
3559 (repeat :inline t (file))))
3561 (if (fboundp 'defvaralias)
3562 (defvaralias 'org-agenda-multi-occur-extra-files
3563 'org-agenda-text-search-extra-files))
3565 (defcustom org-agenda-skip-unavailable-files nil
3566 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3567 A nil value means to remove them, after a query, from the list."
3568 :group 'org-agenda
3569 :type 'boolean)
3571 (defcustom org-calendar-to-agenda-key [?c]
3572 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3573 The command `org-calendar-goto-agenda' will be bound to this key. The
3574 default is the character `c' because then `c' can be used to switch back and
3575 forth between agenda and calendar."
3576 :group 'org-agenda
3577 :type 'sexp)
3579 (defcustom org-calendar-insert-diary-entry-key [?i]
3580 "The key to be installed in `calendar-mode-map' for adding diary entries.
3581 This option is irrelevant until `org-agenda-diary-file' has been configured
3582 to point to an Org-mode file. When that is the case, the command
3583 `org-agenda-diary-entry' will be bound to the key given here, by default
3584 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3585 if you want to continue doing this, you need to change this to a different
3586 key."
3587 :group 'org-agenda
3588 :type 'sexp)
3590 (defcustom org-agenda-diary-file 'diary-file
3591 "File to which to add new entries with the `i' key in agenda and calendar.
3592 When this is the symbol `diary-file', the functionality in the Emacs
3593 calendar will be used to add entries to the `diary-file'. But when this
3594 points to a file, `org-agenda-diary-entry' will be used instead."
3595 :group 'org-agenda
3596 :type '(choice
3597 (const :tag "The standard Emacs diary file" diary-file)
3598 (file :tag "Special Org file diary entries")))
3600 (eval-after-load "calendar"
3601 '(progn
3602 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3603 'org-calendar-goto-agenda)
3604 (add-hook 'calendar-mode-hook
3605 (lambda ()
3606 (unless (eq org-agenda-diary-file 'diary-file)
3607 (define-key calendar-mode-map
3608 org-calendar-insert-diary-entry-key
3609 'org-agenda-diary-entry))))))
3611 (defgroup org-latex nil
3612 "Options for embedding LaTeX code into Org-mode."
3613 :tag "Org LaTeX"
3614 :group 'org)
3616 (defcustom org-format-latex-options
3617 '(:foreground default :background default :scale 1.0
3618 :html-foreground "Black" :html-background "Transparent"
3619 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3620 "Options for creating images from LaTeX fragments.
3621 This is a property list with the following properties:
3622 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3623 `default' means use the foreground of the default face.
3624 `auto' means use the foreground from the text face.
3625 :background the background color, or \"Transparent\".
3626 `default' means use the background of the default face.
3627 `auto' means use the background from the text face.
3628 :scale a scaling factor for the size of the images, to get more pixels
3629 :html-foreground, :html-background, :html-scale
3630 the same numbers for HTML export.
3631 :matchers a list indicating which matchers should be used to
3632 find LaTeX fragments. Valid members of this list are:
3633 \"begin\" find environments
3634 \"$1\" find single characters surrounded by $.$
3635 \"$\" find math expressions surrounded by $...$
3636 \"$$\" find math expressions surrounded by $$....$$
3637 \"\\(\" find math expressions surrounded by \\(...\\)
3638 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3639 :group 'org-latex
3640 :type 'plist)
3642 (defcustom org-format-latex-signal-error t
3643 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3644 When nil, just push out a message."
3645 :group 'org-latex
3646 :version "24.1"
3647 :type 'boolean)
3649 (defcustom org-latex-to-mathml-jar-file nil
3650 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3651 Use this to specify additional executable file say a jar file.
3653 When using MathToWeb as the converter, specify the full-path to
3654 your mathtoweb.jar file."
3655 :group 'org-latex
3656 :version "24.1"
3657 :type '(choice
3658 (const :tag "None" nil)
3659 (file :tag "JAR file" :must-match t)))
3661 (defcustom org-latex-to-mathml-convert-command nil
3662 "Command to convert LaTeX fragments to MathML.
3663 Replace format-specifiers in the command as noted below and use
3664 `shell-command' to convert LaTeX to MathML.
3665 %j: Executable file in fully expanded form as specified by
3666 `org-latex-to-mathml-jar-file'.
3667 %I: Input LaTeX file in fully expanded form
3668 %o: Output MathML file
3669 This command is used by `org-create-math-formula'.
3671 When using MathToWeb as the converter, set this to
3672 \"java -jar %j -unicode -force -df %o %I\"."
3673 :group 'org-latex
3674 :version "24.1"
3675 :type '(choice
3676 (const :tag "None" nil)
3677 (string :tag "\nShell command")))
3679 (defcustom org-latex-create-formula-image-program 'dvipng
3680 "Program to convert LaTeX fragments with.
3682 dvipng Process the LaTeX fragments to dvi file, then convert
3683 dvi files to png files using dvipng.
3684 This will also include processing of non-math environments.
3685 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3686 to convert pdf files to png files"
3687 :group 'org-latex
3688 :version "24.1"
3689 :type '(choice
3690 (const :tag "dvipng" dvipng)
3691 (const :tag "imagemagick" imagemagick)))
3693 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3694 "Path to store latex preview images.
3695 A relative path here creates many directories relative to the
3696 processed org files paths. An absolute path puts all preview
3697 images at the same place."
3698 :group 'org-latex
3699 :version "24.3"
3700 :type 'string)
3702 (defun org-format-latex-mathml-available-p ()
3703 "Return t if `org-latex-to-mathml-convert-command' is usable."
3704 (save-match-data
3705 (when (and (boundp 'org-latex-to-mathml-convert-command)
3706 org-latex-to-mathml-convert-command)
3707 (let ((executable (car (split-string
3708 org-latex-to-mathml-convert-command))))
3709 (when (executable-find executable)
3710 (if (string-match
3711 "%j" org-latex-to-mathml-convert-command)
3712 (file-readable-p org-latex-to-mathml-jar-file)
3713 t))))))
3715 (defcustom org-format-latex-header "\\documentclass{article}
3716 \\usepackage[usenames]{color}
3717 \\usepackage{amsmath}
3718 \\usepackage[mathscr]{eucal}
3719 \\pagestyle{empty} % do not remove
3720 \[PACKAGES]
3721 \[DEFAULT-PACKAGES]
3722 % The settings below are copied from fullpage.sty
3723 \\setlength{\\textwidth}{\\paperwidth}
3724 \\addtolength{\\textwidth}{-3cm}
3725 \\setlength{\\oddsidemargin}{1.5cm}
3726 \\addtolength{\\oddsidemargin}{-2.54cm}
3727 \\setlength{\\evensidemargin}{\\oddsidemargin}
3728 \\setlength{\\textheight}{\\paperheight}
3729 \\addtolength{\\textheight}{-\\headheight}
3730 \\addtolength{\\textheight}{-\\headsep}
3731 \\addtolength{\\textheight}{-\\footskip}
3732 \\addtolength{\\textheight}{-3cm}
3733 \\setlength{\\topmargin}{1.5cm}
3734 \\addtolength{\\topmargin}{-2.54cm}"
3735 "The document header used for processing LaTeX fragments.
3736 It is imperative that this header make sure that no page number
3737 appears on the page. The package defined in the variables
3738 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3739 will either replace the placeholder \"[PACKAGES]\" in this
3740 header, or they will be appended."
3741 :group 'org-latex
3742 :type 'string)
3744 (defun org-set-packages-alist (var val)
3745 "Set the packages alist and make sure it has 3 elements per entry."
3746 (set var (mapcar (lambda (x)
3747 (if (and (consp x) (= (length x) 2))
3748 (list (car x) (nth 1 x) t)
3750 val)))
3752 (defun org-get-packages-alist (var)
3753 "Get the packages alist and make sure it has 3 elements per entry."
3754 (mapcar (lambda (x)
3755 (if (and (consp x) (= (length x) 2))
3756 (list (car x) (nth 1 x) t)
3758 (default-value var)))
3760 (defcustom org-latex-default-packages-alist
3761 '(("AUTO" "inputenc" t)
3762 ("T1" "fontenc" t)
3763 ("" "fixltx2e" nil)
3764 ("" "graphicx" t)
3765 ("" "longtable" nil)
3766 ("" "float" nil)
3767 ("" "wrapfig" nil)
3768 ("" "soul" t)
3769 ("" "textcomp" t)
3770 ("" "marvosym" t)
3771 ("" "wasysym" t)
3772 ("" "latexsym" t)
3773 ("" "amssymb" t)
3774 ("" "hyperref" nil)
3775 "\\tolerance=1000")
3776 "Alist of default packages to be inserted in the header.
3778 Change this only if one of the packages here causes an
3779 incompatibility with another package you are using.
3781 The packages in this list are needed by one part or another of
3782 Org mode to function properly:
3784 - inputenc, fontenc: for basic font and character selection
3785 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3786 symbols used for interpreting the entities in `org-entities'.
3787 You can skip some of these packages if you don't use any of the
3788 symbols in it.
3789 - graphicx: for including images
3790 - float, wrapfig: for figure placement
3791 - longtable: for long tables
3792 - hyperref: for cross references
3794 Therefore you should not modify this variable unless you know
3795 what you are doing. The one reason to change it anyway is that
3796 you might be loading some other package that conflicts with one
3797 of the default packages. Each cell is of the format
3798 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3799 the package also needs to be included when compiling LaTeX
3800 snippets into images for inclusion into non-LaTeX output."
3801 :group 'org-latex
3802 :group 'org-export-latex
3803 :set 'org-set-packages-alist
3804 :get 'org-get-packages-alist
3805 :version "24.1"
3806 :type '(repeat
3807 (choice
3808 (list :tag "options/package pair"
3809 (string :tag "options")
3810 (string :tag "package")
3811 (boolean :tag "Snippet"))
3812 (string :tag "A line of LaTeX"))))
3814 (defcustom org-latex-packages-alist nil
3815 "Alist of packages to be inserted in every LaTeX header.
3817 These will be inserted after `org-latex-default-packages-alist'.
3818 Each cell is of the format:
3820 \(\"options\" \"package\" snippet-flag)
3822 SNIPPET-FLAG, when t, indicates that this package is also needed
3823 when turning LaTeX snippets into images for inclusion into
3824 non-LaTeX output.
3826 Make sure that you only list packages here which:
3828 - you want in every file
3829 - do not conflict with the setup in `org-format-latex-header'.
3830 - do not conflict with the default packages in
3831 `org-latex-default-packages-alist'."
3832 :group 'org-latex
3833 :group 'org-export-latex
3834 :set 'org-set-packages-alist
3835 :get 'org-get-packages-alist
3836 :type '(repeat
3837 (choice
3838 (list :tag "options/package pair"
3839 (string :tag "options")
3840 (string :tag "package")
3841 (boolean :tag "Snippet"))
3842 (string :tag "A line of LaTeX"))))
3844 (defgroup org-appearance nil
3845 "Settings for Org-mode appearance."
3846 :tag "Org Appearance"
3847 :group 'org)
3849 (defcustom org-level-color-stars-only nil
3850 "Non-nil means fontify only the stars in each headline.
3851 When nil, the entire headline is fontified.
3852 Changing it requires restart of `font-lock-mode' to become effective
3853 also in regions already fontified."
3854 :group 'org-appearance
3855 :type 'boolean)
3857 (defcustom org-hide-leading-stars nil
3858 "Non-nil means hide the first N-1 stars in a headline.
3859 This works by using the face `org-hide' for these stars. This
3860 face is white for a light background, and black for a dark
3861 background. You may have to customize the face `org-hide' to
3862 make this work.
3863 Changing it requires restart of `font-lock-mode' to become effective
3864 also in regions already fontified.
3865 You may also set this on a per-file basis by adding one of the following
3866 lines to the buffer:
3868 #+STARTUP: hidestars
3869 #+STARTUP: showstars"
3870 :group 'org-appearance
3871 :type 'boolean)
3873 (defcustom org-hidden-keywords nil
3874 "List of symbols corresponding to keywords to be hidden the org buffer.
3875 For example, a value '(title) for this list will make the document's title
3876 appear in the buffer without the initial #+TITLE: keyword."
3877 :group 'org-appearance
3878 :version "24.1"
3879 :type '(set (const :tag "#+AUTHOR" author)
3880 (const :tag "#+DATE" date)
3881 (const :tag "#+EMAIL" email)
3882 (const :tag "#+TITLE" title)))
3884 (defcustom org-custom-properties nil
3885 "List of properties (as strings) with a special meaning.
3886 The default use of these custom properties is to let the user
3887 hide them with `org-toggle-custom-properties-visibility'."
3888 :group 'org-properties
3889 :group 'org-appearance
3890 :version "24.3"
3891 :type '(repeat (string :tag "Property Name")))
3893 (defcustom org-fontify-done-headline nil
3894 "Non-nil means change the face of a headline if it is marked DONE.
3895 Normally, only the TODO/DONE keyword indicates the state of a headline.
3896 When this is non-nil, the headline after the keyword is set to the
3897 `org-headline-done' as an additional indication."
3898 :group 'org-appearance
3899 :type 'boolean)
3901 (defcustom org-fontify-emphasized-text t
3902 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3903 Changing this variable requires a restart of Emacs to take effect."
3904 :group 'org-appearance
3905 :type 'boolean)
3907 (defcustom org-fontify-whole-heading-line nil
3908 "Non-nil means fontify the whole line for headings.
3909 This is useful when setting a background color for the
3910 org-level-* faces."
3911 :group 'org-appearance
3912 :type 'boolean)
3914 (defcustom org-highlight-latex-and-related nil
3915 "Non-nil means highlight LaTeX related syntax in the buffer.
3916 When non nil, the value should be a list containing any of the
3917 following symbols:
3918 `latex' Highlight LaTeX snippets and environments.
3919 `script' Highlight subscript and superscript.
3920 `entities' Highlight entities."
3921 :group 'org-appearance
3922 :version "24.4"
3923 :package-version '(Org . "8.0")
3924 :type '(choice
3925 (const :tag "No highlighting" nil)
3926 (set :greedy t :tag "Highlight"
3927 (const :tag "LaTeX snippets and environments" latex)
3928 (const :tag "Subscript and superscript" script)
3929 (const :tag "Entities" entities))))
3931 (defcustom org-hide-emphasis-markers nil
3932 "Non-nil mean font-lock should hide the emphasis marker characters."
3933 :group 'org-appearance
3934 :type 'boolean)
3936 (defcustom org-pretty-entities nil
3937 "Non-nil means show entities as UTF8 characters.
3938 When nil, the \\name form remains in the buffer."
3939 :group 'org-appearance
3940 :version "24.1"
3941 :type 'boolean)
3943 (defcustom org-pretty-entities-include-sub-superscripts t
3944 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3945 :group 'org-appearance
3946 :version "24.1"
3947 :type 'boolean)
3949 (defvar org-emph-re nil
3950 "Regular expression for matching emphasis.
3951 After a match, the match groups contain these elements:
3952 0 The match of the full regular expression, including the characters
3953 before and after the proper match
3954 1 The character before the proper match, or empty at beginning of line
3955 2 The proper match, including the leading and trailing markers
3956 3 The leading marker like * or /, indicating the type of highlighting
3957 4 The text between the emphasis markers, not including the markers
3958 5 The character after the match, empty at the end of a line")
3959 (defvar org-verbatim-re nil
3960 "Regular expression for matching verbatim text.")
3961 (defvar org-emphasis-regexp-components) ; defined just below
3962 (defvar org-emphasis-alist) ; defined just below
3963 (defun org-set-emph-re (var val)
3964 "Set variable and compute the emphasis regular expression."
3965 (set var val)
3966 (when (and (boundp 'org-emphasis-alist)
3967 (boundp 'org-emphasis-regexp-components)
3968 org-emphasis-alist org-emphasis-regexp-components)
3969 (let* ((e org-emphasis-regexp-components)
3970 (pre (car e))
3971 (post (nth 1 e))
3972 (border (nth 2 e))
3973 (body (nth 3 e))
3974 (nl (nth 4 e))
3975 (body1 (concat body "*?"))
3976 (markers (mapconcat 'car org-emphasis-alist ""))
3977 (vmarkers (mapconcat
3978 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3979 org-emphasis-alist "")))
3980 ;; make sure special characters appear at the right position in the class
3981 (if (string-match "\\^" markers)
3982 (setq markers (concat (replace-match "" t t markers) "^")))
3983 (if (string-match "-" markers)
3984 (setq markers (concat (replace-match "" t t markers) "-")))
3985 (if (string-match "\\^" vmarkers)
3986 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3987 (if (string-match "-" vmarkers)
3988 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3989 (if (> nl 0)
3990 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3991 (int-to-string nl) "\\}")))
3992 ;; Make the regexp
3993 (setq org-emph-re
3994 (concat "\\([" pre "]\\|^\\)"
3995 "\\("
3996 "\\([" markers "]\\)"
3997 "\\("
3998 "[^" border "]\\|"
3999 "[^" border "]"
4000 body1
4001 "[^" border "]"
4002 "\\)"
4003 "\\3\\)"
4004 "\\([" post "]\\|$\\)"))
4005 (setq org-verbatim-re
4006 (concat "\\([" pre "]\\|^\\)"
4007 "\\("
4008 "\\([" vmarkers "]\\)"
4009 "\\("
4010 "[^" border "]\\|"
4011 "[^" border "]"
4012 body1
4013 "[^" border "]"
4014 "\\)"
4015 "\\3\\)"
4016 "\\([" post "]\\|$\\)")))))
4018 (defcustom org-emphasis-regexp-components
4019 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4020 "Components used to build the regular expression for emphasis.
4021 This is a list with five entries. Terminology: In an emphasis string
4022 like \" *strong word* \", we call the initial space PREMATCH, the final
4023 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4024 and \"trong wor\" is the body. The different components in this variable
4025 specify what is allowed/forbidden in each part:
4027 pre Chars allowed as prematch. Beginning of line will be allowed too.
4028 post Chars allowed as postmatch. End of line will be allowed too.
4029 border The chars *forbidden* as border characters.
4030 body-regexp A regexp like \".\" to match a body character. Don't use
4031 non-shy groups here, and don't allow newline here.
4032 newline The maximum number of newlines allowed in an emphasis exp.
4034 Use customize to modify this, or restart Emacs after changing it."
4035 :group 'org-appearance
4036 :set 'org-set-emph-re
4037 :type '(list
4038 (sexp :tag "Allowed chars in pre ")
4039 (sexp :tag "Allowed chars in post ")
4040 (sexp :tag "Forbidden chars in border ")
4041 (sexp :tag "Regexp for body ")
4042 (integer :tag "number of newlines allowed")
4043 (option (boolean :tag "Please ignore this button"))))
4045 (defcustom org-emphasis-alist
4046 `(("*" bold "<b>" "</b>")
4047 ("/" italic "<i>" "</i>")
4048 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4049 ("=" org-code "<code>" "</code>" verbatim)
4050 ("~" org-verbatim "<code>" "</code>" verbatim)
4051 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4052 "<del>" "</del>")
4054 "Special syntax for emphasized text.
4055 Text starting and ending with a special character will be emphasized, for
4056 example *bold*, _underlined_ and /italic/. This variable sets the marker
4057 characters, the face to be used by font-lock for highlighting in Org-mode
4058 Emacs buffers, and the HTML tags to be used for this.
4059 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4060 Use customize to modify this, or restart Emacs after changing it."
4061 :group 'org-appearance
4062 :set 'org-set-emph-re
4063 :type '(repeat
4064 (list
4065 (string :tag "Marker character")
4066 (choice
4067 (face :tag "Font-lock-face")
4068 (plist :tag "Face property list"))
4069 (string :tag "HTML start tag")
4070 (string :tag "HTML end tag")
4071 (option (const verbatim)))))
4073 (defvar org-protecting-blocks
4074 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4075 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4076 This is needed for font-lock setup.")
4078 ;;; Miscellaneous options
4080 (defgroup org-completion nil
4081 "Completion in Org-mode."
4082 :tag "Org Completion"
4083 :group 'org)
4085 (defcustom org-completion-use-ido nil
4086 "Non-nil means use ido completion wherever possible.
4087 Note that `ido-mode' must be active for this variable to be relevant.
4088 If you decide to turn this variable on, you might well want to turn off
4089 `org-outline-path-complete-in-steps'.
4090 See also `org-completion-use-iswitchb'."
4091 :group 'org-completion
4092 :type 'boolean)
4094 (defcustom org-completion-use-iswitchb nil
4095 "Non-nil means use iswitchb completion wherever possible.
4096 Note that `iswitchb-mode' must be active for this variable to be relevant.
4097 If you decide to turn this variable on, you might well want to turn off
4098 `org-outline-path-complete-in-steps'.
4099 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4100 :group 'org-completion
4101 :type 'boolean)
4103 (defcustom org-completion-fallback-command 'hippie-expand
4104 "The expansion command called by \\[pcomplete] in normal context.
4105 Normal means, no org-mode-specific context."
4106 :group 'org-completion
4107 :type 'function)
4109 ;;; Functions and variables from their packages
4110 ;; Declared here to avoid compiler warnings
4112 ;; XEmacs only
4113 (defvar outline-mode-menu-heading)
4114 (defvar outline-mode-menu-show)
4115 (defvar outline-mode-menu-hide)
4116 (defvar zmacs-regions) ; XEmacs regions
4118 ;; Emacs only
4119 (defvar mark-active)
4121 ;; Various packages
4122 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4123 (declare-function calendar-forward-day "cal-move" (arg))
4124 (declare-function calendar-goto-date "cal-move" (date))
4125 (declare-function calendar-goto-today "cal-move" ())
4126 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4127 (defvar calc-embedded-close-formula)
4128 (defvar calc-embedded-open-formula)
4129 (declare-function cdlatex-tab "ext:cdlatex" ())
4130 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4131 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4132 (defvar font-lock-unfontify-region-function)
4133 (declare-function iswitchb-read-buffer "iswitchb"
4134 (prompt &optional default require-match start matches-set))
4135 (defvar iswitchb-temp-buflist)
4136 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4137 (defvar org-agenda-tags-todo-honor-ignore-options)
4138 (declare-function org-agenda-skip "org-agenda" ())
4139 (declare-function
4140 org-agenda-format-item "org-agenda"
4141 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4142 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4143 (declare-function org-agenda-change-all-lines "org-agenda"
4144 (newhead hdmarker &optional fixface just-this))
4145 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4146 (declare-function org-agenda-maybe-redo "org-agenda" ())
4147 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4148 (beg end))
4149 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4150 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4151 "org-agenda" (&optional end))
4152 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4153 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4154 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4155 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4156 (declare-function org-indent-mode "org-indent" (&optional arg))
4157 (declare-function parse-time-string "parse-time" (string))
4158 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4159 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4160 (defvar remember-data-file)
4161 (defvar texmathp-why)
4162 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4163 (declare-function table--at-cell-p "table" (position &optional object at-column))
4165 (defvar org-latex-regexps)
4167 ;;; Autoload and prepare some org modules
4169 ;; Some table stuff that needs to be defined here, because it is used
4170 ;; by the functions setting up org-mode or checking for table context.
4172 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4173 "Detect an org-type or table-type table.")
4174 (defconst org-table-line-regexp "^[ \t]*|"
4175 "Detect an org-type table line.")
4176 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4177 "Detect an org-type table line.")
4178 (defconst org-table-hline-regexp "^[ \t]*|-"
4179 "Detect an org-type table hline.")
4180 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4181 "Detect a table-type table hline.")
4182 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4183 "Detect the first line outside a table when searching from within it.
4184 This works for both table types.")
4186 ;; Autoload the functions in org-table.el that are needed by functions here.
4188 (eval-and-compile
4189 (org-autoload "org-table"
4190 '(org-table-begin org-table-blank-field org-table-end)))
4192 ;;;###autoload
4193 (defun turn-on-orgtbl ()
4194 "Unconditionally turn on `orgtbl-mode'."
4195 (require 'org-table)
4196 (orgtbl-mode 1))
4198 (defun org-at-table-p (&optional table-type)
4199 "Return t if the cursor is inside an org-type table.
4200 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4201 (if org-enable-table-editor
4202 (save-excursion
4203 (beginning-of-line 1)
4204 (looking-at (if table-type org-table-any-line-regexp
4205 org-table-line-regexp)))
4206 nil))
4207 (defsubst org-table-p () (org-at-table-p))
4209 (defun org-at-table.el-p ()
4210 "Return t if and only if we are at a table.el table."
4211 (and (org-at-table-p 'any)
4212 (save-excursion
4213 (goto-char (org-table-begin 'any))
4214 (looking-at org-table1-hline-regexp))))
4216 (defun org-table-recognize-table.el ()
4217 "If there is a table.el table nearby, recognize it and move into it."
4218 (if org-table-tab-recognizes-table.el
4219 (if (org-at-table.el-p)
4220 (progn
4221 (beginning-of-line 1)
4222 (if (looking-at org-table-dataline-regexp)
4224 (if (looking-at org-table1-hline-regexp)
4225 (progn
4226 (beginning-of-line 2)
4227 (if (looking-at org-table-any-border-regexp)
4228 (beginning-of-line -1)))))
4229 (if (re-search-forward "|" (org-table-end t) t)
4230 (progn
4231 (require 'table)
4232 (if (table--at-cell-p (point))
4234 (message "recognizing table.el table...")
4235 (table-recognize-table)
4236 (message "recognizing table.el table...done")))
4237 (error "This should not happen"))
4239 nil)
4240 nil))
4242 (defun org-at-table-hline-p ()
4243 "Return t if the cursor is inside a hline in a table."
4244 (if org-enable-table-editor
4245 (save-excursion
4246 (beginning-of-line 1)
4247 (looking-at org-table-hline-regexp))
4248 nil))
4250 (defvar org-table-clean-did-remove-column nil)
4251 (defun org-table-map-tables (function &optional quietly)
4252 "Apply FUNCTION to the start of all tables in the buffer."
4253 (save-excursion
4254 (save-restriction
4255 (widen)
4256 (goto-char (point-min))
4257 (while (re-search-forward org-table-any-line-regexp nil t)
4258 (unless quietly
4259 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4260 (beginning-of-line 1)
4261 (when (and (looking-at org-table-line-regexp)
4262 ;; Exclude tables in src/example/verbatim/clocktable blocks
4263 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4264 (save-excursion (funcall function))
4265 (or (looking-at org-table-line-regexp)
4266 (forward-char 1)))
4267 (re-search-forward org-table-any-border-regexp nil 1))))
4268 (unless quietly (message "Mapping tables: done")))
4270 ;; Declare and autoload functions from ox.el and al.
4272 (declare-function org-export-get-environment "ox"
4273 (&optional backend subtreep ext-plist))
4274 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4276 ;; Declare and autoload functions from org-agenda.el
4278 (eval-and-compile
4279 (org-autoload "org-agenda"
4280 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4282 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4283 (declare-function org-clock-update-mode-line "org-clock" ())
4284 (declare-function org-resolve-clocks "org-clock"
4285 (&optional also-non-dangling-p prompt last-valid))
4286 (defvar org-clock-start-time)
4287 (defvar org-clock-marker (make-marker)
4288 "Marker recording the last clock-in.")
4289 (defvar org-clock-hd-marker (make-marker)
4290 "Marker recording the last clock-in, but the headline position.")
4291 (defvar org-clock-heading ""
4292 "The heading of the current clock entry.")
4293 (defun org-clock-is-active ()
4294 "Return non-nil if clock is currently running.
4295 The return value is actually the clock marker."
4296 (marker-buffer org-clock-marker))
4298 (eval-and-compile
4299 (org-autoload "org-clock" '(org-clock-remove-overlays
4300 org-clock-update-time-maybe
4301 org-clocktable-shift)))
4303 (defun org-check-running-clock ()
4304 "Check if the current buffer contains the running clock.
4305 If yes, offer to stop it and to save the buffer with the changes."
4306 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4307 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4308 (buffer-name))))
4309 (org-clock-out)
4310 (when (y-or-n-p "Save changed buffer?")
4311 (save-buffer))))
4313 (defun org-clocktable-try-shift (dir n)
4314 "Check if this line starts a clock table, if yes, shift the time block."
4315 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4316 (org-clocktable-shift dir n)))
4318 ;;;###autoload
4319 (defun org-clock-persistence-insinuate ()
4320 "Set up hooks for clock persistence."
4321 (require 'org-clock)
4322 (add-hook 'org-mode-hook 'org-clock-load)
4323 (add-hook 'kill-emacs-hook 'org-clock-save))
4325 ;; Define the variable already here, to make sure we have it.
4326 (defvar org-indent-mode nil
4327 "Non-nil if Org-Indent mode is enabled.
4328 Use the command `org-indent-mode' to change this variable.")
4330 ;; Autoload archiving code
4331 ;; The stuff that is needed for cycling and tags has to be defined here.
4333 (defgroup org-archive nil
4334 "Options concerning archiving in Org-mode."
4335 :tag "Org Archive"
4336 :group 'org-structure)
4338 (defcustom org-archive-location "%s_archive::"
4339 "The location where subtrees should be archived.
4341 The value of this variable is a string, consisting of two parts,
4342 separated by a double-colon. The first part is a filename and
4343 the second part is a headline.
4345 When the filename is omitted, archiving happens in the same file.
4346 %s in the filename will be replaced by the current file
4347 name (without the directory part). Archiving to a different file
4348 is useful to keep archived entries from contributing to the
4349 Org-mode Agenda.
4351 The archived entries will be filed as subtrees of the specified
4352 headline. When the headline is omitted, the subtrees are simply
4353 filed away at the end of the file, as top-level entries. Also in
4354 the heading you can use %s to represent the file name, this can be
4355 useful when using the same archive for a number of different files.
4357 Here are a few examples:
4358 \"%s_archive::\"
4359 If the current file is Projects.org, archive in file
4360 Projects.org_archive, as top-level trees. This is the default.
4362 \"::* Archived Tasks\"
4363 Archive in the current file, under the top-level headline
4364 \"* Archived Tasks\".
4366 \"~/org/archive.org::\"
4367 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4369 \"~/org/archive.org::* From %s\"
4370 Archive in file ~/org/archive.org (absolute path), under headlines
4371 \"From FILENAME\" where file name is the current file name.
4373 \"~/org/datetree.org::datetree/* Finished Tasks\"
4374 The \"datetree/\" string is special, signifying to archive
4375 items to the datetree. Items are placed in either the CLOSED
4376 date of the item, or the current date if there is no CLOSED date.
4377 The heading will be a subentry to the current date. There doesn't
4378 need to be a heading, but there always needs to be a slash after
4379 datetree. For example, to store archived items directly in the
4380 datetree, use \"~/org/datetree.org::datetree/\".
4382 \"basement::** Finished Tasks\"
4383 Archive in file ./basement (relative path), as level 3 trees
4384 below the level 2 heading \"** Finished Tasks\".
4386 You may set this option on a per-file basis by adding to the buffer a
4387 line like
4389 #+ARCHIVE: basement::** Finished Tasks
4391 You may also define it locally for a subtree by setting an ARCHIVE property
4392 in the entry. If such a property is found in an entry, or anywhere up
4393 the hierarchy, it will be used."
4394 :group 'org-archive
4395 :type 'string)
4397 (defcustom org-archive-tag "ARCHIVE"
4398 "The tag that marks a subtree as archived.
4399 An archived subtree does not open during visibility cycling, and does
4400 not contribute to the agenda listings.
4401 After changing this, font-lock must be restarted in the relevant buffers to
4402 get the proper fontification."
4403 :group 'org-archive
4404 :group 'org-keywords
4405 :type 'string)
4407 (defcustom org-agenda-skip-archived-trees t
4408 "Non-nil means the agenda will skip any items located in archived trees.
4409 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4410 variable is no longer recommended, you should leave it at the value t.
4411 Instead, use the key `v' to cycle the archives-mode in the agenda."
4412 :group 'org-archive
4413 :group 'org-agenda-skip
4414 :type 'boolean)
4416 (defcustom org-columns-skip-archived-trees t
4417 "Non-nil means ignore archived trees when creating column view."
4418 :group 'org-archive
4419 :group 'org-properties
4420 :type 'boolean)
4422 (defcustom org-cycle-open-archived-trees nil
4423 "Non-nil means `org-cycle' will open archived trees.
4424 An archived tree is a tree marked with the tag ARCHIVE.
4425 When nil, archived trees will stay folded. You can still open them with
4426 normal outline commands like `show-all', but not with the cycling commands."
4427 :group 'org-archive
4428 :group 'org-cycle
4429 :type 'boolean)
4431 (defcustom org-sparse-tree-open-archived-trees nil
4432 "Non-nil means sparse tree construction shows matches in archived trees.
4433 When nil, matches in these trees are highlighted, but the trees are kept in
4434 collapsed state."
4435 :group 'org-archive
4436 :group 'org-sparse-trees
4437 :type 'boolean)
4439 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4440 "The default date type when building a sparse tree.
4441 When this is nil, a date is a scheduled or a deadline timestamp.
4442 Otherwise, these types are allowed:
4444 all: all timestamps
4445 active: only active timestamps (<...>)
4446 inactive: only inactive timestamps (<...)
4447 scheduled: only scheduled timestamps
4448 deadline: only deadline timestamps"
4449 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4450 (const :tag "All timestamps" all)
4451 (const :tag "Only active timestamps" active)
4452 (const :tag "Only inactive timestamps" inactive)
4453 (const :tag "Only scheduled timestamps" scheduled)
4454 (const :tag "Only deadline timestamps" deadline))
4455 :version "24.3"
4456 :group 'org-sparse-trees)
4458 (defun org-cycle-hide-archived-subtrees (state)
4459 "Re-hide all archived subtrees after a visibility state change."
4460 (when (and (not org-cycle-open-archived-trees)
4461 (not (memq state '(overview folded))))
4462 (save-excursion
4463 (let* ((globalp (memq state '(contents all)))
4464 (beg (if globalp (point-min) (point)))
4465 (end (if globalp (point-max) (org-end-of-subtree t))))
4466 (org-hide-archived-subtrees beg end)
4467 (goto-char beg)
4468 (if (looking-at (concat ".*:" org-archive-tag ":"))
4469 (message "%s" (substitute-command-keys
4470 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4472 (defun org-force-cycle-archived ()
4473 "Cycle subtree even if it is archived."
4474 (interactive)
4475 (setq this-command 'org-cycle)
4476 (let ((org-cycle-open-archived-trees t))
4477 (call-interactively 'org-cycle)))
4479 (defun org-hide-archived-subtrees (beg end)
4480 "Re-hide all archived subtrees after a visibility state change."
4481 (save-excursion
4482 (let* ((re (concat ":" org-archive-tag ":")))
4483 (goto-char beg)
4484 (while (re-search-forward re end t)
4485 (when (org-at-heading-p)
4486 (org-flag-subtree t)
4487 (org-end-of-subtree t))))))
4489 (declare-function outline-end-of-heading "outline" ())
4490 (declare-function outline-flag-region "outline" (from to flag))
4491 (defun org-flag-subtree (flag)
4492 (save-excursion
4493 (org-back-to-heading t)
4494 (outline-end-of-heading)
4495 (outline-flag-region (point)
4496 (progn (org-end-of-subtree t) (point))
4497 flag)))
4499 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4501 (eval-and-compile
4502 (org-autoload "org-archive"
4503 '(org-add-archive-files)))
4505 ;; Autoload Column View Code
4507 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4508 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4509 (declare-function org-columns-compute "org-colview" (property))
4511 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4512 '(org-columns-number-to-string
4513 org-columns-get-format-and-top-level
4514 org-columns-compute
4515 org-columns-remove-overlays))
4517 ;; Autoload ID code
4519 (declare-function org-id-store-link "org-id")
4520 (declare-function org-id-locations-load "org-id")
4521 (declare-function org-id-locations-save "org-id")
4522 (defvar org-id-track-globally)
4523 (org-autoload "org-id"
4524 '(org-id-new
4525 org-id-copy
4526 org-id-get-with-outline-path-completion
4527 org-id-get-with-outline-drilling))
4529 ;;; Variables for pre-computed regular expressions, all buffer local
4531 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4532 "Matches first line of a hidden block.")
4533 (make-variable-buffer-local 'org-drawer-regexp)
4534 (defvar org-todo-regexp nil
4535 "Matches any of the TODO state keywords.")
4536 (make-variable-buffer-local 'org-todo-regexp)
4537 (defvar org-not-done-regexp nil
4538 "Matches any of the TODO state keywords except the last one.")
4539 (make-variable-buffer-local 'org-not-done-regexp)
4540 (defvar org-not-done-heading-regexp nil
4541 "Matches a TODO headline that is not done.")
4542 (make-variable-buffer-local 'org-not-done-regexp)
4543 (defvar org-todo-line-regexp nil
4544 "Matches a headline and puts TODO state into group 2 if present.")
4545 (make-variable-buffer-local 'org-todo-line-regexp)
4546 (defvar org-complex-heading-regexp nil
4547 "Matches a headline and puts everything into groups:
4548 group 1: the stars
4549 group 2: The todo keyword, maybe
4550 group 3: Priority cookie
4551 group 4: True headline
4552 group 5: Tags")
4553 (make-variable-buffer-local 'org-complex-heading-regexp)
4554 (defvar org-complex-heading-regexp-format nil
4555 "Printf format to make regexp to match an exact headline.
4556 This regexp will match the headline of any node which has the
4557 exact headline text that is put into the format, but may have any
4558 TODO state, priority and tags.")
4559 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4560 (defvar org-todo-line-tags-regexp nil
4561 "Matches a headline and puts TODO state into group 2 if present.
4562 Also put tags into group 4 if tags are present.")
4563 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4564 (defvar org-ds-keyword-length 12
4565 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4566 (make-variable-buffer-local 'org-ds-keyword-length)
4567 (defvar org-deadline-regexp nil
4568 "Matches the DEADLINE keyword.")
4569 (make-variable-buffer-local 'org-deadline-regexp)
4570 (defvar org-deadline-time-regexp nil
4571 "Matches the DEADLINE keyword together with a time stamp.")
4572 (make-variable-buffer-local 'org-deadline-time-regexp)
4573 (defvar org-deadline-line-regexp nil
4574 "Matches the DEADLINE keyword and the rest of the line.")
4575 (make-variable-buffer-local 'org-deadline-line-regexp)
4576 (defvar org-scheduled-regexp nil
4577 "Matches the SCHEDULED keyword.")
4578 (make-variable-buffer-local 'org-scheduled-regexp)
4579 (defvar org-scheduled-time-regexp nil
4580 "Matches the SCHEDULED keyword together with a time stamp.")
4581 (make-variable-buffer-local 'org-scheduled-time-regexp)
4582 (defvar org-closed-time-regexp nil
4583 "Matches the CLOSED keyword together with a time stamp.")
4584 (make-variable-buffer-local 'org-closed-time-regexp)
4586 (defvar org-keyword-time-regexp nil
4587 "Matches any of the 4 keywords, together with the time stamp.")
4588 (make-variable-buffer-local 'org-keyword-time-regexp)
4589 (defvar org-keyword-time-not-clock-regexp nil
4590 "Matches any of the 3 keywords, together with the time stamp.")
4591 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4592 (defvar org-maybe-keyword-time-regexp nil
4593 "Matches a timestamp, possibly preceded by a keyword.")
4594 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4595 (defvar org-all-time-keywords nil
4596 "List of time keywords.")
4597 (make-variable-buffer-local 'org-all-time-keywords)
4599 (defconst org-plain-time-of-day-regexp
4600 (concat
4601 "\\(\\<[012]?[0-9]"
4602 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4603 "\\(--?"
4604 "\\(\\<[012]?[0-9]"
4605 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4606 "\\)?")
4607 "Regular expression to match a plain time or time range.
4608 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4609 groups carry important information:
4610 0 the full match
4611 1 the first time, range or not
4612 8 the second time, if it is a range.")
4614 (defconst org-plain-time-extension-regexp
4615 (concat
4616 "\\(\\<[012]?[0-9]"
4617 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4618 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4619 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4620 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4621 groups carry important information:
4622 0 the full match
4623 7 hours of duration
4624 9 minutes of duration")
4626 (defconst org-stamp-time-of-day-regexp
4627 (concat
4628 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4629 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4630 "\\(--?"
4631 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4632 "Regular expression to match a timestamp time or time range.
4633 After a match, the following groups carry important information:
4634 0 the full match
4635 1 date plus weekday, for back referencing to make sure both times are on the same day
4636 2 the first time, range or not
4637 4 the second time, if it is a range.")
4639 (defconst org-startup-options
4640 '(("fold" org-startup-folded t)
4641 ("overview" org-startup-folded t)
4642 ("nofold" org-startup-folded nil)
4643 ("showall" org-startup-folded nil)
4644 ("showeverything" org-startup-folded showeverything)
4645 ("content" org-startup-folded content)
4646 ("indent" org-startup-indented t)
4647 ("noindent" org-startup-indented nil)
4648 ("hidestars" org-hide-leading-stars t)
4649 ("showstars" org-hide-leading-stars nil)
4650 ("odd" org-odd-levels-only t)
4651 ("oddeven" org-odd-levels-only nil)
4652 ("align" org-startup-align-all-tables t)
4653 ("noalign" org-startup-align-all-tables nil)
4654 ("inlineimages" org-startup-with-inline-images t)
4655 ("noinlineimages" org-startup-with-inline-images nil)
4656 ("latexpreview" org-startup-with-latex-preview t)
4657 ("nolatexpreview" org-startup-with-latex-preview nil)
4658 ("customtime" org-display-custom-times t)
4659 ("logdone" org-log-done time)
4660 ("lognotedone" org-log-done note)
4661 ("nologdone" org-log-done nil)
4662 ("lognoteclock-out" org-log-note-clock-out t)
4663 ("nolognoteclock-out" org-log-note-clock-out nil)
4664 ("logrepeat" org-log-repeat state)
4665 ("lognoterepeat" org-log-repeat note)
4666 ("logdrawer" org-log-into-drawer t)
4667 ("nologdrawer" org-log-into-drawer nil)
4668 ("logstatesreversed" org-log-states-order-reversed t)
4669 ("nologstatesreversed" org-log-states-order-reversed nil)
4670 ("nologrepeat" org-log-repeat nil)
4671 ("logreschedule" org-log-reschedule time)
4672 ("lognotereschedule" org-log-reschedule note)
4673 ("nologreschedule" org-log-reschedule nil)
4674 ("logredeadline" org-log-redeadline time)
4675 ("lognoteredeadline" org-log-redeadline note)
4676 ("nologredeadline" org-log-redeadline nil)
4677 ("logrefile" org-log-refile time)
4678 ("lognoterefile" org-log-refile note)
4679 ("nologrefile" org-log-refile nil)
4680 ("fninline" org-footnote-define-inline t)
4681 ("nofninline" org-footnote-define-inline nil)
4682 ("fnlocal" org-footnote-section nil)
4683 ("fnauto" org-footnote-auto-label t)
4684 ("fnprompt" org-footnote-auto-label nil)
4685 ("fnconfirm" org-footnote-auto-label confirm)
4686 ("fnplain" org-footnote-auto-label plain)
4687 ("fnadjust" org-footnote-auto-adjust t)
4688 ("nofnadjust" org-footnote-auto-adjust nil)
4689 ("constcgs" constants-unit-system cgs)
4690 ("constSI" constants-unit-system SI)
4691 ("noptag" org-tag-persistent-alist nil)
4692 ("hideblocks" org-hide-block-startup t)
4693 ("nohideblocks" org-hide-block-startup nil)
4694 ("beamer" org-startup-with-beamer-mode t)
4695 ("entitiespretty" org-pretty-entities t)
4696 ("entitiesplain" org-pretty-entities nil))
4697 "Variable associated with STARTUP options for org-mode.
4698 Each element is a list of three items: the startup options (as written
4699 in the #+STARTUP line), the corresponding variable, and the value to set
4700 this variable to if the option is found. An optional forth element PUSH
4701 means to push this value onto the list in the variable.")
4703 (defun org-update-property-plist (key val props)
4704 "Update PROPS with KEY and VAL."
4705 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4706 (key (if appending (substring key 0 (- (length key) 1)) key))
4707 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4708 (previous (cdr (assoc key props))))
4709 (if appending
4710 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4711 (cons (cons key val) remainder))))
4713 (defconst org-block-regexp
4714 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4715 "Regular expression for hiding blocks.")
4716 (defconst org-heading-keyword-regexp-format
4717 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4718 "Printf format for a regexp matching a headline with some keyword.
4719 This regexp will match the headline of any node which has the
4720 exact keyword that is put into the format. The keyword isn't in
4721 any group by default, but the stars and the body are.")
4722 (defconst org-heading-keyword-maybe-regexp-format
4723 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4724 "Printf format for a regexp matching a headline, possibly with some keyword.
4725 This regexp can match any headline with the specified keyword, or
4726 without a keyword. The keyword isn't in any group by default,
4727 but the stars and the body are.")
4729 (defun org-set-regexps-and-options ()
4730 "Precompute regular expressions for current buffer."
4731 (when (derived-mode-p 'org-mode)
4732 (org-set-local 'org-todo-kwd-alist nil)
4733 (org-set-local 'org-todo-key-alist nil)
4734 (org-set-local 'org-todo-key-trigger nil)
4735 (org-set-local 'org-todo-keywords-1 nil)
4736 (org-set-local 'org-done-keywords nil)
4737 (org-set-local 'org-todo-heads nil)
4738 (org-set-local 'org-todo-sets nil)
4739 (org-set-local 'org-todo-log-states nil)
4740 (org-set-local 'org-file-properties nil)
4741 (org-set-local 'org-file-tags nil)
4742 (let ((re (org-make-options-regexp
4743 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4744 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4745 "SETUPFILE" "OPTIONS")
4746 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4747 (splitre "[ \t]+")
4748 (scripts org-use-sub-superscripts)
4749 kwds kws0 kwsa key log value cat arch tags const links hw dws
4750 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4751 (start 0))
4752 (save-excursion
4753 (save-restriction
4754 (widen)
4755 (goto-char (point-min))
4756 (while (or (and ext-setup-or-nil
4757 (string-match re ext-setup-or-nil start)
4758 (setq start (match-end 0)))
4759 (and (setq ext-setup-or-nil nil start 0)
4760 (re-search-forward re nil t)))
4761 (setq key (upcase (match-string 1 ext-setup-or-nil))
4762 value (org-match-string-no-properties 2 ext-setup-or-nil))
4763 (if (stringp value) (setq value (org-trim value)))
4764 (cond
4765 ((equal key "CATEGORY")
4766 (setq cat value))
4767 ((member key '("SEQ_TODO" "TODO"))
4768 (push (cons 'sequence (org-split-string value splitre)) kwds))
4769 ((equal key "TYP_TODO")
4770 (push (cons 'type (org-split-string value splitre)) kwds))
4771 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4772 ;; general TODO-like setup
4773 (push (cons (intern (downcase (match-string 1 key)))
4774 (org-split-string value splitre)) kwds))
4775 ((equal key "TAGS")
4776 (setq tags (append tags (if tags '("\\n") nil)
4777 (org-split-string value splitre))))
4778 ((equal key "COLUMNS")
4779 (org-set-local 'org-columns-default-format value))
4780 ((equal key "LINK")
4781 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4782 (push (cons (match-string 1 value)
4783 (org-trim (match-string 2 value)))
4784 links)))
4785 ((equal key "PRIORITIES")
4786 (setq prio (org-split-string value " +")))
4787 ((equal key "PROPERTY")
4788 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4789 (setq props (org-update-property-plist (match-string 1 value)
4790 (match-string 2 value)
4791 props))))
4792 ((equal key "FILETAGS")
4793 (when (string-match "\\S-" value)
4794 (setq ftags
4795 (append
4796 ftags
4797 (apply 'append
4798 (mapcar (lambda (x) (org-split-string x ":"))
4799 (org-split-string value)))))))
4800 ((equal key "DRAWERS")
4801 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4802 ((equal key "CONSTANTS")
4803 (setq const (append const (org-split-string value splitre))))
4804 ((equal key "STARTUP")
4805 (let ((opts (org-split-string value splitre))
4806 l var val)
4807 (while (setq l (pop opts))
4808 (when (setq l (assoc l org-startup-options))
4809 (setq var (nth 1 l) val (nth 2 l))
4810 (if (not (nth 3 l))
4811 (set (make-local-variable var) val)
4812 (if (not (listp (symbol-value var)))
4813 (set (make-local-variable var) nil))
4814 (set (make-local-variable var) (symbol-value var))
4815 (add-to-list var val))))))
4816 ((equal key "ARCHIVE")
4817 (setq arch value)
4818 (remove-text-properties 0 (length arch)
4819 '(face t fontified t) arch))
4820 ((equal key "OPTIONS")
4821 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4822 (setq scripts (read (match-string 2 value)))))
4823 ((equal key "SETUPFILE")
4824 (setq setup-contents (org-file-contents
4825 (expand-file-name
4826 (org-remove-double-quotes value))
4827 'noerror))
4828 (if (not ext-setup-or-nil)
4829 (setq ext-setup-or-nil setup-contents start 0)
4830 (setq ext-setup-or-nil
4831 (concat (substring ext-setup-or-nil 0 start)
4832 "\n" setup-contents "\n"
4833 (substring ext-setup-or-nil start)))))))
4834 ;; search for property blocks
4835 (goto-char (point-min))
4836 (while (re-search-forward org-block-regexp nil t)
4837 (when (equal "PROPERTY" (upcase (match-string 1)))
4838 (setq value (replace-regexp-in-string
4839 "[\n\r]" " " (match-string 4)))
4840 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4841 (setq props (org-update-property-plist (match-string 1 value)
4842 (match-string 2 value)
4843 props)))))))
4844 (org-set-local 'org-use-sub-superscripts scripts)
4845 (when cat
4846 (org-set-local 'org-category (intern cat))
4847 (push (cons "CATEGORY" cat) props))
4848 (when prio
4849 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4850 (setq prio (mapcar 'string-to-char prio))
4851 (org-set-local 'org-highest-priority (nth 0 prio))
4852 (org-set-local 'org-lowest-priority (nth 1 prio))
4853 (org-set-local 'org-default-priority (nth 2 prio)))
4854 (and props (org-set-local 'org-file-properties (nreverse props)))
4855 (and ftags (org-set-local 'org-file-tags
4856 (mapcar 'org-add-prop-inherited ftags)))
4857 (and drawers (org-set-local 'org-drawers drawers))
4858 (and arch (org-set-local 'org-archive-location arch))
4859 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4860 ;; Process the TODO keywords
4861 (unless kwds
4862 ;; Use the global values as if they had been given locally.
4863 (setq kwds (default-value 'org-todo-keywords))
4864 (if (stringp (car kwds))
4865 (setq kwds (list (cons org-todo-interpretation
4866 (default-value 'org-todo-keywords)))))
4867 (setq kwds (reverse kwds)))
4868 (setq kwds (nreverse kwds))
4869 (let (inter kws kw)
4870 (while (setq kws (pop kwds))
4871 (let ((kws (or
4872 (run-hook-with-args-until-success
4873 'org-todo-setup-filter-hook kws)
4874 kws)))
4875 (setq inter (pop kws) sep (member "|" kws)
4876 kws0 (delete "|" (copy-sequence kws))
4877 kwsa nil
4878 kws1 (mapcar
4879 (lambda (x)
4880 ;; 1 2
4881 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4882 (progn
4883 (setq kw (match-string 1 x)
4884 key (and (match-end 2) (match-string 2 x))
4885 log (org-extract-log-state-settings x))
4886 (push (cons kw (and key (string-to-char key))) kwsa)
4887 (and log (push log org-todo-log-states))
4889 (error "Invalid TODO keyword %s" x)))
4890 kws0)
4891 kwsa (if kwsa (append '((:startgroup))
4892 (nreverse kwsa)
4893 '((:endgroup))))
4894 hw (car kws1)
4895 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4896 tail (list inter hw (car dws) (org-last dws))))
4897 (add-to-list 'org-todo-heads hw 'append)
4898 (push kws1 org-todo-sets)
4899 (setq org-done-keywords (append org-done-keywords dws nil))
4900 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4901 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4902 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4903 (setq org-todo-sets (nreverse org-todo-sets)
4904 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4905 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4906 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4907 ;; Process the constants
4908 (when const
4909 (let (e cst)
4910 (while (setq e (pop const))
4911 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4912 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4913 (setq org-table-formula-constants-local cst)))
4915 ;; Process the tags.
4916 (when tags
4917 (let (e tgs)
4918 (while (setq e (pop tags))
4919 (cond
4920 ((equal e "{") (push '(:startgroup) tgs))
4921 ((equal e "}") (push '(:endgroup) tgs))
4922 ((equal e "\\n") (push '(:newline) tgs))
4923 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4924 (push (cons (match-string 1 e)
4925 (string-to-char (match-string 2 e)))
4926 tgs))
4927 (t (push (list e) tgs))))
4928 (org-set-local 'org-tag-alist nil)
4929 (while (setq e (pop tgs))
4930 (or (and (stringp (car e))
4931 (assoc (car e) org-tag-alist))
4932 (push e org-tag-alist)))))
4934 ;; Compute the regular expressions and other local variables.
4935 ;; Using `org-outline-regexp-bol' would complicate them much,
4936 ;; because of the fixed white space at the end of that string.
4937 (if (not org-done-keywords)
4938 (setq org-done-keywords (and org-todo-keywords-1
4939 (list (org-last org-todo-keywords-1)))))
4940 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4941 (length org-scheduled-string)
4942 (length org-clock-string)
4943 (length org-closed-string)))
4944 org-drawer-regexp
4945 (concat "^[ \t]*:\\("
4946 (mapconcat 'regexp-quote org-drawers "\\|")
4947 "\\):[ \t]*$")
4948 org-not-done-keywords
4949 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4950 org-todo-regexp
4951 (concat "\\("
4952 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4953 "\\)")
4954 org-not-done-regexp
4955 (concat "\\("
4956 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4957 "\\)")
4958 org-not-done-heading-regexp
4959 (format org-heading-keyword-regexp-format org-not-done-regexp)
4960 org-todo-line-regexp
4961 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4962 org-complex-heading-regexp
4963 (concat "^\\(\\*+\\)"
4964 "\\(?: +" org-todo-regexp "\\)?"
4965 "\\(?: +\\(\\[#.\\]\\)\\)?"
4966 "\\(?: +\\(.*?\\)\\)??"
4967 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4968 "[ \t]*$")
4969 org-complex-heading-regexp-format
4970 (concat "^\\(\\*+\\)"
4971 "\\(?: +" org-todo-regexp "\\)?"
4972 "\\(?: +\\(\\[#.\\]\\)\\)?"
4973 "\\(?: +"
4974 ;; Stats cookies can be stuck to body.
4975 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4976 "\\(%s\\)"
4977 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4978 "\\)"
4979 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4980 "[ \t]*$")
4981 org-todo-line-tags-regexp
4982 (concat "^\\(\\*+\\)"
4983 "\\(?: +" org-todo-regexp "\\)?"
4984 "\\(?: +\\(.*?\\)\\)??"
4985 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4986 "[ \t]*$")
4987 org-deadline-regexp (concat "\\<" org-deadline-string)
4988 org-deadline-time-regexp
4989 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
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-closed-time-regexp
4997 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4998 org-keyword-time-regexp
4999 (concat "\\<\\(" org-scheduled-string
5000 "\\|" org-deadline-string
5001 "\\|" org-closed-string
5002 "\\|" org-clock-string "\\)"
5003 " *[[<]\\([^]>]+\\)[]>]")
5004 org-keyword-time-not-clock-regexp
5005 (concat "\\<\\(" org-scheduled-string
5006 "\\|" org-deadline-string
5007 "\\|" org-closed-string
5008 "\\)"
5009 " *[[<]\\([^]>]+\\)[]>]")
5010 org-maybe-keyword-time-regexp
5011 (concat "\\(\\<\\(" org-scheduled-string
5012 "\\|" org-deadline-string
5013 "\\|" org-closed-string
5014 "\\|" org-clock-string "\\)\\)?"
5015 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5016 org-all-time-keywords
5017 (mapcar (lambda (w) (substring w 0 -1))
5018 (list org-scheduled-string org-deadline-string
5019 org-clock-string org-closed-string)))
5020 (org-compute-latex-and-related-regexp)
5021 (org-set-font-lock-defaults))))
5023 (defun org-file-contents (file &optional noerror)
5024 "Return the contents of FILE, as a string."
5025 (if (or (not file)
5026 (not (file-readable-p file)))
5027 (if noerror
5028 (progn
5029 (message "Cannot read file \"%s\"" file)
5030 (ding) (sit-for 2)
5032 (error "Cannot read file \"%s\"" file))
5033 (with-temp-buffer
5034 (insert-file-contents file)
5035 (buffer-string))))
5037 (defun org-extract-log-state-settings (x)
5038 "Extract the log state setting from a TODO keyword string.
5039 This will extract info from a string like \"WAIT(w@/!)\"."
5040 (let (kw key log1 log2)
5041 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5042 (setq kw (match-string 1 x)
5043 key (and (match-end 2) (match-string 2 x))
5044 log1 (and (match-end 3) (match-string 3 x))
5045 log2 (and (match-end 4) (match-string 4 x)))
5046 (and (or log1 log2)
5047 (list kw
5048 (and log1 (if (equal log1 "!") 'time 'note))
5049 (and log2 (if (equal log2 "!") 'time 'note)))))))
5051 (defun org-remove-keyword-keys (list)
5052 "Remove a pair of parenthesis at the end of each string in LIST."
5053 (mapcar (lambda (x)
5054 (if (string-match "(.*)$" x)
5055 (substring x 0 (match-beginning 0))
5057 list))
5059 (defun org-assign-fast-keys (alist)
5060 "Assign fast keys to a keyword-key alist.
5061 Respect keys that are already there."
5062 (let (new e (alt ?0))
5063 (while (setq e (pop alist))
5064 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5065 (cdr e)) ;; Key already assigned.
5066 (push e new)
5067 (let ((clist (string-to-list (downcase (car e))))
5068 (used (append new alist)))
5069 (when (= (car clist) ?@)
5070 (pop clist))
5071 (while (and clist (rassoc (car clist) used))
5072 (pop clist))
5073 (unless clist
5074 (while (rassoc alt used)
5075 (incf alt)))
5076 (push (cons (car e) (or (car clist) alt)) new))))
5077 (nreverse new)))
5079 ;;; Some variables used in various places
5081 (defvar org-window-configuration nil
5082 "Used in various places to store a window configuration.")
5083 (defvar org-selected-window nil
5084 "Used in various places to store a window configuration.")
5085 (defvar org-finish-function nil
5086 "Function to be called when `C-c C-c' is used.
5087 This is for getting out of special buffers like capture.")
5090 ;; FIXME: Occasionally check by commenting these, to make sure
5091 ;; no other functions uses these, forgetting to let-bind them.
5092 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5093 (defvar org-last-state)
5094 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5096 ;; Defined somewhere in this file, but used before definition.
5097 (defvar org-entities) ;; defined in org-entities.el
5098 (defvar org-struct-menu)
5099 (defvar org-org-menu)
5100 (defvar org-tbl-menu)
5102 ;;;; Define the Org-mode
5104 ;; We use a before-change function to check if a table might need
5105 ;; an update.
5106 (defvar org-table-may-need-update t
5107 "Indicates that a table might need an update.
5108 This variable is set by `org-before-change-function'.
5109 `org-table-align' sets it back to nil.")
5110 (defun org-before-change-function (beg end)
5111 "Every change indicates that a table might need an update."
5112 (setq org-table-may-need-update t))
5113 (defvar org-mode-map)
5114 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5115 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5116 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5117 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5118 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5119 (defvar org-table-buffer-is-an nil)
5121 (defvar bidi-paragraph-direction)
5122 (defvar buffer-face-mode-face)
5124 (require 'outline)
5125 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5126 (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"))
5127 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5129 ;; Other stuff we need.
5130 (require 'time-date)
5131 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5132 (require 'easymenu)
5133 (require 'overlay)
5135 ;; (require 'org-macs) moved higher up in the file before it is first used
5136 (require 'org-entities)
5137 ;; (require 'org-compat) moved higher up in the file before it is first used
5138 (require 'org-faces)
5139 (require 'org-list)
5140 (require 'org-pcomplete)
5141 (require 'org-src)
5142 (require 'org-footnote)
5143 (require 'org-macro)
5145 ;; babel
5146 (require 'ob)
5148 ;;;###autoload
5149 (define-derived-mode org-mode outline-mode "Org"
5150 "Outline-based notes management and organizer, alias
5151 \"Carsten's outline-mode for keeping track of everything.\"
5153 Org-mode develops organizational tasks around a NOTES file which
5154 contains information about projects as plain text. Org-mode is
5155 implemented on top of outline-mode, which is ideal to keep the content
5156 of large files well structured. It supports ToDo items, deadlines and
5157 time stamps, which magically appear in the diary listing of the Emacs
5158 calendar. Tables are easily created with a built-in table editor.
5159 Plain text URL-like links connect to websites, emails (VM), Usenet
5160 messages (Gnus), BBDB entries, and any files related to the project.
5161 For printing and sharing of notes, an Org-mode file (or a part of it)
5162 can be exported as a structured ASCII or HTML file.
5164 The following commands are available:
5166 \\{org-mode-map}"
5168 ;; Get rid of Outline menus, they are not needed
5169 ;; Need to do this here because define-derived-mode sets up
5170 ;; the keymap so late. Still, it is a waste to call this each time
5171 ;; we switch another buffer into org-mode.
5172 (if (featurep 'xemacs)
5173 (when (boundp 'outline-mode-menu-heading)
5174 ;; Assume this is Greg's port, it uses easymenu
5175 (easy-menu-remove outline-mode-menu-heading)
5176 (easy-menu-remove outline-mode-menu-show)
5177 (easy-menu-remove outline-mode-menu-hide))
5178 (define-key org-mode-map [menu-bar headings] 'undefined)
5179 (define-key org-mode-map [menu-bar hide] 'undefined)
5180 (define-key org-mode-map [menu-bar show] 'undefined))
5182 (org-load-modules-maybe)
5183 (easy-menu-add org-org-menu)
5184 (easy-menu-add org-tbl-menu)
5185 (org-install-agenda-files-menu)
5186 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5187 (add-to-invisibility-spec '(org-cwidth))
5188 (add-to-invisibility-spec '(org-hide-block . t))
5189 (when (featurep 'xemacs)
5190 (org-set-local 'line-move-ignore-invisible t))
5191 (org-set-local 'outline-regexp org-outline-regexp)
5192 (org-set-local 'outline-level 'org-outline-level)
5193 (setq bidi-paragraph-direction 'left-to-right)
5194 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5195 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5196 (when (and org-ellipsis
5197 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5198 (fboundp 'make-glyph-code))
5199 (unless org-display-table
5200 (setq org-display-table (make-display-table)))
5201 (set-display-table-slot
5202 org-display-table 4
5203 (vconcat (mapcar
5204 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5205 org-ellipsis)))
5206 (if (stringp org-ellipsis) org-ellipsis "..."))))
5207 (setq buffer-display-table org-display-table))
5208 (org-set-regexps-and-options)
5209 (when (and org-tag-faces (not org-tags-special-faces-re))
5210 ;; tag faces set outside customize.... force initialization.
5211 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5212 ;; Calc embedded
5213 (org-set-local 'calc-embedded-open-mode "# ")
5214 ;; Modify a few syntax entries
5215 (modify-syntax-entry ?@ "w")
5216 (modify-syntax-entry ?\" "\"")
5217 (if org-startup-truncated (setq truncate-lines t))
5218 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5219 (org-set-local 'font-lock-unfontify-region-function
5220 'org-unfontify-region)
5221 ;; Activate before-change-function
5222 (org-set-local 'org-table-may-need-update t)
5223 (org-add-hook 'before-change-functions 'org-before-change-function nil
5224 'local)
5225 ;; Check for running clock before killing a buffer
5226 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5227 ;; Initialize macros templates.
5228 (org-macro-initialize-templates)
5229 ;; Initialize radio targets.
5230 (org-update-radio-target-regexp)
5231 ;; Indentation.
5232 (org-set-local 'indent-line-function 'org-indent-line)
5233 (org-set-local 'indent-region-function 'org-indent-region)
5234 ;; Filling and auto-filling.
5235 (org-setup-filling)
5236 ;; Comments.
5237 (org-setup-comments-handling)
5238 ;; Beginning/end of defun
5239 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5240 (org-set-local 'end-of-defun-function 'org-forward-element)
5241 ;; Next error for sparse trees
5242 (org-set-local 'next-error-function 'org-occur-next-match)
5243 ;; Make sure dependence stuff works reliably, even for users who set it
5244 ;; too late :-(
5245 (if org-enforce-todo-dependencies
5246 (add-hook 'org-blocker-hook
5247 'org-block-todo-from-children-or-siblings-or-parent)
5248 (remove-hook 'org-blocker-hook
5249 'org-block-todo-from-children-or-siblings-or-parent))
5250 (if org-enforce-todo-checkbox-dependencies
5251 (add-hook 'org-blocker-hook
5252 'org-block-todo-from-checkboxes)
5253 (remove-hook 'org-blocker-hook
5254 'org-block-todo-from-checkboxes))
5256 ;; Align options lines
5257 (org-set-local
5258 'align-mode-rules-list
5259 '((org-in-buffer-settings
5260 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5261 (modes . '(org-mode)))))
5263 ;; Imenu
5264 (org-set-local 'imenu-create-index-function
5265 'org-imenu-get-tree)
5267 ;; Make isearch reveal context
5268 (if (or (featurep 'xemacs)
5269 (not (boundp 'outline-isearch-open-invisible-function)))
5270 ;; Emacs 21 and XEmacs make use of the hook
5271 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5272 ;; Emacs 22 deals with this through a special variable
5273 (org-set-local 'outline-isearch-open-invisible-function
5274 (lambda (&rest ignore) (org-show-context 'isearch)))
5275 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5277 ;; Setup the pcomplete hooks
5278 (set (make-local-variable 'pcomplete-command-completion-function)
5279 'org-pcomplete-initial)
5280 (set (make-local-variable 'pcomplete-command-name-function)
5281 'org-command-at-point)
5282 (set (make-local-variable 'pcomplete-default-completion-function)
5283 'ignore)
5284 (set (make-local-variable 'pcomplete-parse-arguments-function)
5285 'org-parse-arguments)
5286 (set (make-local-variable 'pcomplete-termination-string) "")
5287 (when (>= emacs-major-version 23)
5288 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5290 ;; If empty file that did not turn on org-mode automatically, make it to.
5291 (if (and org-insert-mode-line-in-empty-file
5292 (org-called-interactively-p 'any)
5293 (= (point-min) (point-max)))
5294 (insert "# -*- mode: org -*-\n\n"))
5295 (unless org-inhibit-startup
5296 (org-unmodified
5297 (and org-startup-with-beamer-mode (org-beamer-mode))
5298 (when org-startup-align-all-tables
5299 (org-table-map-tables 'org-table-align 'quietly))
5300 (when org-startup-with-inline-images
5301 (org-display-inline-images))
5302 (when org-startup-with-latex-preview
5303 (org-preview-latex-fragment))
5304 (unless org-inhibit-startup-visibility-stuff
5305 (org-set-startup-visibility))))
5306 ;; Try to set org-hide correctly
5307 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5309 (defvar org-mode-transpose-word-syntax-table
5310 (let ((st (make-syntax-table)))
5311 (mapc (lambda(c) (modify-syntax-entry
5312 (string-to-char (car c)) "w p" st))
5313 org-emphasis-alist)
5314 st))
5316 (when (fboundp 'abbrev-table-put)
5317 (abbrev-table-put org-mode-abbrev-table
5318 :parents (list text-mode-abbrev-table)))
5320 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5322 (defsubst org-fix-ellipsis-at-bol ()
5323 (save-excursion (goto-char (window-start)) (recenter 0)))
5325 (defun org-find-invisible-foreground ()
5326 (let ((candidates (remove
5327 "unspecified-bg"
5328 (nconc
5329 (list (face-background 'default)
5330 (face-background 'org-default))
5331 (mapcar
5332 (lambda (alist)
5333 (when (boundp alist)
5334 (cdr (assoc 'background-color (symbol-value alist)))))
5335 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5336 (list (face-foreground 'org-hide))))))
5337 (car (remove nil candidates))))
5339 (defun org-current-time (&optional rounding-minutes past)
5340 "Current time, possibly rounded to ROUNDING-MINUTES.
5341 When ROUNDING-MINUTES is not an integer, fall back on the car of
5342 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5343 the rounding returns a past time."
5344 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5345 (car org-time-stamp-rounding-minutes)))
5346 (time (decode-time)) res)
5347 (if (< r 1)
5348 (current-time)
5349 (setq res
5350 (apply 'encode-time
5351 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5352 (nthcdr 2 time))))
5353 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5354 (seconds-to-time (- (org-float-time res) (* r 60)))
5355 res))))
5357 (defun org-today ()
5358 "Return today date, considering `org-extend-today-until'."
5359 (time-to-days
5360 (time-subtract (current-time)
5361 (list 0 (* 3600 org-extend-today-until) 0))))
5363 ;;;; Font-Lock stuff, including the activators
5365 (defvar org-mouse-map (make-sparse-keymap))
5366 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5367 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5368 (when org-mouse-1-follows-link
5369 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5370 (when org-tab-follows-link
5371 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5372 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5374 (require 'font-lock)
5376 (defconst org-non-link-chars "]\t\n\r<>")
5377 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5378 "shell" "elisp" "doi" "message"))
5379 (defvar org-link-types-re nil
5380 "Matches a link that has a url-like prefix like \"http:\"")
5381 (defvar org-link-re-with-space nil
5382 "Matches a link with spaces, optional angular brackets around it.")
5383 (defvar org-link-re-with-space2 nil
5384 "Matches a link with spaces, optional angular brackets around it.")
5385 (defvar org-link-re-with-space3 nil
5386 "Matches a link with spaces, only for internal part in bracket links.")
5387 (defvar org-angle-link-re nil
5388 "Matches link with angular brackets, spaces are allowed.")
5389 (defvar org-plain-link-re nil
5390 "Matches plain link, without spaces.")
5391 (defvar org-bracket-link-regexp nil
5392 "Matches a link in double brackets.")
5393 (defvar org-bracket-link-analytic-regexp nil
5394 "Regular expression used to analyze links.
5395 Here is what the match groups contain after a match:
5396 1: http:
5397 2: http
5398 3: path
5399 4: [desc]
5400 5: desc")
5401 (defvar org-bracket-link-analytic-regexp++ nil
5402 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5403 (defvar org-any-link-re nil
5404 "Regular expression matching any link.")
5406 (defconst org-match-sexp-depth 3
5407 "Number of stacked braces for sub/superscript matching.")
5409 (defun org-create-multibrace-regexp (left right n)
5410 "Create a regular expression which will match a balanced sexp.
5411 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5412 as single character strings.
5413 The regexp returned will match the entire expression including the
5414 delimiters. It will also define a single group which contains the
5415 match except for the outermost delimiters. The maximum depth of
5416 stacked delimiters is N. Escaping delimiters is not possible."
5417 (let* ((nothing (concat "[^" left right "]*?"))
5418 (or "\\|")
5419 (re nothing)
5420 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5421 (while (> n 1)
5422 (setq n (1- n)
5423 re (concat re or next)
5424 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5425 (concat left "\\(" re "\\)" right)))
5427 (defvar org-match-substring-regexp
5428 (concat
5429 "\\(\\S-\\)\\([_^]\\)\\("
5430 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5431 "\\|"
5432 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5433 "\\|"
5434 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5435 "The regular expression matching a sub- or superscript.")
5437 (defvar org-match-substring-with-braces-regexp
5438 (concat
5439 "\\(\\S-\\)\\([_^]\\)\\("
5440 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5441 "\\)")
5442 "The regular expression matching a sub- or superscript, forcing braces.")
5444 (defun org-make-link-regexps ()
5445 "Update the link regular expressions.
5446 This should be called after the variable `org-link-types' has changed."
5447 (setq org-link-types-re
5448 (concat
5449 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5450 org-link-re-with-space
5451 (concat
5452 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5453 "\\([^" org-non-link-chars " ]"
5454 "[^" org-non-link-chars "]*"
5455 "[^" org-non-link-chars " ]\\)>?")
5456 org-link-re-with-space2
5457 (concat
5458 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5459 "\\([^" org-non-link-chars " ]"
5460 "[^\t\n\r]*"
5461 "[^" org-non-link-chars " ]\\)>?")
5462 org-link-re-with-space3
5463 (concat
5464 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5465 "\\([^" org-non-link-chars " ]"
5466 "[^\t\n\r]*\\)")
5467 org-angle-link-re
5468 (concat
5469 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5470 "\\([^" org-non-link-chars " ]"
5471 "[^" org-non-link-chars "]*"
5472 "\\)>")
5473 org-plain-link-re
5474 (concat
5475 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5476 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5477 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5478 org-bracket-link-regexp
5479 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5480 org-bracket-link-analytic-regexp
5481 (concat
5482 "\\[\\["
5483 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5484 "\\([^]]+\\)"
5485 "\\]"
5486 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5487 "\\]")
5488 org-bracket-link-analytic-regexp++
5489 (concat
5490 "\\[\\["
5491 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5492 "\\([^]]+\\)"
5493 "\\]"
5494 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5495 "\\]")
5496 org-any-link-re
5497 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5498 org-angle-link-re "\\)\\|\\("
5499 org-plain-link-re "\\)")))
5501 (org-make-link-regexps)
5503 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5504 "Regular expression for fast time stamp matching.")
5505 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5506 "Regular expression for fast time stamp matching.")
5507 (defconst org-ts-regexp0
5508 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5509 "Regular expression matching time strings for analysis.
5510 This one does not require the space after the date, so it can be used
5511 on a string that terminates immediately after the date.")
5512 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5513 "Regular expression matching time strings for analysis.")
5514 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5515 "Regular expression matching time stamps, with groups.")
5516 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5517 "Regular expression matching time stamps (also [..]), with groups.")
5518 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5519 "Regular expression matching a time stamp range.")
5520 (defconst org-tr-regexp-both
5521 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5522 "Regular expression matching a time stamp range.")
5523 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5524 org-ts-regexp "\\)?")
5525 "Regular expression matching a time stamp or time stamp range.")
5526 (defconst org-tsr-regexp-both
5527 (concat org-ts-regexp-both "\\(--?-?"
5528 org-ts-regexp-both "\\)?")
5529 "Regular expression matching a time stamp or time stamp range.
5530 The time stamps may be either active or inactive.")
5532 (defvar org-emph-face nil)
5534 (defun org-do-emphasis-faces (limit)
5535 "Run through the buffer and add overlays to emphasized strings."
5536 (let (rtn a)
5537 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5538 (if (not (= (char-after (match-beginning 3))
5539 (char-after (match-beginning 4))))
5540 (progn
5541 (setq rtn t)
5542 (setq a (assoc (match-string 3) org-emphasis-alist))
5543 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5544 'face
5545 (nth 1 a))
5546 (and (nth 4 a)
5547 (org-remove-flyspell-overlays-in
5548 (match-beginning 0) (match-end 0)))
5549 (add-text-properties (match-beginning 2) (match-end 2)
5550 '(font-lock-multiline t org-emphasis t))
5551 (when org-hide-emphasis-markers
5552 (add-text-properties (match-end 4) (match-beginning 5)
5553 '(invisible org-link))
5554 (add-text-properties (match-beginning 3) (match-end 3)
5555 '(invisible org-link)))))
5556 (backward-char 1))
5557 rtn))
5559 (defun org-emphasize (&optional char)
5560 "Insert or change an emphasis, i.e. a font like bold or italic.
5561 If there is an active region, change that region to a new emphasis.
5562 If there is no region, just insert the marker characters and position
5563 the cursor between them.
5564 CHAR should be either the marker character, or the first character of the
5565 HTML tag associated with that emphasis. If CHAR is a space, the means
5566 to remove the emphasis of the selected region.
5567 If char is not given (for example in an interactive call) it
5568 will be prompted for."
5569 (interactive)
5570 (let ((eal org-emphasis-alist) e det
5571 (erc org-emphasis-regexp-components)
5572 (prompt "")
5573 (string "") beg end move tag c s)
5574 (if (org-region-active-p)
5575 (setq beg (region-beginning) end (region-end)
5576 string (buffer-substring beg end))
5577 (setq move t))
5579 (while (setq e (pop eal))
5580 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5581 c (aref tag 0))
5582 (push (cons c (string-to-char (car e))) det)
5583 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5584 (substring tag 1)))))
5585 (setq det (nreverse det))
5586 (unless char
5587 (message "%s" (concat "Emphasis marker or tag:" prompt))
5588 (setq char (read-char-exclusive)))
5589 (setq char (or (cdr (assoc char det)) char))
5590 (if (equal char ?\ )
5591 (setq s "" move nil)
5592 (unless (assoc (char-to-string char) org-emphasis-alist)
5593 (error "No such emphasis marker: \"%c\"" char))
5594 (setq s (char-to-string char)))
5595 (while (and (> (length string) 1)
5596 (equal (substring string 0 1) (substring string -1))
5597 (assoc (substring string 0 1) org-emphasis-alist))
5598 (setq string (substring string 1 -1)))
5599 (setq string (concat s string s))
5600 (if beg (delete-region beg end))
5601 (unless (or (bolp)
5602 (string-match (concat "[" (nth 0 erc) "\n]")
5603 (char-to-string (char-before (point)))))
5604 (insert " "))
5605 (unless (or (eobp)
5606 (string-match (concat "[" (nth 1 erc) "\n]")
5607 (char-to-string (char-after (point)))))
5608 (insert " ") (backward-char 1))
5609 (insert string)
5610 (and move (backward-char 1))))
5612 (defconst org-nonsticky-props
5613 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5615 (defsubst org-rear-nonsticky-at (pos)
5616 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5618 (defun org-activate-plain-links (limit)
5619 "Run through the buffer and add overlays to links."
5620 (let (f hl)
5621 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5622 (not (org-in-src-block-p)))
5623 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5624 (setq f (get-text-property (match-beginning 0) 'face))
5625 (setq hl (org-match-string-no-properties 0))
5626 (if (or (eq f 'org-tag)
5627 (and (listp f) (memq 'org-tag f)))
5629 (add-text-properties (match-beginning 0) (match-end 0)
5630 (list 'mouse-face 'highlight
5631 'face 'org-link
5632 'htmlize-link `(:uri ,hl)
5633 'keymap org-mouse-map))
5634 (org-rear-nonsticky-at (match-end 0)))
5635 t)))
5637 (defun org-activate-code (limit)
5638 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5639 (progn
5640 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5641 (remove-text-properties (match-beginning 0) (match-end 0)
5642 '(display t invisible t intangible t))
5643 t)))
5645 (defcustom org-src-fontify-natively nil
5646 "When non-nil, fontify code in code blocks."
5647 :type 'boolean
5648 :version "24.1"
5649 :group 'org-appearance
5650 :group 'org-babel)
5652 (defcustom org-allow-promoting-top-level-subtree nil
5653 "When non-nil, allow promoting a top level subtree.
5654 The leading star of the top level headline will be replaced
5655 by a #."
5656 :type 'boolean
5657 :version "24.1"
5658 :group 'org-appearance)
5660 (defun org-fontify-meta-lines-and-blocks (limit)
5661 (condition-case nil
5662 (org-fontify-meta-lines-and-blocks-1 limit)
5663 (error (message "org-mode fontification error"))))
5665 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5666 "Fontify #+ lines and blocks, in the correct ways."
5667 (let ((case-fold-search t))
5668 (if (re-search-forward
5669 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5670 limit t)
5671 (let ((beg (match-beginning 0))
5672 (block-start (match-end 0))
5673 (block-end nil)
5674 (lang (match-string 7))
5675 (beg1 (line-beginning-position 2))
5676 (dc1 (downcase (match-string 2)))
5677 (dc3 (downcase (match-string 3)))
5678 end end1 quoting block-type ovl)
5679 (cond
5680 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5681 ;; a single line of backend-specific content
5682 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5683 (remove-text-properties (match-beginning 0) (match-end 0)
5684 '(display t invisible t intangible t))
5685 (add-text-properties (match-beginning 1) (match-end 3)
5686 '(font-lock-fontified t face org-meta-line))
5687 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5688 '(font-lock-fontified t face org-block))
5689 ; for backend-specific code
5691 ((and (match-end 4) (equal dc3 "+begin"))
5692 ;; Truly a block
5693 (setq block-type (downcase (match-string 5))
5694 quoting (member block-type org-protecting-blocks))
5695 (when (re-search-forward
5696 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5697 nil t) ;; on purpose, we look further than LIMIT
5698 (setq end (min (point-max) (match-end 0))
5699 end1 (min (point-max) (1- (match-beginning 0))))
5700 (setq block-end (match-beginning 0))
5701 (when quoting
5702 (remove-text-properties beg end
5703 '(display t invisible t intangible t)))
5704 (add-text-properties
5705 beg end
5706 '(font-lock-fontified t font-lock-multiline t))
5707 (add-text-properties beg beg1 '(face org-meta-line))
5708 (add-text-properties end1 (min (point-max) (1+ end))
5709 '(face org-meta-line)) ; for end_src
5710 (cond
5711 ((and lang (not (string= lang "")) org-src-fontify-natively)
5712 (org-src-font-lock-fontify-block lang block-start block-end)
5713 ;; remove old background overlays
5714 (mapc (lambda (ov)
5715 (if (eq (overlay-get ov 'face) 'org-block-background)
5716 (delete-overlay ov)))
5717 (overlays-at (/ (+ beg1 block-end) 2)))
5718 ;; add a background overlay
5719 (setq ovl (make-overlay beg1 block-end))
5720 (overlay-put ovl 'face 'org-block-background)
5721 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5722 (quoting
5723 (add-text-properties beg1 (min (point-max) (1+ end1))
5724 '(face org-block))) ; end of source block
5725 ((not org-fontify-quote-and-verse-blocks))
5726 ((string= block-type "quote")
5727 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5728 ((string= block-type "verse")
5729 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5730 (add-text-properties beg beg1 '(face org-block-begin-line))
5731 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5732 '(face org-block-end-line))
5734 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5735 (add-text-properties
5736 beg (match-end 3)
5737 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5738 '(font-lock-fontified t invisible t)
5739 '(font-lock-fontified t face org-document-info-keyword)))
5740 (add-text-properties
5741 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5742 (if (string-equal dc1 "+title:")
5743 '(font-lock-fontified t face org-document-title)
5744 '(font-lock-fontified t face org-document-info))))
5745 ((or (equal dc1 "+results")
5746 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5747 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5748 "+call:" "+header:" "+headers:" "+name:"))
5749 (and (match-end 4) (equal dc3 "+attr")))
5750 (add-text-properties
5751 beg (match-end 0)
5752 '(font-lock-fontified t face org-meta-line))
5754 ((member dc3 '(" " ""))
5755 (add-text-properties
5756 beg (match-end 0)
5757 '(font-lock-fontified t face font-lock-comment-face)))
5758 ((not (member (char-after beg) '(?\ ?\t)))
5759 ;; just any other in-buffer setting, but not indented
5760 (add-text-properties
5761 beg (match-end 0)
5762 '(font-lock-fontified t face org-meta-line))
5764 (t nil))))))
5766 (defun org-activate-angle-links (limit)
5767 "Run through the buffer and add overlays to links."
5768 (if (and (re-search-forward org-angle-link-re limit t)
5769 (not (org-in-src-block-p)))
5770 (progn
5771 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5772 (add-text-properties (match-beginning 0) (match-end 0)
5773 (list 'mouse-face 'highlight
5774 'keymap org-mouse-map))
5775 (org-rear-nonsticky-at (match-end 0))
5776 t)))
5778 (defun org-activate-footnote-links (limit)
5779 "Run through the buffer and add overlays to footnotes."
5780 (let ((fn (org-footnote-next-reference-or-definition limit)))
5781 (when fn
5782 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5783 (org-remove-flyspell-overlays-in beg end)
5784 (add-text-properties beg end
5785 (list 'mouse-face 'highlight
5786 'keymap org-mouse-map
5787 'help-echo
5788 (if (= (point-at-bol) beg)
5789 "Footnote definition"
5790 "Footnote reference")
5791 'font-lock-fontified t
5792 'font-lock-multiline t
5793 'face 'org-footnote))))))
5795 (defun org-activate-bracket-links (limit)
5796 "Run through the buffer and add overlays to bracketed links."
5797 (if (and (re-search-forward org-bracket-link-regexp limit t)
5798 (not (org-in-src-block-p)))
5799 (let* ((hl (org-match-string-no-properties 1))
5800 (help (concat "LINK: " hl))
5801 ;; FIXME: Above we should remove the escapes. But that
5802 ;; requires another match, protecting match data, a lot
5803 ;; of overhead for font-lock.
5804 (ip (org-maybe-intangible
5805 (list 'invisible 'org-link
5806 'keymap org-mouse-map 'mouse-face 'highlight
5807 'font-lock-multiline t 'help-echo help
5808 'htmlize-link `(:uri ,hl))))
5809 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5810 'font-lock-multiline t 'help-echo help
5811 'htmlize-link `(:uri ,hl))))
5812 ;; We need to remove the invisible property here. Table narrowing
5813 ;; may have made some of this invisible.
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (remove-text-properties (match-beginning 0) (match-end 0)
5816 '(invisible nil))
5817 (if (match-end 3)
5818 (progn
5819 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5820 (org-rear-nonsticky-at (match-beginning 3))
5821 (add-text-properties (match-beginning 3) (match-end 3) vp)
5822 (org-rear-nonsticky-at (match-end 3))
5823 (add-text-properties (match-end 3) (match-end 0) ip)
5824 (org-rear-nonsticky-at (match-end 0)))
5825 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5826 (org-rear-nonsticky-at (match-beginning 1))
5827 (add-text-properties (match-beginning 1) (match-end 1) vp)
5828 (org-rear-nonsticky-at (match-end 1))
5829 (add-text-properties (match-end 1) (match-end 0) ip)
5830 (org-rear-nonsticky-at (match-end 0)))
5831 t)))
5833 (defun org-activate-dates (limit)
5834 "Run through the buffer and add overlays to dates."
5835 (if (and (re-search-forward org-tsr-regexp-both limit t)
5836 (not (equal (char-before (match-beginning 0)) 91)))
5837 (progn
5838 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5839 (add-text-properties (match-beginning 0) (match-end 0)
5840 (list 'mouse-face 'highlight
5841 'keymap org-mouse-map))
5842 (org-rear-nonsticky-at (match-end 0))
5843 (when org-display-custom-times
5844 (if (match-end 3)
5845 (org-display-custom-time (match-beginning 3) (match-end 3)))
5846 (org-display-custom-time (match-beginning 1) (match-end 1)))
5847 t)))
5849 (defvar org-target-link-regexp nil
5850 "Regular expression matching radio targets in plain text.")
5851 (make-variable-buffer-local 'org-target-link-regexp)
5852 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5853 "Regular expression matching a link target.")
5854 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5855 "Regular expression matching a radio target.")
5856 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5857 "Regular expression matching any target.")
5859 (defun org-activate-target-links (limit)
5860 "Run through the buffer and add overlays to target matches."
5861 (when org-target-link-regexp
5862 (let ((case-fold-search t))
5863 (if (re-search-forward org-target-link-regexp limit t)
5864 (progn
5865 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5866 (add-text-properties (match-beginning 0) (match-end 0)
5867 (list 'mouse-face 'highlight
5868 'keymap org-mouse-map
5869 'help-echo "Radio target link"
5870 'org-linked-text t))
5871 (org-rear-nonsticky-at (match-end 0))
5872 t)))))
5874 (defun org-update-radio-target-regexp ()
5875 "Find all radio targets in this file and update the regular expression."
5876 (interactive)
5877 (when (memq 'radio org-activate-links)
5878 (setq org-target-link-regexp
5879 (org-make-target-link-regexp (org-all-targets 'radio)))
5880 (org-restart-font-lock)))
5882 (defun org-hide-wide-columns (limit)
5883 (let (s e)
5884 (setq s (text-property-any (point) (or limit (point-max))
5885 'org-cwidth t))
5886 (when s
5887 (setq e (next-single-property-change s 'org-cwidth))
5888 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5889 (goto-char e)
5890 t)))
5892 (defvar org-latex-and-related-regexp nil
5893 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5894 (defvar org-match-substring-regexp)
5895 (defvar org-match-substring-with-braces-regexp)
5897 (defun org-compute-latex-and-related-regexp ()
5898 "Compute regular expression for LaTeX, entities and sub/superscript.
5899 Result depends on variable `org-highlight-latex-and-related'."
5900 (org-set-local
5901 'org-latex-and-related-regexp
5902 (let* ((re-sub
5903 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5904 ((eq org-use-sub-superscripts '{})
5905 (list org-match-substring-with-braces-regexp))
5906 (org-use-sub-superscripts (list org-match-substring-regexp))))
5907 (re-latex
5908 (when (memq 'latex org-highlight-latex-and-related)
5909 (let ((matchers (plist-get org-format-latex-options :matchers)))
5910 (delq nil
5911 (mapcar (lambda (x)
5912 (and (member (car x) matchers) (nth 1 x)))
5913 org-latex-regexps)))))
5914 (re-entities
5915 (when (memq 'entities org-highlight-latex-and-related)
5916 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5917 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5919 (defun org-do-latex-and-related (limit)
5920 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5921 LIMIT bounds the search for syntax to highlight. Stop at first
5922 highlighted object, if any. Return t if some highlighting was
5923 done, nil otherwise."
5924 (when (org-string-nw-p org-latex-and-related-regexp)
5925 (catch 'found
5926 (while (re-search-forward org-latex-and-related-regexp limit t)
5927 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5928 'face))
5929 '(org-code org-verbatim underline))
5930 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5931 '(?_ ?^))
5933 0)))
5934 (font-lock-prepend-text-property
5935 (+ offset (match-beginning 0)) (match-end 0)
5936 'face 'org-latex-and-related)
5937 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5938 '(font-lock-multiline t)))
5939 (throw 'found t)))
5940 nil)))
5942 (defun org-restart-font-lock ()
5943 "Restart `font-lock-mode', to force refontification."
5944 (when (and (boundp 'font-lock-mode) font-lock-mode)
5945 (font-lock-mode -1)
5946 (font-lock-mode 1)))
5948 (defun org-all-targets (&optional radio)
5949 "Return a list of all targets in this file.
5950 When optional argument RADIO is non-nil, only find radio
5951 targets."
5952 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5953 (save-excursion
5954 (goto-char (point-min))
5955 (while (re-search-forward re nil t)
5956 ;; Make sure point is really within the object.
5957 (backward-char)
5958 (let ((obj (org-element-context)))
5959 (when (memq (org-element-type obj) '(radio-target target))
5960 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5961 rtn)))
5963 (defun org-make-target-link-regexp (targets)
5964 "Make regular expression matching all strings in TARGETS.
5965 The regular expression finds the targets also if there is a line break
5966 between words."
5967 (and targets
5968 (concat
5969 "\\<\\("
5970 (mapconcat
5971 (lambda (x)
5972 (setq x (regexp-quote x))
5973 (while (string-match " +" x)
5974 (setq x (replace-match "\\s-+" t t x)))
5976 targets
5977 "\\|")
5978 "\\)\\>")))
5980 (defun org-activate-tags (limit)
5981 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5982 (progn
5983 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5984 (add-text-properties (match-beginning 1) (match-end 1)
5985 (list 'mouse-face 'highlight
5986 'keymap org-mouse-map))
5987 (org-rear-nonsticky-at (match-end 1))
5988 t)))
5990 (defun org-outline-level ()
5991 "Compute the outline level of the heading at point.
5992 If this is called at a normal headline, the level is the number of stars.
5993 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5994 (save-excursion
5995 (if (not (condition-case nil
5996 (org-back-to-heading t)
5997 (error nil)))
5999 (looking-at org-outline-regexp)
6000 (1- (- (match-end 0) (match-beginning 0))))))
6002 (defvar org-font-lock-keywords nil)
6004 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6005 "Regular expression matching a property line.")
6007 (defvar org-font-lock-hook nil
6008 "Functions to be called for special font lock stuff.")
6010 (defvar org-font-lock-set-keywords-hook nil
6011 "Functions that can manipulate `org-font-lock-extra-keywords'.
6012 This is called after `org-font-lock-extra-keywords' is defined, but before
6013 it is installed to be used by font lock. This can be useful if something
6014 needs to be inserted at a specific position in the font-lock sequence.")
6016 (defun org-font-lock-hook (limit)
6017 "Run `org-font-lock-hook' within LIMIT."
6018 (run-hook-with-args 'org-font-lock-hook limit))
6020 (defun org-set-font-lock-defaults ()
6021 "Set font lock defaults for the current buffer."
6022 (let* ((em org-fontify-emphasized-text)
6023 (lk org-activate-links)
6024 (org-font-lock-extra-keywords
6025 (list
6026 ;; Call the hook
6027 '(org-font-lock-hook)
6028 ;; Headlines
6029 `(,(if org-fontify-whole-heading-line
6030 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6031 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6032 (1 (org-get-level-face 1))
6033 (2 (org-get-level-face 2))
6034 (3 (org-get-level-face 3)))
6035 ;; Table lines
6036 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6037 (1 'org-table t))
6038 ;; Table internals
6039 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6040 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6041 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6042 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6043 ;; Drawers
6044 (list org-drawer-regexp '(0 'org-special-keyword t))
6045 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6046 ;; Properties
6047 (list org-property-re
6048 '(1 'org-special-keyword t)
6049 '(3 'org-property-value t))
6050 ;; Links
6051 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6052 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6053 (if (memq 'plain lk) '(org-activate-plain-links))
6054 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6055 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6056 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6057 (if (memq 'footnote lk) '(org-activate-footnote-links))
6058 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6059 '(org-hide-wide-columns (0 nil append))
6060 ;; TODO keyword
6061 (list (format org-heading-keyword-regexp-format
6062 org-todo-regexp)
6063 '(2 (org-get-todo-face 2) t))
6064 ;; DONE
6065 (if org-fontify-done-headline
6066 (list (format org-heading-keyword-regexp-format
6067 (concat
6068 "\\(?:"
6069 (mapconcat 'regexp-quote org-done-keywords "\\|")
6070 "\\)"))
6071 '(2 'org-headline-done t))
6072 nil)
6073 ;; Priorities
6074 '(org-font-lock-add-priority-faces)
6075 ;; Tags
6076 '(org-font-lock-add-tag-faces)
6077 ;; Special keywords
6078 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6079 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6080 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6081 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6082 ;; Emphasis
6083 (if em
6084 (if (featurep 'xemacs)
6085 '(org-do-emphasis-faces (0 nil append))
6086 '(org-do-emphasis-faces)))
6087 ;; Checkboxes
6088 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6089 1 'org-checkbox prepend)
6090 (if (cdr (assq 'checkbox org-list-automatic-rules))
6091 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6092 (0 (org-get-checkbox-statistics-face) t)))
6093 ;; Description list items
6094 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6095 1 'org-list-dt prepend)
6096 ;; ARCHIVEd headings
6097 (list (concat
6098 org-outline-regexp-bol
6099 "\\(.*:" org-archive-tag ":.*\\)")
6100 '(1 'org-archived prepend))
6101 ;; Specials
6102 '(org-do-latex-and-related)
6103 '(org-fontify-entities)
6104 '(org-raise-scripts)
6105 ;; Code
6106 '(org-activate-code (1 'org-code t))
6107 ;; COMMENT
6108 (list (format org-heading-keyword-regexp-format
6109 (concat "\\("
6110 org-comment-string "\\|" org-quote-string
6111 "\\)"))
6112 '(2 'org-special-keyword t))
6113 ;; Blocks and meta lines
6114 '(org-fontify-meta-lines-and-blocks)
6116 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6117 (run-hooks 'org-font-lock-set-keywords-hook)
6118 ;; Now set the full font-lock-keywords
6119 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6120 (org-set-local 'font-lock-defaults
6121 '(org-font-lock-keywords t nil nil backward-paragraph))
6122 (kill-local-variable 'font-lock-keywords) nil))
6124 (defun org-toggle-pretty-entities ()
6125 "Toggle the composition display of entities as UTF8 characters."
6126 (interactive)
6127 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6128 (org-restart-font-lock)
6129 (if org-pretty-entities
6130 (message "Entities are displayed as UTF8 characters")
6131 (save-restriction
6132 (widen)
6133 (org-decompose-region (point-min) (point-max))
6134 (message "Entities are displayed plain"))))
6136 (defvar org-custom-properties-overlays nil
6137 "List of overlays used for custom properties.")
6138 (make-variable-buffer-local 'org-custom-properties-overlays)
6140 (defun org-toggle-custom-properties-visibility ()
6141 "Display or hide properties in `org-custom-properties'."
6142 (interactive)
6143 (if org-custom-properties-overlays
6144 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6145 (setq org-custom-properties-overlays nil))
6146 (unless (not org-custom-properties)
6147 (save-excursion
6148 (save-restriction
6149 (widen)
6150 (goto-char (point-min))
6151 (while (re-search-forward org-property-re nil t)
6152 (mapc (lambda(p)
6153 (when (equal p (substring (match-string 1) 1 -1))
6154 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6155 (overlay-put o 'invisible t)
6156 (overlay-put o 'org-custom-property t)
6157 (push o org-custom-properties-overlays))))
6158 org-custom-properties)))))))
6160 (defun org-fontify-entities (limit)
6161 "Find an entity to fontify."
6162 (let (ee)
6163 (when org-pretty-entities
6164 (catch 'match
6165 (while (re-search-forward
6166 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6167 limit t)
6168 (if (and (not (org-in-indented-comment-line))
6169 (setq ee (org-entity-get (match-string 1)))
6170 (= (length (nth 6 ee)) 1))
6171 (let*
6172 ((end (if (equal (match-string 2) "{}")
6173 (match-end 2)
6174 (match-end 1))))
6175 (add-text-properties
6176 (match-beginning 0) end
6177 (list 'font-lock-fontified t))
6178 (compose-region (match-beginning 0) end
6179 (nth 6 ee) nil)
6180 (backward-char 1)
6181 (throw 'match t))))
6182 nil))))
6184 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6185 "Fontify string S like in Org-mode."
6186 (with-temp-buffer
6187 (insert s)
6188 (let ((org-odd-levels-only odd-levels))
6189 (org-mode)
6190 (font-lock-fontify-buffer)
6191 (buffer-string))))
6193 (defvar org-m nil)
6194 (defvar org-l nil)
6195 (defvar org-f nil)
6196 (defun org-get-level-face (n)
6197 "Get the right face for match N in font-lock matching of headlines."
6198 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6199 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6200 (if org-cycle-level-faces
6201 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6202 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6203 (cond
6204 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6205 ((eq n 2) org-f)
6206 (t (if org-level-color-stars-only nil org-f))))
6209 (defun org-get-todo-face (kwd)
6210 "Get the right face for a TODO keyword KWD.
6211 If KWD is a number, get the corresponding match group."
6212 (if (numberp kwd) (setq kwd (match-string kwd)))
6213 (or (org-face-from-face-or-color
6214 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6215 (and (member kwd org-done-keywords) 'org-done)
6216 'org-todo))
6218 (defun org-face-from-face-or-color (context inherit face-or-color)
6219 "Create a face list that inherits INHERIT, but sets the foreground color.
6220 When FACE-OR-COLOR is not a string, just return it."
6221 (if (stringp face-or-color)
6222 (list :inherit inherit
6223 (cdr (assoc context org-faces-easy-properties))
6224 face-or-color)
6225 face-or-color))
6227 (defun org-font-lock-add-tag-faces (limit)
6228 "Add the special tag faces."
6229 (when (and org-tag-faces org-tags-special-faces-re)
6230 (while (re-search-forward org-tags-special-faces-re limit t)
6231 (add-text-properties (match-beginning 1) (match-end 1)
6232 (list 'face (org-get-tag-face 1)
6233 'font-lock-fontified t))
6234 (backward-char 1))))
6236 (defun org-font-lock-add-priority-faces (limit)
6237 "Add the special priority faces."
6238 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6239 (when (save-match-data (org-at-heading-p))
6240 (add-text-properties
6241 (match-beginning 0) (match-end 0)
6242 (list 'face (or (org-face-from-face-or-color
6243 'priority 'org-priority
6244 (cdr (assoc (char-after (match-beginning 1))
6245 org-priority-faces)))
6246 'org-priority)
6247 'font-lock-fontified t)))))
6249 (defun org-get-tag-face (kwd)
6250 "Get the right face for a TODO keyword KWD.
6251 If KWD is a number, get the corresponding match group."
6252 (if (numberp kwd) (setq kwd (match-string kwd)))
6253 (or (org-face-from-face-or-color
6254 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6255 'org-tag))
6257 (defun org-unfontify-region (beg end &optional maybe_loudly)
6258 "Remove fontification and activation overlays from links."
6259 (font-lock-default-unfontify-region beg end)
6260 (let* ((buffer-undo-list t)
6261 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6262 (inhibit-modification-hooks t)
6263 deactivate-mark buffer-file-name buffer-file-truename)
6264 (org-decompose-region beg end)
6265 (remove-text-properties beg end
6266 '(mouse-face t keymap t org-linked-text t
6267 invisible t intangible t
6268 org-no-flyspell t org-emphasis t))
6269 (org-remove-font-lock-display-properties beg end)))
6271 (defconst org-script-display '(((raise -0.3) (height 0.7))
6272 ((raise 0.3) (height 0.7))
6273 ((raise -0.5))
6274 ((raise 0.5)))
6275 "Display properties for showing superscripts and subscripts.")
6277 (defun org-remove-font-lock-display-properties (beg end)
6278 "Remove specific display properties that have been added by font lock.
6279 The will remove the raise properties that are used to show superscripts
6280 and subscripts."
6281 (let (next prop)
6282 (while (< beg end)
6283 (setq next (next-single-property-change beg 'display nil end)
6284 prop (get-text-property beg 'display))
6285 (if (member prop org-script-display)
6286 (put-text-property beg next 'display nil))
6287 (setq beg next))))
6289 (defun org-raise-scripts (limit)
6290 "Add raise properties to sub/superscripts."
6291 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6292 (if (re-search-forward
6293 (if (eq org-use-sub-superscripts t)
6294 org-match-substring-regexp
6295 org-match-substring-with-braces-regexp)
6296 limit t)
6297 (let* ((pos (point)) table-p comment-p
6298 (mpos (match-beginning 3))
6299 (emph-p (get-text-property mpos 'org-emphasis))
6300 (link-p (get-text-property mpos 'mouse-face))
6301 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6302 (goto-char (point-at-bol))
6303 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6304 comment-p (org-looking-at-p "[ \t]*#"))
6305 (goto-char pos)
6306 ;; FIXME: Should we go back one character here, for a_b^c
6307 ;; (goto-char (1- pos)) ;????????????????????
6308 (if (or comment-p emph-p link-p keyw-p)
6310 (put-text-property (match-beginning 3) (match-end 0)
6311 'display
6312 (if (equal (char-after (match-beginning 2)) ?^)
6313 (nth (if table-p 3 1) org-script-display)
6314 (nth (if table-p 2 0) org-script-display)))
6315 (add-text-properties (match-beginning 2) (match-end 2)
6316 (list 'invisible t
6317 'org-dwidth t 'org-dwidth-n 1))
6318 (if (and (eq (char-after (match-beginning 3)) ?{)
6319 (eq (char-before (match-end 3)) ?}))
6320 (progn
6321 (add-text-properties
6322 (match-beginning 3) (1+ (match-beginning 3))
6323 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6324 (add-text-properties
6325 (1- (match-end 3)) (match-end 3)
6326 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6327 t)))))
6329 ;;;; Visibility cycling, including org-goto and indirect buffer
6331 ;;; Cycling
6333 (defvar org-cycle-global-status nil)
6334 (make-variable-buffer-local 'org-cycle-global-status)
6335 (put 'org-cycle-global-status 'org-state t)
6336 (defvar org-cycle-subtree-status nil)
6337 (make-variable-buffer-local 'org-cycle-subtree-status)
6338 (put 'org-cycle-subtree-status 'org-state t)
6340 (defvar org-inlinetask-min-level)
6342 ;;;###autoload
6343 (defun org-cycle (&optional arg)
6344 "TAB-action and visibility cycling for Org-mode.
6346 This is the command invoked in Org-mode by the TAB key. Its main purpose
6347 is outline visibility cycling, but it also invokes other actions
6348 in special contexts.
6350 - When this function is called with a prefix argument, rotate the entire
6351 buffer through 3 states (global cycling)
6352 1. OVERVIEW: Show only top-level headlines.
6353 2. CONTENTS: Show all headlines of all levels, but no body text.
6354 3. SHOW ALL: Show everything.
6355 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6356 determined by the variable `org-startup-folded', and by any VISIBILITY
6357 properties in the buffer.
6358 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6359 including any drawers.
6361 - When inside a table, re-align the table and move to the next field.
6363 - When point is at the beginning of a headline, rotate the subtree started
6364 by this line through 3 different states (local cycling)
6365 1. FOLDED: Only the main headline is shown.
6366 2. CHILDREN: The main headline and the direct children are shown.
6367 From this state, you can move to one of the children
6368 and zoom in further.
6369 3. SUBTREE: Show the entire subtree, including body text.
6370 If there is no subtree, switch directly from CHILDREN to FOLDED.
6372 - When point is at the beginning of an empty headline and the variable
6373 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6374 of the headline by demoting and promoting it to likely levels. This
6375 speeds up creation document structure by pressing TAB once or several
6376 times right after creating a new headline.
6378 - When there is a numeric prefix, go up to a heading with level ARG, do
6379 a `show-subtree' and return to the previous cursor position. If ARG
6380 is negative, go up that many levels.
6382 - When point is not at the beginning of a headline, execute the global
6383 binding for TAB, which is re-indenting the line. See the option
6384 `org-cycle-emulate-tab' for details.
6386 - Special case: if point is at the beginning of the buffer and there is
6387 no headline in line 1, this function will act as if called with prefix arg
6388 (C-u TAB, same as S-TAB) also when called without prefix arg.
6389 But only if also the variable `org-cycle-global-at-bob' is t."
6390 (interactive "P")
6391 (org-load-modules-maybe)
6392 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6393 (and org-cycle-level-after-item/entry-creation
6394 (or (org-cycle-level)
6395 (org-cycle-item-indentation))))
6396 (let* (message-log-max ; Don't populate the *Messages* buffer
6397 (limit-level
6398 (or org-cycle-max-level
6399 (and (boundp 'org-inlinetask-min-level)
6400 org-inlinetask-min-level
6401 (1- org-inlinetask-min-level))))
6402 (nstars (and limit-level
6403 (if org-odd-levels-only
6404 (and limit-level (1- (* limit-level 2)))
6405 limit-level)))
6406 (org-outline-regexp
6407 (if (not (derived-mode-p 'org-mode))
6408 outline-regexp
6409 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6410 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6411 (not (looking-at org-outline-regexp))))
6412 (org-cycle-hook
6413 (if bob-special
6414 (delq 'org-optimize-window-after-visibility-change
6415 (copy-sequence org-cycle-hook))
6416 org-cycle-hook))
6417 (pos (point)))
6419 (if (or bob-special (equal arg '(4)))
6420 ;; special case: use global cycling
6421 (setq arg t))
6423 (cond
6425 ((equal arg '(16))
6426 (setq last-command 'dummy)
6427 (org-set-startup-visibility)
6428 (message "Startup visibility, plus VISIBILITY properties"))
6430 ((equal arg '(64))
6431 (show-all)
6432 (message "Entire buffer visible, including drawers"))
6434 ;; Table: enter it or move to the next field.
6435 ((org-at-table-p 'any)
6436 (if (org-at-table.el-p)
6437 (message "Use C-c ' to edit table.el tables")
6438 (if arg (org-table-edit-field t)
6439 (org-table-justify-field-maybe)
6440 (call-interactively 'org-table-next-field))))
6442 ((run-hook-with-args-until-success
6443 'org-tab-after-check-for-table-hook))
6445 ;; Global cycling: delegate to `org-cycle-internal-global'.
6446 ((eq arg t) (org-cycle-internal-global))
6448 ;; Drawers: delegate to `org-flag-drawer'.
6449 ((and org-drawers org-drawer-regexp
6450 (save-excursion
6451 (beginning-of-line 1)
6452 (looking-at org-drawer-regexp)))
6453 (org-flag-drawer ; toggle block visibility
6454 (not (get-char-property (match-end 0) 'invisible))))
6456 ;; Show-subtree, ARG levels up from here.
6457 ((integerp arg)
6458 (save-excursion
6459 (org-back-to-heading)
6460 (outline-up-heading (if (< arg 0) (- arg)
6461 (- (funcall outline-level) arg)))
6462 (org-show-subtree)))
6464 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6465 ((and (featurep 'org-inlinetask)
6466 (org-inlinetask-at-task-p)
6467 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6468 (org-inlinetask-toggle-visibility))
6470 ((org-try-cdlatex-tab))
6472 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6473 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6474 (save-excursion (beginning-of-line 1)
6475 (looking-at org-outline-regexp)))
6476 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6477 (org-cycle-internal-local))
6479 ;; From there: TAB emulation and template completion.
6480 (buffer-read-only (org-back-to-heading))
6482 ((run-hook-with-args-until-success
6483 'org-tab-after-check-for-cycling-hook))
6485 ((org-try-structure-completion))
6487 ((run-hook-with-args-until-success
6488 'org-tab-before-tab-emulation-hook))
6490 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6491 (or (not (bolp))
6492 (not (looking-at org-outline-regexp))))
6493 (call-interactively (global-key-binding "\t")))
6495 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6496 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6497 (or (and (eq org-cycle-emulate-tab 'white)
6498 (= (match-end 0) (point-at-eol)))
6499 (and (eq org-cycle-emulate-tab 'whitestart)
6500 (>= (match-end 0) pos))))
6502 (eq org-cycle-emulate-tab t))
6503 (call-interactively (global-key-binding "\t")))
6505 (t (save-excursion
6506 (org-back-to-heading)
6507 (org-cycle)))))))
6509 (defun org-cycle-internal-global ()
6510 "Do the global cycling action."
6511 ;; Hack to avoid display of messages for .org attachments in Gnus
6512 (let (message-log-max ; Don't populate the *Messages* buffer
6513 (ga (string-match "\\*fontification" (buffer-name))))
6514 (cond
6515 ((and (eq last-command this-command)
6516 (eq org-cycle-global-status 'overview))
6517 ;; We just created the overview - now do table of contents
6518 ;; This can be slow in very large buffers, so indicate action
6519 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6520 (unless ga (message "CONTENTS..."))
6521 (org-content)
6522 (unless ga (message "CONTENTS...done"))
6523 (setq org-cycle-global-status 'contents)
6524 (run-hook-with-args 'org-cycle-hook 'contents))
6526 ((and (eq last-command this-command)
6527 (eq org-cycle-global-status 'contents))
6528 ;; We just showed the table of contents - now show everything
6529 (run-hook-with-args 'org-pre-cycle-hook 'all)
6530 (show-all)
6531 (unless ga (message "SHOW ALL"))
6532 (setq org-cycle-global-status 'all)
6533 (run-hook-with-args 'org-cycle-hook 'all))
6536 ;; Default action: go to overview
6537 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6538 (org-overview)
6539 (unless ga (message "OVERVIEW"))
6540 (setq org-cycle-global-status 'overview)
6541 (run-hook-with-args 'org-cycle-hook 'overview)))))
6543 (defun org-cycle-internal-local ()
6544 "Do the local cycling action."
6545 (let (message-log-max ; Don't populate the *Messages* buffer
6546 (goal-column 0) eoh eol eos has-children children-skipped struct)
6547 ;; First, determine end of headline (EOH), end of subtree or item
6548 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6549 (save-excursion
6550 (if (org-at-item-p)
6551 (progn
6552 (beginning-of-line)
6553 (setq struct (org-list-struct))
6554 (setq eoh (point-at-eol))
6555 (setq eos (org-list-get-item-end-before-blank (point) struct))
6556 (setq has-children (org-list-has-child-p (point) struct)))
6557 (org-back-to-heading)
6558 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6559 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6560 (setq has-children
6561 (or (save-excursion
6562 (let ((level (funcall outline-level)))
6563 (outline-next-heading)
6564 (and (org-at-heading-p t)
6565 (> (funcall outline-level) level))))
6566 (save-excursion
6567 (org-list-search-forward (org-item-beginning-re) eos t)))))
6568 ;; Determine end invisible part of buffer (EOL)
6569 (beginning-of-line 2)
6570 ;; XEmacs doesn't have `next-single-char-property-change'
6571 (if (featurep 'xemacs)
6572 (while (and (not (eobp)) ;; this is like `next-line'
6573 (get-char-property (1- (point)) 'invisible))
6574 (beginning-of-line 2))
6575 (while (and (not (eobp)) ;; this is like `next-line'
6576 (get-char-property (1- (point)) 'invisible))
6577 (goto-char (next-single-char-property-change (point) 'invisible))
6578 (and (eolp) (beginning-of-line 2))))
6579 (setq eol (point)))
6580 ;; Find out what to do next and set `this-command'
6581 (cond
6582 ((= eos eoh)
6583 ;; Nothing is hidden behind this heading
6584 (unless (org-before-first-heading-p)
6585 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6586 (message "EMPTY ENTRY")
6587 (setq org-cycle-subtree-status nil)
6588 (save-excursion
6589 (goto-char eos)
6590 (outline-next-heading)
6591 (if (outline-invisible-p) (org-flag-heading nil))))
6592 ((and (or (>= eol eos)
6593 (not (string-match "\\S-" (buffer-substring eol eos))))
6594 (or has-children
6595 (not (setq children-skipped
6596 org-cycle-skip-children-state-if-no-children))))
6597 ;; Entire subtree is hidden in one line: children view
6598 (unless (org-before-first-heading-p)
6599 (run-hook-with-args 'org-pre-cycle-hook 'children))
6600 (if (org-at-item-p)
6601 (org-list-set-item-visibility (point-at-bol) struct 'children)
6602 (org-show-entry)
6603 (org-with-limited-levels (show-children))
6604 ;; FIXME: This slows down the func way too much.
6605 ;; How keep drawers hidden in subtree anyway?
6606 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6607 ;; (org-cycle-hide-drawers 'subtree))
6609 ;; Fold every list in subtree to top-level items.
6610 (when (eq org-cycle-include-plain-lists 'integrate)
6611 (save-excursion
6612 (org-back-to-heading)
6613 (while (org-list-search-forward (org-item-beginning-re) eos t)
6614 (beginning-of-line 1)
6615 (let* ((struct (org-list-struct))
6616 (prevs (org-list-prevs-alist struct))
6617 (end (org-list-get-bottom-point struct)))
6618 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6619 (org-list-get-all-items (point) struct prevs))
6620 (goto-char end))))))
6621 (message "CHILDREN")
6622 (save-excursion
6623 (goto-char eos)
6624 (outline-next-heading)
6625 (if (outline-invisible-p) (org-flag-heading nil)))
6626 (setq org-cycle-subtree-status 'children)
6627 (unless (org-before-first-heading-p)
6628 (run-hook-with-args 'org-cycle-hook 'children)))
6629 ((or children-skipped
6630 (and (eq last-command this-command)
6631 (eq org-cycle-subtree-status 'children)))
6632 ;; We just showed the children, or no children are there,
6633 ;; now show everything.
6634 (unless (org-before-first-heading-p)
6635 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6636 (outline-flag-region eoh eos nil)
6637 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6638 (setq org-cycle-subtree-status 'subtree)
6639 (unless (org-before-first-heading-p)
6640 (run-hook-with-args 'org-cycle-hook 'subtree)))
6642 ;; Default action: hide the subtree.
6643 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6644 (outline-flag-region eoh eos t)
6645 (message "FOLDED")
6646 (setq org-cycle-subtree-status 'folded)
6647 (unless (org-before-first-heading-p)
6648 (run-hook-with-args 'org-cycle-hook 'folded))))))
6650 ;;;###autoload
6651 (defun org-global-cycle (&optional arg)
6652 "Cycle the global visibility. For details see `org-cycle'.
6653 With \\[universal-argument] prefix arg, switch to startup visibility.
6654 With a numeric prefix, show all headlines up to that level."
6655 (interactive "P")
6656 (let ((org-cycle-include-plain-lists
6657 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6658 (cond
6659 ((integerp arg)
6660 (show-all)
6661 (hide-sublevels arg)
6662 (setq org-cycle-global-status 'contents))
6663 ((equal arg '(4))
6664 (org-set-startup-visibility)
6665 (message "Startup visibility, plus VISIBILITY properties."))
6667 (org-cycle '(4))))))
6669 (defun org-set-startup-visibility ()
6670 "Set the visibility required by startup options and properties."
6671 (cond
6672 ((eq org-startup-folded t)
6673 (org-cycle '(4)))
6674 ((eq org-startup-folded 'content)
6675 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6676 (org-cycle '(4)) (org-cycle '(4)))))
6677 (unless (eq org-startup-folded 'showeverything)
6678 (if org-hide-block-startup (org-hide-block-all))
6679 (org-set-visibility-according-to-property 'no-cleanup)
6680 (org-cycle-hide-archived-subtrees 'all)
6681 (org-cycle-hide-drawers 'all)
6682 (org-cycle-show-empty-lines t)))
6684 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6685 "Switch subtree visibilities according to :VISIBILITY: property."
6686 (interactive)
6687 (let (org-show-entry-below state)
6688 (save-excursion
6689 (goto-char (point-min))
6690 (while (re-search-forward
6691 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6692 nil t)
6693 (setq state (match-string 1))
6694 (save-excursion
6695 (org-back-to-heading t)
6696 (hide-subtree)
6697 (org-reveal)
6698 (cond
6699 ((equal state '("fold" "folded"))
6700 (hide-subtree))
6701 ((equal state "children")
6702 (org-show-hidden-entry)
6703 (show-children))
6704 ((equal state "content")
6705 (save-excursion
6706 (save-restriction
6707 (org-narrow-to-subtree)
6708 (org-content))))
6709 ((member state '("all" "showall"))
6710 (show-subtree)))))
6711 (unless no-cleanup
6712 (org-cycle-hide-archived-subtrees 'all)
6713 (org-cycle-hide-drawers 'all)
6714 (org-cycle-show-empty-lines 'all)))))
6716 ;; This function uses outline-regexp instead of the more fundamental
6717 ;; org-outline-regexp so that org-cycle-global works outside of Org
6718 ;; buffers, where outline-regexp is needed.
6719 (defun org-overview ()
6720 "Switch to overview mode, showing only top-level headlines.
6721 Really, this shows all headlines with level equal or greater than the level
6722 of the first headline in the buffer. This is important, because if the
6723 first headline is not level one, then (hide-sublevels 1) gives confusing
6724 results."
6725 (interactive)
6726 (let ((l (org-current-line))
6727 (level (save-excursion
6728 (goto-char (point-min))
6729 (if (re-search-forward (concat "^" outline-regexp) nil t)
6730 (progn
6731 (goto-char (match-beginning 0))
6732 (funcall outline-level))))))
6733 (and level (hide-sublevels level))
6734 (recenter '(4))
6735 (org-goto-line l)))
6737 (defun org-content (&optional arg)
6738 "Show all headlines in the buffer, like a table of contents.
6739 With numerical argument N, show content up to level N."
6740 (interactive "P")
6741 (save-excursion
6742 ;; Visit all headings and show their offspring
6743 (and (integerp arg) (org-overview))
6744 (goto-char (point-max))
6745 (catch 'exit
6746 (while (and (progn (condition-case nil
6747 (outline-previous-visible-heading 1)
6748 (error (goto-char (point-min))))
6750 (looking-at org-outline-regexp))
6751 (if (integerp arg)
6752 (show-children (1- arg))
6753 (show-branches))
6754 (if (bobp) (throw 'exit nil))))))
6757 (defun org-optimize-window-after-visibility-change (state)
6758 "Adjust the window after a change in outline visibility.
6759 This function is the default value of the hook `org-cycle-hook'."
6760 (when (get-buffer-window (current-buffer))
6761 (cond
6762 ((eq state 'content) nil)
6763 ((eq state 'all) nil)
6764 ((eq state 'folded) nil)
6765 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6766 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6768 (defun org-remove-empty-overlays-at (pos)
6769 "Remove outline overlays that do not contain non-white stuff."
6770 (mapc
6771 (lambda (o)
6772 (and (eq 'outline (overlay-get o 'invisible))
6773 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6774 (overlay-end o))))
6775 (delete-overlay o)))
6776 (overlays-at pos)))
6778 (defun org-clean-visibility-after-subtree-move ()
6779 "Fix visibility issues after moving a subtree."
6780 ;; First, find a reasonable region to look at:
6781 ;; Start two siblings above, end three below
6782 (let* ((beg (save-excursion
6783 (and (org-get-last-sibling)
6784 (org-get-last-sibling))
6785 (point)))
6786 (end (save-excursion
6787 (and (org-get-next-sibling)
6788 (org-get-next-sibling)
6789 (org-get-next-sibling))
6790 (if (org-at-heading-p)
6791 (point-at-eol)
6792 (point))))
6793 (level (looking-at "\\*+"))
6794 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6795 (save-excursion
6796 (save-restriction
6797 (narrow-to-region beg end)
6798 (when re
6799 ;; Properly fold already folded siblings
6800 (goto-char (point-min))
6801 (while (re-search-forward re nil t)
6802 (if (and (not (outline-invisible-p))
6803 (save-excursion
6804 (goto-char (point-at-eol)) (outline-invisible-p)))
6805 (hide-entry))))
6806 (org-cycle-show-empty-lines 'overview)
6807 (org-cycle-hide-drawers 'overview)))))
6809 (defun org-cycle-show-empty-lines (state)
6810 "Show empty lines above all visible headlines.
6811 The region to be covered depends on STATE when called through
6812 `org-cycle-hook'. Lisp program can use t for STATE to get the
6813 entire buffer covered. Note that an empty line is only shown if there
6814 are at least `org-cycle-separator-lines' empty lines before the headline."
6815 (when (not (= org-cycle-separator-lines 0))
6816 (save-excursion
6817 (let* ((n (abs org-cycle-separator-lines))
6818 (re (cond
6819 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6820 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6821 (t (let ((ns (number-to-string (- n 2))))
6822 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6823 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6824 beg end b e)
6825 (cond
6826 ((memq state '(overview contents t))
6827 (setq beg (point-min) end (point-max)))
6828 ((memq state '(children folded))
6829 (setq beg (point) end (progn (org-end-of-subtree t t)
6830 (beginning-of-line 2)
6831 (point)))))
6832 (when beg
6833 (goto-char beg)
6834 (while (re-search-forward re end t)
6835 (unless (get-char-property (match-end 1) 'invisible)
6836 (setq e (match-end 1))
6837 (if (< org-cycle-separator-lines 0)
6838 (setq b (save-excursion
6839 (goto-char (match-beginning 0))
6840 (org-back-over-empty-lines)
6841 (if (save-excursion
6842 (goto-char (max (point-min) (1- (point))))
6843 (org-at-heading-p))
6844 (1- (point))
6845 (point))))
6846 (setq b (match-beginning 1)))
6847 (outline-flag-region b e nil)))))))
6848 ;; Never hide empty lines at the end of the file.
6849 (save-excursion
6850 (goto-char (point-max))
6851 (outline-previous-heading)
6852 (outline-end-of-heading)
6853 (if (and (looking-at "[ \t\n]+")
6854 (= (match-end 0) (point-max)))
6855 (outline-flag-region (point) (match-end 0) nil))))
6857 (defun org-show-empty-lines-in-parent ()
6858 "Move to the parent and re-show empty lines before visible headlines."
6859 (save-excursion
6860 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6861 (org-cycle-show-empty-lines context))))
6863 (defun org-files-list ()
6864 "Return `org-agenda-files' list, plus all open org-mode files.
6865 This is useful for operations that need to scan all of a user's
6866 open and agenda-wise Org files."
6867 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6868 (dolist (buf (buffer-list))
6869 (with-current-buffer buf
6870 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6871 (let ((file (expand-file-name (buffer-file-name))))
6872 (unless (member file files)
6873 (push file files))))))
6874 files))
6876 (defsubst org-entry-beginning-position ()
6877 "Return the beginning position of the current entry."
6878 (save-excursion (outline-back-to-heading t) (point)))
6880 (defsubst org-entry-end-position ()
6881 "Return the end position of the current entry."
6882 (save-excursion (outline-next-heading) (point)))
6884 (defun org-cycle-hide-drawers (state)
6885 "Re-hide all drawers after a visibility state change."
6886 (when (and (derived-mode-p 'org-mode)
6887 (not (memq state '(overview folded contents))))
6888 (save-excursion
6889 (let* ((globalp (memq state '(contents all)))
6890 (beg (if globalp (point-min) (point)))
6891 (end (if globalp (point-max)
6892 (if (eq state 'children)
6893 (save-excursion (outline-next-heading) (point))
6894 (org-end-of-subtree t)))))
6895 (goto-char beg)
6896 (while (re-search-forward org-drawer-regexp end t)
6897 (org-flag-drawer t))))))
6899 (defun org-cycle-hide-inline-tasks (state)
6900 "Re-hide inline task when switching to 'contents visibility state."
6901 (when (and (eq state 'contents)
6902 (boundp 'org-inlinetask-min-level)
6903 org-inlinetask-min-level)
6904 (hide-sublevels (1- org-inlinetask-min-level))))
6906 (defun org-flag-drawer (flag)
6907 "When FLAG is non-nil, hide the drawer we are within.
6908 Otherwise make it visible."
6909 (save-excursion
6910 (beginning-of-line 1)
6911 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6912 (let ((b (match-end 0)))
6913 (if (re-search-forward
6914 "^[ \t]*:END:"
6915 (save-excursion (outline-next-heading) (point)) t)
6916 (outline-flag-region b (point-at-eol) flag)
6917 (error ":END: line missing at position %s" b))))))
6919 (defun org-subtree-end-visible-p ()
6920 "Is the end of the current subtree visible?"
6921 (pos-visible-in-window-p
6922 (save-excursion (org-end-of-subtree t) (point))))
6924 (defun org-first-headline-recenter (&optional N)
6925 "Move cursor to the first headline and recenter the headline.
6926 Optional argument N means put the headline into the Nth line of the window."
6927 (goto-char (point-min))
6928 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6929 (beginning-of-line)
6930 (recenter (prefix-numeric-value N))))
6932 ;;; Saving and restoring visibility
6934 (defun org-outline-overlay-data (&optional use-markers)
6935 "Return a list of the locations of all outline overlays.
6936 These are overlays with the `invisible' property value `outline'.
6937 The return value is a list of cons cells, with start and stop
6938 positions for each overlay.
6939 If USE-MARKERS is set, return the positions as markers."
6940 (let (beg end)
6941 (save-excursion
6942 (save-restriction
6943 (widen)
6944 (delq nil
6945 (mapcar (lambda (o)
6946 (when (eq (overlay-get o 'invisible) 'outline)
6947 (setq beg (overlay-start o)
6948 end (overlay-end o))
6949 (and beg end (> end beg)
6950 (if use-markers
6951 (cons (move-marker (make-marker) beg)
6952 (move-marker (make-marker) end))
6953 (cons beg end)))))
6954 (overlays-in (point-min) (point-max))))))))
6956 (defun org-set-outline-overlay-data (data)
6957 "Create visibility overlays for all positions in DATA.
6958 DATA should have been made by `org-outline-overlay-data'."
6959 (let (o)
6960 (save-excursion
6961 (save-restriction
6962 (widen)
6963 (show-all)
6964 (mapc (lambda (c)
6965 (outline-flag-region (car c) (cdr c) t))
6966 data)))))
6968 ;;; Folding of blocks
6970 (defvar org-hide-block-overlays nil
6971 "Overlays hiding blocks.")
6972 (make-variable-buffer-local 'org-hide-block-overlays)
6974 (defun org-block-map (function &optional start end)
6975 "Call FUNCTION at the head of all source blocks in the current buffer.
6976 Optional arguments START and END can be used to limit the range."
6977 (let ((start (or start (point-min)))
6978 (end (or end (point-max))))
6979 (save-excursion
6980 (goto-char start)
6981 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6982 (save-excursion
6983 (save-match-data
6984 (goto-char (match-beginning 0))
6985 (funcall function)))))))
6987 (defun org-hide-block-toggle-all ()
6988 "Toggle the visibility of all blocks in the current buffer."
6989 (org-block-map #'org-hide-block-toggle))
6991 (defun org-hide-block-all ()
6992 "Fold all blocks in the current buffer."
6993 (interactive)
6994 (org-show-block-all)
6995 (org-block-map #'org-hide-block-toggle-maybe))
6997 (defun org-show-block-all ()
6998 "Unfold all blocks in the current buffer."
6999 (interactive)
7000 (mapc 'delete-overlay org-hide-block-overlays)
7001 (setq org-hide-block-overlays nil))
7003 (defun org-hide-block-toggle-maybe ()
7004 "Toggle visibility of block at point."
7005 (interactive)
7006 (let ((case-fold-search t))
7007 (if (save-excursion
7008 (beginning-of-line 1)
7009 (looking-at org-block-regexp))
7010 (progn (org-hide-block-toggle)
7011 t) ;; to signal that we took action
7012 nil))) ;; to signal that we did not
7014 (defun org-hide-block-toggle (&optional force)
7015 "Toggle the visibility of the current block."
7016 (interactive)
7017 (save-excursion
7018 (beginning-of-line)
7019 (if (re-search-forward org-block-regexp nil t)
7020 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7021 (end (match-end 0)) ;; end of entire body
7023 (if (memq t (mapcar (lambda (overlay)
7024 (eq (overlay-get overlay 'invisible)
7025 'org-hide-block))
7026 (overlays-at start)))
7027 (if (or (not force) (eq force 'off))
7028 (mapc (lambda (ov)
7029 (when (member ov org-hide-block-overlays)
7030 (setq org-hide-block-overlays
7031 (delq ov org-hide-block-overlays)))
7032 (when (eq (overlay-get ov 'invisible)
7033 'org-hide-block)
7034 (delete-overlay ov)))
7035 (overlays-at start)))
7036 (setq ov (make-overlay start end))
7037 (overlay-put ov 'invisible 'org-hide-block)
7038 ;; make the block accessible to isearch
7039 (overlay-put
7040 ov 'isearch-open-invisible
7041 (lambda (ov)
7042 (when (member ov org-hide-block-overlays)
7043 (setq org-hide-block-overlays
7044 (delq ov org-hide-block-overlays)))
7045 (when (eq (overlay-get ov 'invisible)
7046 'org-hide-block)
7047 (delete-overlay ov))))
7048 (push ov org-hide-block-overlays)))
7049 (error "Not looking at a source block"))))
7051 ;; org-tab-after-check-for-cycling-hook
7052 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7053 ;; Remove overlays when changing major mode
7054 (add-hook 'org-mode-hook
7055 (lambda () (org-add-hook 'change-major-mode-hook
7056 'org-show-block-all 'append 'local)))
7058 ;;; Org-goto
7060 (defvar org-goto-window-configuration nil)
7061 (defvar org-goto-marker nil)
7062 (defvar org-goto-map)
7063 (defun org-goto-map ()
7064 "Set the keymap `org-goto'."
7065 (setq org-goto-map
7066 (let ((map (make-sparse-keymap)))
7067 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7068 mouse-drag-region universal-argument org-occur))
7069 cmd)
7070 (while (setq cmd (pop cmds))
7071 (substitute-key-definition cmd cmd map global-map)))
7072 (suppress-keymap map)
7073 (org-defkey map "\C-m" 'org-goto-ret)
7074 (org-defkey map [(return)] 'org-goto-ret)
7075 (org-defkey map [(left)] 'org-goto-left)
7076 (org-defkey map [(right)] 'org-goto-right)
7077 (org-defkey map [(control ?g)] 'org-goto-quit)
7078 (org-defkey map "\C-i" 'org-cycle)
7079 (org-defkey map [(tab)] 'org-cycle)
7080 (org-defkey map [(down)] 'outline-next-visible-heading)
7081 (org-defkey map [(up)] 'outline-previous-visible-heading)
7082 (if org-goto-auto-isearch
7083 (if (fboundp 'define-key-after)
7084 (define-key-after map [t] 'org-goto-local-auto-isearch)
7085 nil)
7086 (org-defkey map "q" 'org-goto-quit)
7087 (org-defkey map "n" 'outline-next-visible-heading)
7088 (org-defkey map "p" 'outline-previous-visible-heading)
7089 (org-defkey map "f" 'outline-forward-same-level)
7090 (org-defkey map "b" 'outline-backward-same-level)
7091 (org-defkey map "u" 'outline-up-heading))
7092 (org-defkey map "/" 'org-occur)
7093 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7094 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7095 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7096 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7097 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7098 map)))
7100 (defconst org-goto-help
7101 "Browse buffer copy, to find location or copy text.%s
7102 RET=jump to location C-g=quit and return to previous location
7103 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7105 (defvar org-goto-start-pos) ; dynamically scoped parameter
7107 ;; FIXME: Docstring does not mention both interfaces
7108 (defun org-goto (&optional alternative-interface)
7109 "Look up a different location in the current file, keeping current visibility.
7111 When you want look-up or go to a different location in a
7112 document, the fastest way is often to fold the entire buffer and
7113 then dive into the tree. This method has the disadvantage, that
7114 the previous location will be folded, which may not be what you
7115 want.
7117 This command works around this by showing a copy of the current
7118 buffer in an indirect buffer, in overview mode. You can dive
7119 into the tree in that copy, use org-occur and incremental search
7120 to find a location. When pressing RET or `Q', the command
7121 returns to the original buffer in which the visibility is still
7122 unchanged. After RET it will also jump to the location selected
7123 in the indirect buffer and expose the headline hierarchy above.
7125 With a prefix argument, use the alternative interface: e.g. if
7126 `org-goto-interface' is 'outline use 'outline-path-completion."
7127 (interactive "P")
7128 (org-goto-map)
7129 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7130 (org-refile-use-outline-path t)
7131 (org-refile-target-verify-function nil)
7132 (interface
7133 (if (not alternative-interface)
7134 org-goto-interface
7135 (if (eq org-goto-interface 'outline)
7136 'outline-path-completion
7137 'outline)))
7138 (org-goto-start-pos (point))
7139 (selected-point
7140 (if (eq interface 'outline)
7141 (car (org-get-location (current-buffer) org-goto-help))
7142 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7143 (org-refile-check-position pa)
7144 (nth 3 pa)))))
7145 (if selected-point
7146 (progn
7147 (org-mark-ring-push org-goto-start-pos)
7148 (goto-char selected-point)
7149 (if (or (outline-invisible-p) (org-invisible-p2))
7150 (org-show-context 'org-goto)))
7151 (message "Quit"))))
7153 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7154 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7155 (defvar org-goto-local-auto-isearch-map) ; defined below
7157 (defun org-get-location (buf help)
7158 "Let the user select a location in the Org-mode buffer BUF.
7159 This function uses a recursive edit. It returns the selected position
7160 or nil."
7161 (org-no-popups
7162 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7163 (isearch-hide-immediately nil)
7164 (isearch-search-fun-function
7165 (lambda () 'org-goto-local-search-headings))
7166 (org-goto-selected-point org-goto-exit-command))
7167 (save-excursion
7168 (save-window-excursion
7169 (delete-other-windows)
7170 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7171 (org-pop-to-buffer-same-window
7172 (condition-case nil
7173 (make-indirect-buffer (current-buffer) "*org-goto*")
7174 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7175 (with-output-to-temp-buffer "*Org Help*"
7176 (princ (format help (if org-goto-auto-isearch
7177 " Just type for auto-isearch."
7178 " n/p/f/b/u to navigate, q to quit."))))
7179 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7180 (setq buffer-read-only nil)
7181 (let ((org-startup-truncated t)
7182 (org-startup-folded nil)
7183 (org-startup-align-all-tables nil))
7184 (org-mode)
7185 (org-overview))
7186 (setq buffer-read-only t)
7187 (if (and (boundp 'org-goto-start-pos)
7188 (integer-or-marker-p org-goto-start-pos))
7189 (let ((org-show-hierarchy-above t)
7190 (org-show-siblings t)
7191 (org-show-following-heading t))
7192 (goto-char org-goto-start-pos)
7193 (and (outline-invisible-p) (org-show-context)))
7194 (goto-char (point-min)))
7195 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7196 (message "Select location and press RET")
7197 (use-local-map org-goto-map)
7198 (recursive-edit)))
7199 (kill-buffer "*org-goto*")
7200 (cons org-goto-selected-point org-goto-exit-command))))
7202 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7203 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7204 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7205 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7207 (defun org-goto-local-search-headings (string bound noerror)
7208 "Search and make sure that any matches are in headlines."
7209 (catch 'return
7210 (while (if isearch-forward
7211 (search-forward string bound noerror)
7212 (search-backward string bound noerror))
7213 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7214 (and (member :headline context)
7215 (not (member :tags context))))
7216 (throw 'return (point))))))
7218 (defun org-goto-local-auto-isearch ()
7219 "Start isearch."
7220 (interactive)
7221 (goto-char (point-min))
7222 (let ((keys (this-command-keys)))
7223 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7224 (isearch-mode t)
7225 (isearch-process-search-char (string-to-char keys)))))
7227 (defun org-goto-ret (&optional arg)
7228 "Finish `org-goto' by going to the new location."
7229 (interactive "P")
7230 (setq org-goto-selected-point (point)
7231 org-goto-exit-command 'return)
7232 (throw 'exit nil))
7234 (defun org-goto-left ()
7235 "Finish `org-goto' by going to the new location."
7236 (interactive)
7237 (if (org-at-heading-p)
7238 (progn
7239 (beginning-of-line 1)
7240 (setq org-goto-selected-point (point)
7241 org-goto-exit-command 'left)
7242 (throw 'exit nil))
7243 (error "Not on a heading")))
7245 (defun org-goto-right ()
7246 "Finish `org-goto' by going to the new location."
7247 (interactive)
7248 (if (org-at-heading-p)
7249 (progn
7250 (setq org-goto-selected-point (point)
7251 org-goto-exit-command 'right)
7252 (throw 'exit nil))
7253 (error "Not on a heading")))
7255 (defun org-goto-quit ()
7256 "Finish `org-goto' without cursor motion."
7257 (interactive)
7258 (setq org-goto-selected-point nil)
7259 (setq org-goto-exit-command 'quit)
7260 (throw 'exit nil))
7262 ;;; Indirect buffer display of subtrees
7264 (defvar org-indirect-dedicated-frame nil
7265 "This is the frame being used for indirect tree display.")
7266 (defvar org-last-indirect-buffer nil)
7268 (defun org-tree-to-indirect-buffer (&optional arg)
7269 "Create indirect buffer and narrow it to current subtree.
7270 With a numerical prefix ARG, go up to this level and then take that tree.
7271 If ARG is negative, go up that many levels.
7273 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7274 indirect buffer previously made with this command, to avoid proliferation of
7275 indirect buffers. However, when you call the command with a \
7276 \\[universal-argument] prefix, or
7277 when `org-indirect-buffer-display' is `new-frame', the last buffer
7278 is kept so that you can work with several indirect buffers at the same time.
7279 If `org-indirect-buffer-display' is `dedicated-frame', the \
7280 \\[universal-argument] prefix also
7281 requests that a new frame be made for the new buffer, so that the dedicated
7282 frame is not changed."
7283 (interactive "P")
7284 (let ((cbuf (current-buffer))
7285 (cwin (selected-window))
7286 (pos (point))
7287 beg end level heading ibuf)
7288 (save-excursion
7289 (org-back-to-heading t)
7290 (when (numberp arg)
7291 (setq level (org-outline-level))
7292 (if (< arg 0) (setq arg (+ level arg)))
7293 (while (> (setq level (org-outline-level)) arg)
7294 (org-up-heading-safe)))
7295 (setq beg (point)
7296 heading (org-get-heading))
7297 (org-end-of-subtree t t)
7298 (if (org-at-heading-p) (backward-char 1))
7299 (setq end (point)))
7300 (if (and (buffer-live-p org-last-indirect-buffer)
7301 (not (eq org-indirect-buffer-display 'new-frame))
7302 (not arg))
7303 (kill-buffer org-last-indirect-buffer))
7304 (setq ibuf (org-get-indirect-buffer cbuf)
7305 org-last-indirect-buffer ibuf)
7306 (cond
7307 ((or (eq org-indirect-buffer-display 'new-frame)
7308 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7309 (select-frame (make-frame))
7310 (delete-other-windows)
7311 (org-pop-to-buffer-same-window ibuf)
7312 (org-set-frame-title heading))
7313 ((eq org-indirect-buffer-display 'dedicated-frame)
7314 (raise-frame
7315 (select-frame (or (and org-indirect-dedicated-frame
7316 (frame-live-p org-indirect-dedicated-frame)
7317 org-indirect-dedicated-frame)
7318 (setq org-indirect-dedicated-frame (make-frame)))))
7319 (delete-other-windows)
7320 (org-pop-to-buffer-same-window ibuf)
7321 (org-set-frame-title (concat "Indirect: " heading)))
7322 ((eq org-indirect-buffer-display 'current-window)
7323 (org-pop-to-buffer-same-window ibuf))
7324 ((eq org-indirect-buffer-display 'other-window)
7325 (pop-to-buffer ibuf))
7326 (t (error "Invalid value")))
7327 (if (featurep 'xemacs)
7328 (save-excursion (org-mode) (turn-on-font-lock)))
7329 (narrow-to-region beg end)
7330 (show-all)
7331 (goto-char pos)
7332 (run-hook-with-args 'org-cycle-hook 'all)
7333 (and (window-live-p cwin) (select-window cwin))))
7335 (defun org-get-indirect-buffer (&optional buffer)
7336 (setq buffer (or buffer (current-buffer)))
7337 (let ((n 1) (base (buffer-name buffer)) bname)
7338 (while (buffer-live-p
7339 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7340 (setq n (1+ n)))
7341 (condition-case nil
7342 (make-indirect-buffer buffer bname 'clone)
7343 (error (make-indirect-buffer buffer bname)))))
7345 (defun org-set-frame-title (title)
7346 "Set the title of the current frame to the string TITLE."
7347 ;; FIXME: how to name a single frame in XEmacs???
7348 (unless (featurep 'xemacs)
7349 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7351 ;;;; Structure editing
7353 ;;; Inserting headlines
7355 (defun org-previous-line-empty-p (&optional next)
7356 "Is the previous line a blank line?
7357 When NEXT is non-nil, check the next line instead."
7358 (save-excursion
7359 (and (not (bobp))
7360 (or (beginning-of-line (if next 2 0)) t)
7361 (save-match-data
7362 (looking-at "[ \t]*$")))))
7364 (defun org-insert-heading (&optional arg invisible-ok)
7365 "Insert a new heading or item with same depth at point.
7366 If point is in a plain list and ARG is nil, create a new list item.
7367 With one universal prefix argument, insert a heading even in lists.
7368 With two universal prefix arguments, insert the heading at the end
7369 of the parent subtree.
7371 If point is at the beginning of a headline, insert a sibling before
7372 the current headline. If point is not at the beginning, split the line
7373 and create a new headline with the text in the current line after point
7374 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7376 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7377 This is important for non-interactive uses of the command."
7378 (interactive "P")
7379 (if (or (= (buffer-size) 0)
7380 (and (not (save-excursion
7381 (and (ignore-errors (org-back-to-heading invisible-ok))
7382 (org-at-heading-p))))
7383 (or arg (not (org-in-item-p)))))
7384 (progn
7385 (insert
7386 (if (org-previous-line-empty-p) "" "\n")
7387 (if (org-in-src-block-p) ",* " "* "))
7388 (run-hooks 'org-insert-heading-hook))
7389 (when (or arg
7390 (not (org-insert-item
7391 (save-excursion
7392 (beginning-of-line)
7393 (looking-at org-list-full-item-re)
7394 (match-string 3)))))
7395 (let* ((empty-line-p nil)
7396 (eops (equal arg '(16))) ; insert at end of parent subtree
7397 (org-insert-heading-respect-content
7398 (or (not (null arg)) org-insert-heading-respect-content))
7399 (level nil)
7400 (on-heading (org-at-heading-p))
7401 (head (save-excursion
7402 (condition-case nil
7403 (progn
7404 (org-back-to-heading invisible-ok)
7405 (when (and (not on-heading)
7406 (featurep 'org-inlinetask)
7407 (integerp org-inlinetask-min-level)
7408 (>= (length (match-string 0))
7409 org-inlinetask-min-level))
7410 ;; Find a heading level before the inline task
7411 (while (and (setq level (org-up-heading-safe))
7412 (>= level org-inlinetask-min-level)))
7413 (if (org-at-heading-p)
7414 (org-back-to-heading invisible-ok)
7415 (error "This should not happen")))
7416 (unless (and (save-excursion
7417 (save-match-data
7418 (org-backward-heading-same-level 1 invisible-ok))
7419 (= (point) (match-beginning 0)))
7420 (not (org-previous-line-empty-p t)))
7421 (setq empty-line-p (org-previous-line-empty-p)))
7422 (match-string 0))
7423 (error "* "))))
7424 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7425 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7426 pos hide-previous previous-pos)
7427 (cond
7428 ;; At the beginning of a heading, open a new line for insertiong
7429 ((and (bolp) (org-at-heading-p)
7430 (not eops)
7431 (or (bobp)
7432 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7433 (open-line (if blank 2 1)))
7435 (save-excursion
7436 (setq previous-pos (point-at-bol))
7437 (end-of-line)
7438 (setq hide-previous (outline-invisible-p)))
7439 (and org-insert-heading-respect-content
7440 (save-excursion
7441 (while (outline-invisible-p)
7442 (org-show-subtree)
7443 (org-up-heading-safe))))
7444 (let ((split
7445 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7446 (save-excursion
7447 (let ((p (point)))
7448 (goto-char (point-at-bol))
7449 (and (looking-at org-complex-heading-regexp)
7450 (match-beginning 4)
7451 (> p (match-beginning 4)))))))
7452 tags pos)
7453 (cond
7454 ;; Insert a new line, possibly at end of parent subtree
7455 (org-insert-heading-respect-content
7456 (if (not eops)
7457 (progn
7458 (org-end-of-subtree nil t)
7459 (and (looking-at "^\\*") (backward-char 1))
7460 (while (and (not (bobp))
7461 ;; Don't delete spaces in empty headlines
7462 (not (looking-back org-outline-regexp))
7463 (member (char-before) '(?\ ?\t ?\n)))
7464 (backward-delete-char 1)))
7465 (let ((p (point)))
7466 (org-up-heading-safe)
7467 (if (= p (point))
7468 (goto-char (point-max))
7469 (org-end-of-subtree nil t))))
7470 (when (featurep 'org-inlinetask)
7471 (while (and (not (eobp))
7472 (looking-at "\\(\\*+\\)[ \t]+")
7473 (>= (length (match-string 1))
7474 org-inlinetask-min-level))
7475 (org-end-of-subtree nil t)))
7476 (or (bolp) (newline))
7477 (or (org-previous-line-empty-p)
7478 (and blank (newline)))
7479 (if (or empty-line-p eops) (open-line 1)))
7480 ;; Insert a headling containing text after point
7481 ((org-at-heading-p)
7482 (when hide-previous
7483 (show-children)
7484 (org-show-entry))
7485 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7486 (setq tags (and (match-end 2) (match-string 2)))
7487 (and (match-end 1)
7488 (delete-region (match-beginning 1) (match-end 1)))
7489 (setq pos (point-at-bol))
7490 (or split (end-of-line 1))
7491 (delete-horizontal-space)
7492 (if (string-match "\\`\\*+\\'"
7493 (buffer-substring (point-at-bol) (point)))
7494 (insert " "))
7495 (newline (if blank 2 1))
7496 (when tags
7497 (save-excursion
7498 (goto-char pos)
7499 (end-of-line 1)
7500 (insert " " tags)
7501 (org-set-tags nil 'align))))
7503 (or split (end-of-line 1))
7504 (newline (if blank 2 1)))))))
7505 (insert head) (just-one-space)
7506 (setq pos (point))
7507 (end-of-line 1)
7508 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7509 (when (and org-insert-heading-respect-content hide-previous)
7510 (save-excursion
7511 (goto-char previous-pos)
7512 (hide-subtree)))
7513 (run-hooks 'org-insert-heading-hook)))))
7515 (defun org-get-heading (&optional no-tags no-todo)
7516 "Return the heading of the current entry, without the stars.
7517 When NO-TAGS is non-nil, don't include tags.
7518 When NO-TODO is non-nil, don't include TODO keywords."
7519 (save-excursion
7520 (org-back-to-heading t)
7521 (cond
7522 ((and no-tags no-todo)
7523 (looking-at org-complex-heading-regexp)
7524 (match-string 4))
7525 (no-tags
7526 (looking-at (concat org-outline-regexp
7527 "\\(.*?\\)"
7528 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7529 (match-string 1))
7530 (no-todo
7531 (looking-at org-todo-line-regexp)
7532 (match-string 3))
7533 (t (looking-at org-heading-regexp)
7534 (match-string 2)))))
7536 (defvar orgstruct-mode) ; defined below
7538 (defun org-heading-components ()
7539 "Return the components of the current heading.
7540 This is a list with the following elements:
7541 - the level as an integer
7542 - the reduced level, different if `org-odd-levels-only' is set.
7543 - the TODO keyword, or nil
7544 - the priority character, like ?A, or nil if no priority is given
7545 - the headline text itself, or the tags string if no headline text
7546 - the tags string, or nil."
7547 (save-excursion
7548 (org-back-to-heading t)
7549 (if (let (case-fold-search)
7550 (looking-at
7551 (if orgstruct-mode
7552 org-heading-regexp
7553 org-complex-heading-regexp)))
7554 (if orgstruct-mode
7555 (list (length (match-string 1))
7556 (org-reduced-level (length (match-string 1)))
7559 (match-string 2)
7560 nil)
7561 (list (length (match-string 1))
7562 (org-reduced-level (length (match-string 1)))
7563 (org-match-string-no-properties 2)
7564 (and (match-end 3) (aref (match-string 3) 2))
7565 (org-match-string-no-properties 4)
7566 (org-match-string-no-properties 5))))))
7568 (defun org-get-entry ()
7569 "Get the entry text, after heading, entire subtree."
7570 (save-excursion
7571 (org-back-to-heading t)
7572 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7574 (defun org-insert-heading-after-current ()
7575 "Insert a new heading with same level as current, after current subtree."
7576 (interactive)
7577 (org-back-to-heading)
7578 (org-insert-heading)
7579 (org-move-subtree-down)
7580 (end-of-line 1))
7582 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7583 "Insert heading with `org-insert-heading-respect-content' set to t."
7584 (interactive "P")
7585 (let ((org-insert-heading-respect-content t))
7586 (org-insert-heading arg invisible-ok)))
7588 (defun org-insert-todo-heading-respect-content (&optional force-state)
7589 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7590 (interactive "P")
7591 (let ((org-insert-heading-respect-content t))
7592 (org-insert-todo-heading force-state t)))
7594 (defun org-insert-todo-heading (arg &optional force-heading)
7595 "Insert a new heading with the same level and TODO state as current heading.
7596 If the heading has no TODO state, or if the state is DONE, use the first
7597 state (TODO by default). Also one prefix arg, force first state. With two
7598 prefix args, force inserting at the end of the parent subtree."
7599 (interactive "P")
7600 (when (or force-heading (not (org-insert-item 'checkbox)))
7601 (org-insert-heading (or (and (equal arg '(16)) '(16))
7602 force-heading))
7603 (save-excursion
7604 (org-back-to-heading)
7605 (outline-previous-heading)
7606 (looking-at org-todo-line-regexp))
7607 (let*
7608 ((new-mark-x
7609 (if (or arg
7610 (not (match-beginning 2))
7611 (member (match-string 2) org-done-keywords))
7612 (car org-todo-keywords-1)
7613 (match-string 2)))
7614 (new-mark
7616 (run-hook-with-args-until-success
7617 'org-todo-get-default-hook new-mark-x nil)
7618 new-mark-x)))
7619 (beginning-of-line 1)
7620 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7621 (if org-treat-insert-todo-heading-as-state-change
7622 (org-todo new-mark)
7623 (insert new-mark " "))))
7624 (when org-provide-todo-statistics
7625 (org-update-parent-todo-statistics))))
7627 (defun org-insert-subheading (arg)
7628 "Insert a new subheading and demote it.
7629 Works for outline headings and for plain lists alike."
7630 (interactive "P")
7631 (org-insert-heading arg)
7632 (cond
7633 ((org-at-heading-p) (org-do-demote))
7634 ((org-at-item-p) (org-indent-item))))
7636 (defun org-insert-todo-subheading (arg)
7637 "Insert a new subheading with TODO keyword or checkbox and demote it.
7638 Works for outline headings and for plain lists alike."
7639 (interactive "P")
7640 (org-insert-todo-heading arg)
7641 (cond
7642 ((org-at-heading-p) (org-do-demote))
7643 ((org-at-item-p) (org-indent-item))))
7645 ;;; Promotion and Demotion
7647 (defvar org-after-demote-entry-hook nil
7648 "Hook run after an entry has been demoted.
7649 The cursor will be at the beginning of the entry.
7650 When a subtree is being demoted, the hook will be called for each node.")
7652 (defvar org-after-promote-entry-hook nil
7653 "Hook run after an entry has been promoted.
7654 The cursor will be at the beginning of the entry.
7655 When a subtree is being promoted, the hook will be called for each node.")
7657 (defun org-promote-subtree ()
7658 "Promote the entire subtree.
7659 See also `org-promote'."
7660 (interactive)
7661 (save-excursion
7662 (org-with-limited-levels (org-map-tree 'org-promote)))
7663 (org-fix-position-after-promote))
7665 (defun org-demote-subtree ()
7666 "Demote the entire subtree. See `org-demote'.
7667 See also `org-promote'."
7668 (interactive)
7669 (save-excursion
7670 (org-with-limited-levels (org-map-tree 'org-demote)))
7671 (org-fix-position-after-promote))
7674 (defun org-do-promote ()
7675 "Promote the current heading higher up the tree.
7676 If the region is active in `transient-mark-mode', promote all headings
7677 in the region."
7678 (interactive)
7679 (save-excursion
7680 (if (org-region-active-p)
7681 (org-map-region 'org-promote (region-beginning) (region-end))
7682 (org-promote)))
7683 (org-fix-position-after-promote))
7685 (defun org-do-demote ()
7686 "Demote the current heading lower down the tree.
7687 If the region is active in `transient-mark-mode', demote all headings
7688 in the region."
7689 (interactive)
7690 (save-excursion
7691 (if (org-region-active-p)
7692 (org-map-region 'org-demote (region-beginning) (region-end))
7693 (org-demote)))
7694 (org-fix-position-after-promote))
7696 (defun org-fix-position-after-promote ()
7697 "Make sure that after pro/demotion cursor position is right."
7698 (let ((pos (point)))
7699 (when (save-excursion
7700 (beginning-of-line 1)
7701 (looking-at org-todo-line-regexp)
7702 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7703 (cond ((eobp) (insert " "))
7704 ((eolp) (insert " "))
7705 ((equal (char-after) ?\ ) (forward-char 1))))))
7707 (defun org-current-level ()
7708 "Return the level of the current entry, or nil if before the first headline.
7709 The level is the number of stars at the beginning of the headline."
7710 (save-excursion
7711 (org-with-limited-levels
7712 (if (ignore-errors (org-back-to-heading t))
7713 (funcall outline-level)))))
7715 (defun org-get-previous-line-level ()
7716 "Return the outline depth of the last headline before the current line.
7717 Returns 0 for the first headline in the buffer, and nil if before the
7718 first headline."
7719 (let ((current-level (org-current-level))
7720 (prev-level (when (> (line-number-at-pos) 1)
7721 (save-excursion
7722 (beginning-of-line 0)
7723 (org-current-level)))))
7724 (cond ((null current-level) nil) ; Before first headline
7725 ((null prev-level) 0) ; At first headline
7726 (prev-level))))
7728 (defun org-reduced-level (l)
7729 "Compute the effective level of a heading.
7730 This takes into account the setting of `org-odd-levels-only'."
7731 (cond
7732 ((zerop l) 0)
7733 (org-odd-levels-only (1+ (floor (/ l 2))))
7734 (t l)))
7736 (defun org-level-increment ()
7737 "Return the number of stars that will be added or removed at a
7738 time to headlines when structure editing, based on the value of
7739 `org-odd-levels-only'."
7740 (if org-odd-levels-only 2 1))
7742 (defun org-get-valid-level (level &optional change)
7743 "Rectify a level change under the influence of `org-odd-levels-only'
7744 LEVEL is a current level, CHANGE is by how much the level should be
7745 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7746 even level numbers will become the next higher odd number."
7747 (if org-odd-levels-only
7748 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7749 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7750 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7751 (max 1 (+ level (or change 0)))))
7753 (if (boundp 'define-obsolete-function-alias)
7754 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7755 (define-obsolete-function-alias 'org-get-legal-level
7756 'org-get-valid-level)
7757 (define-obsolete-function-alias 'org-get-legal-level
7758 'org-get-valid-level "23.1")))
7760 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7761 ;; ̀org-with-limited-levels'
7762 (defun org-promote ()
7763 "Promote the current heading higher up the tree.
7764 If the region is active in `transient-mark-mode', promote all headings
7765 in the region."
7766 (org-back-to-heading t)
7767 (let* ((level (save-match-data (funcall outline-level)))
7768 (after-change-functions (remove 'flyspell-after-change-function
7769 after-change-functions))
7770 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7771 (diff (abs (- level (length up-head) -1))))
7772 (cond ((and (= level 1) org-called-with-limited-levels
7773 org-allow-promoting-top-level-subtree)
7774 (replace-match "# " nil t))
7775 ((= level 1)
7776 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7777 (t (replace-match up-head nil t)))
7778 ;; Fixup tag positioning
7779 (unless (= level 1)
7780 (and org-auto-align-tags (org-set-tags nil t))
7781 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7782 (run-hooks 'org-after-promote-entry-hook)))
7784 (defun org-demote ()
7785 "Demote the current heading lower down the tree.
7786 If the region is active in `transient-mark-mode', demote all headings
7787 in the region."
7788 (org-back-to-heading t)
7789 (let* ((level (save-match-data (funcall outline-level)))
7790 (after-change-functions (remove 'flyspell-after-change-function
7791 after-change-functions))
7792 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7793 (diff (abs (- level (length down-head) -1))))
7794 (replace-match down-head nil t)
7795 ;; Fixup tag positioning
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-demote-entry-hook)))
7800 (defun org-cycle-level ()
7801 "Cycle the level of an empty headline through possible states.
7802 This goes first to child, then to parent, level, then up the hierarchy.
7803 After top level, it switches back to sibling level."
7804 (interactive)
7805 (let ((org-adapt-indentation nil))
7806 (when (org-point-at-end-of-empty-headline)
7807 (setq this-command 'org-cycle-level) ; Only needed for caching
7808 (let ((cur-level (org-current-level))
7809 (prev-level (org-get-previous-line-level)))
7810 (cond
7811 ;; If first headline in file, promote to top-level.
7812 ((= prev-level 0)
7813 (loop repeat (/ (- cur-level 1) (org-level-increment))
7814 do (org-do-promote)))
7815 ;; If same level as prev, demote one.
7816 ((= prev-level cur-level)
7817 (org-do-demote))
7818 ;; If parent is top-level, promote to top level if not already.
7819 ((= prev-level 1)
7820 (loop repeat (/ (- cur-level 1) (org-level-increment))
7821 do (org-do-promote)))
7822 ;; If top-level, return to prev-level.
7823 ((= cur-level 1)
7824 (loop repeat (/ (- prev-level 1) (org-level-increment))
7825 do (org-do-demote)))
7826 ;; If less than prev-level, promote one.
7827 ((< cur-level prev-level)
7828 (org-do-promote))
7829 ;; If deeper than prev-level, promote until higher than
7830 ;; prev-level.
7831 ((> cur-level prev-level)
7832 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7833 do (org-do-promote))))
7834 t))))
7836 (defun org-map-tree (fun)
7837 "Call FUN for every heading underneath the current one."
7838 (org-back-to-heading)
7839 (let ((level (funcall outline-level)))
7840 (save-excursion
7841 (funcall fun)
7842 (while (and (progn
7843 (outline-next-heading)
7844 (> (funcall outline-level) level))
7845 (not (eobp)))
7846 (funcall fun)))))
7848 (defun org-map-region (fun beg end)
7849 "Call FUN for every heading between BEG and END."
7850 (let ((org-ignore-region t))
7851 (save-excursion
7852 (setq end (copy-marker end))
7853 (goto-char beg)
7854 (if (and (re-search-forward org-outline-regexp-bol nil t)
7855 (< (point) end))
7856 (funcall fun))
7857 (while (and (progn
7858 (outline-next-heading)
7859 (< (point) end))
7860 (not (eobp)))
7861 (funcall fun)))))
7863 (defvar org-property-end-re) ; silence byte-compiler
7864 (defun org-fixup-indentation (diff)
7865 "Change the indentation in the current entry by DIFF.
7866 However, if any line in the current entry has no indentation, or if it
7867 would end up with no indentation after the change, nothing at all is done."
7868 (save-excursion
7869 (let ((end (save-excursion (outline-next-heading)
7870 (point-marker)))
7871 (prohibit (if (> diff 0)
7872 "^\\S-"
7873 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7874 col)
7875 (unless (save-excursion (end-of-line 1)
7876 (re-search-forward prohibit end t))
7877 (while (and (< (point) end)
7878 (re-search-forward "^[ \t]+" end t))
7879 (goto-char (match-end 0))
7880 (setq col (current-column))
7881 (if (< diff 0) (replace-match ""))
7882 (org-indent-to-column (+ diff col))))
7883 (move-marker end nil))))
7885 (defun org-convert-to-odd-levels ()
7886 "Convert an org-mode file with all levels allowed to one with odd levels.
7887 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7888 level 5 etc."
7889 (interactive)
7890 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7891 (let ((outline-level 'org-outline-level)
7892 (org-odd-levels-only nil) n)
7893 (save-excursion
7894 (goto-char (point-min))
7895 (while (re-search-forward "^\\*\\*+ " nil t)
7896 (setq n (- (length (match-string 0)) 2))
7897 (while (>= (setq n (1- n)) 0)
7898 (org-demote))
7899 (end-of-line 1))))))
7901 (defun org-convert-to-oddeven-levels ()
7902 "Convert an org-mode file with only odd levels to one with odd/even levels.
7903 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7904 file contains a section with an even level, conversion would
7905 destroy the structure of the file. An error is signaled in this
7906 case."
7907 (interactive)
7908 (goto-char (point-min))
7909 ;; First check if there are no even levels
7910 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7911 (org-show-context t)
7912 (error "Not all levels are odd in this file. Conversion not possible"))
7913 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7914 (let ((outline-regexp org-outline-regexp)
7915 (outline-level 'org-outline-level)
7916 (org-odd-levels-only nil) n)
7917 (save-excursion
7918 (goto-char (point-min))
7919 (while (re-search-forward "^\\*\\*+ " nil t)
7920 (setq n (/ (1- (length (match-string 0))) 2))
7921 (while (>= (setq n (1- n)) 0)
7922 (org-promote))
7923 (end-of-line 1))))))
7925 (defun org-tr-level (n)
7926 "Make N odd if required."
7927 (if org-odd-levels-only (1+ (/ n 2)) n))
7929 ;;; Vertical tree motion, cutting and pasting of subtrees
7931 (defun org-move-subtree-up (&optional arg)
7932 "Move the current subtree up past ARG headlines of the same level."
7933 (interactive "p")
7934 (org-move-subtree-down (- (prefix-numeric-value arg))))
7936 (defun org-move-subtree-down (&optional arg)
7937 "Move the current subtree down past ARG headlines of the same level."
7938 (interactive "p")
7939 (setq arg (prefix-numeric-value arg))
7940 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7941 'org-get-last-sibling))
7942 (ins-point (make-marker))
7943 (cnt (abs arg))
7944 (col (current-column))
7945 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7946 ;; Select the tree
7947 (org-back-to-heading)
7948 (setq beg0 (point))
7949 (save-excursion
7950 (setq ne-beg (org-back-over-empty-lines))
7951 (setq beg (point)))
7952 (save-match-data
7953 (save-excursion (outline-end-of-heading)
7954 (setq folded (outline-invisible-p)))
7955 (outline-end-of-subtree))
7956 (outline-next-heading)
7957 (setq ne-end (org-back-over-empty-lines))
7958 (setq end (point))
7959 (goto-char beg0)
7960 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7961 ;; include less whitespace
7962 (save-excursion
7963 (goto-char beg)
7964 (forward-line (- ne-beg ne-end))
7965 (setq beg (point))))
7966 ;; Find insertion point, with error handling
7967 (while (> cnt 0)
7968 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7969 (progn (goto-char beg0)
7970 (user-error "Cannot move past superior level or buffer limit")))
7971 (setq cnt (1- cnt)))
7972 (if (> arg 0)
7973 ;; Moving forward - still need to move over subtree
7974 (progn (org-end-of-subtree t t)
7975 (save-excursion
7976 (org-back-over-empty-lines)
7977 (or (bolp) (newline)))))
7978 (setq ne-ins (org-back-over-empty-lines))
7979 (move-marker ins-point (point))
7980 (setq txt (buffer-substring beg end))
7981 (org-save-markers-in-region beg end)
7982 (delete-region beg end)
7983 (org-remove-empty-overlays-at beg)
7984 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7985 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7986 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7987 (let ((bbb (point)))
7988 (insert-before-markers txt)
7989 (org-reinstall-markers-in-region bbb)
7990 (move-marker ins-point bbb))
7991 (or (bolp) (insert "\n"))
7992 (setq ins-end (point))
7993 (goto-char ins-point)
7994 (org-skip-whitespace)
7995 (when (and (< arg 0)
7996 (org-first-sibling-p)
7997 (> ne-ins ne-beg))
7998 ;; Move whitespace back to beginning
7999 (save-excursion
8000 (goto-char ins-end)
8001 (let ((kill-whole-line t))
8002 (kill-line (- ne-ins ne-beg)) (point)))
8003 (insert (make-string (- ne-ins ne-beg) ?\n)))
8004 (move-marker ins-point nil)
8005 (if folded
8006 (hide-subtree)
8007 (org-show-entry)
8008 (show-children)
8009 (org-cycle-hide-drawers 'children))
8010 (org-clean-visibility-after-subtree-move)
8011 ;; move back to the initial column we were at
8012 (move-to-column col)))
8014 (defvar org-subtree-clip ""
8015 "Clipboard for cut and paste of subtrees.
8016 This is actually only a copy of the kill, because we use the normal kill
8017 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8019 (defvar org-subtree-clip-folded nil
8020 "Was the last copied subtree folded?
8021 This is used to fold the tree back after pasting.")
8023 (defun org-cut-subtree (&optional n)
8024 "Cut the current subtree into the clipboard.
8025 With prefix arg N, cut this many sequential subtrees.
8026 This is a short-hand for marking the subtree and then cutting it."
8027 (interactive "p")
8028 (org-copy-subtree n 'cut))
8030 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8031 "Cut the current subtree into the clipboard.
8032 With prefix arg N, cut this many sequential subtrees.
8033 This is a short-hand for marking the subtree and then copying it.
8034 If CUT is non-nil, actually cut the subtree.
8035 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8036 of some markers in the region, even if CUT is non-nil. This is
8037 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8038 (interactive "p")
8039 (let (beg end folded (beg0 (point)))
8040 (if (org-called-interactively-p 'any)
8041 (org-back-to-heading nil) ; take what looks like a subtree
8042 (org-back-to-heading t)) ; take what is really there
8043 (setq beg (point))
8044 (skip-chars-forward " \t\r\n")
8045 (save-match-data
8046 (if nosubtrees
8047 (outline-next-heading)
8048 (save-excursion (outline-end-of-heading)
8049 (setq folded (outline-invisible-p)))
8050 (condition-case nil
8051 (org-forward-heading-same-level (1- n) t)
8052 (error nil))
8053 (org-end-of-subtree t t)))
8054 (setq end (point))
8055 (goto-char beg0)
8056 (when (> end beg)
8057 (setq org-subtree-clip-folded folded)
8058 (when (or cut force-store-markers)
8059 (org-save-markers-in-region beg end))
8060 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8061 (setq org-subtree-clip (current-kill 0))
8062 (message "%s: Subtree(s) with %d characters"
8063 (if cut "Cut" "Copied")
8064 (length org-subtree-clip)))))
8066 (defun org-paste-subtree (&optional level tree for-yank)
8067 "Paste the clipboard as a subtree, with modification of headline level.
8068 The entire subtree is promoted or demoted in order to match a new headline
8069 level.
8071 If the cursor is at the beginning of a headline, the same level as
8072 that headline is used to paste the tree.
8074 If not, the new level is derived from the *visible* headings
8075 before and after the insertion point, and taken to be the inferior headline
8076 level of the two. So if the previous visible heading is level 3 and the
8077 next is level 4 (or vice versa), level 4 will be used for insertion.
8078 This makes sure that the subtree remains an independent subtree and does
8079 not swallow low level entries.
8081 You can also force a different level, either by using a numeric prefix
8082 argument, or by inserting the heading marker by hand. For example, if the
8083 cursor is after \"*****\", then the tree will be shifted to level 5.
8085 If optional TREE is given, use this text instead of the kill ring.
8087 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8088 move back over whitespace before inserting, and move point to the end of
8089 the inserted text when done."
8090 (interactive "P")
8091 (setq tree (or tree (and kill-ring (current-kill 0))))
8092 (unless (org-kill-is-subtree-p tree)
8093 (error "%s"
8094 (substitute-command-keys
8095 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8096 (org-with-limited-levels
8097 (let* ((visp (not (outline-invisible-p)))
8098 (txt tree)
8099 (^re_ "\\(\\*+\\)[ \t]*")
8100 (old-level (if (string-match org-outline-regexp-bol txt)
8101 (- (match-end 0) (match-beginning 0) 1)
8102 -1))
8103 (force-level (cond (level (prefix-numeric-value level))
8104 ((and (looking-at "[ \t]*$")
8105 (string-match
8106 "^\\*+$" (buffer-substring
8107 (point-at-bol) (point))))
8108 (- (match-end 1) (match-beginning 1)))
8109 ((and (bolp)
8110 (looking-at org-outline-regexp))
8111 (- (match-end 0) (point) 1))))
8112 (previous-level (save-excursion
8113 (condition-case nil
8114 (progn
8115 (outline-previous-visible-heading 1)
8116 (if (looking-at ^re_)
8117 (- (match-end 0) (match-beginning 0) 1)
8119 (error 1))))
8120 (next-level (save-excursion
8121 (condition-case nil
8122 (progn
8123 (or (looking-at org-outline-regexp)
8124 (outline-next-visible-heading 1))
8125 (if (looking-at ^re_)
8126 (- (match-end 0) (match-beginning 0) 1)
8128 (error 1))))
8129 (new-level (or force-level (max previous-level next-level)))
8130 (shift (if (or (= old-level -1)
8131 (= new-level -1)
8132 (= old-level new-level))
8134 (- new-level old-level)))
8135 (delta (if (> shift 0) -1 1))
8136 (func (if (> shift 0) 'org-demote 'org-promote))
8137 (org-odd-levels-only nil)
8138 beg end newend)
8139 ;; Remove the forced level indicator
8140 (if force-level
8141 (delete-region (point-at-bol) (point)))
8142 ;; Paste
8143 (beginning-of-line (if (bolp) 1 2))
8144 (setq beg (point))
8145 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8146 (insert-before-markers txt)
8147 (unless (string-match "\n\\'" txt) (insert "\n"))
8148 (setq newend (point))
8149 (org-reinstall-markers-in-region beg)
8150 (setq end (point))
8151 (goto-char beg)
8152 (skip-chars-forward " \t\n\r")
8153 (setq beg (point))
8154 (if (and (outline-invisible-p) visp)
8155 (save-excursion (outline-show-heading)))
8156 ;; Shift if necessary
8157 (unless (= shift 0)
8158 (save-restriction
8159 (narrow-to-region beg end)
8160 (while (not (= shift 0))
8161 (org-map-region func (point-min) (point-max))
8162 (setq shift (+ delta shift)))
8163 (goto-char (point-min))
8164 (setq newend (point-max))))
8165 (when (or (org-called-interactively-p 'interactive) for-yank)
8166 (message "Clipboard pasted as level %d subtree" new-level))
8167 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8168 kill-ring
8169 (eq org-subtree-clip (current-kill 0))
8170 org-subtree-clip-folded)
8171 ;; The tree was folded before it was killed/copied
8172 (hide-subtree))
8173 (and for-yank (goto-char newend)))))
8175 (defun org-kill-is-subtree-p (&optional txt)
8176 "Check if the current kill is an outline subtree, or a set of trees.
8177 Returns nil if kill does not start with a headline, or if the first
8178 headline level is not the largest headline level in the tree.
8179 So this will actually accept several entries of equal levels as well,
8180 which is OK for `org-paste-subtree'.
8181 If optional TXT is given, check this string instead of the current kill."
8182 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8183 (re (org-get-limited-outline-regexp))
8184 (^re (concat "^" re))
8185 (start-level (and kill
8186 (string-match
8187 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8188 kill)
8189 (- (match-end 2) (match-beginning 2) 1)))
8190 (start (1+ (or (match-beginning 2) -1))))
8191 (if (not start-level)
8192 (progn
8193 nil) ;; does not even start with a heading
8194 (catch 'exit
8195 (while (setq start (string-match ^re kill (1+ start)))
8196 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8197 (throw 'exit nil)))
8198 t))))
8200 (defvar org-markers-to-move nil
8201 "Markers that should be moved with a cut-and-paste operation.
8202 Those markers are stored together with their positions relative to
8203 the start of the region.")
8205 (defun org-save-markers-in-region (beg end)
8206 "Check markers in region.
8207 If these markers are between BEG and END, record their position relative
8208 to BEG, so that after moving the block of text, we can put the markers back
8209 into place.
8210 This function gets called just before an entry or tree gets cut from the
8211 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8212 called immediately, to move the markers with the entries."
8213 (setq org-markers-to-move nil)
8214 (when (featurep 'org-clock)
8215 (org-clock-save-markers-for-cut-and-paste beg end))
8216 (when (featurep 'org-agenda)
8217 (org-agenda-save-markers-for-cut-and-paste beg end)))
8219 (defun org-check-and-save-marker (marker beg end)
8220 "Check if MARKER is between BEG and END.
8221 If yes, remember the marker and the distance to BEG."
8222 (when (and (marker-buffer marker)
8223 (equal (marker-buffer marker) (current-buffer)))
8224 (if (and (>= marker beg) (< marker end))
8225 (push (cons marker (- marker beg)) org-markers-to-move))))
8227 (defun org-reinstall-markers-in-region (beg)
8228 "Move all remembered markers to their position relative to BEG."
8229 (mapc (lambda (x)
8230 (move-marker (car x) (+ beg (cdr x))))
8231 org-markers-to-move)
8232 (setq org-markers-to-move nil))
8234 (defun org-narrow-to-subtree ()
8235 "Narrow buffer to the current subtree."
8236 (interactive)
8237 (save-excursion
8238 (save-match-data
8239 (org-with-limited-levels
8240 (narrow-to-region
8241 (progn (org-back-to-heading t) (point))
8242 (progn (org-end-of-subtree t t)
8243 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8244 (point)))))))
8246 (defun org-narrow-to-block ()
8247 "Narrow buffer to the current block."
8248 (interactive)
8249 (let* ((case-fold-search t)
8250 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8251 "^[ \t]*#\\+end_.*")))
8252 (if blockp
8253 (narrow-to-region (car blockp) (cdr blockp))
8254 (error "Not in a block"))))
8256 (eval-when-compile
8257 (defvar org-property-drawer-re))
8259 (defvar org-property-start-re) ;; defined below
8260 (defun org-clone-subtree-with-time-shift (n &optional shift)
8261 "Clone the task (subtree) at point N times.
8262 The clones will be inserted as siblings.
8264 In interactive use, the user will be prompted for the number of
8265 clones to be produced, and for a time SHIFT, which may be a
8266 repeater as used in time stamps, for example `+3d'.
8268 When a valid repeater is given and the entry contains any time
8269 stamps, the clones will become a sequence in time, with time
8270 stamps in the subtree shifted for each clone produced. If SHIFT
8271 is nil or the empty string, time stamps will be left alone. The
8272 ID property of the original subtree is removed.
8274 If the original subtree did contain time stamps with a repeater,
8275 the following will happen:
8276 - the repeater will be removed in each clone
8277 - an additional clone will be produced, with the current, unshifted
8278 date(s) in the entry.
8279 - the original entry will be placed *after* all the clones, with
8280 repeater intact.
8281 - the start days in the repeater in the original entry will be shifted
8282 to past the last clone.
8283 In this way you can spell out a number of instances of a repeating task,
8284 and still retain the repeater to cover future instances of the task."
8285 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8286 (let (beg end template task idprop
8287 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8288 (drawer-re org-drawer-regexp))
8289 (if (not (and (integerp n) (> n 0)))
8290 (error "Invalid number of replications %s" n))
8291 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8292 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8293 shift)))
8294 (error "Invalid shift specification %s" shift))
8295 (when doshift
8296 (setq shift-n (string-to-number (match-string 1 shift))
8297 shift-what (cdr (assoc (match-string 2 shift)
8298 '(("d" . day) ("w" . week)
8299 ("m" . month) ("y" . year))))))
8300 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8301 (setq nmin 1 nmax n)
8302 (org-back-to-heading t)
8303 (setq beg (point))
8304 (setq idprop (org-entry-get nil "ID"))
8305 (org-end-of-subtree t t)
8306 (or (bolp) (insert "\n"))
8307 (setq end (point))
8308 (setq template (buffer-substring beg end))
8309 (when (and doshift
8310 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8311 (delete-region beg end)
8312 (setq end beg)
8313 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8314 (goto-char end)
8315 (loop for n from nmin to nmax do
8316 ;; prepare clone
8317 (with-temp-buffer
8318 (insert template)
8319 (org-mode)
8320 (goto-char (point-min))
8321 (org-show-subtree)
8322 (and idprop (if org-clone-delete-id
8323 (org-entry-delete nil "ID")
8324 (org-id-get-create t)))
8325 (unless (= n 0)
8326 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8327 (kill-whole-line))
8328 (goto-char (point-min))
8329 (while (re-search-forward drawer-re nil t)
8330 (mapc (lambda (d)
8331 (org-remove-empty-drawer-at d (point))) org-drawers)))
8332 (goto-char (point-min))
8333 (when doshift
8334 (while (re-search-forward org-ts-regexp-both nil t)
8335 (org-timestamp-change (* n shift-n) shift-what))
8336 (unless (= n n-no-remove)
8337 (goto-char (point-min))
8338 (while (re-search-forward org-ts-regexp nil t)
8339 (save-excursion
8340 (goto-char (match-beginning 0))
8341 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8342 (delete-region (match-beginning 1) (match-end 1)))))))
8343 (setq task (buffer-string)))
8344 (insert task))
8345 (goto-char beg)))
8347 ;;; Outline Sorting
8349 (defun org-sort (with-case)
8350 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8351 Optional argument WITH-CASE means sort case-sensitively."
8352 (interactive "P")
8353 (cond
8354 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8355 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8357 (org-call-with-arg 'org-sort-entries with-case))))
8359 (defun org-sort-remove-invisible (s)
8360 "Remove invisible links from string S."
8361 (remove-text-properties 0 (length s) org-rm-props s)
8362 (while (string-match org-bracket-link-regexp s)
8363 (setq s (replace-match (if (match-end 2)
8364 (match-string 3 s)
8365 (match-string 1 s)) t t s)))
8366 (let ((st (format " %s " s)))
8367 (while (string-match org-emph-re st)
8368 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8369 (setq s (substring st 1 -1)))
8372 (defvar org-priority-regexp) ; defined later in the file
8374 (defvar org-after-sorting-entries-or-items-hook nil
8375 "Hook that is run after a bunch of entries or items have been sorted.
8376 When children are sorted, the cursor is in the parent line when this
8377 hook gets called. When a region or a plain list is sorted, the cursor
8378 will be in the first entry of the sorted region/list.")
8380 (defun org-sort-entries
8381 (&optional with-case sorting-type getkey-func compare-func property)
8382 "Sort entries on a certain level of an outline tree.
8383 If there is an active region, the entries in the region are sorted.
8384 Else, if the cursor is before the first entry, sort the top-level items.
8385 Else, the children of the entry at point are sorted.
8387 Sorting can be alphabetically, numerically, by date/time as given by
8388 a time stamp, by a property, by priority order, or by a custom function.
8390 The command prompts for the sorting type unless it has been given to the
8391 function through the SORTING-TYPE argument, which needs to be a character,
8392 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8393 precise meaning of each character:
8395 n Numerically, by converting the beginning of the entry/item to a number.
8396 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8397 o By order of TODO keywords.
8398 t By date/time, either the first active time stamp in the entry, or, if
8399 none exist, by the first inactive one.
8400 s By the scheduled date/time.
8401 d By deadline date/time.
8402 c By creation time, which is assumed to be the first inactive time stamp
8403 at the beginning of a line.
8404 p By priority according to the cookie.
8405 r By the value of a property.
8407 Capital letters will reverse the sort order.
8409 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8410 called with point at the beginning of the record. It must return either
8411 a string or a number that should serve as the sorting key for that record.
8413 Comparing entries ignores case by default. However, with an optional argument
8414 WITH-CASE, the sorting considers case as well.
8416 Sorting is done against the visible part of the headlines, it ignores hidden
8417 links."
8418 (interactive "P")
8419 (let ((case-func (if with-case 'identity 'downcase))
8420 (cmstr
8421 ;; The clock marker is lost when using `sort-subr', let's
8422 ;; store the clocking string.
8423 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8424 (save-excursion
8425 (goto-char org-clock-marker)
8426 (looking-back "^.*") (match-string-no-properties 0))))
8427 start beg end stars re re2
8428 txt what tmp)
8429 ;; Find beginning and end of region to sort
8430 (cond
8431 ((org-region-active-p)
8432 ;; we will sort the region
8433 (setq end (region-end)
8434 what "region")
8435 (goto-char (region-beginning))
8436 (if (not (org-at-heading-p)) (outline-next-heading))
8437 (setq start (point)))
8438 ((or (org-at-heading-p)
8439 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8440 ;; we will sort the children of the current headline
8441 (org-back-to-heading)
8442 (setq start (point)
8443 end (progn (org-end-of-subtree t t)
8444 (or (bolp) (insert "\n"))
8445 (org-back-over-empty-lines)
8446 (point))
8447 what "children")
8448 (goto-char start)
8449 (show-subtree)
8450 (outline-next-heading))
8452 ;; we will sort the top-level entries in this file
8453 (goto-char (point-min))
8454 (or (org-at-heading-p) (outline-next-heading))
8455 (setq start (point))
8456 (goto-char (point-max))
8457 (beginning-of-line 1)
8458 (when (looking-at ".*?\\S-")
8459 ;; File ends in a non-white line
8460 (end-of-line 1)
8461 (insert "\n"))
8462 (setq end (point-max))
8463 (setq what "top-level")
8464 (goto-char start)
8465 (show-all)))
8467 (setq beg (point))
8468 (if (>= beg end) (error "Nothing to sort"))
8470 (looking-at "\\(\\*+\\)")
8471 (setq stars (match-string 1)
8472 re (concat "^" (regexp-quote stars) " +")
8473 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8474 txt (buffer-substring beg end))
8475 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8476 (if (and (not (equal stars "*")) (string-match re2 txt))
8477 (error "Region to sort contains a level above the first entry"))
8479 (unless sorting-type
8480 (message
8481 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8482 [t]ime [s]cheduled [d]eadline [c]reated
8483 A/N/P/R/O/F/T/S/D/C means reversed:"
8484 what)
8485 (setq sorting-type (read-char-exclusive))
8487 (unless getkey-func
8488 (and (= (downcase sorting-type) ?f)
8489 (setq getkey-func
8490 (org-icompleting-read "Sort using function: "
8491 obarray 'fboundp t nil nil))
8492 (setq getkey-func (intern getkey-func))))
8494 (and (= (downcase sorting-type) ?r)
8495 (not property)
8496 (setq property
8497 (org-icompleting-read "Property: "
8498 (mapcar 'list (org-buffer-property-keys t))
8499 nil t))))
8501 (message "Sorting entries...")
8503 (save-restriction
8504 (narrow-to-region start end)
8505 (let ((dcst (downcase sorting-type))
8506 (case-fold-search nil)
8507 (now (current-time)))
8508 (sort-subr
8509 (/= dcst sorting-type)
8510 ;; This function moves to the beginning character of the "record" to
8511 ;; be sorted.
8512 (lambda nil
8513 (if (re-search-forward re nil t)
8514 (goto-char (match-beginning 0))
8515 (goto-char (point-max))))
8516 ;; This function moves to the last character of the "record" being
8517 ;; sorted.
8518 (lambda nil
8519 (save-match-data
8520 (condition-case nil
8521 (outline-forward-same-level 1)
8522 (error
8523 (goto-char (point-max))))))
8524 ;; This function returns the value that gets sorted against.
8525 (lambda nil
8526 (cond
8527 ((= dcst ?n)
8528 (if (looking-at org-complex-heading-regexp)
8529 (string-to-number (org-sort-remove-invisible (match-string 4)))
8530 nil))
8531 ((= dcst ?a)
8532 (if (looking-at org-complex-heading-regexp)
8533 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8534 nil))
8535 ((= dcst ?t)
8536 (let ((end (save-excursion (outline-next-heading) (point))))
8537 (if (or (re-search-forward org-ts-regexp end t)
8538 (re-search-forward org-ts-regexp-both end t))
8539 (org-time-string-to-seconds (match-string 0))
8540 (org-float-time now))))
8541 ((= dcst ?c)
8542 (let ((end (save-excursion (outline-next-heading) (point))))
8543 (if (re-search-forward
8544 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8545 end t)
8546 (org-time-string-to-seconds (match-string 0))
8547 (org-float-time now))))
8548 ((= dcst ?s)
8549 (let ((end (save-excursion (outline-next-heading) (point))))
8550 (if (re-search-forward org-scheduled-time-regexp end t)
8551 (org-time-string-to-seconds (match-string 1))
8552 (org-float-time now))))
8553 ((= dcst ?d)
8554 (let ((end (save-excursion (outline-next-heading) (point))))
8555 (if (re-search-forward org-deadline-time-regexp end t)
8556 (org-time-string-to-seconds (match-string 1))
8557 (org-float-time now))))
8558 ((= dcst ?p)
8559 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8560 (string-to-char (match-string 2))
8561 org-default-priority))
8562 ((= dcst ?r)
8563 (or (org-entry-get nil property) ""))
8564 ((= dcst ?o)
8565 (if (looking-at org-complex-heading-regexp)
8566 (- 9999 (length (member (match-string 2)
8567 org-todo-keywords-1)))))
8568 ((= dcst ?f)
8569 (if getkey-func
8570 (progn
8571 (setq tmp (funcall getkey-func))
8572 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8573 tmp)
8574 (error "Invalid key function `%s'" getkey-func)))
8575 (t (error "Invalid sorting type `%c'" sorting-type))))
8577 (cond
8578 ((= dcst ?a) 'string<)
8579 ((= dcst ?f) compare-func)
8580 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8581 (run-hooks 'org-after-sorting-entries-or-items-hook)
8582 ;; Reset the clock marker if needed
8583 (when cmstr
8584 (save-excursion
8585 (goto-char start)
8586 (search-forward cmstr nil t)
8587 (move-marker org-clock-marker (point))))
8588 (message "Sorting entries...done")))
8590 (defun org-do-sort (table what &optional with-case sorting-type)
8591 "Sort TABLE of WHAT according to SORTING-TYPE.
8592 The user will be prompted for the SORTING-TYPE if the call to this
8593 function does not specify it. WHAT is only for the prompt, to indicate
8594 what is being sorted. The sorting key will be extracted from
8595 the car of the elements of the table.
8596 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8597 (unless sorting-type
8598 (message
8599 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8600 what)
8601 (setq sorting-type (read-char-exclusive)))
8602 (let ((dcst (downcase sorting-type))
8603 extractfun comparefun)
8604 ;; Define the appropriate functions
8605 (cond
8606 ((= dcst ?n)
8607 (setq extractfun 'string-to-number
8608 comparefun (if (= dcst sorting-type) '< '>)))
8609 ((= dcst ?a)
8610 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8611 (lambda(x) (downcase (org-sort-remove-invisible x))))
8612 comparefun (if (= dcst sorting-type)
8613 'string<
8614 (lambda (a b) (and (not (string< a b))
8615 (not (string= a b)))))))
8616 ((= dcst ?t)
8617 (setq extractfun
8618 (lambda (x)
8619 (if (or (string-match org-ts-regexp x)
8620 (string-match org-ts-regexp-both x))
8621 (org-float-time
8622 (org-time-string-to-time (match-string 0 x)))
8624 comparefun (if (= dcst sorting-type) '< '>)))
8625 (t (error "Invalid sorting type `%c'" sorting-type)))
8627 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8628 table)
8629 (lambda (a b) (funcall comparefun (car a) (car b))))))
8632 ;;; The orgstruct minor mode
8634 ;; Define a minor mode which can be used in other modes in order to
8635 ;; integrate the org-mode structure editing commands.
8637 ;; This is really a hack, because the org-mode structure commands use
8638 ;; keys which normally belong to the major mode. Here is how it
8639 ;; works: The minor mode defines all the keys necessary to operate the
8640 ;; structure commands, but wraps the commands into a function which
8641 ;; tests if the cursor is currently at a headline or a plain list
8642 ;; item. If that is the case, the structure command is used,
8643 ;; temporarily setting many Org-mode variables like regular
8644 ;; expressions for filling etc. However, when any of those keys is
8645 ;; used at a different location, function uses `key-binding' to look
8646 ;; up if the key has an associated command in another currently active
8647 ;; keymap (minor modes, major mode, global), and executes that
8648 ;; command. There might be problems if any of the keys is otherwise
8649 ;; used as a prefix key.
8651 (defcustom orgstruct-heading-prefix-regexp ""
8652 "Regexp that matches the custom prefix of Org headlines in
8653 orgstruct(++)-mode."
8654 :group 'org
8655 :version "24.4"
8656 :package-version '(Org . "8.0")
8657 :type 'string)
8658 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8660 (defcustom orgstruct-setup-hook nil
8661 "Hook run after orgstruct-mode-map is filled."
8662 :group 'org
8663 :version "24.4"
8664 :package-version '(Org . "8.0")
8665 :type 'hook)
8667 (defvar orgstruct-initialized nil)
8669 (defvar org-local-vars nil
8670 "List of local variables, for use by `orgstruct-mode'.")
8672 ;;;###autoload
8673 (define-minor-mode orgstruct-mode
8674 "Toggle the minor mode `orgstruct-mode'.
8675 This mode is for using Org-mode structure commands in other
8676 modes. The following keys behave as if Org-mode were active, if
8677 the cursor is on a headline, or on a plain list item (both as
8678 defined by Org-mode)."
8679 nil " OrgStruct" (make-sparse-keymap)
8680 (when orgstruct-mode
8681 (org-load-modules-maybe)
8682 (unless orgstruct-initialized
8683 (orgstruct-setup)
8684 (setq orgstruct-initialized t))))
8686 ;;;###autoload
8687 (defun turn-on-orgstruct ()
8688 "Unconditionally turn on `orgstruct-mode'."
8689 (orgstruct-mode 1))
8691 (defvar org-fb-vars nil)
8692 (make-variable-buffer-local 'org-fb-vars)
8693 (defun orgstruct++-mode (&optional arg)
8694 "Toggle `orgstruct-mode', the enhanced version of it.
8695 In addition to setting orgstruct-mode, this also exports all
8696 indentation and autofilling variables from org-mode into the
8697 buffer. It will also recognize item context in multiline items."
8698 (interactive "P")
8699 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8700 (if (< arg 1)
8701 (progn (orgstruct-mode -1)
8702 (mapc (lambda(v)
8703 (org-set-local (car v)
8704 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8705 org-fb-vars))
8706 (orgstruct-mode 1)
8707 (setq org-fb-vars nil)
8708 (let (var val)
8709 (mapc
8710 (lambda (x)
8711 (when (string-match
8712 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8713 (symbol-name (car x)))
8714 (setq var (car x) val (nth 1 x))
8715 (push (list var `(quote ,(eval var))) org-fb-vars)
8716 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8717 org-local-vars)
8718 (org-set-local 'orgstruct-is-++ t))))
8720 (defvar orgstruct-is-++ nil
8721 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8722 (make-variable-buffer-local 'orgstruct-is-++)
8724 ;;;###autoload
8725 (defun turn-on-orgstruct++ ()
8726 "Unconditionally turn on `orgstruct++-mode'."
8727 (orgstruct++-mode 1))
8729 (defun orgstruct-error ()
8730 "Error when there is no default binding for a structure key."
8731 (interactive)
8732 (error "This key has no function outside structure elements"))
8734 (defun orgstruct-setup ()
8735 "Setup orgstruct keymap."
8736 (dolist (f
8737 '("org-meta"
8738 "org-shift"
8739 "org-shiftmeta"
8740 org-shifttab
8741 org-backward-element
8742 org-backward-heading-same-level
8743 org-ctrl-c-ret
8744 org-cycle
8745 org-forward-heading-same-level
8746 org-insert-heading
8747 org-insert-heading-respect-content
8748 org-kill-note-or-show-branches
8749 org-mark-subtree
8750 org-narrow-to-subtree
8751 org-promote-subtree
8752 org-reveal
8753 org-show-subtree
8754 org-sort
8755 org-up-element
8756 outline-demote
8757 outline-next-visible-heading
8758 outline-previous-visible-heading
8759 outline-promote
8760 outline-up-heading
8761 show-children))
8762 (dolist (f (if (stringp f)
8763 (let ((flist))
8764 (dolist (postfix
8765 '("-return" "tab" "left" "right" "up" "down")
8766 flist)
8767 (let ((f (intern (concat f postfix))))
8768 (when (fboundp f)
8769 (push f flist)))))
8770 (list f)))
8771 (dolist (binding (nconc (where-is-internal f org-mode-map)
8772 (where-is-internal f outline-mode-map)))
8773 ;; TODO use local-function-key-map
8774 (dolist (rep '(("<tab>" . "TAB")
8775 ("<return>" . "RET")
8776 ("<escape>" . "ESC")
8777 ("<delete>" . "DEL")))
8778 (setq binding (read-kbd-macro (replace-regexp-in-string
8779 (regexp-quote (car rep))
8780 (cdr rep)
8781 (key-description binding)))))
8782 (let ((key (lookup-key orgstruct-mode-map binding)))
8783 (when (or (not key) (numberp key))
8784 (condition-case nil
8785 (org-defkey orgstruct-mode-map
8786 binding
8787 (orgstruct-make-binding f binding))
8788 (error nil)))))))
8789 (run-hooks 'orgstruct-setup-hook))
8791 (defun orgstruct-make-binding (fun key)
8792 "Create a function for binding in the structure minor mode.
8793 FUN is the command to call inside a table. KEY is the key that
8794 should be checked in for a command to execute outside of tables."
8795 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8796 (let ((nname name)
8797 (i 0))
8798 (while (fboundp (intern nname))
8799 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8800 (setq name (intern nname)))
8801 (eval
8802 (let ((bindings '((org-heading-regexp
8803 (concat "^"
8804 orgstruct-heading-prefix-regexp
8805 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8806 (org-outline-regexp
8807 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8808 (org-outline-regexp-bol
8809 (concat "^" org-outline-regexp))
8810 (outline-regexp org-outline-regexp)
8811 (outline-heading-end-regexp "\n")
8812 (outline-level 'outline-level)
8813 (outline-heading-alist))))
8814 `(defun ,name (arg)
8815 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8816 "Outside of structure, run the binding of `"
8817 (key-description key) "'.")
8818 (interactive "p")
8819 (unless
8820 (let* ,bindings
8821 (when (org-context-p 'headline 'item
8822 ,(when (memq fun '(org-insert-heading))
8823 '(when orgstruct-is-++
8824 'item-body)))
8825 (org-run-like-in-org-mode
8826 (lambda ()
8827 (interactive)
8828 (let* ,bindings
8829 (call-interactively ',fun))))
8831 (let* ((orgstruct-mode)
8832 (binding (key-binding ,key)))
8833 (if (keymapp binding)
8834 (set-temporary-overlay-map binding)
8835 (call-interactively
8836 (or binding 'orgstruct-error))))))))
8837 name))
8839 (defun org-contextualize-keys (alist contexts)
8840 "Return valid elements in ALIST depending on CONTEXTS.
8842 `org-agenda-custom-commands' or `org-capture-templates' are the
8843 values used for ALIST, and `org-agenda-custom-commands-contexts'
8844 or `org-capture-templates-contexts' are the associated contexts
8845 definitions."
8846 (let ((contexts
8847 ;; normalize contexts
8848 (mapcar
8849 (lambda(c) (cond ((listp (cadr c))
8850 (list (car c) (car c) (cadr c)))
8851 ((string= "" (cadr c))
8852 (list (car c) (car c) (caddr c)))
8853 (t c))) contexts))
8854 (a alist) c r s)
8855 ;; loop over all commands or templates
8856 (while (setq c (pop a))
8857 (let (vrules repl)
8858 (cond
8859 ((not (assoc (car c) contexts))
8860 (push c r))
8861 ((and (assoc (car c) contexts)
8862 (setq vrules (org-contextualize-validate-key
8863 (car c) contexts)))
8864 (mapc (lambda (vr)
8865 (when (not (equal (car vr) (cadr vr)))
8866 (setq repl vr))) vrules)
8867 (if (not repl) (push c r)
8868 (push (cadr repl) s)
8869 (push
8870 (cons (car c)
8871 (cdr (or (assoc (cadr repl) alist)
8872 (error "Undefined key `%s' as contextual replacement for `%s'"
8873 (cadr repl) (car c)))))
8874 r))))))
8875 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8876 (delq
8878 (delete-dups
8879 (mapcar (lambda (x)
8880 (let ((tpl (car x)))
8881 (when (not (delq
8883 (mapcar (lambda(y)
8884 (equal y tpl)) s))) x)))
8885 (reverse r))))))
8887 (defun org-contextualize-validate-key (key contexts)
8888 "Check CONTEXTS for agenda or capture KEY."
8889 (let (r rr res)
8890 (while (setq r (pop contexts))
8891 (mapc
8892 (lambda (rr)
8893 (when
8894 (and (equal key (car r))
8895 (if (functionp rr) (funcall rr)
8896 (or (and (eq (car rr) 'in-file)
8897 (buffer-file-name)
8898 (string-match (cdr rr) (buffer-file-name)))
8899 (and (eq (car rr) 'in-mode)
8900 (string-match (cdr rr) (symbol-name major-mode)))
8901 (and (eq (car rr) 'in-buffer)
8902 (string-match (cdr rr) (buffer-name)))
8903 (when (and (eq (car rr) 'not-in-file)
8904 (buffer-file-name))
8905 (not (string-match (cdr rr) (buffer-file-name))))
8906 (when (eq (car rr) 'not-in-mode)
8907 (not (string-match (cdr rr) (symbol-name major-mode))))
8908 (when (eq (car rr) 'not-in-buffer)
8909 (not (string-match (cdr rr) (buffer-name)))))))
8910 (push r res)))
8911 (car (last r))))
8912 (delete-dups (delq nil res))))
8914 (defun org-context-p (&rest contexts)
8915 "Check if local context is any of CONTEXTS.
8916 Possible values in the list of contexts are `table', `headline', and `item'."
8917 (let ((pos (point)))
8918 (goto-char (point-at-bol))
8919 (prog1 (or (and (memq 'table contexts)
8920 (looking-at "[ \t]*|"))
8921 (and (memq 'headline contexts)
8922 (looking-at org-outline-regexp))
8923 (and (memq 'item contexts)
8924 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8925 (and (memq 'item-body contexts)
8926 (org-in-item-p)))
8927 (goto-char pos))))
8929 (defun org-get-local-variables ()
8930 "Return a list of all local variables in an Org mode buffer."
8931 (let (varlist)
8932 (with-current-buffer (get-buffer-create "*Org tmp*")
8933 (erase-buffer)
8934 (org-mode)
8935 (setq varlist (buffer-local-variables)))
8936 (kill-buffer "*Org tmp*")
8937 (delq nil
8938 (mapcar
8939 (lambda (x)
8940 (setq x
8941 (if (symbolp x)
8942 (list x)
8943 (list (car x) (cdr x))))
8944 (if (and (not (get (car x) 'org-state))
8945 (string-match
8946 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8947 (symbol-name (car x))))
8948 x nil))
8949 varlist))))
8951 (defun org-clone-local-variables (from-buffer &optional regexp)
8952 "Clone local variables from FROM-BUFFER.
8953 Optional argument REGEXP selects variables to clone."
8954 (mapc
8955 (lambda (pair)
8956 (and (symbolp (car pair))
8957 (or (null regexp)
8958 (string-match regexp (symbol-name (car pair))))
8959 (set (make-local-variable (car pair))
8960 (cdr pair))))
8961 (buffer-local-variables from-buffer)))
8963 ;;;###autoload
8964 (defun org-run-like-in-org-mode (cmd)
8965 "Run a command, pretending that the current buffer is in Org-mode.
8966 This will temporarily bind local variables that are typically bound in
8967 Org-mode to the values they have in Org-mode, and then interactively
8968 call CMD."
8969 (org-load-modules-maybe)
8970 (unless org-local-vars
8971 (setq org-local-vars (org-get-local-variables)))
8972 (let (binds)
8973 (dolist (var org-local-vars)
8974 (when (or (not (boundp (car var)))
8975 (eq (symbol-value (car var))
8976 (default-value (car var))))
8977 (push (list (car var) `(quote ,(cadr var))) binds)))
8978 (eval `(let ,binds
8979 (call-interactively (quote ,cmd))))))
8981 ;;;; Archiving
8983 (defun org-get-category (&optional pos force-refresh)
8984 "Get the category applying to position POS."
8985 (save-match-data
8986 (if force-refresh (org-refresh-category-properties))
8987 (let ((pos (or pos (point))))
8988 (or (get-text-property pos 'org-category)
8989 (progn (org-refresh-category-properties)
8990 (get-text-property pos 'org-category))))))
8992 (defun org-refresh-category-properties ()
8993 "Refresh category text properties in the buffer."
8994 (let ((case-fold-search t)
8995 (inhibit-read-only t)
8996 (def-cat (cond
8997 ((null org-category)
8998 (if buffer-file-name
8999 (file-name-sans-extension
9000 (file-name-nondirectory buffer-file-name))
9001 "???"))
9002 ((symbolp org-category) (symbol-name org-category))
9003 (t org-category)))
9004 beg end cat pos optionp)
9005 (org-with-silent-modifications
9006 (save-excursion
9007 (save-restriction
9008 (widen)
9009 (goto-char (point-min))
9010 (put-text-property (point) (point-max) 'org-category def-cat)
9011 (while (re-search-forward
9012 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9013 (setq pos (match-end 0)
9014 optionp (equal (char-after (match-beginning 0)) ?#)
9015 cat (org-trim (match-string 2)))
9016 (if optionp
9017 (setq beg (point-at-bol) end (point-max))
9018 (org-back-to-heading t)
9019 (setq beg (point) end (org-end-of-subtree t t)))
9020 (put-text-property beg end 'org-category cat)
9021 (put-text-property beg end 'org-category-position beg)
9022 (goto-char pos)))))))
9024 (defun org-refresh-properties (dprop tprop)
9025 "Refresh buffer text properties.
9026 DPROP is the drawer property and TPROP is the corresponding text
9027 property to set."
9028 (let ((case-fold-search t)
9029 (inhibit-read-only t) p)
9030 (org-with-silent-modifications
9031 (save-excursion
9032 (save-restriction
9033 (widen)
9034 (goto-char (point-min))
9035 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9036 (setq p (org-match-string-no-properties 1))
9037 (save-excursion
9038 (org-back-to-heading t)
9039 (put-text-property
9040 (point-at-bol) (point-at-eol) tprop p))))))))
9043 ;;;; Link Stuff
9045 ;;; Link abbreviations
9047 (defun org-link-expand-abbrev (link)
9048 "Apply replacements as defined in `org-link-abbrev-alist'."
9049 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9050 (let* ((key (match-string 1 link))
9051 (as (or (assoc key org-link-abbrev-alist-local)
9052 (assoc key org-link-abbrev-alist)))
9053 (tag (and (match-end 2) (match-string 3 link)))
9054 rpl)
9055 (if (not as)
9056 link
9057 (setq rpl (cdr as))
9058 (cond
9059 ((symbolp rpl) (funcall rpl tag))
9060 ((string-match "%(\\([^)]+\\))" rpl)
9061 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9062 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9063 ((string-match "%h" rpl)
9064 (replace-match (url-hexify-string (or tag "")) t t rpl))
9065 (t (concat rpl tag)))))
9066 link))
9068 ;;; Storing and inserting links
9070 (defvar org-insert-link-history nil
9071 "Minibuffer history for links inserted with `org-insert-link'.")
9073 (defvar org-stored-links nil
9074 "Contains the links stored with `org-store-link'.")
9076 (defvar org-store-link-plist nil
9077 "Plist with info about the most recently link created with `org-store-link'.")
9079 (defvar org-link-protocols nil
9080 "Link protocols added to Org-mode using `org-add-link-type'.")
9082 (defvar org-store-link-functions nil
9083 "List of functions that are called to create and store a link.
9084 Each function will be called in turn until one returns a non-nil
9085 value. Each function should check if it is responsible for creating
9086 this link (for example by looking at the major mode).
9087 If not, it must exit and return nil.
9088 If yes, it should return a non-nil value after a calling
9089 `org-store-link-props' with a list of properties and values.
9090 Special properties are:
9092 :type The link prefix, like \"http\". This must be given.
9093 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9094 This is obligatory as well.
9095 :description Optional default description for the second pair
9096 of brackets in an Org-mode link. The user can still change
9097 this when inserting this link into an Org-mode buffer.
9099 In addition to these, any additional properties can be specified
9100 and then used in capture templates.")
9102 (defun org-add-link-type (type &optional follow export)
9103 "Add TYPE to the list of `org-link-types'.
9104 Re-compute all regular expressions depending on `org-link-types'
9106 FOLLOW and EXPORT are two functions.
9108 FOLLOW should take the link path as the single argument and do whatever
9109 is necessary to follow the link, for example find a file or display
9110 a mail message.
9112 EXPORT should format the link path for export to one of the export formats.
9113 It should be a function accepting three arguments:
9115 path the path of the link, the text after the prefix (like \"http:\")
9116 desc the description of the link, if any, or a description added by
9117 org-export-normalize-links if there is none
9118 format the export format, a symbol like `html' or `latex' or `ascii'..
9120 The function may use the FORMAT information to return different values
9121 depending on the format. The return value will be put literally into
9122 the exported file. If the return value is nil, this means Org should
9123 do what it normally does with links which do not have EXPORT defined.
9125 Org-mode has a built-in default for exporting links. If you are happy with
9126 this default, there is no need to define an export function for the link
9127 type. For a simple example of an export function, see `org-bbdb.el'."
9128 (add-to-list 'org-link-types type t)
9129 (org-make-link-regexps)
9130 (if (assoc type org-link-protocols)
9131 (setcdr (assoc type org-link-protocols) (list follow export))
9132 (push (list type follow export) org-link-protocols)))
9134 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9135 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9137 ;;;###autoload
9138 (defun org-store-link (arg)
9139 "\\<org-mode-map>Store an org-link to the current location.
9140 This link is added to `org-stored-links' and can later be inserted
9141 into an org-buffer with \\[org-insert-link].
9143 For some link types, a prefix arg is interpreted.
9144 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9145 For file links, arg negates `org-context-in-file-links'.
9147 A double prefix arg force skipping storing functions that are not
9148 part of Org's core."
9149 (interactive "P")
9150 (org-load-modules-maybe)
9151 (setq org-store-link-plist nil) ; reset
9152 (org-with-limited-levels
9153 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9154 (cond
9155 ((and (not (equal arg '(16)))
9156 (setq sfuns
9157 (delq
9158 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9159 org-store-link-functions))
9160 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9161 (or (and (cdr sfuns)
9162 (funcall (intern
9163 (completing-read "Which function for creating the link? "
9164 sfunsn t (car sfunsn)))))
9165 (funcall (caar sfuns)))
9166 (setq link (plist-get org-store-link-plist :link)
9167 desc (or (plist-get org-store-link-plist :description) link))))
9168 ((org-src-edit-buffer-p)
9169 (let (label gc)
9170 (while (or (not label)
9171 (save-excursion
9172 (save-restriction
9173 (widen)
9174 (goto-char (point-min))
9175 (re-search-forward
9176 (regexp-quote (format org-coderef-label-format label))
9177 nil t))))
9178 (when label (message "Label exists already") (sit-for 2))
9179 (setq label (read-string "Code line label: " label)))
9180 (end-of-line 1)
9181 (setq link (format org-coderef-label-format label))
9182 (setq gc (- 79 (length link)))
9183 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9184 (insert link)
9185 (setq link (concat "(" label ")") desc nil)))
9187 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9188 ;; We are in the agenda, link to referenced location
9189 (let ((m (or (get-text-property (point) 'org-hd-marker)
9190 (get-text-property (point) 'org-marker))))
9191 (when m
9192 (org-with-point-at m
9193 (setq agenda-link
9194 (if (org-called-interactively-p 'any)
9195 (call-interactively 'org-store-link)
9196 (org-store-link nil)))))))
9198 ((eq major-mode 'calendar-mode)
9199 (let ((cd (calendar-cursor-to-date)))
9200 (setq link
9201 (format-time-string
9202 (car org-time-stamp-formats)
9203 (apply 'encode-time
9204 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9205 nil nil nil))))
9206 (org-store-link-props :type "calendar" :date cd)))
9208 ((eq major-mode 'help-mode)
9209 (setq link (concat "help:" (save-excursion
9210 (goto-char (point-min))
9211 (looking-at "^[^ ]+")
9212 (match-string 0))))
9213 (org-store-link-props :type "help"))
9215 ((eq major-mode 'w3-mode)
9216 (setq cpltxt (if (and (buffer-name)
9217 (not (string-match "Untitled" (buffer-name))))
9218 (buffer-name)
9219 (url-view-url t))
9220 link (url-view-url t))
9221 (org-store-link-props :type "w3" :url (url-view-url t)))
9223 ((setq search (run-hook-with-args-until-success
9224 'org-create-file-search-functions))
9225 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9226 "::" search))
9227 (setq cpltxt (or description link)))
9229 ((eq major-mode 'image-mode)
9230 (setq cpltxt (concat "file:"
9231 (abbreviate-file-name buffer-file-name))
9232 link cpltxt)
9233 (org-store-link-props :type "image" :file buffer-file-name))
9235 ((eq major-mode 'dired-mode)
9236 ;; link to the file in the current line
9237 (let ((file (dired-get-filename nil t)))
9238 (setq file (if file
9239 (abbreviate-file-name
9240 (expand-file-name (dired-get-filename nil t)))
9241 ;; otherwise, no file so use current directory.
9242 default-directory))
9243 (setq cpltxt (concat "file:" file)
9244 link cpltxt)))
9246 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9247 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9248 (cond
9249 ((org-in-regexp "<<\\(.*?\\)>>")
9250 (setq cpltxt
9251 (concat "file:"
9252 (abbreviate-file-name
9253 (buffer-file-name (buffer-base-buffer)))
9254 "::" (match-string 1))
9255 link cpltxt))
9256 ((and (featurep 'org-id)
9257 (or (eq org-id-link-to-org-use-id t)
9258 (and (org-called-interactively-p 'any)
9259 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9260 (and (eq org-id-link-to-org-use-id
9261 'create-if-interactive-and-no-custom-id)
9262 (not custom-id))))
9263 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9264 ;; We can make a link using the ID.
9265 (setq link (condition-case nil
9266 (prog1 (org-id-store-link)
9267 (setq desc (plist-get org-store-link-plist :description)))
9268 (error
9269 ;; probably before first headline, link to file only
9270 (concat "file:"
9271 (abbreviate-file-name
9272 (buffer-file-name (buffer-base-buffer))))))))
9274 ;; Just link to current headline
9275 (setq cpltxt (concat "file:"
9276 (abbreviate-file-name
9277 (buffer-file-name (buffer-base-buffer)))))
9278 ;; Add a context search string
9279 (when (org-xor org-context-in-file-links arg)
9280 (let* ((ee (org-element-at-point))
9281 (et (org-element-type ee))
9282 (ev (plist-get (cadr ee) :value)))
9283 (setq txt (cond
9284 ((org-at-heading-p) nil)
9285 ((eq et 'keyword) ev)
9286 ((org-region-active-p)
9287 (buffer-substring (region-beginning) (region-end)))))
9288 (when (or (null txt) (string-match "\\S-" txt))
9289 (setq cpltxt
9290 (concat cpltxt "::"
9291 (condition-case nil
9292 (org-make-org-heading-search-string txt)
9293 (error "")))
9294 desc (or (and (eq et 'keyword) ev)
9295 (nth 4 (ignore-errors (org-heading-components)))
9296 "NONE")))))
9297 (if (string-match "::\\'" cpltxt)
9298 (setq cpltxt (substring cpltxt 0 -2)))
9299 (setq link cpltxt))))
9301 ((buffer-file-name (buffer-base-buffer))
9302 ;; Just link to this file here.
9303 (setq cpltxt (concat "file:"
9304 (abbreviate-file-name
9305 (buffer-file-name (buffer-base-buffer)))))
9306 ;; Add a context string
9307 (when (org-xor org-context-in-file-links arg)
9308 (setq txt (if (org-region-active-p)
9309 (buffer-substring (region-beginning) (region-end))
9310 (buffer-substring (point-at-bol) (point-at-eol))))
9311 ;; Only use search option if there is some text.
9312 (when (string-match "\\S-" txt)
9313 (setq cpltxt
9314 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9315 desc "NONE")))
9316 (setq link cpltxt))
9318 ((org-called-interactively-p 'interactive)
9319 (user-error "No method for storing a link from this buffer"))
9321 (t (setq link nil)))
9323 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9324 (setq link (or link cpltxt)
9325 desc (or desc cpltxt))
9326 (cond ((equal desc "NONE") (setq desc nil))
9327 ((string-match org-bracket-link-regexp desc)
9328 (setq desc (replace-regexp-in-string
9329 org-bracket-link-regexp
9330 (concat "\\3" (if (equal (length (match-string 0 desc))
9331 (length desc)) "*" "")) desc))))
9333 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9334 (progn
9335 (setq org-stored-links
9336 (cons (list link desc) org-stored-links))
9337 (message "Stored: %s" (or desc link))
9338 (when custom-id
9339 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9340 "::#" custom-id))
9341 (setq org-stored-links
9342 (cons (list link desc) org-stored-links))))
9343 (or agenda-link (and link (org-make-link-string link desc)))))))
9345 (defun org-store-link-props (&rest plist)
9346 "Store link properties, extract names and addresses."
9347 (let (x adr)
9348 (when (setq x (plist-get plist :from))
9349 (setq adr (mail-extract-address-components x))
9350 (setq plist (plist-put plist :fromname (car adr)))
9351 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9352 (when (setq x (plist-get plist :to))
9353 (setq adr (mail-extract-address-components x))
9354 (setq plist (plist-put plist :toname (car adr)))
9355 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9356 (let ((from (plist-get plist :from))
9357 (to (plist-get plist :to)))
9358 (when (and from to org-from-is-user-regexp)
9359 (setq plist
9360 (plist-put plist :fromto
9361 (if (string-match org-from-is-user-regexp from)
9362 (concat "to %t")
9363 (concat "from %f"))))))
9364 (setq org-store-link-plist plist))
9366 (defun org-add-link-props (&rest plist)
9367 "Add these properties to the link property list."
9368 (let (key value)
9369 (while plist
9370 (setq key (pop plist) value (pop plist))
9371 (setq org-store-link-plist
9372 (plist-put org-store-link-plist key value)))))
9374 (defun org-email-link-description (&optional fmt)
9375 "Return the description part of an email link.
9376 This takes information from `org-store-link-plist' and formats it
9377 according to FMT (default from `org-email-link-description-format')."
9378 (setq fmt (or fmt org-email-link-description-format))
9379 (let* ((p org-store-link-plist)
9380 (to (plist-get p :toaddress))
9381 (from (plist-get p :fromaddress))
9382 (table
9383 (list
9384 (cons "%c" (plist-get p :fromto))
9385 (cons "%F" (plist-get p :from))
9386 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9387 (cons "%T" (plist-get p :to))
9388 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9389 (cons "%s" (plist-get p :subject))
9390 (cons "%d" (plist-get p :date))
9391 (cons "%m" (plist-get p :message-id)))))
9392 (when (string-match "%c" fmt)
9393 ;; Check if the user wrote this message
9394 (if (and org-from-is-user-regexp from to
9395 (save-match-data (string-match org-from-is-user-regexp from)))
9396 (setq fmt (replace-match "to %t" t t fmt))
9397 (setq fmt (replace-match "from %f" t t fmt))))
9398 (org-replace-escapes fmt table)))
9400 (defun org-make-org-heading-search-string (&optional string)
9401 "Make search string for the current headline or STRING."
9402 (let ((s (or string
9403 (and (derived-mode-p 'org-mode)
9404 (save-excursion
9405 (org-back-to-heading t)
9406 (org-element-property :raw-value (org-element-at-point))))))
9407 (lines org-context-in-file-links))
9408 (or string (setq s (concat "*" s))) ; Add * for headlines
9409 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9410 (when (and string (integerp lines) (> lines 0))
9411 (let ((slines (org-split-string s "\n")))
9412 (when (< lines (length slines))
9413 (setq s (mapconcat
9414 'identity
9415 (reverse (nthcdr (- (length slines) lines)
9416 (reverse slines))) "\n")))))
9417 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9419 (defun org-make-link-string (link &optional description)
9420 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9421 (unless (string-match "\\S-" link)
9422 (error "Empty link"))
9423 (when (and description
9424 (stringp description)
9425 (not (string-match "\\S-" description)))
9426 (setq description nil))
9427 (when (stringp description)
9428 ;; Remove brackets from the description, they are fatal.
9429 (while (string-match "\\[" description)
9430 (setq description (replace-match "{" t t description)))
9431 (while (string-match "\\]" description)
9432 (setq description (replace-match "}" t t description))))
9433 (when (equal link description)
9434 ;; No description needed, it is identical
9435 (setq description nil))
9436 (when (and (not description)
9437 (not (string-match (org-image-file-name-regexp) link))
9438 (not (equal link (org-link-escape link))))
9439 (setq description (org-extract-attributes link)))
9440 (setq link
9441 (cond ((string-match (org-image-file-name-regexp) link) link)
9442 ((string-match org-link-types-re link)
9443 (concat (match-string 1 link)
9444 (org-link-escape (substring link (match-end 1)))))
9445 (t (org-link-escape link))))
9446 (concat "[[" link "]"
9447 (if description (concat "[" description "]") "")
9448 "]"))
9450 (defconst org-link-escape-chars
9451 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9452 "List of characters that should be escaped in link.
9453 This is the list that is used for internal purposes.")
9455 (defconst org-link-escape-chars-browser
9456 '(?\ )
9457 "List of escapes for characters that are problematic in links.
9458 This is the list that is used before handing over to the browser.")
9460 (defun org-link-escape (text &optional table merge)
9461 "Return percent escaped representation of TEXT.
9462 TEXT is a string with the text to escape.
9463 Optional argument TABLE is a list with characters that should be
9464 escaped. When nil, `org-link-escape-chars' is used.
9465 If optional argument MERGE is set, merge TABLE into
9466 `org-link-escape-chars'."
9467 (cond
9468 ((and table merge)
9469 (mapc (lambda (defchr)
9470 (unless (member defchr table)
9471 (setq table (cons defchr table)))) org-link-escape-chars))
9472 ((null table)
9473 (setq table org-link-escape-chars)))
9474 (mapconcat
9475 (lambda (char)
9476 (if (or (member char table)
9477 (and (or (< char 32) (= char 37) (> char 126))
9478 org-url-hexify-p))
9479 (mapconcat (lambda (sequence-element)
9480 (format "%%%.2X" sequence-element))
9481 (or (encode-coding-char char 'utf-8)
9482 (error "Unable to percent escape character: %s"
9483 (char-to-string char))) "")
9484 (char-to-string char))) text ""))
9486 (defun org-link-unescape (str)
9487 "Unhex hexified Unicode strings as returned from the JavaScript function
9488 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9489 (unless (and (null str) (string= "" str))
9490 (let ((pos 0) (case-fold-search t) unhexed)
9491 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9492 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9493 (setq str (replace-match unhexed t t str))
9494 (setq pos (+ pos (length unhexed))))))
9495 str)
9497 (defun org-link-unescape-compound (hex)
9498 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9499 Note: this function also decodes single byte encodings like
9500 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9501 (save-match-data
9502 (let* ((bytes (cdr (split-string hex "%")))
9503 (ret "")
9504 (eat 0)
9505 (sum 0))
9506 (while bytes
9507 (let* ((val (string-to-number (pop bytes) 16))
9508 (shift-xor
9509 (if (= 0 eat)
9510 (cond
9511 ((>= val 252) (cons 6 252))
9512 ((>= val 248) (cons 5 248))
9513 ((>= val 240) (cons 4 240))
9514 ((>= val 224) (cons 3 224))
9515 ((>= val 192) (cons 2 192))
9516 (t (cons 0 0)))
9517 (cons 6 128))))
9518 (if (>= val 192) (setq eat (car shift-xor)))
9519 (setq val (logxor val (cdr shift-xor)))
9520 (setq sum (+ (lsh sum (car shift-xor)) val))
9521 (if (> eat 0) (setq eat (- eat 1)))
9522 (cond
9523 ((= 0 eat) ;multi byte
9524 (setq ret (concat ret (org-char-to-string sum)))
9525 (setq sum 0))
9526 ((not bytes) ; single byte(s)
9527 (setq ret (org-link-unescape-single-byte-sequence hex))))
9528 )) ;; end (while bytes
9529 ret )))
9531 (defun org-link-unescape-single-byte-sequence (hex)
9532 "Unhexify hex-encoded single byte character sequences."
9533 (mapconcat (lambda (byte)
9534 (char-to-string (string-to-number byte 16)))
9535 (cdr (split-string hex "%")) ""))
9537 (defun org-xor (a b)
9538 "Exclusive or."
9539 (if a (not b) b))
9541 (defun org-fixup-message-id-for-http (s)
9542 "Replace special characters in a message id, so it can be used in an http query."
9543 (when (string-match "%" s)
9544 (setq s (mapconcat (lambda (c)
9545 (if (eq c ?%)
9546 "%25"
9547 (char-to-string c)))
9548 s "")))
9549 (while (string-match "<" s)
9550 (setq s (replace-match "%3C" t t s)))
9551 (while (string-match ">" s)
9552 (setq s (replace-match "%3E" t t s)))
9553 (while (string-match "@" s)
9554 (setq s (replace-match "%40" t t s)))
9557 (defun org-link-prettify (link)
9558 "Return a human-readable representation of LINK.
9559 The car of LINK must be a raw link the cdr of LINK must be either
9560 a link description or nil."
9561 (let ((desc (or (cadr link) "<no description>")))
9562 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9563 "<" (car link) ">")))
9565 ;;;###autoload
9566 (defun org-insert-link-global ()
9567 "Insert a link like Org-mode does.
9568 This command can be called in any mode to insert a link in Org-mode syntax."
9569 (interactive)
9570 (org-load-modules-maybe)
9571 (org-run-like-in-org-mode 'org-insert-link))
9573 (defun org-insert-all-links (&optional keep)
9574 "Insert all links in `org-stored-links'."
9575 (interactive "P")
9576 (let ((links (copy-sequence org-stored-links)) l)
9577 (while (setq l (if keep (pop links) (pop org-stored-links)))
9578 (insert "- ")
9579 (org-insert-link nil (car l) (cadr l))
9580 (insert "\n"))))
9582 (defun org-link-fontify-links-to-this-file ()
9583 "Fontify links to the current file in `org-stored-links'."
9584 (let ((f (buffer-file-name)) a b)
9585 (setq a (mapcar (lambda(l)
9586 (let ((ll (car l)))
9587 (when (and (string-match "^file:\\(.+\\)::" ll)
9588 (equal f (expand-file-name (match-string 1 ll))))
9589 ll)))
9590 org-stored-links))
9591 (when (featurep 'org-id)
9592 (setq b (mapcar (lambda(l)
9593 (let ((ll (car l)))
9594 (when (and (string-match "^id:\\(.+\\)$" ll)
9595 (equal f (expand-file-name
9596 (or (org-id-find-id-file
9597 (match-string 1 ll)) ""))))
9598 ll)))
9599 org-stored-links)))
9600 (mapcar (lambda(l)
9601 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9602 (delq nil (append a b)))))
9604 (defvar org-link-links-in-this-file nil)
9605 (defun org-insert-link (&optional complete-file link-location default-description)
9606 "Insert a link. At the prompt, enter the link.
9608 Completion can be used to insert any of the link protocol prefixes like
9609 http or ftp in use.
9611 The history can be used to select a link previously stored with
9612 `org-store-link'. When the empty string is entered (i.e. if you just
9613 press RET at the prompt), the link defaults to the most recently
9614 stored link. As SPC triggers completion in the minibuffer, you need to
9615 use M-SPC or C-q SPC to force the insertion of a space character.
9617 You will also be prompted for a description, and if one is given, it will
9618 be displayed in the buffer instead of the link.
9620 If there is already a link at point, this command will allow you to edit link
9621 and description parts.
9623 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9624 be selected using completion. The path to the file will be relative to the
9625 current directory if the file is in the current directory or a subdirectory.
9626 Otherwise, the link will be the absolute path as completed in the minibuffer
9627 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9628 option `org-link-file-path-type'.
9630 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9631 the current directory or below.
9633 With three \\[universal-argument] prefixes, negate the meaning of
9634 `org-keep-stored-link-after-insertion'.
9636 If `org-make-link-description-function' is non-nil, this function will be
9637 called with the link target, and the result will be the default
9638 link description.
9640 If the LINK-LOCATION parameter is non-nil, this value will be
9641 used as the link location instead of reading one interactively.
9643 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9644 be used as the default description."
9645 (interactive "P")
9646 (let* ((wcf (current-window-configuration))
9647 (origbuf (current-buffer))
9648 (region (if (org-region-active-p)
9649 (buffer-substring (region-beginning) (region-end))))
9650 (remove (and region (list (region-beginning) (region-end))))
9651 (desc region)
9652 tmphist ; byte-compile incorrectly complains about this
9653 (link link-location)
9654 (abbrevs org-link-abbrev-alist-local)
9655 entry file all-prefixes auto-desc)
9656 (cond
9657 (link-location) ; specified by arg, just use it.
9658 ((org-in-regexp org-bracket-link-regexp 1)
9659 ;; We do have a link at point, and we are going to edit it.
9660 (setq remove (list (match-beginning 0) (match-end 0)))
9661 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9662 (setq link (read-string "Link: "
9663 (org-link-unescape
9664 (org-match-string-no-properties 1)))))
9665 ((or (org-in-regexp org-angle-link-re)
9666 (org-in-regexp org-plain-link-re))
9667 ;; Convert to bracket link
9668 (setq remove (list (match-beginning 0) (match-end 0))
9669 link (read-string "Link: "
9670 (org-remove-angle-brackets (match-string 0)))))
9671 ((member complete-file '((4) (16)))
9672 ;; Completing read for file names.
9673 (setq link (org-file-complete-link complete-file)))
9675 ;; Read link, with completion for stored links.
9676 (org-link-fontify-links-to-this-file)
9677 (org-switch-to-buffer-other-window "*Org Links*")
9678 (with-current-buffer "*Org Links*"
9679 (erase-buffer)
9680 (insert "Insert a link.
9681 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9682 (when org-stored-links
9683 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9684 (insert (mapconcat 'org-link-prettify
9685 (reverse org-stored-links) "\n")))
9686 (goto-char (point-min)))
9687 (let ((cw (selected-window)))
9688 (select-window (get-buffer-window "*Org Links*" 'visible))
9689 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9690 (unless (pos-visible-in-window-p (point-max))
9691 (org-fit-window-to-buffer))
9692 (and (window-live-p cw) (select-window cw)))
9693 ;; Fake a link history, containing the stored links.
9694 (setq tmphist (append (mapcar 'car org-stored-links)
9695 org-insert-link-history))
9696 (setq all-prefixes (append (mapcar 'car abbrevs)
9697 (mapcar 'car org-link-abbrev-alist)
9698 org-link-types))
9699 (unwind-protect
9700 (progn
9701 (setq link
9702 (org-completing-read
9703 "Link: "
9704 (append
9705 (mapcar (lambda (x) (concat x ":"))
9706 all-prefixes)
9707 (mapcar 'car org-stored-links))
9708 nil nil nil
9709 'tmphist
9710 (caar org-stored-links)))
9711 (if (not (string-match "\\S-" link))
9712 (error "No link selected"))
9713 (mapc (lambda(l)
9714 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9715 org-stored-links)
9716 (if (or (member link all-prefixes)
9717 (and (equal ":" (substring link -1))
9718 (member (substring link 0 -1) all-prefixes)
9719 (setq link (substring link 0 -1))))
9720 (setq link (with-current-buffer origbuf
9721 (org-link-try-special-completion link)))))
9722 (set-window-configuration wcf)
9723 (kill-buffer "*Org Links*"))
9724 (setq entry (assoc link org-stored-links))
9725 (or entry (push link org-insert-link-history))
9726 (setq desc (or desc (nth 1 entry)))))
9728 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9729 (not org-keep-stored-link-after-insertion))
9730 (setq org-stored-links (delq (assoc link org-stored-links)
9731 org-stored-links)))
9733 (if (string-match org-plain-link-re link)
9734 ;; URL-like link, normalize the use of angular brackets.
9735 (setq link (org-remove-angle-brackets link)))
9737 ;; Check if we are linking to the current file with a search
9738 ;; option If yes, simplify the link by using only the search
9739 ;; option.
9740 (when (and buffer-file-name
9741 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9742 (let* ((path (match-string 1 link))
9743 (case-fold-search nil)
9744 (search (match-string 2 link)))
9745 (save-match-data
9746 (if (equal (file-truename buffer-file-name) (file-truename path))
9747 ;; We are linking to this same file, with a search option
9748 (setq link search)))))
9750 ;; Check if we can/should use a relative path. If yes, simplify the link
9751 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9752 (let* ((type (match-string 1 link))
9753 (path (match-string 2 link))
9754 (origpath path)
9755 (case-fold-search nil))
9756 (cond
9757 ((or (eq org-link-file-path-type 'absolute)
9758 (equal complete-file '(16)))
9759 (setq path (abbreviate-file-name (expand-file-name path))))
9760 ((eq org-link-file-path-type 'noabbrev)
9761 (setq path (expand-file-name path)))
9762 ((eq org-link-file-path-type 'relative)
9763 (setq path (file-relative-name path)))
9765 (save-match-data
9766 (if (string-match (concat "^" (regexp-quote
9767 (expand-file-name
9768 (file-name-as-directory
9769 default-directory))))
9770 (expand-file-name path))
9771 ;; We are linking a file with relative path name.
9772 (setq path (substring (expand-file-name path)
9773 (match-end 0)))
9774 (setq path (abbreviate-file-name (expand-file-name path)))))))
9775 (setq link (concat type path))
9776 (if (equal desc origpath)
9777 (setq desc path))))
9779 (if org-make-link-description-function
9780 (setq desc
9781 (or (condition-case nil
9782 (funcall org-make-link-description-function link desc)
9783 (error (progn (message "Can't get link description from `%s'"
9784 (symbol-name org-make-link-description-function))
9785 (sit-for 2) nil)))
9786 (read-string "Description: " default-description)))
9787 (if default-description (setq desc default-description)
9788 (setq desc (or (and auto-desc desc)
9789 (read-string "Description: " desc)))))
9791 (unless (string-match "\\S-" desc) (setq desc nil))
9792 (if remove (apply 'delete-region remove))
9793 (insert (org-make-link-string link desc))))
9795 (defun org-link-try-special-completion (type)
9796 "If there is completion support for link type TYPE, offer it."
9797 (let ((fun (intern (concat "org-" type "-complete-link"))))
9798 (if (functionp fun)
9799 (funcall fun)
9800 (read-string "Link (no completion support): " (concat type ":")))))
9802 (defun org-file-complete-link (&optional arg)
9803 "Create a file link using completion."
9804 (let (file link)
9805 (setq file (org-iread-file-name "File: "))
9806 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9807 (pwd1 (file-name-as-directory (abbreviate-file-name
9808 (expand-file-name ".")))))
9809 (cond
9810 ((equal arg '(16))
9811 (setq link (concat
9812 "file:"
9813 (abbreviate-file-name (expand-file-name file)))))
9814 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9815 (setq link (concat "file:" (match-string 1 file))))
9816 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9817 (expand-file-name file))
9818 (setq link (concat
9819 "file:" (match-string 1 (expand-file-name file)))))
9820 (t (setq link (concat "file:" file)))))
9821 link))
9823 (defun org-iread-file-name (&rest args)
9824 "Read-file-name using `ido-mode' speedup if available.
9825 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9826 See `read-file-name' for a description of parameters."
9827 (org-without-partial-completion
9828 (if (and org-completion-use-ido
9829 (fboundp 'ido-read-file-name)
9830 (boundp 'ido-mode) ido-mode
9831 (listp (second args)))
9832 (let ((ido-enter-matching-directory nil))
9833 (apply 'ido-read-file-name args))
9834 (apply 'read-file-name args))))
9836 (defun org-completing-read (&rest args)
9837 "Completing-read with SPACE being a normal character."
9838 (let ((enable-recursive-minibuffers t)
9839 (minibuffer-local-completion-map
9840 (copy-keymap minibuffer-local-completion-map)))
9841 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9842 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9843 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9844 (apply 'org-icompleting-read args)))
9846 (defun org-completing-read-no-i (&rest args)
9847 (let (org-completion-use-ido org-completion-use-iswitchb)
9848 (apply 'org-completing-read args)))
9850 (defun org-iswitchb-completing-read (prompt choices &rest args)
9851 "Use iswitch as a completing-read replacement to choose from choices.
9852 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9853 from."
9854 (let* ((iswitchb-use-virtual-buffers nil)
9855 (iswitchb-make-buflist-hook
9856 (lambda ()
9857 (setq iswitchb-temp-buflist choices))))
9858 (iswitchb-read-buffer prompt)))
9860 (defun org-icompleting-read (&rest args)
9861 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9862 (org-without-partial-completion
9863 (if (and org-completion-use-ido
9864 (fboundp 'ido-completing-read)
9865 (boundp 'ido-mode) ido-mode
9866 (listp (second args)))
9867 (let ((ido-enter-matching-directory nil))
9868 (apply 'ido-completing-read (concat (car args))
9869 (if (consp (car (nth 1 args)))
9870 (mapcar 'car (nth 1 args))
9871 (nth 1 args))
9872 (cddr args)))
9873 (if (and org-completion-use-iswitchb
9874 (boundp 'iswitchb-mode) iswitchb-mode
9875 (listp (second args)))
9876 (apply 'org-iswitchb-completing-read (concat (car args))
9877 (if (consp (car (nth 1 args)))
9878 (mapcar 'car (nth 1 args))
9879 (nth 1 args))
9880 (cddr args))
9881 (apply 'completing-read args)))))
9883 (defun org-extract-attributes (s)
9884 "Extract the attributes cookie from a string and set as text property."
9885 (let (a attr (start 0) key value)
9886 (save-match-data
9887 (when (string-match "{{\\([^}]+\\)}}$" s)
9888 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9889 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9890 (setq key (match-string 1 a) value (match-string 2 a)
9891 start (match-end 0)
9892 attr (plist-put attr (intern key) value))))
9893 (org-add-props s nil 'org-attr attr))
9896 (defun org-extract-attributes-from-string (tag)
9897 (let (key value attr)
9898 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9899 (setq key (match-string 1 tag) value (match-string 2 tag)
9900 tag (replace-match "" t t tag)
9901 attr (plist-put attr (intern key) value)))
9902 (cons tag attr)))
9904 (defun org-attributes-to-string (plist)
9905 "Format a property list into an HTML attribute list."
9906 (let ((s "") key value)
9907 (while plist
9908 (setq key (pop plist) value (pop plist))
9909 (and value
9910 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9913 ;;; Opening/following a link
9915 (defvar org-link-search-failed nil)
9917 (defvar org-open-link-functions nil
9918 "Hook for functions finding a plain text link.
9919 These functions must take a single argument, the link content.
9920 They will be called for links that look like [[link text][description]]
9921 when LINK TEXT does not have a protocol like \"http:\" and does not look
9922 like a filename (e.g. \"./blue.png\").
9924 These functions will be called *before* Org attempts to resolve the
9925 link by doing text searches in the current buffer - so if you want a
9926 link \"[[target]]\" to still find \"<<target>>\", your function should
9927 handle this as a special case.
9929 When the function does handle the link, it must return a non-nil value.
9930 If it decides that it is not responsible for this link, it must return
9931 nil to indicate that that Org-mode can continue with other options
9932 like exact and fuzzy text search.")
9934 (defun org-next-link (&optional search-backward)
9935 "Move forward to the next link.
9936 If the link is in hidden text, expose it."
9937 (interactive "P")
9938 (when (and org-link-search-failed (eq this-command last-command))
9939 (goto-char (point-min))
9940 (message "Link search wrapped back to beginning of buffer"))
9941 (setq org-link-search-failed nil)
9942 (let* ((pos (point))
9943 (ct (org-context))
9944 (a (assoc :link ct))
9945 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9946 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9947 ((looking-at org-any-link-re)
9948 ;; Don't stay stuck at link without an org-link face
9949 (forward-char (if search-backward -1 1))))
9950 (if (funcall srch-fun org-any-link-re nil t)
9951 (progn
9952 (goto-char (match-beginning 0))
9953 (if (outline-invisible-p) (org-show-context)))
9954 (goto-char pos)
9955 (setq org-link-search-failed t)
9956 (message "No further link found"))))
9958 (defun org-previous-link ()
9959 "Move backward to the previous link.
9960 If the link is in hidden text, expose it."
9961 (interactive)
9962 (funcall 'org-next-link t))
9964 (defun org-translate-link (s)
9965 "Translate a link string if a translation function has been defined."
9966 (if (and org-link-translation-function
9967 (fboundp org-link-translation-function)
9968 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9969 (progn
9970 (setq s (funcall org-link-translation-function
9971 (match-string 1 s) (match-string 2 s)))
9972 (concat (car s) ":" (cdr s)))
9975 (defun org-translate-link-from-planner (type path)
9976 "Translate a link from Emacs Planner syntax so that Org can follow it.
9977 This is still an experimental function, your mileage may vary."
9978 (cond
9979 ((member type '("http" "https" "news" "ftp"))
9980 ;; standard Internet links are the same.
9981 nil)
9982 ((and (equal type "irc") (string-match "^//" path))
9983 ;; Planner has two / at the beginning of an irc link, we have 1.
9984 ;; We should have zero, actually....
9985 (setq path (substring path 1)))
9986 ((and (equal type "lisp") (string-match "^/" path))
9987 ;; Planner has a slash, we do not.
9988 (setq type "elisp" path (substring path 1)))
9989 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9990 ;; A typical message link. Planner has the id after the final slash,
9991 ;; we separate it with a hash mark
9992 (setq path (concat (match-string 1 path) "#"
9993 (org-remove-angle-brackets (match-string 2 path)))))
9995 (cons type path))
9997 (defun org-find-file-at-mouse (ev)
9998 "Open file link or URL at mouse."
9999 (interactive "e")
10000 (mouse-set-point ev)
10001 (org-open-at-point 'in-emacs))
10003 (defun org-open-at-mouse (ev)
10004 "Open file link or URL at mouse.
10005 See the docstring of `org-open-file' for details."
10006 (interactive "e")
10007 (mouse-set-point ev)
10008 (if (eq major-mode 'org-agenda-mode)
10009 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10010 (org-open-at-point))
10012 (defvar org-window-config-before-follow-link nil
10013 "The window configuration before following a link.
10014 This is saved in case the need arises to restore it.")
10016 (defvar org-open-link-marker (make-marker)
10017 "Marker pointing to the location where `org-open-at-point; was called.")
10019 ;;;###autoload
10020 (defun org-open-at-point-global ()
10021 "Follow a link like Org-mode does.
10022 This command can be called in any mode to follow a link that has
10023 Org-mode syntax."
10024 (interactive)
10025 (org-run-like-in-org-mode 'org-open-at-point))
10027 ;;;###autoload
10028 (defun org-open-link-from-string (s &optional arg reference-buffer)
10029 "Open a link in the string S, as if it was in Org-mode."
10030 (interactive "sLink: \nP")
10031 (let ((reference-buffer (or reference-buffer (current-buffer))))
10032 (with-temp-buffer
10033 (let ((org-inhibit-startup (not reference-buffer)))
10034 (org-mode)
10035 (insert s)
10036 (goto-char (point-min))
10037 (when reference-buffer
10038 (setq org-link-abbrev-alist-local
10039 (with-current-buffer reference-buffer
10040 org-link-abbrev-alist-local)))
10041 (org-open-at-point arg reference-buffer)))))
10043 (defvar org-open-at-point-functions nil
10044 "Hook that is run when following a link at point.
10046 Functions in this hook must return t if they identify and follow
10047 a link at point. If they don't find anything interesting at point,
10048 they must return nil.")
10050 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10051 (defun org-open-at-point (&optional arg reference-buffer)
10052 "Open link at or after point.
10053 If there is no link at point, this function will search forward up to
10054 the end of the current line.
10055 Normally, files will be opened by an appropriate application. If the
10056 optional prefix argument ARG is non-nil, Emacs will visit the file.
10057 With a double prefix argument, try to open outside of Emacs, in the
10058 application the system uses for this file type."
10059 (interactive "P")
10060 ;; if in a code block, then open the block's results
10061 (unless (call-interactively #'org-babel-open-src-block-result)
10062 (org-load-modules-maybe)
10063 (move-marker org-open-link-marker (point))
10064 (setq org-window-config-before-follow-link (current-window-configuration))
10065 (org-remove-occur-highlights nil nil t)
10066 (cond
10067 ((and (org-at-heading-p)
10068 (not (org-at-timestamp-p t))
10069 (not (org-in-regexp
10070 (concat org-plain-link-re "\\|"
10071 org-bracket-link-regexp "\\|"
10072 org-angle-link-re "\\|"
10073 "[ \t]:[^ \t\n]+:[ \t]*$")))
10074 (not (get-text-property (point) 'org-linked-text)))
10075 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10076 (lk0 (car lkall))
10077 (lk (if (stringp lk0) (list lk0) lk0))
10078 (lkend (cdr lkall)))
10079 (mapcar (lambda(l)
10080 (search-forward l nil lkend)
10081 (goto-char (match-beginning 0))
10082 (org-open-at-point))
10083 lk))
10084 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10085 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10086 ((and (org-at-timestamp-p t)
10087 (not (org-in-regexp org-bracket-link-regexp)))
10088 (org-follow-timestamp-link))
10089 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10090 (not (org-in-regexp org-any-link-re)))
10091 (org-footnote-action))
10093 (let (type path link line search (pos (point)))
10094 (catch 'match
10095 (save-excursion
10096 (skip-chars-forward "^]\n\r")
10097 (when (org-in-regexp org-bracket-link-regexp 1)
10098 (setq link (org-extract-attributes
10099 (org-link-unescape (org-match-string-no-properties 1))))
10100 (while (string-match " *\n *" link)
10101 (setq link (replace-match " " t t link)))
10102 (setq link (org-link-expand-abbrev link))
10103 (cond
10104 ((or (file-name-absolute-p link)
10105 (string-match "^\\.\\.?/" link))
10106 (setq type "file" path link))
10107 ((string-match org-link-re-with-space3 link)
10108 (setq type (match-string 1 link) path (match-string 2 link)))
10109 ((string-match "^help:+\\(.+\\)" link)
10110 (setq type "help" path (match-string 1 link)))
10111 (t (setq type "thisfile" path link)))
10112 (throw 'match t)))
10114 (when (get-text-property (point) 'org-linked-text)
10115 (setq type "thisfile"
10116 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10117 (1+ (point)) (point))
10118 path (buffer-substring
10119 (or (previous-single-property-change pos 'org-linked-text)
10120 (point-min))
10121 (or (next-single-property-change pos 'org-linked-text)
10122 (point-max))))
10123 (throw 'match t))
10125 (save-excursion
10126 (when (or (org-in-regexp org-angle-link-re)
10127 (let ((match (org-in-regexp org-plain-link-re)))
10128 ;; Check a plain link is not within a bracket link
10129 (and match
10130 (save-excursion
10131 (progn
10132 (goto-char (car match))
10133 (not (org-in-regexp org-bracket-link-regexp))))))
10134 (let ((line_ending (save-excursion (end-of-line) (point))))
10135 ;; We are in a line before a plain or bracket link
10136 (or (re-search-forward org-plain-link-re line_ending t)
10137 (re-search-forward org-bracket-link-regexp line_ending t))))
10138 (setq type (match-string 1)
10139 path (org-link-unescape (match-string 2)))
10140 (throw 'match t)))
10141 (save-excursion
10142 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10143 (setq type "tags"
10144 path (match-string 1))
10145 (while (string-match ":" path)
10146 (setq path (replace-match "+" t t path)))
10147 (throw 'match t)))
10148 (when (org-in-regexp "<\\([^><\n]+\\)>")
10149 (setq type "tree-match"
10150 path (match-string 1))
10151 (throw 'match t)))
10152 (unless path
10153 (user-error "No link found"))
10155 ;; switch back to reference buffer
10156 ;; needed when if called in a temporary buffer through
10157 ;; org-open-link-from-string
10158 (with-current-buffer (or reference-buffer (current-buffer))
10160 ;; Remove any trailing spaces in path
10161 (if (string-match " +\\'" path)
10162 (setq path (replace-match "" t t path)))
10163 (if (and org-link-translation-function
10164 (fboundp org-link-translation-function))
10165 ;; Check if we need to translate the link
10166 (let ((tmp (funcall org-link-translation-function type path)))
10167 (setq type (car tmp) path (cdr tmp))))
10169 (cond
10171 ((assoc type org-link-protocols)
10172 (funcall (nth 1 (assoc type org-link-protocols)) path))
10174 ((equal type "help")
10175 (let ((f-or-v (intern path)))
10176 (cond ((fboundp f-or-v)
10177 (describe-function f-or-v))
10178 ((boundp f-or-v)
10179 (describe-variable f-or-v))
10180 (t (error "Not a known function or variable")))))
10182 ((equal type "mailto")
10183 (let ((cmd (car org-link-mailto-program))
10184 (args (cdr org-link-mailto-program)) args1
10185 (address path) (subject "") a)
10186 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10187 (setq address (match-string 1 path)
10188 subject (org-link-escape (match-string 2 path))))
10189 (while args
10190 (cond
10191 ((not (stringp (car args))) (push (pop args) args1))
10192 (t (setq a (pop args))
10193 (if (string-match "%a" a)
10194 (setq a (replace-match address t t a)))
10195 (if (string-match "%s" a)
10196 (setq a (replace-match subject t t a)))
10197 (push a args1))))
10198 (apply cmd (nreverse args1))))
10200 ((member type '("http" "https" "ftp" "news"))
10201 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10202 (org-link-escape
10203 path org-link-escape-chars-browser)
10204 path))))
10206 ((string= type "doi")
10207 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10208 (org-link-escape
10209 path org-link-escape-chars-browser)
10210 path))))
10212 ((member type '("message"))
10213 (browse-url (concat type ":" path)))
10215 ((string= type "tags")
10216 (org-tags-view arg path))
10218 ((string= type "tree-match")
10219 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10221 ((string= type "file")
10222 (if (string-match "::\\([0-9]+\\)\\'" path)
10223 (setq line (string-to-number (match-string 1 path))
10224 path (substring path 0 (match-beginning 0)))
10225 (if (string-match "::\\(.+\\)\\'" path)
10226 (setq search (match-string 1 path)
10227 path (substring path 0 (match-beginning 0)))))
10228 (if (string-match "[*?{]" (file-name-nondirectory path))
10229 (dired path)
10230 (org-open-file path arg line search)))
10232 ((string= type "shell")
10233 (let ((buf (generate-new-buffer "*Org Shell Output"))
10234 (cmd path))
10235 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10236 (string-match org-confirm-shell-link-not-regexp cmd))
10237 (not org-confirm-shell-link-function)
10238 (funcall org-confirm-shell-link-function
10239 (format "Execute \"%s\" in shell? "
10240 (org-add-props cmd nil
10241 'face 'org-warning))))
10242 (progn
10243 (message "Executing %s" cmd)
10244 (shell-command cmd buf)
10245 (if (featurep 'midnight)
10246 (setq clean-buffer-list-kill-buffer-names
10247 (cons buf clean-buffer-list-kill-buffer-names))))
10248 (error "Abort"))))
10250 ((string= type "elisp")
10251 (let ((cmd path))
10252 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10253 (string-match org-confirm-elisp-link-not-regexp cmd))
10254 (not org-confirm-elisp-link-function)
10255 (funcall org-confirm-elisp-link-function
10256 (format "Execute \"%s\" as elisp? "
10257 (org-add-props cmd nil
10258 'face 'org-warning))))
10259 (message "%s => %s" cmd
10260 (if (equal (string-to-char cmd) ?\()
10261 (eval (read cmd))
10262 (call-interactively (read cmd))))
10263 (error "Abort"))))
10265 ((and (string= type "thisfile")
10266 (run-hook-with-args-until-success
10267 'org-open-link-functions path)))
10269 ((string= type "thisfile")
10270 (if arg
10271 (switch-to-buffer-other-window
10272 (org-get-buffer-for-internal-link (current-buffer)))
10273 (org-mark-ring-push))
10274 (let ((cmd `(org-link-search
10275 ,path
10276 ,(cond ((equal arg '(4)) ''occur)
10277 ((equal arg '(16)) ''org-occur))
10278 ,pos)))
10279 (condition-case nil (let ((org-link-search-inhibit-query t))
10280 (eval cmd))
10281 (error (progn (widen) (eval cmd))))))
10283 (t (browse-url-at-point)))))))
10284 (move-marker org-open-link-marker nil)
10285 (run-hook-with-args 'org-follow-link-hook)))
10287 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10288 "Offer links in the current entry and return the selected link.
10289 If there is only one link, return it.
10290 If NTH is an integer, return the NTH link found.
10291 If ZERO is a string, check also this string for a link, and if
10292 there is one, return it."
10293 (with-current-buffer buffer
10294 (save-excursion
10295 (save-restriction
10296 (widen)
10297 (goto-char marker)
10298 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10299 "\\(" org-angle-link-re "\\)\\|"
10300 "\\(" org-plain-link-re "\\)"))
10301 (cnt ?0)
10302 (in-emacs (if (integerp nth) nil nth))
10303 have-zero end links link c)
10304 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10305 (push (match-string 0 zero) links)
10306 (setq cnt (1- cnt) have-zero t))
10307 (save-excursion
10308 (org-back-to-heading t)
10309 (setq end (save-excursion (outline-next-heading) (point)))
10310 (while (re-search-forward re end t)
10311 (push (match-string 0) links))
10312 (setq links (org-uniquify (reverse links))))
10313 (cond
10314 ((null links)
10315 (message "No links"))
10316 ((equal (length links) 1)
10317 (setq link (car links)))
10318 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10319 (setq link (nth (if have-zero nth (1- nth)) links)))
10320 (t ; we have to select a link
10321 (save-excursion
10322 (save-window-excursion
10323 (delete-other-windows)
10324 (with-output-to-temp-buffer "*Select Link*"
10325 (mapc (lambda (l)
10326 (if (not (string-match org-bracket-link-regexp l))
10327 (princ (format "[%c] %s\n" (incf cnt)
10328 (org-remove-angle-brackets l)))
10329 (if (match-end 3)
10330 (princ (format "[%c] %s (%s)\n" (incf cnt)
10331 (match-string 3 l) (match-string 1 l)))
10332 (princ (format "[%c] %s\n" (incf cnt)
10333 (match-string 1 l))))))
10334 links))
10335 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10336 (message "Select link to open, RET to open all:")
10337 (setq c (read-char-exclusive))
10338 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10339 (when (equal c ?q) (error "Abort"))
10340 (if (equal c ?\C-m)
10341 (setq link links)
10342 (setq nth (- c ?0))
10343 (if have-zero (setq nth (1+ nth)))
10344 (unless (and (integerp nth) (>= (length links) nth))
10345 (error "Invalid link selection"))
10346 (setq link (nth (1- nth) links)))))
10347 (cons link end))))))
10349 ;; Add special file links that specify the way of opening
10351 (org-add-link-type "file+sys" 'org-open-file-with-system)
10352 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10353 (defun org-open-file-with-system (path)
10354 "Open file at PATH using the system way of opening it."
10355 (org-open-file path 'system))
10356 (defun org-open-file-with-emacs (path)
10357 "Open file at PATH in Emacs."
10358 (org-open-file path 'emacs))
10361 ;;; File search
10363 (defvar org-create-file-search-functions nil
10364 "List of functions to construct the right search string for a file link.
10365 These functions are called in turn with point at the location to
10366 which the link should point.
10368 A function in the hook should first test if it would like to
10369 handle this file type, for example by checking the `major-mode'
10370 or the file extension. If it decides not to handle this file, it
10371 should just return nil to give other functions a chance. If it
10372 does handle the file, it must return the search string to be used
10373 when following the link. The search string will be part of the
10374 file link, given after a double colon, and `org-open-at-point'
10375 will automatically search for it. If special measures must be
10376 taken to make the search successful, another function should be
10377 added to the companion hook `org-execute-file-search-functions',
10378 which see.
10380 A function in this hook may also use `setq' to set the variable
10381 `description' to provide a suggestion for the descriptive text to
10382 be used for this link when it gets inserted into an Org-mode
10383 buffer with \\[org-insert-link].")
10385 (defvar org-execute-file-search-functions nil
10386 "List of functions to execute a file search triggered by a link.
10388 Functions added to this hook must accept a single argument, the
10389 search string that was part of the file link, the part after the
10390 double colon. The function must first check if it would like to
10391 handle this search, for example by checking the `major-mode' or
10392 the file extension. If it decides not to handle this search, it
10393 should just return nil to give other functions a chance. If it
10394 does handle the search, it must return a non-nil value to keep
10395 other functions from trying.
10397 Each function can access the current prefix argument through the
10398 variable `current-prefix-argument'. Note that a single prefix is
10399 used to force opening a link in Emacs, so it may be good to only
10400 use a numeric or double prefix to guide the search function.
10402 In case this is needed, a function in this hook can also restore
10403 the window configuration before `org-open-at-point' was called using:
10405 (set-window-configuration org-window-config-before-follow-link)")
10407 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10408 (defun org-link-search (s &optional type avoid-pos stealth)
10409 "Search for a link search option.
10410 If S is surrounded by forward slashes, it is interpreted as a
10411 regular expression. In org-mode files, this will create an `org-occur'
10412 sparse tree. In ordinary files, `occur' will be used to list matches.
10413 If the current buffer is in `dired-mode', grep will be used to search
10414 in all files. If AVOID-POS is given, ignore matches near that position.
10416 When optional argument STEALTH is non-nil, do not modify
10417 visibility around point, thus ignoring
10418 `org-show-hierarchy-above', `org-show-following-heading' and
10419 `org-show-siblings' variables."
10420 (let ((case-fold-search t)
10421 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10422 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10423 (append '(("") (" ") ("\t") ("\n"))
10424 org-emphasis-alist)
10425 "\\|") "\\)"))
10426 (pos (point))
10427 (pre nil) (post nil)
10428 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10429 (cond
10430 ;; First check if there are any special search functions
10431 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10432 ;; Now try the builtin stuff
10433 ((and (equal (string-to-char s0) ?#)
10434 (> (length s0) 1)
10435 (save-excursion
10436 (goto-char (point-min))
10437 (and
10438 (re-search-forward
10439 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10440 (setq type 'dedicated
10441 pos (match-beginning 0))))
10442 ;; There is an exact target for this
10443 (goto-char pos)
10444 (org-back-to-heading t)))
10445 ((save-excursion
10446 (goto-char (point-min))
10447 (and
10448 (re-search-forward
10449 (concat "<<" (regexp-quote s0) ">>") nil t)
10450 (setq type 'dedicated
10451 pos (match-beginning 0))))
10452 ;; There is an exact target for this
10453 (goto-char pos))
10454 ((save-excursion
10455 (goto-char (point-min))
10456 (and
10457 (re-search-forward
10458 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10459 (setq type 'dedicated pos (match-beginning 0))))
10460 ;; Found an invisible target.
10461 (goto-char pos))
10462 ((save-excursion
10463 (goto-char (point-min))
10464 (and
10465 (re-search-forward
10466 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10467 (setq type 'dedicated pos (match-beginning 0))))
10468 ;; Found an element with a matching #+name affiliated keyword.
10469 (goto-char pos))
10470 ((and (string-match "^(\\(.*\\))$" s0)
10471 (save-excursion
10472 (goto-char (point-min))
10473 (and
10474 (re-search-forward
10475 (concat "[^[]" (regexp-quote
10476 (format org-coderef-label-format
10477 (match-string 1 s0))))
10478 nil t)
10479 (setq type 'dedicated
10480 pos (1+ (match-beginning 0))))))
10481 ;; There is a coderef target for this
10482 (goto-char pos))
10483 ((string-match "^/\\(.*\\)/$" s)
10484 ;; A regular expression
10485 (cond
10486 ((derived-mode-p 'org-mode)
10487 (org-occur (match-string 1 s)))
10488 (t (org-do-occur (match-string 1 s)))))
10489 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10490 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10491 (goto-char (point-min))
10492 (cond
10493 ((let (case-fold-search)
10494 (re-search-forward (format org-complex-heading-regexp-format
10495 (regexp-quote s))
10496 nil t))
10497 ;; OK, found a match
10498 (setq type 'dedicated)
10499 (goto-char (match-beginning 0)))
10500 ((and (not org-link-search-inhibit-query)
10501 (eq org-link-search-must-match-exact-headline 'query-to-create)
10502 (y-or-n-p "No match - create this as a new heading? "))
10503 (goto-char (point-max))
10504 (or (bolp) (newline))
10505 (insert "* " s "\n")
10506 (beginning-of-line 0))
10508 (goto-char pos)
10509 (error "No match"))))
10511 ;; A normal search string
10512 (when (equal (string-to-char s) ?*)
10513 ;; Anchor on headlines, post may include tags.
10514 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10515 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10516 s (substring s 1)))
10517 (remove-text-properties
10518 0 (length s)
10519 '(face nil mouse-face nil keymap nil fontified nil) s)
10520 ;; Make a series of regular expressions to find a match
10521 (setq words (org-split-string s "[ \n\r\t]+")
10523 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10524 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10525 "\\)" markers)
10526 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10527 re2a (concat "[ \t\r\n]" re2a_)
10528 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10529 re4 (concat "[^a-zA-Z_]" re4_)
10531 re1 (concat pre re2 post)
10532 re3 (concat pre (if pre re4_ re4) post)
10533 re5 (concat pre ".*" re4)
10534 re2 (concat pre re2)
10535 re2a (concat pre (if pre re2a_ re2a))
10536 re4 (concat pre (if pre re4_ re4))
10537 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10538 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10539 re5 "\\)"
10541 (cond
10542 ((eq type 'org-occur) (org-occur reall))
10543 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10544 (t (goto-char (point-min))
10545 (setq type 'fuzzy)
10546 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10547 (org-search-not-self 1 re1 nil t)
10548 (org-search-not-self 1 re2 nil t)
10549 (org-search-not-self 1 re2a nil t)
10550 (org-search-not-self 1 re3 nil t)
10551 (org-search-not-self 1 re4 nil t)
10552 (org-search-not-self 1 re5 nil t)
10554 (goto-char (match-beginning 1))
10555 (goto-char pos)
10556 (error "No match"))))))
10557 (and (derived-mode-p 'org-mode)
10558 (not stealth)
10559 (org-show-context 'link-search))
10560 type))
10562 (defun org-search-not-self (group &rest args)
10563 "Execute `re-search-forward', but only accept matches that do not
10564 enclose the position of `org-open-link-marker'."
10565 (let ((m org-open-link-marker))
10566 (catch 'exit
10567 (while (apply 're-search-forward args)
10568 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10569 (goto-char (match-end group))
10570 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10571 (> (match-beginning 0) (marker-position m))
10572 (< (match-end 0) (marker-position m)))
10573 (save-match-data
10574 (or (not (org-in-regexp
10575 org-bracket-link-analytic-regexp 1))
10576 (not (match-end 4)) ; no description
10577 (and (<= (match-beginning 4) (point))
10578 (>= (match-end 4) (point))))))
10579 (throw 'exit (point))))))))
10581 (defun org-get-buffer-for-internal-link (buffer)
10582 "Return a buffer to be used for displaying the link target of internal links."
10583 (cond
10584 ((not org-display-internal-link-with-indirect-buffer)
10585 buffer)
10586 ((string-match "(Clone)$" (buffer-name buffer))
10587 (message "Buffer is already a clone, not making another one")
10588 ;; we also do not modify visibility in this case
10589 buffer)
10590 (t ; make a new indirect buffer for displaying the link
10591 (let* ((bn (buffer-name buffer))
10592 (ibn (concat bn "(Clone)"))
10593 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10594 (with-current-buffer ib (org-overview))
10595 ib))))
10597 (defun org-do-occur (regexp &optional cleanup)
10598 "Call the Emacs command `occur'.
10599 If CLEANUP is non-nil, remove the printout of the regular expression
10600 in the *Occur* buffer. This is useful if the regex is long and not useful
10601 to read."
10602 (occur regexp)
10603 (when cleanup
10604 (let ((cwin (selected-window)) win beg end)
10605 (when (setq win (get-buffer-window "*Occur*"))
10606 (select-window win))
10607 (goto-char (point-min))
10608 (when (re-search-forward "match[a-z]+" nil t)
10609 (setq beg (match-end 0))
10610 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10611 (setq end (1- (match-beginning 0)))))
10612 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10613 (goto-char (point-min))
10614 (select-window cwin))))
10616 ;;; The mark ring for links jumps
10618 (defvar org-mark-ring nil
10619 "Mark ring for positions before jumps in Org-mode.")
10620 (defvar org-mark-ring-last-goto nil
10621 "Last position in the mark ring used to go back.")
10622 ;; Fill and close the ring
10623 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10624 (loop for i from 1 to org-mark-ring-length do
10625 (push (make-marker) org-mark-ring))
10626 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10627 org-mark-ring)
10629 (defun org-mark-ring-push (&optional pos buffer)
10630 "Put the current position or POS into the mark ring and rotate it."
10631 (interactive)
10632 (setq pos (or pos (point)))
10633 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10634 (move-marker (car org-mark-ring)
10635 (or pos (point))
10636 (or buffer (current-buffer)))
10637 (message "%s"
10638 (substitute-command-keys
10639 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10641 (defun org-mark-ring-goto (&optional n)
10642 "Jump to the previous position in the mark ring.
10643 With prefix arg N, jump back that many stored positions. When
10644 called several times in succession, walk through the entire ring.
10645 Org-mode commands jumping to a different position in the current file,
10646 or to another Org-mode file, automatically push the old position
10647 onto the ring."
10648 (interactive "p")
10649 (let (p m)
10650 (if (eq last-command this-command)
10651 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10652 (setq p org-mark-ring))
10653 (setq org-mark-ring-last-goto p)
10654 (setq m (car p))
10655 (org-pop-to-buffer-same-window (marker-buffer m))
10656 (goto-char m)
10657 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10659 (defun org-remove-angle-brackets (s)
10660 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10661 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10663 (defun org-add-angle-brackets (s)
10664 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10665 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10667 (defun org-remove-double-quotes (s)
10668 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10669 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10672 ;;; Following specific links
10674 (defun org-follow-timestamp-link ()
10675 "Open an agenda view for the time-stamp date/range at point."
10676 (cond
10677 ((org-at-date-range-p t)
10678 (let ((org-agenda-start-on-weekday)
10679 (t1 (match-string 1))
10680 (t2 (match-string 2)) tt1 tt2)
10681 (setq tt1 (time-to-days (org-time-string-to-time t1))
10682 tt2 (time-to-days (org-time-string-to-time t2)))
10683 (let ((org-agenda-buffer-tmp-name
10684 (format "*Org Agenda(a:%s)"
10685 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10686 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10687 ((org-at-timestamp-p t)
10688 (let ((org-agenda-buffer-tmp-name
10689 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10690 (org-agenda-list nil (time-to-days (org-time-string-to-time
10691 (substring (match-string 1) 0 10)))
10692 1)))
10693 (t (error "This should not happen"))))
10696 ;;; Following file links
10697 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10698 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10699 (declare-function mailcap-mime-info
10700 "mailcap" (string &optional request no-decode))
10701 (defvar org-wait nil)
10702 (defun org-open-file (path &optional in-emacs line search)
10703 "Open the file at PATH.
10704 First, this expands any special file name abbreviations. Then the
10705 configuration variable `org-file-apps' is checked if it contains an
10706 entry for this file type, and if yes, the corresponding command is launched.
10708 If no application is found, Emacs simply visits the file.
10710 With optional prefix argument IN-EMACS, Emacs will visit the file.
10711 With a double \\[universal-argument] \\[universal-argument] \
10712 prefix arg, Org tries to avoid opening in Emacs
10713 and to use an external application to visit the file.
10715 Optional LINE specifies a line to go to, optional SEARCH a string
10716 to search for. If LINE or SEARCH is given, the file will be
10717 opened in Emacs, unless an entry from org-file-apps that makes
10718 use of groups in a regexp matches.
10720 If you want to change the way frames are used when following a
10721 link, please customize `org-link-frame-setup'.
10723 If the file does not exist, an error is thrown."
10724 (let* ((file (if (equal path "")
10725 buffer-file-name
10726 (substitute-in-file-name (expand-file-name path))))
10727 (file-apps (append org-file-apps (org-default-apps)))
10728 (apps (org-remove-if
10729 'org-file-apps-entry-match-against-dlink-p file-apps))
10730 (apps-dlink (org-remove-if-not
10731 'org-file-apps-entry-match-against-dlink-p file-apps))
10732 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10733 (dirp (if remp nil (file-directory-p file)))
10734 (file (if (and dirp org-open-directory-means-index-dot-org)
10735 (concat (file-name-as-directory file) "index.org")
10736 file))
10737 (a-m-a-p (assq 'auto-mode apps))
10738 (dfile (downcase file))
10739 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10740 (link (cond ((and (eq line nil)
10741 (eq search nil))
10742 file)
10743 (line
10744 (concat file "::" (number-to-string line)))
10745 (search
10746 (concat file "::" search))))
10747 (dlink (downcase link))
10748 (old-buffer (current-buffer))
10749 (old-pos (point))
10750 (old-mode major-mode)
10751 ext cmd link-match-data)
10752 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10753 (setq ext (match-string 1 dfile))
10754 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10755 (setq ext (match-string 1 dfile))))
10756 (cond
10757 ((member in-emacs '((16) system))
10758 (setq cmd (cdr (assoc 'system apps))))
10759 (in-emacs (setq cmd 'emacs))
10761 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10762 (and dirp (cdr (assoc 'directory apps)))
10763 ; first, try matching against apps-dlink
10764 ; if we get a match here, store the match data for later
10765 (let ((match (assoc-default dlink apps-dlink
10766 'string-match)))
10767 (if match
10768 (progn (setq link-match-data (match-data))
10769 match)
10770 (progn (setq in-emacs (or in-emacs line search))
10771 nil))) ; if we have no match in apps-dlink,
10772 ; always open the file in emacs if line or search
10773 ; is given (for backwards compatibility)
10774 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10775 'string-match)
10776 (cdr (assoc ext apps))
10777 (cdr (assoc t apps))))))
10778 (when (eq cmd 'system)
10779 (setq cmd (cdr (assoc 'system apps))))
10780 (when (eq cmd 'default)
10781 (setq cmd (cdr (assoc t apps))))
10782 (when (eq cmd 'mailcap)
10783 (require 'mailcap)
10784 (mailcap-parse-mailcaps)
10785 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10786 (command (mailcap-mime-info mime-type)))
10787 (if (stringp command)
10788 (setq cmd command)
10789 (setq cmd 'emacs))))
10790 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10791 (not (file-exists-p file))
10792 (not org-open-non-existing-files))
10793 (error "No such file: %s" file))
10794 (cond
10795 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10796 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10797 (while (string-match "['\"]%s['\"]" cmd)
10798 (setq cmd (replace-match "%s" t t cmd)))
10799 (while (string-match "%s" cmd)
10800 (setq cmd (replace-match
10801 (save-match-data
10802 (shell-quote-argument
10803 (convert-standard-filename file)))
10804 t t cmd)))
10806 ;; Replace "%1", "%2" etc. in command with group matches from regex
10807 (save-match-data
10808 (let ((match-index 1)
10809 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10810 (set-match-data link-match-data)
10811 (while (<= match-index number-of-groups)
10812 (let ((regex (concat "%" (number-to-string match-index)))
10813 (replace-with (match-string match-index dlink)))
10814 (while (string-match regex cmd)
10815 (setq cmd (replace-match replace-with t t cmd))))
10816 (setq match-index (+ match-index 1)))))
10818 (save-window-excursion
10819 (message "Running %s...done" cmd)
10820 (start-process-shell-command cmd nil cmd)
10821 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10822 ((or (stringp cmd)
10823 (eq cmd 'emacs))
10824 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10825 (widen)
10826 (if line (org-goto-line line)
10827 (if search (org-link-search search))))
10828 ((consp cmd)
10829 (let ((file (convert-standard-filename file)))
10830 (save-match-data
10831 (set-match-data link-match-data)
10832 (eval cmd))))
10833 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10834 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10835 (or (not (equal old-buffer (current-buffer)))
10836 (not (equal old-pos (point))))
10837 (org-mark-ring-push old-pos old-buffer))))
10839 (defun org-file-apps-entry-match-against-dlink-p (entry)
10840 "This function returns non-nil if `entry' uses a regular
10841 expression which should be matched against the whole link by
10842 org-open-file.
10844 It assumes that is the case when the entry uses a regular
10845 expression which has at least one grouping construct and the
10846 action is either a lisp form or a command string containing
10847 '%1', i.e. using at least one subexpression match as a
10848 parameter."
10849 (let ((selector (car entry))
10850 (action (cdr entry)))
10851 (if (stringp selector)
10852 (and (> (regexp-opt-depth selector) 0)
10853 (or (and (stringp action)
10854 (string-match "%[0-9]" action))
10855 (consp action)))
10856 nil)))
10858 (defun org-default-apps ()
10859 "Return the default applications for this operating system."
10860 (cond
10861 ((eq system-type 'darwin)
10862 org-file-apps-defaults-macosx)
10863 ((eq system-type 'windows-nt)
10864 org-file-apps-defaults-windowsnt)
10865 (t org-file-apps-defaults-gnu)))
10867 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10868 "Convert extensions to regular expressions in the cars of LIST.
10869 Also, weed out any non-string entries, because the return value is used
10870 only for regexp matching.
10871 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10872 point to the symbol `emacs', indicating that the file should
10873 be opened in Emacs."
10874 (append
10875 (delq nil
10876 (mapcar (lambda (x)
10877 (if (not (stringp (car x)))
10879 (if (string-match "\\W" (car x))
10881 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10882 list))
10883 (if add-auto-mode
10884 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10886 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10887 (defun org-file-remote-p (file)
10888 "Test whether FILE specifies a location on a remote system.
10889 Return non-nil if the location is indeed remote.
10891 For example, the filename \"/user@host:/foo\" specifies a location
10892 on the system \"/user@host:\"."
10893 (cond ((fboundp 'file-remote-p)
10894 (file-remote-p file))
10895 ((fboundp 'tramp-handle-file-remote-p)
10896 (tramp-handle-file-remote-p file))
10897 ((and (boundp 'ange-ftp-name-format)
10898 (string-match (car ange-ftp-name-format) file))
10899 t)))
10902 ;;;; Refiling
10904 (defun org-get-org-file ()
10905 "Read a filename, with default directory `org-directory'."
10906 (let ((default (or org-default-notes-file remember-data-file)))
10907 (read-file-name (format "File name [%s]: " default)
10908 (file-name-as-directory org-directory)
10909 default)))
10911 (defun org-notes-order-reversed-p ()
10912 "Check if the current file should receive notes in reversed order."
10913 (cond
10914 ((not org-reverse-note-order) nil)
10915 ((eq t org-reverse-note-order) t)
10916 ((not (listp org-reverse-note-order)) nil)
10917 (t (catch 'exit
10918 (let ((all org-reverse-note-order)
10919 entry)
10920 (while (setq entry (pop all))
10921 (if (string-match (car entry) buffer-file-name)
10922 (throw 'exit (cdr entry))))
10923 nil)))))
10925 (defvar org-refile-target-table nil
10926 "The list of refile targets, created by `org-refile'.")
10928 (defvar org-agenda-new-buffers nil
10929 "Buffers created to visit agenda files.")
10931 (defvar org-refile-cache nil
10932 "Cache for refile targets.")
10934 (defvar org-refile-markers nil
10935 "All the markers used for caching refile locations.")
10937 (defun org-refile-marker (pos)
10938 "Get a new refile marker, but only if caching is in use."
10939 (if (not org-refile-use-cache)
10941 (let ((m (make-marker)))
10942 (move-marker m pos)
10943 (push m org-refile-markers)
10944 m)))
10946 (defun org-refile-cache-clear ()
10947 "Clear the refile cache and disable all the markers."
10948 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10949 (setq org-refile-markers nil)
10950 (setq org-refile-cache nil)
10951 (message "Refile cache has been cleared"))
10953 (defun org-refile-cache-check-set (set)
10954 "Check if all the markers in the cache still have live buffers."
10955 (let (marker)
10956 (catch 'exit
10957 (while (and set (setq marker (nth 3 (pop set))))
10958 ;; if org-refile-use-outline-path is 'file, marker may be nil
10959 (when (and marker (null (marker-buffer marker)))
10960 (message "not found") (sit-for 3)
10961 (throw 'exit nil)))
10962 t)))
10964 (defun org-refile-cache-put (set &rest identifiers)
10965 "Push the refile targets SET into the cache, under IDENTIFIERS."
10966 (let* ((key (sha1 (prin1-to-string identifiers)))
10967 (entry (assoc key org-refile-cache)))
10968 (if entry
10969 (setcdr entry set)
10970 (push (cons key set) org-refile-cache))))
10972 (defun org-refile-cache-get (&rest identifiers)
10973 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10974 (cond
10975 ((not org-refile-cache) nil)
10976 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10978 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10979 org-refile-cache))))
10980 (and set (org-refile-cache-check-set set) set)))))
10982 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10983 "Produce a table with refile targets."
10984 (let ((case-fold-search nil)
10985 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10986 (entries (or org-refile-targets '((nil . (:level . 1)))))
10987 targets tgs txt re files f desc descre fast-path-p level pos0)
10988 (message "Getting targets...")
10989 (with-current-buffer (or default-buffer (current-buffer))
10990 (while (setq entry (pop entries))
10991 (setq files (car entry) desc (cdr entry))
10992 (setq fast-path-p nil)
10993 (cond
10994 ((null files) (setq files (list (current-buffer))))
10995 ((eq files 'org-agenda-files)
10996 (setq files (org-agenda-files 'unrestricted)))
10997 ((and (symbolp files) (fboundp files))
10998 (setq files (funcall files)))
10999 ((and (symbolp files) (boundp files))
11000 (setq files (symbol-value files))))
11001 (if (stringp files) (setq files (list files)))
11002 (cond
11003 ((eq (car desc) :tag)
11004 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11005 ((eq (car desc) :todo)
11006 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11007 ((eq (car desc) :regexp)
11008 (setq descre (cdr desc)))
11009 ((eq (car desc) :level)
11010 (setq descre (concat "^\\*\\{" (number-to-string
11011 (if org-odd-levels-only
11012 (1- (* 2 (cdr desc)))
11013 (cdr desc)))
11014 "\\}[ \t]")))
11015 ((eq (car desc) :maxlevel)
11016 (setq fast-path-p t)
11017 (setq descre (concat "^\\*\\{1," (number-to-string
11018 (if org-odd-levels-only
11019 (1- (* 2 (cdr desc)))
11020 (cdr desc)))
11021 "\\}[ \t]")))
11022 (t (error "Bad refiling target description %s" desc)))
11023 (while (setq f (pop files))
11024 (with-current-buffer
11025 (if (bufferp f) f (org-get-agenda-file-buffer f))
11027 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11028 (progn
11029 (if (bufferp f) (setq f (buffer-file-name
11030 (buffer-base-buffer f))))
11031 (setq f (and f (expand-file-name f)))
11032 (if (eq org-refile-use-outline-path 'file)
11033 (push (list (file-name-nondirectory f) f nil nil) tgs))
11034 (save-excursion
11035 (save-restriction
11036 (widen)
11037 (goto-char (point-min))
11038 (while (re-search-forward descre nil t)
11039 (goto-char (setq pos0 (point-at-bol)))
11040 (catch 'next
11041 (when org-refile-target-verify-function
11042 (save-match-data
11043 (or (funcall org-refile-target-verify-function)
11044 (throw 'next t))))
11045 (when (and (looking-at org-complex-heading-regexp)
11046 (not (member (match-string 4) excluded-entries))
11047 (match-string 4))
11048 (setq level (org-reduced-level
11049 (- (match-end 1) (match-beginning 1)))
11050 txt (org-link-display-format (match-string 4))
11051 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11052 re (format org-complex-heading-regexp-format
11053 (regexp-quote (match-string 4))))
11054 (when org-refile-use-outline-path
11055 (setq txt (mapconcat
11056 'org-protect-slash
11057 (append
11058 (if (eq org-refile-use-outline-path
11059 'file)
11060 (list (file-name-nondirectory
11061 (buffer-file-name
11062 (buffer-base-buffer))))
11063 (if (eq org-refile-use-outline-path
11064 'full-file-path)
11065 (list (buffer-file-name
11066 (buffer-base-buffer)))))
11067 (org-get-outline-path fast-path-p
11068 level txt)
11069 (list txt))
11070 "/")))
11071 (push (list txt f re (org-refile-marker (point)))
11072 tgs)))
11073 (when (= (point) pos0)
11074 ;; verification function has not moved point
11075 (goto-char (point-at-eol))))))))
11076 (when org-refile-use-cache
11077 (org-refile-cache-put tgs (buffer-file-name) descre))
11078 (setq targets (append tgs targets))
11079 ))))
11080 (message "Getting targets...done")
11081 (nreverse targets)))
11083 (defun org-protect-slash (s)
11084 (while (string-match "/" s)
11085 (setq s (replace-match "\\" t t s)))
11088 (defvar org-olpa (make-vector 20 nil))
11090 (defun org-get-outline-path (&optional fastp level heading)
11091 "Return the outline path to the current entry, as a list.
11093 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11094 routine which makes outline path derivations for an entire file,
11095 avoiding backtracing. Refile target collection makes use of that."
11096 (if fastp
11097 (progn
11098 (if (> level 19)
11099 (error "Outline path failure, more than 19 levels"))
11100 (loop for i from level upto 19 do
11101 (aset org-olpa i nil))
11102 (prog1
11103 (delq nil (append org-olpa nil))
11104 (aset org-olpa level heading)))
11105 (let (rtn case-fold-search)
11106 (save-excursion
11107 (save-restriction
11108 (widen)
11109 (while (org-up-heading-safe)
11110 (when (looking-at org-complex-heading-regexp)
11111 (push (org-match-string-no-properties 4) rtn)))
11112 rtn)))))
11114 (defun org-format-outline-path (path &optional width prefix separator)
11115 "Format the outline path PATH for display.
11116 WIDTH is the maximum number of characters that is available.
11117 PREFIX is a prefix to be included in the returned string,
11118 such as the file name.
11119 SEPARATOR is inserted between the different parts of the path,
11120 the default is \"/\"."
11121 (setq width (or width 79))
11122 (if prefix (setq width (- width (length prefix))))
11123 (if (not path)
11124 (or prefix "")
11125 (let* ((nsteps (length path))
11126 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11127 (maxwidth (if (<= total-width width)
11128 10000 ;; everything fits
11129 ;; we need to shorten the level headings
11130 (/ (- width nsteps) nsteps)))
11131 (org-odd-levels-only nil)
11132 (n 0)
11133 (total (1+ (length prefix))))
11134 (setq maxwidth (max maxwidth 10))
11135 (concat prefix
11136 (if prefix (or separator "/"))
11137 (mapconcat
11138 (lambda (h)
11139 (setq n (1+ n))
11140 (if (and (= n nsteps) (< maxwidth 10000))
11141 (setq maxwidth (- total-width total)))
11142 (if (< (length h) maxwidth)
11143 (progn (setq total (+ total (length h) 1)) h)
11144 (setq h (substring h 0 (- maxwidth 2))
11145 total (+ total maxwidth 1))
11146 (if (string-match "[ \t]+\\'" h)
11147 (setq h (substring h 0 (match-beginning 0))))
11148 (setq h (concat h "..")))
11149 (org-add-props h nil 'face
11150 (nth (% (1- n) org-n-level-faces)
11151 org-level-faces))
11153 path (or separator "/"))))))
11155 (defun org-display-outline-path (&optional file current separator just-return-string)
11156 "Display the current outline path in the echo area.
11158 If FILE is non-nil, prepend the output with the file name.
11159 If CURRENT is non-nil, append the current heading to the output.
11160 SEPARATOR is passed through to `org-format-outline-path'. It separates
11161 the different parts of the path and defaults to \"/\".
11162 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11163 (interactive "P")
11164 (let* (case-fold-search
11165 message-log-max ; Don't populate the *Messages* buffer
11166 (bfn (buffer-file-name (buffer-base-buffer)))
11167 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11168 res)
11169 (if current (setq path (append path
11170 (save-excursion
11171 (org-back-to-heading t)
11172 (if (looking-at org-complex-heading-regexp)
11173 (list (match-string 4)))))))
11174 (setq res
11175 (org-format-outline-path
11176 path
11177 (1- (frame-width))
11178 (and file bfn (concat (file-name-nondirectory bfn) separator))
11179 separator))
11180 (if just-return-string
11181 (org-no-properties res)
11182 (message "%s" res))))
11184 (defvar org-refile-history nil
11185 "History for refiling operations.")
11187 (defvar org-after-refile-insert-hook nil
11188 "Hook run after `org-refile' has inserted its stuff at the new location.
11189 Note that this is still *before* the stuff will be removed from
11190 the *old* location.")
11192 (defvar org-capture-last-stored-marker)
11193 (defvar org-refile-keep nil
11194 "Non-nil means `org-refile' will copy instead of refile.")
11196 (defun org-copy ()
11197 "Like `org-refile', but copy."
11198 (interactive)
11199 (let ((org-refile-keep t))
11200 (funcall 'org-refile nil nil nil "Copy")))
11202 (defun org-refile (&optional goto default-buffer rfloc msg)
11203 "Move the entry or entries at point to another heading.
11204 The list of target headings is compiled using the information in
11205 `org-refile-targets', which see.
11207 At the target location, the entry is filed as a subitem of the target
11208 heading. Depending on `org-reverse-note-order', the new subitem will
11209 either be the first or the last subitem.
11211 If there is an active region, all entries in that region will be moved.
11212 However, the region must fulfill the requirement that the first heading
11213 is the first one sets the top-level of the moved text - at most siblings
11214 below it are allowed.
11216 With prefix arg GOTO, the command will only visit the target location
11217 and not actually move anything.
11219 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11220 go to the location where the last refiling operation has put the subtree.
11221 With a prefix argument of `2', refile to the running clock.
11223 RFLOC can be a refile location obtained in a different way.
11225 MSG is a string to replace \"Refile\" in the default prompt with
11226 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11228 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11230 If you are using target caching (see `org-refile-use-cache'),
11231 you have to clear the target cache in order to find new targets.
11232 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11233 prefix argument (`C-u C-u C-u C-c C-w')."
11235 (interactive "P")
11236 (if (member goto '(0 (64)))
11237 (org-refile-cache-clear)
11238 (let* ((actionmsg (or msg "Refile"))
11239 (cbuf (current-buffer))
11240 (regionp (org-region-active-p))
11241 (region-start (and regionp (region-beginning)))
11242 (region-end (and regionp (region-end)))
11243 (region-length (and regionp (- region-end region-start)))
11244 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11245 pos it nbuf file re level reversed)
11246 (setq last-command nil)
11247 (when regionp
11248 (goto-char region-start)
11249 (or (bolp) (goto-char (point-at-bol)))
11250 (setq region-start (point))
11251 (unless (or (org-kill-is-subtree-p
11252 (buffer-substring region-start region-end))
11253 (prog1 org-refile-active-region-within-subtree
11254 (org-toggle-heading)))
11255 (error "The region is not a (sequence of) subtree(s)")))
11256 (if (equal goto '(16))
11257 (org-refile-goto-last-stored)
11258 (when (or
11259 (and (equal goto 2)
11260 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11261 (prog1
11262 (setq it (list (or org-clock-heading "running clock")
11263 (buffer-file-name
11264 (marker-buffer org-clock-hd-marker))
11266 (marker-position org-clock-hd-marker)))
11267 (setq goto nil)))
11268 (setq it (or rfloc
11269 (let (heading-text)
11270 (save-excursion
11271 (unless goto
11272 (org-back-to-heading t)
11273 (setq heading-text
11274 (nth 4 (org-heading-components))))
11276 (org-refile-get-location
11277 (cond (goto "Goto")
11278 (regionp (concat actionmsg " region to"))
11279 (t (concat actionmsg " subtree \""
11280 heading-text "\" to")))
11281 default-buffer
11282 (and (not (equal '(4) goto))
11283 org-refile-allow-creating-parent-nodes)
11284 goto))))))
11285 (setq file (nth 1 it)
11286 re (nth 2 it)
11287 pos (nth 3 it))
11288 (if (and (not goto)
11290 (equal (buffer-file-name) file)
11291 (if regionp
11292 (and (>= pos region-start)
11293 (<= pos region-end))
11294 (and (>= pos (point))
11295 (< pos (save-excursion
11296 (org-end-of-subtree t t))))))
11297 (error "Cannot refile to position inside the tree or region"))
11299 (setq nbuf (or (find-buffer-visiting file)
11300 (find-file-noselect file)))
11301 (if goto
11302 (progn
11303 (org-pop-to-buffer-same-window nbuf)
11304 (goto-char pos)
11305 (org-show-context 'org-goto))
11306 (if regionp
11307 (progn
11308 (org-kill-new (buffer-substring region-start region-end))
11309 (org-save-markers-in-region region-start region-end))
11310 (org-copy-subtree 1 nil t))
11311 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11312 (find-file-noselect file)))
11313 (setq reversed (org-notes-order-reversed-p))
11314 (save-excursion
11315 (save-restriction
11316 (widen)
11317 (if pos
11318 (progn
11319 (goto-char pos)
11320 (looking-at org-outline-regexp)
11321 (setq level (org-get-valid-level (funcall outline-level) 1))
11322 (goto-char
11323 (if reversed
11324 (or (outline-next-heading) (point-max))
11325 (or (save-excursion (org-get-next-sibling))
11326 (org-end-of-subtree t t)
11327 (point-max)))))
11328 (setq level 1)
11329 (if (not reversed)
11330 (goto-char (point-max))
11331 (goto-char (point-min))
11332 (or (outline-next-heading) (goto-char (point-max)))))
11333 (if (not (bolp)) (newline))
11334 (org-paste-subtree level)
11335 (when org-log-refile
11336 (org-add-log-setup 'refile nil nil 'findpos
11337 org-log-refile)
11338 (unless (eq org-log-refile 'note)
11339 (save-excursion (org-add-log-note))))
11340 (and org-auto-align-tags
11341 (let ((org-loop-over-headlines-in-active-region nil))
11342 (org-set-tags nil t)))
11343 (with-demoted-errors
11344 (bookmark-set "org-refile-last-stored"))
11345 ;; If we are refiling for capture, make sure that the
11346 ;; last-capture pointers point here
11347 (when (org-bound-and-true-p org-refile-for-capture)
11348 (with-demoted-errors
11349 (bookmark-set "org-capture-last-stored-marker"))
11350 (move-marker org-capture-last-stored-marker (point)))
11351 (if (fboundp 'deactivate-mark) (deactivate-mark))
11352 (run-hooks 'org-after-refile-insert-hook))))
11353 (unless org-refile-keep
11354 (if regionp
11355 (delete-region (point) (+ (point) region-length))
11356 (org-cut-subtree)))
11357 (when (featurep 'org-inlinetask)
11358 (org-inlinetask-remove-END-maybe))
11359 (setq org-markers-to-move nil)
11360 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11362 (defun org-refile-goto-last-stored ()
11363 "Go to the location where the last refile was stored."
11364 (interactive)
11365 (bookmark-jump "org-refile-last-stored")
11366 (message "This is the location of the last refile"))
11368 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11369 no-exclude)
11370 "Prompt the user for a refile location, using PROMPT.
11371 PROMPT should not be suffixed with a colon and a space, because
11372 this function appends the default value from
11373 `org-refile-history' automatically, if that is not empty.
11374 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11375 this is used for the GOTO interface."
11376 (let ((org-refile-targets org-refile-targets)
11377 (org-refile-use-outline-path org-refile-use-outline-path)
11378 excluded-entries)
11379 (when (and (derived-mode-p 'org-mode)
11380 (not org-refile-use-cache)
11381 (not no-exclude))
11382 (org-map-tree
11383 (lambda()
11384 (setq excluded-entries
11385 (append excluded-entries (list (org-get-heading t t)))))))
11386 (setq org-refile-target-table
11387 (org-refile-get-targets default-buffer excluded-entries)))
11388 (unless org-refile-target-table
11389 (error "No refile targets"))
11390 (let* ((cbuf (current-buffer))
11391 (partial-completion-mode nil)
11392 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11393 (cfunc (if (and org-refile-use-outline-path
11394 org-outline-path-complete-in-steps)
11395 'org-olpath-completing-read
11396 'org-icompleting-read))
11397 (extra (if org-refile-use-outline-path "/" ""))
11398 (cbnex (concat (buffer-name) extra))
11399 (filename (and cfn (expand-file-name cfn)))
11400 (tbl (mapcar
11401 (lambda (x)
11402 (if (and (not (member org-refile-use-outline-path
11403 '(file full-file-path)))
11404 (not (equal filename (nth 1 x))))
11405 (cons (concat (car x) extra " ("
11406 (file-name-nondirectory (nth 1 x)) ")")
11407 (cdr x))
11408 (cons (concat (car x) extra) (cdr x))))
11409 org-refile-target-table))
11410 (completion-ignore-case t)
11411 cdef
11412 (prompt (concat prompt
11413 (or (and (car org-refile-history)
11414 (concat " (default " (car org-refile-history) ")"))
11415 (and (assoc cbnex tbl) (setq cdef cbnex)
11416 (concat " (default " cbnex ")"))) ": "))
11417 pa answ parent-target child parent old-hist)
11418 (setq old-hist org-refile-history)
11419 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11420 nil 'org-refile-history (or cdef (car org-refile-history))))
11421 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11422 (org-refile-check-position pa)
11423 (if pa
11424 (progn
11425 (when (or (not org-refile-history)
11426 (not (eq old-hist org-refile-history))
11427 (not (equal (car pa) (car org-refile-history))))
11428 (setq org-refile-history
11429 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11430 org-refile-history
11431 (cdr org-refile-history))))
11432 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11433 (pop org-refile-history)))
11435 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11436 (progn
11437 (setq parent (match-string 1 answ)
11438 child (match-string 2 answ))
11439 (setq parent-target (or (assoc parent tbl)
11440 (assoc (concat parent "/") tbl)))
11441 (when (and parent-target
11442 (or (eq new-nodes t)
11443 (and (eq new-nodes 'confirm)
11444 (y-or-n-p (format "Create new node \"%s\"? "
11445 child)))))
11446 (org-refile-new-child parent-target child)))
11447 (error "Invalid target location")))))
11449 (declare-function org-string-nw-p "org-macs" (s))
11450 (defun org-refile-check-position (refile-pointer)
11451 "Check if the refile pointer matches the headline to which it points."
11452 (let* ((file (nth 1 refile-pointer))
11453 (re (nth 2 refile-pointer))
11454 (pos (nth 3 refile-pointer))
11455 buffer)
11456 (if (and (not (markerp pos)) (not file))
11457 (error "Please save the buffer to a file before refiling")
11458 (when (org-string-nw-p re)
11459 (setq buffer (if (markerp pos)
11460 (marker-buffer pos)
11461 (or (find-buffer-visiting file)
11462 (find-file-noselect file))))
11463 (with-current-buffer buffer
11464 (save-excursion
11465 (save-restriction
11466 (widen)
11467 (goto-char pos)
11468 (beginning-of-line 1)
11469 (unless (org-looking-at-p re)
11470 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11472 (defun org-refile-new-child (parent-target child)
11473 "Use refile target PARENT-TARGET to add new CHILD below it."
11474 (unless parent-target
11475 (error "Cannot find parent for new node"))
11476 (let ((file (nth 1 parent-target))
11477 (pos (nth 3 parent-target))
11478 level)
11479 (with-current-buffer (or (find-buffer-visiting file)
11480 (find-file-noselect file))
11481 (save-excursion
11482 (save-restriction
11483 (widen)
11484 (if pos
11485 (goto-char pos)
11486 (goto-char (point-max))
11487 (if (not (bolp)) (newline)))
11488 (when (looking-at org-outline-regexp)
11489 (setq level (funcall outline-level))
11490 (org-end-of-subtree t t))
11491 (org-back-over-empty-lines)
11492 (insert "\n" (make-string
11493 (if pos (org-get-valid-level level 1) 1) ?*)
11494 " " child "\n")
11495 (beginning-of-line 0)
11496 (list (concat (car parent-target) "/" child) file "" (point)))))))
11498 (defun org-olpath-completing-read (prompt collection &rest args)
11499 "Read an outline path like a file name."
11500 (let ((thetable collection)
11501 (org-completion-use-ido nil) ; does not work with ido.
11502 (org-completion-use-iswitchb nil)) ; or iswitchb
11503 (apply
11504 'org-icompleting-read prompt
11505 (lambda (string predicate &optional flag)
11506 (let (rtn r f (l (length string)))
11507 (cond
11508 ((eq flag nil)
11509 ;; try completion
11510 (try-completion string thetable))
11511 ((eq flag t)
11512 ;; all-completions
11513 (setq rtn (all-completions string thetable predicate))
11514 (mapcar
11515 (lambda (x)
11516 (setq r (substring x l))
11517 (if (string-match " ([^)]*)$" x)
11518 (setq f (match-string 0 x))
11519 (setq f ""))
11520 (if (string-match "/" r)
11521 (concat string (substring r 0 (match-end 0)) f)
11523 rtn))
11524 ((eq flag 'lambda)
11525 ;; exact match?
11526 (assoc string thetable)))))
11527 args)))
11529 ;;;; Dynamic blocks
11531 (defun org-find-dblock (name)
11532 "Find the first dynamic block with name NAME in the buffer.
11533 If not found, stay at current position and return nil."
11534 (let ((case-fold-search t) pos)
11535 (save-excursion
11536 (goto-char (point-min))
11537 (setq pos (and (re-search-forward
11538 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11539 (match-beginning 0))))
11540 (if pos (goto-char pos))
11541 pos))
11543 (defconst org-dblock-start-re
11544 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11545 "Matches the start line of a dynamic block, with parameters.")
11547 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11548 "Matches the end of a dynamic block.")
11550 (defun org-create-dblock (plist)
11551 "Create a dynamic block section, with parameters taken from PLIST.
11552 PLIST must contain a :name entry which is used as name of the block."
11553 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11554 (end-of-line 1)
11555 (newline))
11556 (let ((col (current-column))
11557 (name (plist-get plist :name)))
11558 (insert "#+BEGIN: " name)
11559 (while plist
11560 (if (eq (car plist) :name)
11561 (setq plist (cddr plist))
11562 (insert " " (prin1-to-string (pop plist)))))
11563 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11564 (beginning-of-line -2)))
11566 (defun org-prepare-dblock ()
11567 "Prepare dynamic block for refresh.
11568 This empties the block, puts the cursor at the insert position and returns
11569 the property list including an extra property :name with the block name."
11570 (unless (looking-at org-dblock-start-re)
11571 (error "Not at a dynamic block"))
11572 (let* ((begdel (1+ (match-end 0)))
11573 (name (org-no-properties (match-string 1)))
11574 (params (append (list :name name)
11575 (read (concat "(" (match-string 3) ")")))))
11576 (save-excursion
11577 (beginning-of-line 1)
11578 (skip-chars-forward " \t")
11579 (setq params (plist-put params :indentation-column (current-column))))
11580 (unless (re-search-forward org-dblock-end-re nil t)
11581 (error "Dynamic block not terminated"))
11582 (setq params
11583 (append params
11584 (list :content (buffer-substring
11585 begdel (match-beginning 0)))))
11586 (delete-region begdel (match-beginning 0))
11587 (goto-char begdel)
11588 (open-line 1)
11589 params))
11591 (defun org-map-dblocks (&optional command)
11592 "Apply COMMAND to all dynamic blocks in the current buffer.
11593 If COMMAND is not given, use `org-update-dblock'."
11594 (let ((cmd (or command 'org-update-dblock)))
11595 (save-excursion
11596 (goto-char (point-min))
11597 (while (re-search-forward org-dblock-start-re nil t)
11598 (goto-char (match-beginning 0))
11599 (save-excursion
11600 (condition-case nil
11601 (funcall cmd)
11602 (error (message "Error during update of dynamic block"))))
11603 (unless (re-search-forward org-dblock-end-re nil t)
11604 (error "Dynamic block not terminated"))))))
11606 (defun org-dblock-update (&optional arg)
11607 "User command for updating dynamic blocks.
11608 Update the dynamic block at point. With prefix ARG, update all dynamic
11609 blocks in the buffer."
11610 (interactive "P")
11611 (if arg
11612 (org-update-all-dblocks)
11613 (or (looking-at org-dblock-start-re)
11614 (org-beginning-of-dblock))
11615 (org-update-dblock)))
11617 (defun org-update-dblock ()
11618 "Update the dynamic block at point.
11619 This means to empty the block, parse for parameters and then call
11620 the correct writing function."
11621 (interactive)
11622 (save-window-excursion
11623 (let* ((pos (point))
11624 (line (org-current-line))
11625 (params (org-prepare-dblock))
11626 (name (plist-get params :name))
11627 (indent (plist-get params :indentation-column))
11628 (cmd (intern (concat "org-dblock-write:" name))))
11629 (message "Updating dynamic block `%s' at line %d..." name line)
11630 (funcall cmd params)
11631 (message "Updating dynamic block `%s' at line %d...done" name line)
11632 (goto-char pos)
11633 (when (and indent (> indent 0))
11634 (setq indent (make-string indent ?\ ))
11635 (save-excursion
11636 (org-beginning-of-dblock)
11637 (forward-line 1)
11638 (while (not (looking-at org-dblock-end-re))
11639 (insert indent)
11640 (beginning-of-line 2))
11641 (when (looking-at org-dblock-end-re)
11642 (and (looking-at "[ \t]+")
11643 (replace-match ""))
11644 (insert indent)))))))
11646 (defun org-beginning-of-dblock ()
11647 "Find the beginning of the dynamic block at point.
11648 Error if there is no such block at point."
11649 (let ((pos (point))
11650 beg)
11651 (end-of-line 1)
11652 (if (and (re-search-backward org-dblock-start-re nil t)
11653 (setq beg (match-beginning 0))
11654 (re-search-forward org-dblock-end-re nil t)
11655 (> (match-end 0) pos))
11656 (goto-char beg)
11657 (goto-char pos)
11658 (error "Not in a dynamic block"))))
11660 (defun org-update-all-dblocks ()
11661 "Update all dynamic blocks in the buffer.
11662 This function can be used in a hook."
11663 (interactive)
11664 (when (derived-mode-p 'org-mode)
11665 (org-map-dblocks 'org-update-dblock)))
11668 ;;;; Completion
11670 (defun org-get-export-keywords ()
11671 "Return a list of all currently understood export keywords.
11672 Export keywords include options, block names, attributes and
11673 keywords relative to each registered export back-end."
11674 (delq nil
11675 (let (keywords)
11676 (mapc
11677 (lambda (back-end)
11678 (let ((props (cdr back-end)))
11679 ;; Back-end name (for keywords, like #+LATEX:)
11680 (push (upcase (symbol-name (car back-end))) keywords)
11681 ;; Back-end options.
11682 (mapc (lambda (option) (push (cadr option) keywords))
11683 (plist-get (cdr back-end) :options-alist))))
11684 (org-bound-and-true-p org-export-registered-backends))
11685 keywords)))
11687 (defconst org-options-keywords
11688 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11689 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11690 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11691 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11692 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11694 (defcustom org-structure-template-alist
11695 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11696 "<src lang=\"?\">\n\n</src>")
11697 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11698 "<example>\n?\n</example>")
11699 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11700 "<quote>\n?\n</quote>")
11701 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11702 "<verse>\n?\n</verse>")
11703 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11704 "<verbatim>\n?\n</verbatim>")
11705 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11706 "<center>\n?\n</center>")
11707 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11708 "<literal style=\"latex\">\n?\n</literal>")
11709 ("L" "#+LaTeX: "
11710 "<literal style=\"latex\">?</literal>")
11711 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11712 "<literal style=\"html\">\n?\n</literal>")
11713 ("H" "#+HTML: "
11714 "<literal style=\"html\">?</literal>")
11715 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11716 ("A" "#+ASCII: ")
11717 ("i" "#+INDEX: ?"
11718 "#+INDEX: ?")
11719 ("I" "#+INCLUDE: %file ?"
11720 "<include file=%file markup=\"?\">"))
11721 "Structure completion elements.
11722 This is a list of abbreviation keys and values. The value gets inserted
11723 if you type `<' followed by the key and then press the completion key,
11724 usually `M-TAB'. %file will be replaced by a file name after prompting
11725 for the file using completion. The cursor will be placed at the position
11726 of the `?` in the template.
11727 There are two templates for each key, the first uses the original Org syntax,
11728 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11729 the default when the /org-mtags.el/ module has been loaded. See also the
11730 variable `org-mtags-prefer-muse-templates'."
11731 :group 'org-completion
11732 :type '(repeat
11733 (string :tag "Key")
11734 (string :tag "Template")
11735 (string :tag "Muse Template")))
11737 (defun org-try-structure-completion ()
11738 "Try to complete a structure template before point.
11739 This looks for strings like \"<e\" on an otherwise empty line and
11740 expands them."
11741 (let ((l (buffer-substring (point-at-bol) (point)))
11743 (when (and (looking-at "[ \t]*$")
11744 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11745 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11746 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11747 (match-beginning 1)) a)
11748 t)))
11750 (defun org-complete-expand-structure-template (start cell)
11751 "Expand a structure template."
11752 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11753 (rpl (nth (if musep 2 1) cell))
11754 (ind ""))
11755 (delete-region start (point))
11756 (when (string-match "\\`#\\+" rpl)
11757 (cond
11758 ((bolp))
11759 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11760 (setq ind (buffer-substring (point-at-bol) (point))))
11761 (t (newline))))
11762 (setq start (point))
11763 (if (string-match "%file" rpl)
11764 (setq rpl (replace-match
11765 (concat
11766 "\""
11767 (save-match-data
11768 (abbreviate-file-name (read-file-name "Include file: ")))
11769 "\"")
11770 t t rpl)))
11771 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11772 (concat "\n" ind)))
11773 (insert rpl)
11774 (if (re-search-backward "\\?" start t) (delete-char 1))))
11776 ;;;; TODO, DEADLINE, Comments
11778 (defun org-toggle-comment ()
11779 "Change the COMMENT state of an entry."
11780 (interactive)
11781 (save-excursion
11782 (org-back-to-heading)
11783 (let (case-fold-search)
11784 (cond
11785 ((looking-at (format org-heading-keyword-regexp-format
11786 org-comment-string))
11787 (goto-char (match-end 1))
11788 (looking-at (concat " +" org-comment-string))
11789 (replace-match "" t t)
11790 (when (eolp) (insert " ")))
11791 ((looking-at org-outline-regexp)
11792 (goto-char (match-end 0))
11793 (insert org-comment-string " "))))))
11795 (defvar org-last-todo-state-is-todo nil
11796 "This is non-nil when the last TODO state change led to a TODO state.
11797 If the last change removed the TODO tag or switched to DONE, then
11798 this is nil.")
11800 (defvar org-setting-tags nil) ; dynamically skipped
11802 (defvar org-todo-setup-filter-hook nil
11803 "Hook for functions that pre-filter todo specs.
11804 Each function takes a todo spec and returns either nil or the spec
11805 transformed into canonical form." )
11807 (defvar org-todo-get-default-hook nil
11808 "Hook for functions that get a default item for todo.
11809 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11810 nil or a string to be used for the todo mark." )
11812 (defvar org-agenda-headline-snapshot-before-repeat)
11814 (defun org-current-effective-time ()
11815 "Return current time adjusted for `org-extend-today-until' variable."
11816 (let* ((ct (org-current-time))
11817 (dct (decode-time ct))
11818 (ct1
11819 (cond
11820 (org-use-last-clock-out-time-as-effective-time
11821 (or (org-clock-get-last-clock-out-time) ct))
11822 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11823 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11824 (t ct))))
11825 ct1))
11827 (defun org-todo-yesterday (&optional arg)
11828 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11829 (interactive "P")
11830 (if (eq major-mode 'org-agenda-mode)
11831 (apply 'org-agenda-todo-yesterday arg)
11832 (let* ((hour (third (decode-time
11833 (org-current-time))))
11834 (org-extend-today-until (1+ hour)))
11835 (org-todo arg))))
11837 (defvar org-block-entry-blocking ""
11838 "First entry preventing the TODO state change.")
11840 (defun org-todo (&optional arg)
11841 "Change the TODO state of an item.
11842 The state of an item is given by a keyword at the start of the heading,
11843 like
11844 *** TODO Write paper
11845 *** DONE Call mom
11847 The different keywords are specified in the variable `org-todo-keywords'.
11848 By default the available states are \"TODO\" and \"DONE\".
11849 So for this example: when the item starts with TODO, it is changed to DONE.
11850 When it starts with DONE, the DONE is removed. And when neither TODO nor
11851 DONE are present, add TODO at the beginning of the heading.
11853 With \\[universal-argument] prefix arg, use completion to determine the new \
11854 state.
11855 With numeric prefix arg, switch to that state.
11856 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11857 keywords (nextset).
11858 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11859 With a numeric prefix arg of 0, inhibit note taking for the change.
11861 For calling through lisp, arg is also interpreted in the following way:
11862 'none -> empty state
11863 \"\"(empty string) -> switch to empty state
11864 'done -> switch to DONE
11865 'nextset -> switch to the next set of keywords
11866 'previousset -> switch to the previous set of keywords
11867 \"WAITING\" -> switch to the specified keyword, but only if it
11868 really is a member of `org-todo-keywords'."
11869 (interactive "P")
11870 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11871 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11872 'region-start-level 'region))
11873 org-loop-over-headlines-in-active-region)
11874 (org-map-entries
11875 `(org-todo ,arg)
11876 org-loop-over-headlines-in-active-region
11877 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11878 (if (equal arg '(16)) (setq arg 'nextset))
11879 (let ((org-blocker-hook org-blocker-hook)
11880 commentp
11881 case-fold-search)
11882 (when (equal arg '(64))
11883 (setq arg nil org-blocker-hook nil))
11884 (when (and org-blocker-hook
11885 (or org-inhibit-blocking
11886 (org-entry-get nil "NOBLOCKING")))
11887 (setq org-blocker-hook nil))
11888 (save-excursion
11889 (catch 'exit
11890 (org-back-to-heading t)
11891 (when (looking-at (concat "^\\*+ " org-comment-string))
11892 (org-toggle-comment)
11893 (setq commentp t))
11894 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11895 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11896 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11897 (let* ((match-data (match-data))
11898 (startpos (point-at-bol))
11899 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11900 (org-log-done org-log-done)
11901 (org-log-repeat org-log-repeat)
11902 (org-todo-log-states org-todo-log-states)
11903 (org-inhibit-logging
11904 (if (equal arg 0)
11905 (progn (setq arg nil) 'note) org-inhibit-logging))
11906 (this (match-string 1))
11907 (hl-pos (match-beginning 0))
11908 (head (org-get-todo-sequence-head this))
11909 (ass (assoc head org-todo-kwd-alist))
11910 (interpret (nth 1 ass))
11911 (done-word (nth 3 ass))
11912 (final-done-word (nth 4 ass))
11913 (org-last-state (or this ""))
11914 (completion-ignore-case t)
11915 (member (member this org-todo-keywords-1))
11916 (tail (cdr member))
11917 (org-state (cond
11918 ((and org-todo-key-trigger
11919 (or (and (equal arg '(4))
11920 (eq org-use-fast-todo-selection 'prefix))
11921 (and (not arg) org-use-fast-todo-selection
11922 (not (eq org-use-fast-todo-selection
11923 'prefix)))))
11924 ;; Use fast selection
11925 (org-fast-todo-selection))
11926 ((and (equal arg '(4))
11927 (or (not org-use-fast-todo-selection)
11928 (not org-todo-key-trigger)))
11929 ;; Read a state with completion
11930 (org-icompleting-read
11931 "State: " (mapcar (lambda(x) (list x))
11932 org-todo-keywords-1)
11933 nil t))
11934 ((eq arg 'right)
11935 (if this
11936 (if tail (car tail) nil)
11937 (car org-todo-keywords-1)))
11938 ((eq arg 'left)
11939 (if (equal member org-todo-keywords-1)
11941 (if this
11942 (nth (- (length org-todo-keywords-1)
11943 (length tail) 2)
11944 org-todo-keywords-1)
11945 (org-last org-todo-keywords-1))))
11946 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11947 (setq arg nil))) ; hack to fall back to cycling
11948 (arg
11949 ;; user or caller requests a specific state
11950 (cond
11951 ((equal arg "") nil)
11952 ((eq arg 'none) nil)
11953 ((eq arg 'done) (or done-word (car org-done-keywords)))
11954 ((eq arg 'nextset)
11955 (or (car (cdr (member head org-todo-heads)))
11956 (car org-todo-heads)))
11957 ((eq arg 'previousset)
11958 (let ((org-todo-heads (reverse org-todo-heads)))
11959 (or (car (cdr (member head org-todo-heads)))
11960 (car org-todo-heads))))
11961 ((car (member arg org-todo-keywords-1)))
11962 ((stringp arg)
11963 (error "State `%s' not valid in this file" arg))
11964 ((nth (1- (prefix-numeric-value arg))
11965 org-todo-keywords-1))))
11966 ((null member) (or head (car org-todo-keywords-1)))
11967 ((equal this final-done-word) nil) ;; -> make empty
11968 ((null tail) nil) ;; -> first entry
11969 ((memq interpret '(type priority))
11970 (if (eq this-command last-command)
11971 (car tail)
11972 (if (> (length tail) 0)
11973 (or done-word (car org-done-keywords))
11974 nil)))
11976 (car tail))))
11977 (org-state (or
11978 (run-hook-with-args-until-success
11979 'org-todo-get-default-hook org-state org-last-state)
11980 org-state))
11981 (next (if org-state (concat " " org-state " ") " "))
11982 (change-plist (list :type 'todo-state-change :from this :to org-state
11983 :position startpos))
11984 dolog now-done-p)
11985 (when org-blocker-hook
11986 (setq org-last-todo-state-is-todo
11987 (not (member this org-done-keywords)))
11988 (unless (save-excursion
11989 (save-match-data
11990 (org-with-wide-buffer
11991 (run-hook-with-args-until-failure
11992 'org-blocker-hook change-plist))))
11993 (if (org-called-interactively-p 'interactive)
11994 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11995 this org-state org-block-entry-blocking)
11996 ;; fail silently
11997 (message "TODO state change from %s to %s blocked (by \"%s\")"
11998 this org-state org-block-entry-blocking)
11999 (throw 'exit nil))))
12000 (store-match-data match-data)
12001 (replace-match next t t)
12002 (unless (pos-visible-in-window-p hl-pos)
12003 (message "TODO state changed to %s" (org-trim next)))
12004 (unless head
12005 (setq head (org-get-todo-sequence-head org-state)
12006 ass (assoc head org-todo-kwd-alist)
12007 interpret (nth 1 ass)
12008 done-word (nth 3 ass)
12009 final-done-word (nth 4 ass)))
12010 (when (memq arg '(nextset previousset))
12011 (message "Keyword-Set %d/%d: %s"
12012 (- (length org-todo-sets) -1
12013 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12014 (length org-todo-sets)
12015 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12016 (setq org-last-todo-state-is-todo
12017 (not (member org-state org-done-keywords)))
12018 (setq now-done-p (and (member org-state org-done-keywords)
12019 (not (member this org-done-keywords))))
12020 (and logging (org-local-logging logging))
12021 (when (and (or org-todo-log-states org-log-done)
12022 (not (eq org-inhibit-logging t))
12023 (not (memq arg '(nextset previousset))))
12024 ;; we need to look at recording a time and note
12025 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12026 (nth 2 (assoc this org-todo-log-states))))
12027 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12028 (setq dolog 'time))
12029 (when (and org-state
12030 (member org-state org-not-done-keywords)
12031 (not (member this org-not-done-keywords)))
12032 ;; This is now a todo state and was not one before
12033 ;; If there was a CLOSED time stamp, get rid of it.
12034 (org-add-planning-info nil nil 'closed))
12035 (when (and now-done-p org-log-done)
12036 ;; It is now done, and it was not done before
12037 (org-add-planning-info 'closed (org-current-effective-time))
12038 (if (and (not dolog) (eq 'note org-log-done))
12039 (org-add-log-setup 'done org-state this 'findpos 'note)))
12040 (when (and org-state dolog)
12041 ;; This is a non-nil state, and we need to log it
12042 (org-add-log-setup 'state org-state this 'findpos dolog)))
12043 ;; Fixup tag positioning
12044 (org-todo-trigger-tag-changes org-state)
12045 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12046 (when org-provide-todo-statistics
12047 (org-update-parent-todo-statistics))
12048 (run-hooks 'org-after-todo-state-change-hook)
12049 (if (and arg (not (member org-state org-done-keywords)))
12050 (setq head (org-get-todo-sequence-head org-state)))
12051 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12052 ;; Do we need to trigger a repeat?
12053 (when now-done-p
12054 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12055 ;; This is for the agenda, take a snapshot of the headline.
12056 (save-match-data
12057 (setq org-agenda-headline-snapshot-before-repeat
12058 (org-get-heading))))
12059 (org-auto-repeat-maybe org-state))
12060 ;; Fixup cursor location if close to the keyword
12061 (if (and (outline-on-heading-p)
12062 (not (bolp))
12063 (save-excursion (beginning-of-line 1)
12064 (looking-at org-todo-line-regexp))
12065 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12066 (progn
12067 (goto-char (or (match-end 2) (match-end 1)))
12068 (and (looking-at " ") (just-one-space))))
12069 (when org-trigger-hook
12070 (save-excursion
12071 (run-hook-with-args 'org-trigger-hook change-plist)))
12072 (when commentp (org-toggle-comment))))))))
12074 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12075 "Block turning an entry into a TODO, using the hierarchy.
12076 This checks whether the current task should be blocked from state
12077 changes. Such blocking occurs when:
12079 1. The task has children which are not all in a completed state.
12081 2. A task has a parent with the property :ORDERED:, and there
12082 are siblings prior to the current task with incomplete
12083 status.
12085 3. The parent of the task is blocked because it has siblings that should
12086 be done first, or is child of a block grandparent TODO entry."
12088 (if (not org-enforce-todo-dependencies)
12089 t ; if locally turned off don't block
12090 (catch 'dont-block
12091 ;; If this is not a todo state change, or if this entry is already DONE,
12092 ;; do not block
12093 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12094 (member (plist-get change-plist :from)
12095 (cons 'done org-done-keywords))
12096 (member (plist-get change-plist :to)
12097 (cons 'todo org-not-done-keywords))
12098 (not (plist-get change-plist :to)))
12099 (throw 'dont-block t))
12100 ;; If this task has children, and any are undone, it's blocked
12101 (save-excursion
12102 (org-back-to-heading t)
12103 (let ((this-level (funcall outline-level)))
12104 (outline-next-heading)
12105 (let ((child-level (funcall outline-level)))
12106 (while (and (not (eobp))
12107 (> child-level this-level))
12108 ;; this todo has children, check whether they are all
12109 ;; completed
12110 (if (and (not (org-entry-is-done-p))
12111 (org-entry-is-todo-p))
12112 (progn (setq org-block-entry-blocking (org-get-heading))
12113 (throw 'dont-block nil)))
12114 (outline-next-heading)
12115 (setq child-level (funcall outline-level))))))
12116 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12117 ;; any previous siblings are undone, it's blocked
12118 (save-excursion
12119 (org-back-to-heading t)
12120 (let* ((pos (point))
12121 (parent-pos (and (org-up-heading-safe) (point))))
12122 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12123 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12124 (forward-line 1)
12125 (re-search-forward org-not-done-heading-regexp pos t))
12126 (setq org-block-entry-blocking (match-string 0))
12127 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12128 ;; Search further up the hierarchy, to see if an ancestor is blocked
12129 (while t
12130 (goto-char parent-pos)
12131 (if (not (looking-at org-not-done-heading-regexp))
12132 (throw 'dont-block t)) ; do not block, parent is not a TODO
12133 (setq pos (point))
12134 (setq parent-pos (and (org-up-heading-safe) (point)))
12135 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12136 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12137 (forward-line 1)
12138 (re-search-forward org-not-done-heading-regexp pos t)
12139 (setq org-block-entry-blocking (org-get-heading)))
12140 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12142 (defcustom org-track-ordered-property-with-tag nil
12143 "Should the ORDERED property also be shown as a tag?
12144 The ORDERED property decides if an entry should require subtasks to be
12145 completed in sequence. Since a property is not very visible, setting
12146 this option means that toggling the ORDERED property with the command
12147 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12148 not relevant for the behavior, but it makes things more visible.
12150 Note that toggling the tag with tags commands will not change the property
12151 and therefore not influence behavior!
12153 This can be t, meaning the tag ORDERED should be used, It can also be a
12154 string to select a different tag for this task."
12155 :group 'org-todo
12156 :type '(choice
12157 (const :tag "No tracking" nil)
12158 (const :tag "Track with ORDERED tag" t)
12159 (string :tag "Use other tag")))
12161 (defun org-toggle-ordered-property ()
12162 "Toggle the ORDERED property of the current entry.
12163 For better visibility, you can track the value of this property with a tag.
12164 See variable `org-track-ordered-property-with-tag'."
12165 (interactive)
12166 (let* ((t1 org-track-ordered-property-with-tag)
12167 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12168 (save-excursion
12169 (org-back-to-heading)
12170 (if (org-entry-get nil "ORDERED")
12171 (progn
12172 (org-delete-property "ORDERED" "PROPERTIES")
12173 (and tag (org-toggle-tag tag 'off))
12174 (message "Subtasks can be completed in arbitrary order"))
12175 (org-entry-put nil "ORDERED" "t")
12176 (and tag (org-toggle-tag tag 'on))
12177 (message "Subtasks must be completed in sequence")))))
12179 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12180 (defun org-block-todo-from-checkboxes (change-plist)
12181 "Block turning an entry into a TODO, using checkboxes.
12182 This checks whether the current task should be blocked from state
12183 changes because there are unchecked boxes in this entry."
12184 (if (not org-enforce-todo-checkbox-dependencies)
12185 t ; if locally turned off don't block
12186 (catch 'dont-block
12187 ;; If this is not a todo state change, or if this entry is already DONE,
12188 ;; do not block
12189 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12190 (member (plist-get change-plist :from)
12191 (cons 'done org-done-keywords))
12192 (member (plist-get change-plist :to)
12193 (cons 'todo org-not-done-keywords))
12194 (not (plist-get change-plist :to)))
12195 (throw 'dont-block t))
12196 ;; If this task has checkboxes that are not checked, it's blocked
12197 (save-excursion
12198 (org-back-to-heading t)
12199 (let ((beg (point)) end)
12200 (outline-next-heading)
12201 (setq end (point))
12202 (goto-char beg)
12203 (if (org-list-search-forward
12204 (concat (org-item-beginning-re)
12205 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12206 "\\[[- ]\\]")
12207 end t)
12208 (progn
12209 (if (boundp 'org-blocked-by-checkboxes)
12210 (setq org-blocked-by-checkboxes t))
12211 (throw 'dont-block nil)))))
12212 t))) ; do not block
12214 (defun org-entry-blocked-p ()
12215 "Is the current entry blocked?"
12216 (org-with-silent-modifications
12217 (if (org-entry-get nil "NOBLOCKING")
12218 nil ;; Never block this entry
12219 (not (run-hook-with-args-until-failure
12220 'org-blocker-hook
12221 (list :type 'todo-state-change
12222 :position (point)
12223 :from 'todo
12224 :to 'done))))))
12226 (defun org-update-statistics-cookies (all)
12227 "Update the statistics cookie, either from TODO or from checkboxes.
12228 This should be called with the cursor in a line with a statistics cookie."
12229 (interactive "P")
12230 (if all
12231 (progn
12232 (org-update-checkbox-count 'all)
12233 (org-map-entries 'org-update-parent-todo-statistics))
12234 (if (not (org-at-heading-p))
12235 (org-update-checkbox-count)
12236 (let ((pos (point-marker))
12237 end l1 l2)
12238 (ignore-errors (org-back-to-heading t))
12239 (if (not (org-at-heading-p))
12240 (org-update-checkbox-count)
12241 (setq l1 (org-outline-level))
12242 (setq end (save-excursion
12243 (outline-next-heading)
12244 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12245 (point)))
12246 (if (and (save-excursion
12247 (re-search-forward
12248 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12249 (not (save-excursion (re-search-forward
12250 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12251 (org-update-checkbox-count)
12252 (if (and l2 (> l2 l1))
12253 (progn
12254 (goto-char end)
12255 (org-update-parent-todo-statistics))
12256 (goto-char pos)
12257 (beginning-of-line 1)
12258 (while (re-search-forward
12259 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12260 (point-at-eol) t)
12261 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12262 (goto-char pos)
12263 (move-marker pos nil)))))
12265 (defvar org-entry-property-inherited-from) ;; defined below
12266 (defun org-update-parent-todo-statistics ()
12267 "Update any statistics cookie in the parent of the current headline.
12268 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12269 the entire subtree and this will travel up the hierarchy and update
12270 statistics everywhere."
12271 (let* ((prop (save-excursion (org-up-heading-safe)
12272 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12273 (recursive (or (not org-hierarchical-todo-statistics)
12274 (and prop (string-match "\\<recursive\\>" prop))))
12275 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12277 (first t)
12278 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12279 level ltoggle l1 new ndel
12280 (cnt-all 0) (cnt-done 0) is-percent kwd
12281 checkbox-beg ov ovs ove cookie-present)
12282 (catch 'exit
12283 (save-excursion
12284 (beginning-of-line 1)
12285 (setq ltoggle (funcall outline-level))
12286 ;; Three situations are to consider:
12288 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12289 ;; to the top-level ancestor on the headline;
12291 ;; 2. If parent has "recursive" property, repeat up to the
12292 ;; headline setting that property, taking inheritance into
12293 ;; account;
12295 ;; 3. Else, move up to direct parent and proceed only once.
12296 (while (and (setq level (org-up-heading-safe))
12297 (or recursive first)
12298 (>= (point) lim))
12299 (setq first nil cookie-present nil)
12300 (unless (and level
12301 (not (string-match
12302 "\\<checkbox\\>"
12303 (downcase (or (org-entry-get nil "COOKIE_DATA")
12304 "")))))
12305 (throw 'exit nil))
12306 (while (re-search-forward box-re (point-at-eol) t)
12307 (setq cnt-all 0 cnt-done 0 cookie-present t)
12308 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12309 (save-match-data
12310 (unless (outline-next-heading) (throw 'exit nil))
12311 (while (and (looking-at org-complex-heading-regexp)
12312 (> (setq l1 (length (match-string 1))) level))
12313 (setq kwd (and (or recursive (= l1 ltoggle))
12314 (match-string 2)))
12315 (if (or (eq org-provide-todo-statistics 'all-headlines)
12316 (and (listp org-provide-todo-statistics)
12317 (or (member kwd org-provide-todo-statistics)
12318 (member kwd org-done-keywords))))
12319 (setq cnt-all (1+ cnt-all))
12320 (if (eq org-provide-todo-statistics t)
12321 (and kwd (setq cnt-all (1+ cnt-all)))))
12322 (and (member kwd org-done-keywords)
12323 (setq cnt-done (1+ cnt-done)))
12324 (outline-next-heading)))
12325 (setq new
12326 (if is-percent
12327 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12328 (format "[%d/%d]" cnt-done cnt-all))
12329 ndel (- (match-end 0) checkbox-beg))
12330 ;; handle overlays when updating cookie from column view
12331 (when (setq ov (car (overlays-at checkbox-beg)))
12332 (setq ovs (overlay-start ov) ove (overlay-end ov))
12333 (delete-overlay ov))
12334 (goto-char checkbox-beg)
12335 (insert new)
12336 (delete-region (point) (+ (point) ndel))
12337 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12338 (when ov (move-overlay ov ovs ove)))
12339 (when cookie-present
12340 (run-hook-with-args 'org-after-todo-statistics-hook
12341 cnt-done (- cnt-all cnt-done))))))
12342 (run-hooks 'org-todo-statistics-hook)))
12344 (defvar org-after-todo-statistics-hook nil
12345 "Hook that is called after a TODO statistics cookie has been updated.
12346 Each function is called with two arguments: the number of not-done entries
12347 and the number of done entries.
12349 For example, the following function, when added to this hook, will switch
12350 an entry to DONE when all children are done, and back to TODO when new
12351 entries are set to a TODO status. Note that this hook is only called
12352 when there is a statistics cookie in the headline!
12354 (defun org-summary-todo (n-done n-not-done)
12355 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12356 (let (org-log-done org-log-states) ; turn off logging
12357 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12360 (defvar org-todo-statistics-hook nil
12361 "Hook that is run whenever Org thinks TODO statistics should be updated.
12362 This hook runs even if there is no statistics cookie present, in which case
12363 `org-after-todo-statistics-hook' would not run.")
12365 (defun org-todo-trigger-tag-changes (state)
12366 "Apply the changes defined in `org-todo-state-tags-triggers'."
12367 (let ((l org-todo-state-tags-triggers)
12368 changes)
12369 (when (or (not state) (equal state ""))
12370 (setq changes (append changes (cdr (assoc "" l)))))
12371 (when (and (stringp state) (> (length state) 0))
12372 (setq changes (append changes (cdr (assoc state l)))))
12373 (when (member state org-not-done-keywords)
12374 (setq changes (append changes (cdr (assoc 'todo l)))))
12375 (when (member state org-done-keywords)
12376 (setq changes (append changes (cdr (assoc 'done l)))))
12377 (dolist (c changes)
12378 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12380 (defun org-local-logging (value)
12381 "Get logging settings from a property VALUE."
12382 (let* (words w a)
12383 ;; directly set the variables, they are already local.
12384 (setq org-log-done nil
12385 org-log-repeat nil
12386 org-todo-log-states nil)
12387 (setq words (org-split-string value))
12388 (while (setq w (pop words))
12389 (cond
12390 ((setq a (assoc w org-startup-options))
12391 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12392 (set (nth 1 a) (nth 2 a))))
12393 ((setq a (org-extract-log-state-settings w))
12394 (and (member (car a) org-todo-keywords-1)
12395 (push a org-todo-log-states)))))))
12397 (defun org-get-todo-sequence-head (kwd)
12398 "Return the head of the TODO sequence to which KWD belongs.
12399 If KWD is not set, check if there is a text property remembering the
12400 right sequence."
12401 (let (p)
12402 (cond
12403 ((not kwd)
12404 (or (get-text-property (point-at-bol) 'org-todo-head)
12405 (progn
12406 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12407 nil (point-at-eol)))
12408 (get-text-property p 'org-todo-head))))
12409 ((not (member kwd org-todo-keywords-1))
12410 (car org-todo-keywords-1))
12411 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12413 (defun org-fast-todo-selection ()
12414 "Fast TODO keyword selection with single keys.
12415 Returns the new TODO keyword, or nil if no state change should occur."
12416 (let* ((fulltable org-todo-key-alist)
12417 (done-keywords org-done-keywords) ;; needed for the faces.
12418 (maxlen (apply 'max (mapcar
12419 (lambda (x)
12420 (if (stringp (car x)) (string-width (car x)) 0))
12421 fulltable)))
12422 (expert nil)
12423 (fwidth (+ maxlen 3 1 3))
12424 (ncol (/ (- (window-width) 4) fwidth))
12425 tg cnt e c tbl
12426 groups ingroup)
12427 (save-excursion
12428 (save-window-excursion
12429 (if expert
12430 (set-buffer (get-buffer-create " *Org todo*"))
12431 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12432 (erase-buffer)
12433 (org-set-local 'org-done-keywords done-keywords)
12434 (setq tbl fulltable cnt 0)
12435 (while (setq e (pop tbl))
12436 (cond
12437 ((equal e '(:startgroup))
12438 (push '() groups) (setq ingroup t)
12439 (when (not (= cnt 0))
12440 (setq cnt 0)
12441 (insert "\n"))
12442 (insert "{ "))
12443 ((equal e '(:endgroup))
12444 (setq ingroup nil cnt 0)
12445 (insert "}\n"))
12446 ((equal e '(:newline))
12447 (when (not (= cnt 0))
12448 (setq cnt 0)
12449 (insert "\n")
12450 (setq e (car tbl))
12451 (while (equal (car tbl) '(:newline))
12452 (insert "\n")
12453 (setq tbl (cdr tbl)))))
12455 (setq tg (car e) c (cdr e))
12456 (if ingroup (push tg (car groups)))
12457 (setq tg (org-add-props tg nil 'face
12458 (org-get-todo-face tg)))
12459 (if (and (= cnt 0) (not ingroup)) (insert " "))
12460 (insert "[" c "] " tg (make-string
12461 (- fwidth 4 (length tg)) ?\ ))
12462 (when (= (setq cnt (1+ cnt)) ncol)
12463 (insert "\n")
12464 (if ingroup (insert " "))
12465 (setq cnt 0)))))
12466 (insert "\n")
12467 (goto-char (point-min))
12468 (if (not expert) (org-fit-window-to-buffer))
12469 (message "[a-z..]:Set [SPC]:clear")
12470 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12471 (cond
12472 ((or (= c ?\C-g)
12473 (and (= c ?q) (not (rassoc c fulltable))))
12474 (setq quit-flag t))
12475 ((= c ?\ ) nil)
12476 ((setq e (rassoc c fulltable) tg (car e))
12478 (t (setq quit-flag t)))))))
12480 (defun org-entry-is-todo-p ()
12481 (member (org-get-todo-state) org-not-done-keywords))
12483 (defun org-entry-is-done-p ()
12484 (member (org-get-todo-state) org-done-keywords))
12486 (defun org-get-todo-state ()
12487 (save-excursion
12488 (org-back-to-heading t)
12489 (and (looking-at org-todo-line-regexp)
12490 (match-end 2)
12491 (match-string 2))))
12493 (defun org-at-date-range-p (&optional inactive-ok)
12494 "Is the cursor inside a date range?"
12495 (interactive)
12496 (save-excursion
12497 (catch 'exit
12498 (let ((pos (point)))
12499 (skip-chars-backward "^[<\r\n")
12500 (skip-chars-backward "<[")
12501 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12502 (>= (match-end 0) pos)
12503 (throw 'exit t))
12504 (skip-chars-backward "^<[\r\n")
12505 (skip-chars-backward "<[")
12506 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12507 (>= (match-end 0) pos)
12508 (throw 'exit t)))
12509 nil)))
12511 (defun org-get-repeat (&optional tagline)
12512 "Check if there is a deadline/schedule with repeater in this entry."
12513 (save-match-data
12514 (save-excursion
12515 (org-back-to-heading t)
12516 (and (re-search-forward (if tagline
12517 (concat tagline "\\s-*" org-repeat-re)
12518 org-repeat-re)
12519 (org-entry-end-position) t)
12520 (match-string-no-properties 1)))))
12522 (defvar org-last-changed-timestamp)
12523 (defvar org-last-inserted-timestamp)
12524 (defvar org-log-post-message)
12525 (defvar org-log-note-purpose)
12526 (defvar org-log-note-how)
12527 (defvar org-log-note-extra)
12528 (defun org-auto-repeat-maybe (done-word)
12529 "Check if the current headline contains a repeated deadline/schedule.
12530 If yes, set TODO state back to what it was and change the base date
12531 of repeating deadline/scheduled time stamps to new date.
12532 This function is run automatically after each state change to a DONE state."
12533 ;; last-state is dynamically scoped into this function
12534 (let* ((repeat (org-get-repeat))
12535 (aa (assoc org-last-state org-todo-kwd-alist))
12536 (interpret (nth 1 aa))
12537 (head (nth 2 aa))
12538 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12539 (msg "Entry repeats: ")
12540 (org-log-done nil)
12541 (org-todo-log-states nil)
12542 re type n what ts time to-state)
12543 (when repeat
12544 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12545 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12546 org-todo-repeat-to-state))
12547 (unless (and to-state (member to-state org-todo-keywords-1))
12548 (setq to-state (if (eq interpret 'type) org-last-state head)))
12549 (org-todo to-state)
12550 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12551 (org-entry-put nil "LAST_REPEAT" (format-time-string
12552 (org-time-stamp-format t t))))
12553 (when org-log-repeat
12554 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12555 (memq 'org-add-log-note post-command-hook))
12556 ;; OK, we are already setup for some record
12557 (if (eq org-log-repeat 'note)
12558 ;; make sure we take a note, not only a time stamp
12559 (setq org-log-note-how 'note))
12560 ;; Set up for taking a record
12561 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12562 org-last-state
12563 'findpos org-log-repeat)))
12564 (org-back-to-heading t)
12565 (org-add-planning-info nil nil 'closed)
12566 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12567 org-deadline-time-regexp "\\)\\|\\("
12568 org-ts-regexp "\\)"))
12569 (while (re-search-forward
12570 re (save-excursion (outline-next-heading) (point)) t)
12571 (setq type (if (match-end 1) org-scheduled-string
12572 (if (match-end 3) org-deadline-string "Plain:"))
12573 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12574 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12575 (setq n (string-to-number (match-string 2 ts))
12576 what (match-string 3 ts))
12577 (if (equal what "w") (setq n (* n 7) what "d"))
12578 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12579 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12580 ;; Preparation, see if we need to modify the start date for the change
12581 (when (match-end 1)
12582 (setq time (save-match-data (org-time-string-to-time ts)))
12583 (cond
12584 ((equal (match-string 1 ts) ".")
12585 ;; Shift starting date to today
12586 (org-timestamp-change
12587 (- (org-today) (time-to-days time))
12588 'day))
12589 ((equal (match-string 1 ts) "+")
12590 (let ((nshiftmax 10) (nshift 0))
12591 (while (or (= nshift 0)
12592 (<= (time-to-days time)
12593 (time-to-days (current-time))))
12594 (when (= (incf nshift) nshiftmax)
12595 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12596 (error "Abort")))
12597 (org-timestamp-change n (cdr (assoc what whata)))
12598 (org-at-timestamp-p t)
12599 (setq ts (match-string 1))
12600 (setq time (save-match-data (org-time-string-to-time ts)))))
12601 (org-timestamp-change (- n) (cdr (assoc what whata)))
12602 ;; rematch, so that we have everything in place for the real shift
12603 (org-at-timestamp-p t)
12604 (setq ts (match-string 1))
12605 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12606 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12607 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12608 (setq org-log-post-message msg)
12609 (message "%s" msg))))
12611 (defun org-show-todo-tree (arg)
12612 "Make a compact tree which shows all headlines marked with TODO.
12613 The tree will show the lines where the regexp matches, and all higher
12614 headlines above the match.
12615 With a \\[universal-argument] prefix, prompt for a regexp to match.
12616 With a numeric prefix N, construct a sparse tree for the Nth element
12617 of `org-todo-keywords-1'."
12618 (interactive "P")
12619 (let ((case-fold-search nil)
12620 (kwd-re
12621 (cond ((null arg) org-not-done-regexp)
12622 ((equal arg '(4))
12623 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12624 (mapcar 'list org-todo-keywords-1))))
12625 (concat "\\("
12626 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12627 "\\)\\>")))
12628 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12629 (regexp-quote (nth (1- (prefix-numeric-value arg))
12630 org-todo-keywords-1)))
12631 (t (error "Invalid prefix argument: %s" arg)))))
12632 (message "%d TODO entries found"
12633 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12635 (defun org-deadline (arg &optional time)
12636 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12637 With one universal prefix argument, remove any deadline from the item.
12638 With two universal prefix arguments, prompt for a warning delay.
12639 With argument TIME, set the deadline at the corresponding date. TIME
12640 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12641 (interactive "P")
12642 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12643 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12644 'region-start-level 'region))
12645 org-loop-over-headlines-in-active-region)
12646 (org-map-entries
12647 `(org-deadline ',arg ,time)
12648 org-loop-over-headlines-in-active-region
12649 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12650 (let* ((old-date (org-entry-get nil "DEADLINE"))
12651 (old-date-time (if old-date (org-time-string-to-time old-date)))
12652 (repeater (and old-date
12653 (string-match
12654 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12655 old-date)
12656 (match-string 1 old-date))))
12657 (cond
12658 ((equal arg '(4))
12659 (when (and old-date org-log-redeadline)
12660 (org-add-log-setup 'deldeadline nil old-date 'findpos
12661 org-log-redeadline))
12662 (org-remove-timestamp-with-keyword org-deadline-string)
12663 (message "Item no longer has a deadline."))
12664 ((equal arg '(16))
12665 (save-excursion
12666 (if (re-search-forward
12667 org-deadline-time-regexp
12668 (save-excursion (outline-next-heading) (point)) t)
12669 (let* ((rpl0 (match-string 1))
12670 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12671 (replace-match
12672 (concat org-deadline-string
12673 " <" rpl
12674 (format " -%dd"
12675 (abs
12676 (- (time-to-days
12677 (save-match-data
12678 (org-read-date nil t nil "Warn starting from" old-date-time)))
12679 (time-to-days old-date-time))))
12680 ">") t t))
12681 (user-error "No deadline information to update"))))
12683 (org-add-planning-info 'deadline time 'closed)
12684 (when (and old-date org-log-redeadline
12685 (not (equal old-date
12686 (substring org-last-inserted-timestamp 1 -1))))
12687 (org-add-log-setup 'redeadline nil old-date 'findpos
12688 org-log-redeadline))
12689 (when repeater
12690 (save-excursion
12691 (org-back-to-heading t)
12692 (when (re-search-forward (concat org-deadline-string " "
12693 org-last-inserted-timestamp)
12694 (save-excursion
12695 (outline-next-heading) (point)) t)
12696 (goto-char (1- (match-end 0)))
12697 (insert " " repeater)
12698 (setq org-last-inserted-timestamp
12699 (concat (substring org-last-inserted-timestamp 0 -1)
12700 " " repeater
12701 (substring org-last-inserted-timestamp -1))))))
12702 (message "Deadline on %s" org-last-inserted-timestamp))))))
12704 (defun org-schedule (arg &optional time)
12705 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12706 With one universal prefix argument, remove any scheduling date from the item.
12707 With two universal prefix arguments, prompt for a delay cookie.
12708 With argument TIME, scheduled at the corresponding date. TIME can
12709 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12710 (interactive "P")
12711 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12712 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12713 'region-start-level 'region))
12714 org-loop-over-headlines-in-active-region)
12715 (org-map-entries
12716 `(org-schedule ',arg ,time)
12717 org-loop-over-headlines-in-active-region
12718 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12719 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12720 (old-date-time (if old-date (org-time-string-to-time old-date)))
12721 (repeater (and old-date
12722 (string-match
12723 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12724 old-date)
12725 (match-string 1 old-date))))
12726 (cond
12727 ((equal arg '(4))
12728 (progn
12729 (when (and old-date org-log-reschedule)
12730 (org-add-log-setup 'delschedule nil old-date 'findpos
12731 org-log-reschedule))
12732 (org-remove-timestamp-with-keyword org-scheduled-string)
12733 (message "Item is no longer scheduled.")))
12734 ((equal arg '(16))
12735 (save-excursion
12736 (if (re-search-forward
12737 org-scheduled-time-regexp
12738 (save-excursion (outline-next-heading) (point)) t)
12739 (let* ((rpl0 (match-string 1))
12740 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12741 (replace-match
12742 (concat org-scheduled-string
12743 " <" rpl
12744 (format " -%dd"
12745 (abs
12746 (- (time-to-days
12747 (save-match-data
12748 (org-read-date nil t nil "Delay until" old-date-time)))
12749 (time-to-days old-date-time))))
12750 ">") t t))
12751 (user-error "No scheduled information to update"))))
12753 (org-add-planning-info 'scheduled time 'closed)
12754 (when (and old-date org-log-reschedule
12755 (not (equal old-date
12756 (substring org-last-inserted-timestamp 1 -1))))
12757 (org-add-log-setup 'reschedule nil old-date 'findpos
12758 org-log-reschedule))
12759 (when repeater
12760 (save-excursion
12761 (org-back-to-heading t)
12762 (when (re-search-forward (concat org-scheduled-string " "
12763 org-last-inserted-timestamp)
12764 (save-excursion
12765 (outline-next-heading) (point)) t)
12766 (goto-char (1- (match-end 0)))
12767 (insert " " repeater)
12768 (setq org-last-inserted-timestamp
12769 (concat (substring org-last-inserted-timestamp 0 -1)
12770 " " repeater
12771 (substring org-last-inserted-timestamp -1))))))
12772 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12774 (defun org-get-scheduled-time (pom &optional inherit)
12775 "Get the scheduled time as a time tuple, of a format suitable
12776 for calling org-schedule with, or if there is no scheduling,
12777 returns nil."
12778 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12779 (when time
12780 (apply 'encode-time (org-parse-time-string time)))))
12782 (defun org-get-deadline-time (pom &optional inherit)
12783 "Get the deadline as a time tuple, of a format suitable for
12784 calling org-deadline with, or if there is no scheduling, returns
12785 nil."
12786 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12787 (when time
12788 (apply 'encode-time (org-parse-time-string time)))))
12790 (defun org-remove-timestamp-with-keyword (keyword)
12791 "Remove all time stamps with KEYWORD in the current entry."
12792 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12793 beg)
12794 (save-excursion
12795 (org-back-to-heading t)
12796 (setq beg (point))
12797 (outline-next-heading)
12798 (while (re-search-backward re beg t)
12799 (replace-match "")
12800 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12801 (equal (char-before) ?\ ))
12802 (backward-delete-char 1)
12803 (if (string-match "^[ \t]*$" (buffer-substring
12804 (point-at-bol) (point-at-eol)))
12805 (delete-region (point-at-bol)
12806 (min (point-max) (1+ (point-at-eol))))))))))
12808 (defun org-add-planning-info (what &optional time &rest remove)
12809 "Insert new timestamp with keyword in the line directly after the headline.
12810 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12811 If non is given, the user is prompted for a date.
12812 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12813 be removed."
12814 (interactive)
12815 (let (org-time-was-given org-end-time-was-given ts
12816 end default-time default-input)
12818 (catch 'exit
12819 (when (and (memq what '(scheduled deadline))
12820 (or (not time)
12821 (and (stringp time)
12822 (string-match "^[-+]+[0-9]" time))))
12823 ;; Try to get a default date/time from existing timestamp
12824 (save-excursion
12825 (org-back-to-heading t)
12826 (setq end (save-excursion (outline-next-heading) (point)))
12827 (when (re-search-forward (if (eq what 'scheduled)
12828 org-scheduled-time-regexp
12829 org-deadline-time-regexp)
12830 end t)
12831 (setq ts (match-string 1)
12832 default-time
12833 (apply 'encode-time (org-parse-time-string ts))
12834 default-input (and ts (org-get-compact-tod ts))))))
12835 (when what
12836 (setq time
12837 (if (stringp time)
12838 ;; This is a string (relative or absolute), set proper date
12839 (apply 'encode-time
12840 (org-read-date-analyze
12841 time default-time (decode-time default-time)))
12842 ;; If necessary, get the time from the user
12843 (or time (org-read-date nil 'to-time nil nil
12844 default-time default-input)))))
12846 (when (and org-insert-labeled-timestamps-at-point
12847 (member what '(scheduled deadline)))
12848 (insert
12849 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12850 (org-insert-time-stamp time org-time-was-given
12851 nil nil nil (list org-end-time-was-given))
12852 (setq what nil))
12853 (save-excursion
12854 (save-restriction
12855 (let (col list elt ts buffer-invisibility-spec)
12856 (org-back-to-heading t)
12857 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12858 (goto-char (match-end 1))
12859 (setq col (current-column))
12860 (goto-char (match-end 0))
12861 (if (eobp) (insert "\n") (forward-char 1))
12862 (when (and (not what)
12863 (not (looking-at
12864 (concat "[ \t]*"
12865 org-keyword-time-not-clock-regexp))))
12866 ;; Nothing to add, nothing to remove...... :-)
12867 (throw 'exit nil))
12868 (if (and (not (looking-at org-outline-regexp))
12869 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12870 "[^\r\n]*"))
12871 (not (equal (match-string 1) org-clock-string)))
12872 (narrow-to-region (match-beginning 0) (match-end 0))
12873 (insert-before-markers "\n")
12874 (backward-char 1)
12875 (narrow-to-region (point) (point))
12876 (and org-adapt-indentation (org-indent-to-column col)))
12877 ;; Check if we have to remove something.
12878 (setq list (cons what remove))
12879 (while list
12880 (setq elt (pop list))
12881 (when (or (and (eq elt 'scheduled)
12882 (re-search-forward org-scheduled-time-regexp nil t))
12883 (and (eq elt 'deadline)
12884 (re-search-forward org-deadline-time-regexp nil t))
12885 (and (eq elt 'closed)
12886 (re-search-forward org-closed-time-regexp nil t)))
12887 (replace-match "")
12888 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12889 (and (looking-at "[ \t]+") (replace-match ""))
12890 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12891 (when what
12892 (insert
12893 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12894 (cond ((eq what 'scheduled) org-scheduled-string)
12895 ((eq what 'deadline) org-deadline-string)
12896 ((eq what 'closed) org-closed-string))
12897 " ")
12898 (setq ts (org-insert-time-stamp
12899 time
12900 (or org-time-was-given
12901 (and (eq what 'closed) org-log-done-with-time))
12902 (eq what 'closed)
12903 nil nil (list org-end-time-was-given)))
12904 (insert
12905 (if (not (or (bolp) (eq (char-before) ?\ )
12906 (memq (char-after) '(32 10))
12907 (eobp))) " " ""))
12908 (end-of-line 1))
12909 (goto-char (point-min))
12910 (widen)
12911 (if (and (looking-at "[ \t]*\n")
12912 (equal (char-before) ?\n))
12913 (delete-region (1- (point)) (point-at-eol)))
12914 ts))))))
12916 (defvar org-log-note-marker (make-marker))
12917 (defvar org-log-note-purpose nil)
12918 (defvar org-log-note-state nil)
12919 (defvar org-log-note-previous-state nil)
12920 (defvar org-log-note-how nil)
12921 (defvar org-log-note-extra nil)
12922 (defvar org-log-note-window-configuration nil)
12923 (defvar org-log-note-return-to (make-marker))
12924 (defvar org-log-note-effective-time nil
12925 "Remembered current time so that dynamically scoped
12926 `org-extend-today-until' affects tha timestamps in state change
12927 log")
12929 (defvar org-log-post-message nil
12930 "Message to be displayed after a log note has been stored.
12931 The auto-repeater uses this.")
12933 (defun org-add-note ()
12934 "Add a note to the current entry.
12935 This is done in the same way as adding a state change note."
12936 (interactive)
12937 (org-add-log-setup 'note nil nil 'findpos nil))
12939 (defvar org-property-end-re)
12940 (defun org-add-log-setup (&optional purpose state prev-state
12941 findpos how extra)
12942 "Set up the post command hook to take a note.
12943 If this is about to TODO state change, the new state is expected in STATE.
12944 When FINDPOS is non-nil, find the correct position for the note in
12945 the current entry. If not, assume that it can be inserted at point.
12946 HOW is an indicator what kind of note should be created.
12947 EXTRA is additional text that will be inserted into the notes buffer."
12948 (let* ((org-log-into-drawer (org-log-into-drawer))
12949 (drawer (cond ((stringp org-log-into-drawer)
12950 org-log-into-drawer)
12951 (org-log-into-drawer "LOGBOOK"))))
12952 (save-restriction
12953 (save-excursion
12954 (when findpos
12955 (org-back-to-heading t)
12956 (narrow-to-region (point) (save-excursion
12957 (outline-next-heading) (point)))
12958 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12959 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12960 "[^\r\n]*\\)?"))
12961 (goto-char (match-end 0))
12962 (cond
12963 (drawer
12964 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12965 nil t)
12966 (progn
12967 (goto-char (match-end 0))
12968 (or org-log-states-order-reversed
12969 (and (re-search-forward org-property-end-re nil t)
12970 (goto-char (1- (match-beginning 0))))))
12971 (insert "\n:" drawer ":\n:END:")
12972 (beginning-of-line 0)
12973 (org-indent-line)
12974 (beginning-of-line 2)
12975 (org-indent-line)
12976 (end-of-line 0)))
12977 ((and org-log-state-notes-insert-after-drawers
12978 (save-excursion
12979 (forward-line) (looking-at org-drawer-regexp)))
12980 (forward-line)
12981 (while (looking-at org-drawer-regexp)
12982 (goto-char (match-end 0))
12983 (re-search-forward org-property-end-re (point-max) t)
12984 (forward-line))
12985 (forward-line -1)))
12986 (unless org-log-states-order-reversed
12987 (and (= (char-after) ?\n) (forward-char 1))
12988 (org-skip-over-state-notes)
12989 (skip-chars-backward " \t\n\r")))
12990 (move-marker org-log-note-marker (point))
12991 (setq org-log-note-purpose purpose
12992 org-log-note-state state
12993 org-log-note-previous-state prev-state
12994 org-log-note-how how
12995 org-log-note-extra extra
12996 org-log-note-effective-time (org-current-effective-time))
12997 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12999 (defun org-skip-over-state-notes ()
13000 "Skip past the list of State notes in an entry."
13001 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13002 (when (ignore-errors (goto-char (org-in-item-p)))
13003 (let* ((struct (org-list-struct))
13004 (prevs (org-list-prevs-alist struct)))
13005 (while (looking-at "[ \t]*- State")
13006 (goto-char (or (org-list-get-next-item (point) struct prevs)
13007 (org-list-get-item-end (point) struct)))))))
13009 (defun org-add-log-note (&optional purpose)
13010 "Pop up a window for taking a note, and add this note later at point."
13011 (remove-hook 'post-command-hook 'org-add-log-note)
13012 (setq org-log-note-window-configuration (current-window-configuration))
13013 (delete-other-windows)
13014 (move-marker org-log-note-return-to (point))
13015 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13016 (goto-char org-log-note-marker)
13017 (org-switch-to-buffer-other-window "*Org Note*")
13018 (erase-buffer)
13019 (if (memq org-log-note-how '(time state))
13020 (let (current-prefix-arg) (org-store-log-note))
13021 (let ((org-inhibit-startup t)) (org-mode))
13022 (insert (format "# Insert note for %s.
13023 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13024 (cond
13025 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13026 ((eq org-log-note-purpose 'done) "closed todo item")
13027 ((eq org-log-note-purpose 'state)
13028 (format "state change from \"%s\" to \"%s\""
13029 (or org-log-note-previous-state "")
13030 (or org-log-note-state "")))
13031 ((eq org-log-note-purpose 'reschedule)
13032 "rescheduling")
13033 ((eq org-log-note-purpose 'delschedule)
13034 "no longer scheduled")
13035 ((eq org-log-note-purpose 'redeadline)
13036 "changing deadline")
13037 ((eq org-log-note-purpose 'deldeadline)
13038 "removing deadline")
13039 ((eq org-log-note-purpose 'refile)
13040 "refiling")
13041 ((eq org-log-note-purpose 'note)
13042 "this entry")
13043 (t (error "This should not happen")))))
13044 (if org-log-note-extra (insert org-log-note-extra))
13045 (org-set-local 'org-finish-function 'org-store-log-note)
13046 (run-hooks 'org-log-buffer-setup-hook)))
13048 (defvar org-note-abort nil) ; dynamically scoped
13049 (defun org-store-log-note ()
13050 "Finish taking a log note, and insert it to where it belongs."
13051 (let ((txt (buffer-string)))
13052 (kill-buffer (current-buffer))
13053 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13054 lines ind bul)
13055 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13056 (setq txt (replace-match "" t t txt)))
13057 (if (string-match "\\s-+\\'" txt)
13058 (setq txt (replace-match "" t t txt)))
13059 (setq lines (org-split-string txt "\n"))
13060 (when (and note (string-match "\\S-" note))
13061 (setq note
13062 (org-replace-escapes
13063 note
13064 (list (cons "%u" (user-login-name))
13065 (cons "%U" user-full-name)
13066 (cons "%t" (format-time-string
13067 (org-time-stamp-format 'long 'inactive)
13068 org-log-note-effective-time))
13069 (cons "%T" (format-time-string
13070 (org-time-stamp-format 'long nil)
13071 org-log-note-effective-time))
13072 (cons "%d" (format-time-string
13073 (org-time-stamp-format nil 'inactive)
13074 org-log-note-effective-time))
13075 (cons "%D" (format-time-string
13076 (org-time-stamp-format nil nil)
13077 org-log-note-effective-time))
13078 (cons "%s" (if org-log-note-state
13079 (concat "\"" org-log-note-state "\"")
13080 ""))
13081 (cons "%S" (if org-log-note-previous-state
13082 (concat "\"" org-log-note-previous-state "\"")
13083 "\"\"")))))
13084 (if lines (setq note (concat note " \\\\")))
13085 (push note lines))
13086 (when (or current-prefix-arg org-note-abort)
13087 (when org-log-into-drawer
13088 (org-remove-empty-drawer-at
13089 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13090 org-log-note-marker))
13091 (setq lines nil))
13092 (when lines
13093 (with-current-buffer (marker-buffer org-log-note-marker)
13094 (save-excursion
13095 (goto-char org-log-note-marker)
13096 (move-marker org-log-note-marker nil)
13097 (end-of-line 1)
13098 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13099 (setq ind (save-excursion
13100 (if (ignore-errors (goto-char (org-in-item-p)))
13101 (let ((struct (org-list-struct)))
13102 (org-list-get-ind
13103 (org-list-get-top-point struct) struct))
13104 (skip-chars-backward " \r\t\n")
13105 (cond
13106 ((and (org-at-heading-p)
13107 org-adapt-indentation)
13108 (1+ (org-current-level)))
13109 ((org-at-heading-p) 0)
13110 (t (org-get-indentation))))))
13111 (setq bul (org-list-bullet-string "-"))
13112 (org-indent-line-to ind)
13113 (insert bul (pop lines))
13114 (let ((ind-body (+ (length bul) ind)))
13115 (while lines
13116 (insert "\n")
13117 (org-indent-line-to ind-body)
13118 (insert (pop lines))))
13119 (message "Note stored")
13120 (org-back-to-heading t)
13121 (org-cycle-hide-drawers 'children))))))
13122 (set-window-configuration org-log-note-window-configuration)
13123 (with-current-buffer (marker-buffer org-log-note-return-to)
13124 (goto-char org-log-note-return-to))
13125 (move-marker org-log-note-return-to nil)
13126 (and org-log-post-message (message "%s" org-log-post-message)))
13128 (defun org-remove-empty-drawer-at (drawer pos)
13129 "Remove an empty drawer DRAWER at position POS.
13130 POS may also be a marker."
13131 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13132 (save-excursion
13133 (save-restriction
13134 (widen)
13135 (goto-char pos)
13136 (if (org-in-regexp
13137 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13138 (replace-match ""))))))
13140 (defvar org-ts-type nil)
13141 (defun org-sparse-tree (&optional arg type)
13142 "Create a sparse tree, prompt for the details.
13143 This command can create sparse trees. You first need to select the type
13144 of match used to create the tree:
13146 t Show all TODO entries.
13147 T Show entries with a specific TODO keyword.
13148 m Show entries selected by a tags/property match.
13149 p Enter a property name and its value (both with completion on existing
13150 names/values) and show entries with that property.
13151 r Show entries matching a regular expression (`/' can be used as well).
13152 b Show deadlines and scheduled items before a date.
13153 a Show deadlines and scheduled items after a date.
13154 d Show deadlines due within `org-deadline-warning-days'.
13155 D Show deadlines and scheduled items between a date range."
13156 (interactive "P")
13157 (let (ans kwd value ts-type)
13158 (setq type (or type org-sparse-tree-default-date-type))
13159 (setq org-ts-type type)
13160 (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"
13161 (cond ((eq type 'all) "all timestamps")
13162 ((eq type 'scheduled) "only scheduled")
13163 ((eq type 'deadline) "only deadline")
13164 ((eq type 'active) "only active timestamps")
13165 ((eq type 'inactive) "only inactive timestamps")
13166 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13167 (t "scheduled/deadline")))
13168 (setq ans (read-char-exclusive))
13169 (cond
13170 ((equal ans ?c)
13171 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13172 ((equal ans ?d)
13173 (call-interactively 'org-check-deadlines))
13174 ((equal ans ?b)
13175 (call-interactively 'org-check-before-date))
13176 ((equal ans ?a)
13177 (call-interactively 'org-check-after-date))
13178 ((equal ans ?D)
13179 (call-interactively 'org-check-dates-range))
13180 ((equal ans ?t)
13181 (call-interactively 'org-show-todo-tree))
13182 ((equal ans ?T)
13183 (org-show-todo-tree '(4)))
13184 ((member ans '(?T ?m))
13185 (call-interactively 'org-match-sparse-tree))
13186 ((member ans '(?p ?P))
13187 (setq kwd (org-icompleting-read "Property: "
13188 (mapcar 'list (org-buffer-property-keys))))
13189 (setq value (org-icompleting-read "Value: "
13190 (mapcar 'list (org-property-values kwd))))
13191 (unless (string-match "\\`{.*}\\'" value)
13192 (setq value (concat "\"" value "\"")))
13193 (org-match-sparse-tree arg (concat kwd "=" value)))
13194 ((member ans '(?r ?R ?/))
13195 (call-interactively 'org-occur))
13196 (t (error "No such sparse tree command \"%c\"" ans)))))
13198 (defvar org-occur-highlights nil
13199 "List of overlays used for occur matches.")
13200 (make-variable-buffer-local 'org-occur-highlights)
13201 (defvar org-occur-parameters nil
13202 "Parameters of the active org-occur calls.
13203 This is a list, each call to org-occur pushes as cons cell,
13204 containing the regular expression and the callback, onto the list.
13205 The list can contain several entries if `org-occur' has been called
13206 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13207 will only contain one set of parameters. When the highlights are
13208 removed (for example with `C-c C-c', or with the next edit (depending
13209 on `org-remove-highlights-with-change'), this variable is emptied
13210 as well.")
13211 (make-variable-buffer-local 'org-occur-parameters)
13213 (defun org-occur (regexp &optional keep-previous callback)
13214 "Make a compact tree which shows all matches of REGEXP.
13215 The tree will show the lines where the regexp matches, and all higher
13216 headlines above the match. It will also show the heading after the match,
13217 to make sure editing the matching entry is easy.
13218 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13219 call to `org-occur' will be kept, to allow stacking of calls to this
13220 command.
13221 If CALLBACK is non-nil, it is a function which is called to confirm
13222 that the match should indeed be shown."
13223 (interactive "sRegexp: \nP")
13224 (when (equal regexp "")
13225 (error "Regexp cannot be empty"))
13226 (unless keep-previous
13227 (org-remove-occur-highlights nil nil t))
13228 (push (cons regexp callback) org-occur-parameters)
13229 (let ((cnt 0))
13230 (save-excursion
13231 (goto-char (point-min))
13232 (if (or (not keep-previous) ; do not want to keep
13233 (not org-occur-highlights)) ; no previous matches
13234 ;; hide everything
13235 (org-overview))
13236 (while (re-search-forward regexp nil t)
13237 (when (or (not callback)
13238 (save-match-data (funcall callback)))
13239 (setq cnt (1+ cnt))
13240 (when org-highlight-sparse-tree-matches
13241 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13242 (org-show-context 'occur-tree))))
13243 (when org-remove-highlights-with-change
13244 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13245 nil 'local))
13246 (unless org-sparse-tree-open-archived-trees
13247 (org-hide-archived-subtrees (point-min) (point-max)))
13248 (run-hooks 'org-occur-hook)
13249 (if (org-called-interactively-p 'interactive)
13250 (message "%d match(es) for regexp %s" cnt regexp))
13251 cnt))
13253 (defun org-occur-next-match (&optional n reset)
13254 "Function for `next-error-function' to find sparse tree matches.
13255 N is the number of matches to move, when negative move backwards.
13256 RESET is entirely ignored - this function always goes back to the
13257 starting point when no match is found."
13258 (let* ((limit (if (< n 0) (point-min) (point-max)))
13259 (search-func (if (< n 0)
13260 'previous-single-char-property-change
13261 'next-single-char-property-change))
13262 (n (abs n))
13263 (pos (point))
13265 (catch 'exit
13266 (while (setq p1 (funcall search-func (point) 'org-type))
13267 (when (equal p1 limit)
13268 (goto-char pos)
13269 (error "No more matches"))
13270 (when (equal (get-char-property p1 'org-type) 'org-occur)
13271 (setq n (1- n))
13272 (when (= n 0)
13273 (goto-char p1)
13274 (throw 'exit (point))))
13275 (goto-char p1))
13276 (goto-char p1)
13277 (error "No more matches"))))
13279 (defun org-show-context (&optional key)
13280 "Make sure point and context are visible.
13281 How much context is shown depends upon the variables
13282 `org-show-hierarchy-above', `org-show-following-heading',
13283 `org-show-entry-below' and `org-show-siblings'."
13284 (let ((heading-p (org-at-heading-p t))
13285 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13286 (following-p (org-get-alist-option org-show-following-heading key))
13287 (entry-p (org-get-alist-option org-show-entry-below key))
13288 (siblings-p (org-get-alist-option org-show-siblings key)))
13289 ;; Show heading or entry text
13290 (if (and heading-p (not entry-p))
13291 (org-flag-heading nil) ; only show the heading
13292 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13293 (org-show-hidden-entry))) ; show entire entry
13294 (when following-p
13295 ;; Show next sibling, or heading below text
13296 (save-excursion
13297 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13298 (org-flag-heading nil))))
13299 (when siblings-p (org-show-siblings))
13300 (when hierarchy-p
13301 ;; show all higher headings, possibly with siblings
13302 (save-excursion
13303 (while (and (condition-case nil
13304 (progn (org-up-heading-all 1) t)
13305 (error nil))
13306 (not (bobp)))
13307 (org-flag-heading nil)
13308 (when siblings-p (org-show-siblings)))))
13309 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13311 (defvar org-reveal-start-hook nil
13312 "Hook run before revealing a location.")
13314 (defun org-reveal (&optional siblings)
13315 "Show current entry, hierarchy above it, and the following headline.
13316 This can be used to show a consistent set of context around locations
13317 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13318 not t for the search context.
13320 With optional argument SIBLINGS, on each level of the hierarchy all
13321 siblings are shown. This repairs the tree structure to what it would
13322 look like when opened with hierarchical calls to `org-cycle'.
13323 With double optional argument \\[universal-argument] \\[universal-argument], \
13324 go to the parent and show the
13325 entire tree."
13326 (interactive "P")
13327 (run-hooks 'org-reveal-start-hook)
13328 (let ((org-show-hierarchy-above t)
13329 (org-show-following-heading t)
13330 (org-show-siblings (if siblings t org-show-siblings)))
13331 (org-show-context nil))
13332 (when (equal siblings '(16))
13333 (save-excursion
13334 (when (org-up-heading-safe)
13335 (org-show-subtree)
13336 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13338 (defun org-highlight-new-match (beg end)
13339 "Highlight from BEG to END and mark the highlight is an occur headline."
13340 (let ((ov (make-overlay beg end)))
13341 (overlay-put ov 'face 'secondary-selection)
13342 (overlay-put ov 'org-type 'org-occur)
13343 (push ov org-occur-highlights)))
13345 (defun org-remove-occur-highlights (&optional beg end noremove)
13346 "Remove the occur highlights from the buffer.
13347 BEG and END are ignored. If NOREMOVE is nil, remove this function
13348 from the `before-change-functions' in the current buffer."
13349 (interactive)
13350 (unless org-inhibit-highlight-removal
13351 (mapc 'delete-overlay org-occur-highlights)
13352 (setq org-occur-highlights nil)
13353 (setq org-occur-parameters nil)
13354 (unless noremove
13355 (remove-hook 'before-change-functions
13356 'org-remove-occur-highlights 'local))))
13358 ;;;; Priorities
13360 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13361 "Regular expression matching the priority indicator.")
13363 (defvar org-remove-priority-next-time nil)
13365 (defun org-priority-up ()
13366 "Increase the priority of the current item."
13367 (interactive)
13368 (org-priority 'up))
13370 (defun org-priority-down ()
13371 "Decrease the priority of the current item."
13372 (interactive)
13373 (org-priority 'down))
13375 (defun org-priority (&optional action show)
13376 "Change the priority of an item.
13377 ACTION can be `set', `up', `down', or a character."
13378 (interactive "P")
13379 (if (equal action '(4))
13380 (org-show-priority)
13381 (unless org-enable-priority-commands
13382 (error "Priority commands are disabled"))
13383 (setq action (or action 'set))
13384 (let (current new news have remove)
13385 (save-excursion
13386 (org-back-to-heading t)
13387 (if (looking-at org-priority-regexp)
13388 (setq current (string-to-char (match-string 2))
13389 have t))
13390 (cond
13391 ((eq action 'remove)
13392 (setq remove t new ?\ ))
13393 ((or (eq action 'set)
13394 (if (featurep 'xemacs) (characterp action) (integerp action)))
13395 (if (not (eq action 'set))
13396 (setq new action)
13397 (message "Priority %c-%c, SPC to remove: "
13398 org-highest-priority org-lowest-priority)
13399 (save-match-data
13400 (setq new (read-char-exclusive))))
13401 (if (and (= (upcase org-highest-priority) org-highest-priority)
13402 (= (upcase org-lowest-priority) org-lowest-priority))
13403 (setq new (upcase new)))
13404 (cond ((equal new ?\ ) (setq remove t))
13405 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13406 (error "Priority must be between `%c' and `%c'"
13407 org-highest-priority org-lowest-priority))))
13408 ((eq action 'up)
13409 (setq new (if have
13410 (1- current) ; normal cycling
13411 ;; last priority was empty
13412 (if (eq last-command this-command)
13413 org-lowest-priority ; wrap around empty to lowest
13414 ;; default
13415 (if org-priority-start-cycle-with-default
13416 org-default-priority
13417 (1- org-default-priority))))))
13418 ((eq action 'down)
13419 (setq new (if have
13420 (1+ current) ; normal cycling
13421 ;; last priority was empty
13422 (if (eq last-command this-command)
13423 org-highest-priority ; wrap around empty to highest
13424 ;; default
13425 (if org-priority-start-cycle-with-default
13426 org-default-priority
13427 (1+ org-default-priority))))))
13428 (t (error "Invalid action")))
13429 (if (or (< (upcase new) org-highest-priority)
13430 (> (upcase new) org-lowest-priority))
13431 (if (and (memq action '(up down))
13432 (not have) (not (eq last-command this-command)))
13433 ;; `new' is from default priority
13434 (error
13435 "The default can not be set, see `org-default-priority' why")
13436 ;; normal cycling: `new' is beyond highest/lowest priority
13437 ;; and is wrapped around to the empty priority
13438 (setq remove t)))
13439 (setq news (format "%c" new))
13440 (if have
13441 (if remove
13442 (replace-match "" t t nil 1)
13443 (replace-match news t t nil 2))
13444 (if remove
13445 (error "No priority cookie found in line")
13446 (let ((case-fold-search nil))
13447 (looking-at org-todo-line-regexp))
13448 (if (match-end 2)
13449 (progn
13450 (goto-char (match-end 2))
13451 (insert " [#" news "]"))
13452 (goto-char (match-beginning 3))
13453 (insert "[#" news "] "))))
13454 (org-preserve-lc (org-set-tags nil 'align)))
13455 (if remove
13456 (message "Priority removed")
13457 (message "Priority of current item set to %s" news)))))
13459 (defun org-show-priority ()
13460 "Show the priority of the current item.
13461 This priority is composed of the main priority given with the [#A] cookies,
13462 and by additional input from the age of a schedules or deadline entry."
13463 (interactive)
13464 (let ((pri (if (eq major-mode 'org-agenda-mode)
13465 (org-get-at-bol 'priority)
13466 (save-excursion
13467 (save-match-data
13468 (beginning-of-line)
13469 (and (looking-at org-heading-regexp)
13470 (org-get-priority (match-string 0))))))))
13471 (message "Priority is %d" (if pri pri -1000))))
13473 (defun org-get-priority (s)
13474 "Find priority cookie and return priority."
13475 (save-match-data
13476 (if (functionp org-get-priority-function)
13477 (funcall org-get-priority-function)
13478 (if (not (string-match org-priority-regexp s))
13479 (* 1000 (- org-lowest-priority org-default-priority))
13480 (* 1000 (- org-lowest-priority
13481 (string-to-char (match-string 2 s))))))))
13483 ;;;; Tags
13485 (defvar org-agenda-archives-mode)
13486 (defvar org-map-continue-from nil
13487 "Position from where mapping should continue.
13488 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13490 (defvar org-scanner-tags nil
13491 "The current tag list while the tags scanner is running.")
13492 (defvar org-trust-scanner-tags nil
13493 "Should `org-get-tags-at' use the tags for the scanner.
13494 This is for internal dynamical scoping only.
13495 When this is non-nil, the function `org-get-tags-at' will return the value
13496 of `org-scanner-tags' instead of building the list by itself. This
13497 can lead to large speed-ups when the tags scanner is used in a file with
13498 many entries, and when the list of tags is retrieved, for example to
13499 obtain a list of properties. Building the tags list for each entry in such
13500 a file becomes an N^2 operation - but with this variable set, it scales
13501 as N.")
13503 (defun org-scan-tags (action matcher todo-only &optional start-level)
13504 "Sca headline tags with inheritance and produce output ACTION.
13506 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13507 or `agenda' to produce an entry list for an agenda view. It can also be
13508 a Lisp form or a function that should be called at each matched headline, in
13509 this case the return value is a list of all return values from these calls.
13511 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13512 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13513 only lines with a not-done TODO keyword are included in the output.
13514 This should be the same variable that was scoped into
13515 and set by `org-make-tags-matcher' when it constructed MATCHER.
13517 START-LEVEL can be a string with asterisks, reducing the scope to
13518 headlines matching this string."
13519 (require 'org-agenda)
13520 (let* ((re (concat "^"
13521 (if start-level
13522 ;; Get the correct level to match
13523 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13524 org-outline-regexp)
13525 " *\\(\\<\\("
13526 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13527 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13528 (props (list 'face 'default
13529 'done-face 'org-agenda-done
13530 'undone-face 'default
13531 'mouse-face 'highlight
13532 'org-not-done-regexp org-not-done-regexp
13533 'org-todo-regexp org-todo-regexp
13534 'org-complex-heading-regexp org-complex-heading-regexp
13535 'help-echo
13536 (format "mouse-2 or RET jump to org file %s"
13537 (abbreviate-file-name
13538 (or (buffer-file-name (buffer-base-buffer))
13539 (buffer-name (buffer-base-buffer)))))))
13540 (case-fold-search nil)
13541 (org-map-continue-from nil)
13542 lspos tags tags-list
13543 (tags-alist (list (cons 0 org-file-tags)))
13544 (llast 0) rtn rtn1 level category i txt
13545 todo marker entry priority)
13546 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13547 (setq action (list 'lambda nil action)))
13548 (save-excursion
13549 (goto-char (point-min))
13550 (when (eq action 'sparse-tree)
13551 (org-overview)
13552 (org-remove-occur-highlights))
13553 (while (re-search-forward re nil t)
13554 (setq org-map-continue-from nil)
13555 (catch :skip
13556 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13557 tags (if (match-end 4) (org-match-string-no-properties 4)))
13558 (goto-char (setq lspos (match-beginning 0)))
13559 (setq level (org-reduced-level (org-outline-level))
13560 category (org-get-category))
13561 (setq i llast llast level)
13562 ;; remove tag lists from same and sublevels
13563 (while (>= i level)
13564 (when (setq entry (assoc i tags-alist))
13565 (setq tags-alist (delete entry tags-alist)))
13566 (setq i (1- i)))
13567 ;; add the next tags
13568 (when tags
13569 (setq tags (org-split-string tags ":")
13570 tags-alist
13571 (cons (cons level tags) tags-alist)))
13572 ;; compile tags for current headline
13573 (setq tags-list
13574 (if org-use-tag-inheritance
13575 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13576 tags)
13577 org-scanner-tags tags-list)
13578 (when org-use-tag-inheritance
13579 (setcdr (car tags-alist)
13580 (mapcar (lambda (x)
13581 (setq x (copy-sequence x))
13582 (org-add-prop-inherited x))
13583 (cdar tags-alist))))
13584 (when (and tags org-use-tag-inheritance
13585 (or (not (eq t org-use-tag-inheritance))
13586 org-tags-exclude-from-inheritance))
13587 ;; selective inheritance, remove uninherited ones
13588 (setcdr (car tags-alist)
13589 (org-remove-uninherited-tags (cdar tags-alist))))
13590 (when (and
13592 ;; eval matcher only when the todo condition is OK
13593 (and (or (not todo-only) (member todo org-not-done-keywords))
13594 (let ((case-fold-search t) (org-trust-scanner-tags t))
13595 (eval matcher)))
13597 ;; Call the skipper, but return t if it does not skip,
13598 ;; so that the `and' form continues evaluating
13599 (progn
13600 (unless (eq action 'sparse-tree) (org-agenda-skip))
13603 ;; Check if timestamps are deselecting this entry
13604 (or (not todo-only)
13605 (and (member todo org-not-done-keywords)
13606 (or (not org-agenda-tags-todo-honor-ignore-options)
13607 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13609 ;; select this headline
13610 (cond
13611 ((eq action 'sparse-tree)
13612 (and org-highlight-sparse-tree-matches
13613 (org-get-heading) (match-end 0)
13614 (org-highlight-new-match
13615 (match-beginning 1) (match-end 1)))
13616 (org-show-context 'tags-tree))
13617 ((eq action 'agenda)
13618 (setq txt (org-agenda-format-item
13620 (concat
13621 (if (eq org-tags-match-list-sublevels 'indented)
13622 (make-string (1- level) ?.) "")
13623 (org-get-heading))
13624 level category
13625 tags-list)
13626 priority (org-get-priority txt))
13627 (goto-char lspos)
13628 (setq marker (org-agenda-new-marker))
13629 (org-add-props txt props
13630 'org-marker marker 'org-hd-marker marker 'org-category category
13631 'todo-state todo
13632 'priority priority 'type "tagsmatch")
13633 (push txt rtn))
13634 ((functionp action)
13635 (setq org-map-continue-from nil)
13636 (save-excursion
13637 (setq rtn1 (funcall action))
13638 (push rtn1 rtn)))
13639 (t (error "Invalid action")))
13641 ;; if we are to skip sublevels, jump to end of subtree
13642 (unless org-tags-match-list-sublevels
13643 (org-end-of-subtree t)
13644 (backward-char 1))))
13645 ;; Get the correct position from where to continue
13646 (if org-map-continue-from
13647 (goto-char org-map-continue-from)
13648 (and (= (point) lspos) (end-of-line 1)))))
13649 (when (and (eq action 'sparse-tree)
13650 (not org-sparse-tree-open-archived-trees))
13651 (org-hide-archived-subtrees (point-min) (point-max)))
13652 (nreverse rtn)))
13654 (defun org-remove-uninherited-tags (tags)
13655 "Remove all tags that are not inherited from the list TAGS."
13656 (cond
13657 ((eq org-use-tag-inheritance t)
13658 (if org-tags-exclude-from-inheritance
13659 (org-delete-all org-tags-exclude-from-inheritance tags)
13660 tags))
13661 ((not org-use-tag-inheritance) nil)
13662 ((stringp org-use-tag-inheritance)
13663 (delq nil (mapcar
13664 (lambda (x)
13665 (if (and (string-match org-use-tag-inheritance x)
13666 (not (member x org-tags-exclude-from-inheritance)))
13667 x nil))
13668 tags)))
13669 ((listp org-use-tag-inheritance)
13670 (delq nil (mapcar
13671 (lambda (x)
13672 (if (member x org-use-tag-inheritance) x nil))
13673 tags)))))
13675 (defun org-match-sparse-tree (&optional todo-only match)
13676 "Create a sparse tree according to tags string MATCH.
13677 MATCH can contain positive and negative selection of tags, like
13678 \"+WORK+URGENT-WITHBOSS\".
13679 If optional argument TODO-ONLY is non-nil, only select lines that are
13680 also TODO lines."
13681 (interactive "P")
13682 (org-agenda-prepare-buffers (list (current-buffer)))
13683 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13685 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13687 (defvar org-cached-props nil)
13688 (defun org-cached-entry-get (pom property)
13689 (if (or (eq t org-use-property-inheritance)
13690 (and (stringp org-use-property-inheritance)
13691 (string-match org-use-property-inheritance property))
13692 (and (listp org-use-property-inheritance)
13693 (member property org-use-property-inheritance)))
13694 ;; Caching is not possible, check it directly
13695 (org-entry-get pom property 'inherit)
13696 ;; Get all properties, so that we can do complicated checks easily
13697 (cdr (assoc property (or org-cached-props
13698 (setq org-cached-props
13699 (org-entry-properties pom)))))))
13701 (defun org-global-tags-completion-table (&optional files)
13702 "Return the list of all tags in all agenda buffer/files.
13703 Optional FILES argument is a list of files which can be used
13704 instead of the agenda files."
13705 (save-excursion
13706 (org-uniquify
13707 (delq nil
13708 (apply 'append
13709 (mapcar
13710 (lambda (file)
13711 (set-buffer (find-file-noselect file))
13712 (append (org-get-buffer-tags)
13713 (mapcar (lambda (x) (if (stringp (car-safe x))
13714 (list (car-safe x)) nil))
13715 org-tag-alist)))
13716 (if (and files (car files))
13717 files
13718 (org-agenda-files))))))))
13720 (defun org-make-tags-matcher (match)
13721 "Create the TAGS/TODO matcher form for the selection string MATCH.
13723 The variable `todo-only' is scoped dynamically into this function.
13724 It will be set to t if the matcher restricts matching to TODO entries,
13725 otherwise will not be touched.
13727 Returns a cons of the selection string MATCH and the constructed
13728 lisp form implementing the matcher. The matcher is to be evaluated
13729 at an Org entry, with point on the headline, and returns t if the
13730 entry matches the selection string MATCH. The returned lisp form
13731 references two variables with information about the entry, which
13732 must be bound around the form's evaluation: todo, the TODO keyword
13733 at the entry (or nil of none); and tags-list, the list of all tags
13734 at the entry including inherited ones. Additionally, the category
13735 of the entry (if any) must be specified as the text property
13736 'org-category on the headline.
13738 See also `org-scan-tags'.
13740 (declare (special todo-only))
13741 (unless (boundp 'todo-only)
13742 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13743 (unless match
13744 ;; Get a new match request, with completion
13745 (let ((org-last-tags-completion-table
13746 (org-global-tags-completion-table)))
13747 (setq match (org-completing-read-no-i
13748 "Match: " 'org-tags-completion-function nil nil nil
13749 'org-tags-history))))
13751 ;; Parse the string and create a lisp form
13752 (let ((match0 match)
13753 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13754 minus tag mm
13755 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13756 orterms term orlist re-p str-p level-p level-op time-p
13757 prop-p pn pv po gv rest)
13758 (if (string-match "/+" match)
13759 ;; match contains also a todo-matching request
13760 (progn
13761 (setq tagsmatch (substring match 0 (match-beginning 0))
13762 todomatch (substring match (match-end 0)))
13763 (if (string-match "^!" todomatch)
13764 (setq todo-only t todomatch (substring todomatch 1)))
13765 (if (string-match "^\\s-*$" todomatch)
13766 (setq todomatch nil)))
13767 ;; only matching tags
13768 (setq tagsmatch match todomatch nil))
13770 ;; Make the tags matcher
13771 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13772 (setq tagsmatcher t)
13773 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13774 (while (setq term (pop orterms))
13775 (while (and (equal (substring term -1) "\\") orterms)
13776 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13777 (while (string-match re term)
13778 (setq rest (substring term (match-end 0))
13779 minus (and (match-end 1)
13780 (equal (match-string 1 term) "-"))
13781 tag (save-match-data (replace-regexp-in-string
13782 "\\\\-" "-"
13783 (match-string 2 term)))
13784 re-p (equal (string-to-char tag) ?{)
13785 level-p (match-end 4)
13786 prop-p (match-end 5)
13787 mm (cond
13788 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13789 (level-p
13790 (setq level-op (org-op-to-function (match-string 3 term)))
13791 `(,level-op level ,(string-to-number
13792 (match-string 4 term))))
13793 (prop-p
13794 (setq pn (match-string 5 term)
13795 po (match-string 6 term)
13796 pv (match-string 7 term)
13797 re-p (equal (string-to-char pv) ?{)
13798 str-p (equal (string-to-char pv) ?\")
13799 time-p (save-match-data
13800 (string-match "^\"[[<].*[]>]\"$" pv))
13801 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13802 (if time-p (setq pv (org-matcher-time pv)))
13803 (setq po (org-op-to-function po (if time-p 'time str-p)))
13804 (cond
13805 ((equal pn "CATEGORY")
13806 (setq gv '(get-text-property (point) 'org-category)))
13807 ((equal pn "TODO")
13808 (setq gv 'todo))
13810 (setq gv `(org-cached-entry-get nil ,pn))))
13811 (if re-p
13812 (if (eq po 'org<>)
13813 `(not (string-match ,pv (or ,gv "")))
13814 `(string-match ,pv (or ,gv "")))
13815 (if str-p
13816 `(,po (or ,gv "") ,pv)
13817 `(,po (string-to-number (or ,gv ""))
13818 ,(string-to-number pv) ))))
13819 (t `(member ,tag tags-list)))
13820 mm (if minus (list 'not mm) mm)
13821 term rest)
13822 (push mm tagsmatcher))
13823 (push (if (> (length tagsmatcher) 1)
13824 (cons 'and tagsmatcher)
13825 (car tagsmatcher))
13826 orlist)
13827 (setq tagsmatcher nil))
13828 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13829 (setq tagsmatcher
13830 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13831 ;; Make the todo matcher
13832 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13833 (setq todomatcher t)
13834 (setq orterms (org-split-string todomatch "|") orlist nil)
13835 (while (setq term (pop orterms))
13836 (while (string-match re term)
13837 (setq minus (and (match-end 1)
13838 (equal (match-string 1 term) "-"))
13839 kwd (match-string 2 term)
13840 re-p (equal (string-to-char kwd) ?{)
13841 term (substring term (match-end 0))
13842 mm (if re-p
13843 `(string-match ,(substring kwd 1 -1) todo)
13844 (list 'equal 'todo kwd))
13845 mm (if minus (list 'not mm) mm))
13846 (push mm todomatcher))
13847 (push (if (> (length todomatcher) 1)
13848 (cons 'and todomatcher)
13849 (car todomatcher))
13850 orlist)
13851 (setq todomatcher nil))
13852 (setq todomatcher (if (> (length orlist) 1)
13853 (cons 'or orlist) (car orlist))))
13855 ;; Return the string and lisp forms of the matcher
13856 (setq matcher (if todomatcher
13857 (list 'and tagsmatcher todomatcher)
13858 tagsmatcher))
13859 (when todo-only
13860 (setq matcher (list 'and '(member todo org-not-done-keywords)
13861 matcher)))
13862 (cons match0 matcher)))
13864 (defun org-op-to-function (op &optional stringp)
13865 "Turn an operator into the appropriate function."
13866 (setq op
13867 (cond
13868 ((equal op "<" ) '(< string< org-time<))
13869 ((equal op ">" ) '(> org-string> org-time>))
13870 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13871 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13872 ((member op '("=" "==")) '(= string= org-time=))
13873 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13874 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13876 (defun org<> (a b) (not (= a b)))
13877 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13878 (defun org-string>= (a b) (not (string< a b)))
13879 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13880 (defun org-string<> (a b) (not (string= a b)))
13881 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13882 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13883 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13884 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13885 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13886 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13887 (defun org-2ft (s)
13888 "Convert S to a floating point time.
13889 If S is already a number, just return it. If it is a string, parse
13890 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13891 (cond
13892 ((numberp s) s)
13893 ((stringp s)
13894 (condition-case nil
13895 (float-time (apply 'encode-time (org-parse-time-string s)))
13896 (error 0.)))
13897 (t 0.)))
13899 (defun org-time-today ()
13900 "Time in seconds today at 0:00.
13901 Returns the float number of seconds since the beginning of the
13902 epoch to the beginning of today (00:00)."
13903 (float-time (apply 'encode-time
13904 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13906 (defun org-matcher-time (s)
13907 "Interpret a time comparison value."
13908 (save-match-data
13909 (cond
13910 ((string= s "<now>") (float-time))
13911 ((string= s "<today>") (org-time-today))
13912 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13913 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13914 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13915 (+ (org-time-today)
13916 (* (string-to-number (match-string 1 s))
13917 (cdr (assoc (match-string 2 s)
13918 '(("d" . 86400.0) ("w" . 604800.0)
13919 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13920 (t (org-2ft s)))))
13922 (defun org-match-any-p (re list)
13923 "Does re match any element of list?"
13924 (setq list (mapcar (lambda (x) (string-match re x)) list))
13925 (delq nil list))
13927 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13928 (defvar org-tags-overlay (make-overlay 1 1))
13929 (org-detach-overlay org-tags-overlay)
13931 (defun org-get-local-tags-at (&optional pos)
13932 "Get a list of tags defined in the current headline."
13933 (org-get-tags-at pos 'local))
13935 (defun org-get-local-tags ()
13936 "Get a list of tags defined in the current headline."
13937 (org-get-tags-at nil 'local))
13939 (defun org-get-tags-at (&optional pos local)
13940 "Get a list of all headline tags applicable at POS.
13941 POS defaults to point. If tags are inherited, the list contains
13942 the targets in the same sequence as the headlines appear, i.e.
13943 the tags of the current headline come last.
13944 When LOCAL is non-nil, only return tags from the current headline,
13945 ignore inherited ones."
13946 (interactive)
13947 (if (and org-trust-scanner-tags
13948 (or (not pos) (equal pos (point)))
13949 (not local))
13950 org-scanner-tags
13951 (let (tags ltags lastpos parent)
13952 (save-excursion
13953 (save-restriction
13954 (widen)
13955 (goto-char (or pos (point)))
13956 (save-match-data
13957 (catch 'done
13958 (condition-case nil
13959 (progn
13960 (org-back-to-heading t)
13961 (while (not (equal lastpos (point)))
13962 (setq lastpos (point))
13963 (when (looking-at
13964 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13965 (setq ltags (org-split-string
13966 (org-match-string-no-properties 1) ":"))
13967 (when parent
13968 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13969 (setq tags (append
13970 (if parent
13971 (org-remove-uninherited-tags ltags)
13972 ltags)
13973 tags)))
13974 (or org-use-tag-inheritance (throw 'done t))
13975 (if local (throw 'done t))
13976 (or (org-up-heading-safe) (error nil))
13977 (setq parent t)))
13978 (error nil)))))
13979 (if local
13980 tags
13981 (reverse (delete-dups
13982 (reverse (append
13983 (org-remove-uninherited-tags
13984 org-file-tags) tags)))))))))
13986 (defun org-add-prop-inherited (s)
13987 (add-text-properties 0 (length s) '(inherited t) s)
13990 (defun org-toggle-tag (tag &optional onoff)
13991 "Toggle the tag TAG for the current line.
13992 If ONOFF is `on' or `off', don't toggle but set to this state."
13993 (let (res current)
13994 (save-excursion
13995 (org-back-to-heading t)
13996 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13997 (point-at-eol) t)
13998 (progn
13999 (setq current (match-string 1))
14000 (replace-match ""))
14001 (setq current ""))
14002 (setq current (nreverse (org-split-string current ":")))
14003 (cond
14004 ((eq onoff 'on)
14005 (setq res t)
14006 (or (member tag current) (push tag current)))
14007 ((eq onoff 'off)
14008 (or (not (member tag current)) (setq current (delete tag current))))
14009 (t (if (member tag current)
14010 (setq current (delete tag current))
14011 (setq res t)
14012 (push tag current))))
14013 (end-of-line 1)
14014 (if current
14015 (progn
14016 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14017 (org-set-tags nil t))
14018 (delete-horizontal-space))
14019 (run-hooks 'org-after-tags-change-hook))
14020 res))
14022 (defun org-align-tags-here (to-col)
14023 ;; Assumes that this is a headline
14024 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14025 (beginning-of-line 1)
14026 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14027 (< pos (match-beginning 2)))
14028 (progn
14029 (setq tags-l (- (match-end 2) (match-beginning 2)))
14030 (goto-char (match-beginning 1))
14031 (insert " ")
14032 (delete-region (point) (1+ (match-beginning 2)))
14033 (setq ncol (max (current-column)
14034 (1+ col)
14035 (if (> to-col 0)
14036 to-col
14037 (- (abs to-col) tags-l))))
14038 (setq p (point))
14039 (insert (make-string (- ncol (current-column)) ?\ ))
14040 (setq ncol (current-column))
14041 (when indent-tabs-mode (tabify p (point-at-eol)))
14042 (org-move-to-column (min ncol col) t))
14043 (goto-char pos))))
14045 (defun org-set-tags-command (&optional arg just-align)
14046 "Call the set-tags command for the current entry."
14047 (interactive "P")
14048 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14049 (org-set-tags arg just-align)
14050 (save-excursion
14051 (unless (and (org-region-active-p)
14052 org-loop-over-headlines-in-active-region)
14053 (org-back-to-heading t))
14054 (org-set-tags arg just-align))))
14056 (defun org-set-tags-to (data)
14057 "Set the tags of the current entry to DATA, replacing the current tags.
14058 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14059 If DATA is nil or the empty string, any tags will be removed."
14060 (interactive "sTags: ")
14061 (setq data
14062 (cond
14063 ((eq data nil) "")
14064 ((equal data "") "")
14065 ((stringp data)
14066 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14067 ":"))
14068 ((listp data)
14069 (concat ":" (mapconcat 'identity data ":") ":"))))
14070 (when data
14071 (save-excursion
14072 (org-back-to-heading t)
14073 (when (looking-at org-complex-heading-regexp)
14074 (if (match-end 5)
14075 (progn
14076 (goto-char (match-beginning 5))
14077 (insert data)
14078 (delete-region (point) (point-at-eol))
14079 (org-set-tags nil 'align))
14080 (goto-char (point-at-eol))
14081 (insert " " data)
14082 (org-set-tags nil 'align)))
14083 (beginning-of-line 1)
14084 (if (looking-at ".*?\\([ \t]+\\)$")
14085 (delete-region (match-beginning 1) (match-end 1))))))
14087 (defun org-align-all-tags ()
14088 "Align the tags i all headings."
14089 (interactive)
14090 (save-excursion
14091 (or (ignore-errors (org-back-to-heading t))
14092 (outline-next-heading))
14093 (if (org-at-heading-p)
14094 (org-set-tags t)
14095 (message "No headings"))))
14097 (defvar org-indent-indentation-per-level)
14098 (defun org-set-tags (&optional arg just-align)
14099 "Set the tags for the current headline.
14100 With prefix ARG, realign all tags in headings in the current buffer."
14101 (interactive "P")
14102 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14103 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14104 'region-start-level 'region))
14105 org-loop-over-headlines-in-active-region)
14106 (org-map-entries
14107 ;; We don't use ARG and JUST-ALIGN here these args are not
14108 ;; useful when looping over headlines
14109 `(org-set-tags)
14110 org-loop-over-headlines-in-active-region
14111 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14112 (let* ((re org-outline-regexp-bol)
14113 (current (unless arg (org-get-tags-string)))
14114 (col (current-column))
14115 (org-setting-tags t)
14116 table current-tags inherited-tags ; computed below when needed
14117 tags p0 c0 c1 rpl di tc level)
14118 (if arg
14119 (save-excursion
14120 (goto-char (point-min))
14121 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14122 (while (re-search-forward re nil t)
14123 (org-set-tags nil t)
14124 (end-of-line 1)))
14125 (message "All tags realigned to column %d" org-tags-column))
14126 (if just-align
14127 (setq tags current)
14128 ;; Get a new set of tags from the user
14129 (save-excursion
14130 (setq table (append org-tag-persistent-alist
14131 (or org-tag-alist (org-get-buffer-tags))
14132 (and
14133 org-complete-tags-always-offer-all-agenda-tags
14134 (org-global-tags-completion-table
14135 (org-agenda-files))))
14136 org-last-tags-completion-table table
14137 current-tags (org-split-string current ":")
14138 inherited-tags (nreverse
14139 (nthcdr (length current-tags)
14140 (nreverse (org-get-tags-at))))
14141 tags
14142 (if (or (eq t org-use-fast-tag-selection)
14143 (and org-use-fast-tag-selection
14144 (delq nil (mapcar 'cdr table))))
14145 (org-fast-tag-selection
14146 current-tags inherited-tags table
14147 (if org-fast-tag-selection-include-todo
14148 org-todo-key-alist))
14149 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14150 (org-trim
14151 (org-icompleting-read "Tags: "
14152 'org-tags-completion-function
14153 nil nil current 'org-tags-history))))))
14154 (while (string-match "[-+&]+" tags)
14155 ;; No boolean logic, just a list
14156 (setq tags (replace-match ":" t t tags))))
14158 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14160 (if org-tags-sort-function
14161 (setq tags (mapconcat 'identity
14162 (sort (org-split-string
14163 tags (org-re "[^[:alnum:]_@#%]+"))
14164 org-tags-sort-function) ":")))
14166 (if (string-match "\\`[\t ]*\\'" tags)
14167 (setq tags "")
14168 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14169 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14171 ;; Insert new tags at the correct column
14172 (beginning-of-line 1)
14173 (setq level (or (and (looking-at org-outline-regexp)
14174 (- (match-end 0) (point) 1))
14176 (cond
14177 ((and (equal current "") (equal tags "")))
14178 ((re-search-forward
14179 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14180 (point-at-eol) t)
14181 (if (equal tags "")
14182 (setq rpl "")
14183 (goto-char (match-beginning 0))
14184 (setq c0 (current-column)
14185 ;; compute offset for the case of org-indent-mode active
14186 di (if org-indent-mode
14187 (* (1- org-indent-indentation-per-level) (1- level))
14189 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14190 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14191 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14192 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14193 (replace-match rpl t t)
14194 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14195 tags)
14196 (t (error "Tags alignment failed")))
14197 (org-move-to-column col)
14198 (unless just-align
14199 (run-hooks 'org-after-tags-change-hook))))))
14201 (defun org-change-tag-in-region (beg end tag off)
14202 "Add or remove TAG for each entry in the region.
14203 This works in the agenda, and also in an org-mode buffer."
14204 (interactive
14205 (list (region-beginning) (region-end)
14206 (let ((org-last-tags-completion-table
14207 (if (derived-mode-p 'org-mode)
14208 (org-get-buffer-tags)
14209 (org-global-tags-completion-table))))
14210 (org-icompleting-read
14211 "Tag: " 'org-tags-completion-function nil nil nil
14212 'org-tags-history))
14213 (progn
14214 (message "[s]et or [r]emove? ")
14215 (equal (read-char-exclusive) ?r))))
14216 (if (fboundp 'deactivate-mark) (deactivate-mark))
14217 (let ((agendap (equal major-mode 'org-agenda-mode))
14218 l1 l2 m buf pos newhead (cnt 0))
14219 (goto-char end)
14220 (setq l2 (1- (org-current-line)))
14221 (goto-char beg)
14222 (setq l1 (org-current-line))
14223 (loop for l from l1 to l2 do
14224 (org-goto-line l)
14225 (setq m (get-text-property (point) 'org-hd-marker))
14226 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14227 (and agendap m))
14228 (setq buf (if agendap (marker-buffer m) (current-buffer))
14229 pos (if agendap m (point)))
14230 (with-current-buffer buf
14231 (save-excursion
14232 (save-restriction
14233 (goto-char pos)
14234 (setq cnt (1+ cnt))
14235 (org-toggle-tag tag (if off 'off 'on))
14236 (setq newhead (org-get-heading)))))
14237 (and agendap (org-agenda-change-all-lines newhead m))))
14238 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14240 (defun org-tags-completion-function (string predicate &optional flag)
14241 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14242 (confirm (lambda (x) (stringp (car x)))))
14243 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14244 (setq s1 (match-string 1 string)
14245 s2 (match-string 2 string))
14246 (setq s1 "" s2 string))
14247 (cond
14248 ((eq flag nil)
14249 ;; try completion
14250 (setq rtn (try-completion s2 ctable confirm))
14251 (if (stringp rtn)
14252 (setq rtn
14253 (concat s1 s2 (substring rtn (length s2))
14254 (if (and org-add-colon-after-tag-completion
14255 (assoc rtn ctable))
14256 ":" ""))))
14257 rtn)
14258 ((eq flag t)
14259 ;; all-completions
14260 (all-completions s2 ctable confirm)
14262 ((eq flag 'lambda)
14263 ;; exact match?
14264 (assoc s2 ctable)))
14267 (defun org-fast-tag-insert (kwd tags face &optional end)
14268 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14269 (insert (format "%-12s" (concat kwd ":"))
14270 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14271 (or end "")))
14273 (defun org-fast-tag-show-exit (flag)
14274 (save-excursion
14275 (org-goto-line 3)
14276 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14277 (replace-match ""))
14278 (when flag
14279 (end-of-line 1)
14280 (org-move-to-column (- (window-width) 19) t)
14281 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14283 (defun org-set-current-tags-overlay (current prefix)
14284 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14285 (if (featurep 'xemacs)
14286 (org-overlay-display org-tags-overlay (concat prefix s)
14287 'secondary-selection)
14288 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14289 (org-overlay-display org-tags-overlay (concat prefix s)))))
14291 (defvar org-last-tag-selection-key nil)
14292 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14293 "Fast tag selection with single keys.
14294 CURRENT is the current list of tags in the headline, INHERITED is the
14295 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14296 possibly with grouping information. TODO-TABLE is a similar table with
14297 TODO keywords, should these have keys assigned to them.
14298 If the keys are nil, a-z are automatically assigned.
14299 Returns the new tags string, or nil to not change the current settings."
14300 (let* ((fulltable (append table todo-table))
14301 (maxlen (apply 'max (mapcar
14302 (lambda (x)
14303 (if (stringp (car x)) (string-width (car x)) 0))
14304 fulltable)))
14305 (buf (current-buffer))
14306 (expert (eq org-fast-tag-selection-single-key 'expert))
14307 (buffer-tags nil)
14308 (fwidth (+ maxlen 3 1 3))
14309 (ncol (/ (- (window-width) 4) fwidth))
14310 (i-face 'org-done)
14311 (c-face 'org-todo)
14312 tg cnt e c char c1 c2 ntable tbl rtn
14313 ov-start ov-end ov-prefix
14314 (exit-after-next org-fast-tag-selection-single-key)
14315 (done-keywords org-done-keywords)
14316 groups ingroup)
14317 (save-excursion
14318 (beginning-of-line 1)
14319 (if (looking-at
14320 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14321 (setq ov-start (match-beginning 1)
14322 ov-end (match-end 1)
14323 ov-prefix "")
14324 (setq ov-start (1- (point-at-eol))
14325 ov-end (1+ ov-start))
14326 (skip-chars-forward "^\n\r")
14327 (setq ov-prefix
14328 (concat
14329 (buffer-substring (1- (point)) (point))
14330 (if (> (current-column) org-tags-column)
14332 (make-string (- org-tags-column (current-column)) ?\ ))))))
14333 (move-overlay org-tags-overlay ov-start ov-end)
14334 (save-window-excursion
14335 (if expert
14336 (set-buffer (get-buffer-create " *Org tags*"))
14337 (delete-other-windows)
14338 (split-window-vertically)
14339 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14340 (erase-buffer)
14341 (org-set-local 'org-done-keywords done-keywords)
14342 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14343 (org-fast-tag-insert "Current" current c-face "\n\n")
14344 (org-fast-tag-show-exit exit-after-next)
14345 (org-set-current-tags-overlay current ov-prefix)
14346 (setq tbl fulltable char ?a cnt 0)
14347 (while (setq e (pop tbl))
14348 (cond
14349 ((equal (car e) :startgroup)
14350 (push '() groups) (setq ingroup t)
14351 (when (not (= cnt 0))
14352 (setq cnt 0)
14353 (insert "\n"))
14354 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14355 ((equal (car e) :endgroup)
14356 (setq ingroup nil cnt 0)
14357 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14358 ((equal e '(:newline))
14359 (when (not (= cnt 0))
14360 (setq cnt 0)
14361 (insert "\n")
14362 (setq e (car tbl))
14363 (while (equal (car tbl) '(:newline))
14364 (insert "\n")
14365 (setq tbl (cdr tbl)))))
14367 (setq tg (copy-sequence (car e)) c2 nil)
14368 (if (cdr e)
14369 (setq c (cdr e))
14370 ;; automatically assign a character.
14371 (setq c1 (string-to-char
14372 (downcase (substring
14373 tg (if (= (string-to-char tg) ?@) 1 0)))))
14374 (if (or (rassoc c1 ntable) (rassoc c1 table))
14375 (while (or (rassoc char ntable) (rassoc char table))
14376 (setq char (1+ char)))
14377 (setq c2 c1))
14378 (setq c (or c2 char)))
14379 (if ingroup (push tg (car groups)))
14380 (setq tg (org-add-props tg nil 'face
14381 (cond
14382 ((not (assoc tg table))
14383 (org-get-todo-face tg))
14384 ((member tg current) c-face)
14385 ((member tg inherited) i-face))))
14386 (if (and (= cnt 0) (not ingroup)) (insert " "))
14387 (insert "[" c "] " tg (make-string
14388 (- fwidth 4 (length tg)) ?\ ))
14389 (push (cons tg c) ntable)
14390 (when (= (setq cnt (1+ cnt)) ncol)
14391 (insert "\n")
14392 (if ingroup (insert " "))
14393 (setq cnt 0)))))
14394 (setq ntable (nreverse ntable))
14395 (insert "\n")
14396 (goto-char (point-min))
14397 (if (not expert) (org-fit-window-to-buffer))
14398 (setq rtn
14399 (catch 'exit
14400 (while t
14401 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14402 (if (not groups) "no " "")
14403 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14404 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14405 (setq org-last-tag-selection-key c)
14406 (cond
14407 ((= c ?\r) (throw 'exit t))
14408 ((= c ?!)
14409 (setq groups (not groups))
14410 (goto-char (point-min))
14411 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14412 ((= c ?\C-c)
14413 (if (not expert)
14414 (org-fast-tag-show-exit
14415 (setq exit-after-next (not exit-after-next)))
14416 (setq expert nil)
14417 (delete-other-windows)
14418 (set-window-buffer (split-window-vertically) " *Org tags*")
14419 (org-switch-to-buffer-other-window " *Org tags*")
14420 (org-fit-window-to-buffer)))
14421 ((or (= c ?\C-g)
14422 (and (= c ?q) (not (rassoc c ntable))))
14423 (org-detach-overlay org-tags-overlay)
14424 (setq quit-flag t))
14425 ((= c ?\ )
14426 (setq current nil)
14427 (if exit-after-next (setq exit-after-next 'now)))
14428 ((= c ?\t)
14429 (condition-case nil
14430 (setq tg (org-icompleting-read
14431 "Tag: "
14432 (or buffer-tags
14433 (with-current-buffer buf
14434 (org-get-buffer-tags)))))
14435 (quit (setq tg "")))
14436 (when (string-match "\\S-" tg)
14437 (add-to-list 'buffer-tags (list tg))
14438 (if (member tg current)
14439 (setq current (delete tg current))
14440 (push tg current)))
14441 (if exit-after-next (setq exit-after-next 'now)))
14442 ((setq e (rassoc c todo-table) tg (car e))
14443 (with-current-buffer buf
14444 (save-excursion (org-todo tg)))
14445 (if exit-after-next (setq exit-after-next 'now)))
14446 ((setq e (rassoc c ntable) tg (car e))
14447 (if (member tg current)
14448 (setq current (delete tg current))
14449 (loop for g in groups do
14450 (if (member tg g)
14451 (mapc (lambda (x)
14452 (setq current (delete x current)))
14453 g)))
14454 (push tg current))
14455 (if exit-after-next (setq exit-after-next 'now))))
14457 ;; Create a sorted list
14458 (setq current
14459 (sort current
14460 (lambda (a b)
14461 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14462 (if (eq exit-after-next 'now) (throw 'exit t))
14463 (goto-char (point-min))
14464 (beginning-of-line 2)
14465 (delete-region (point) (point-at-eol))
14466 (org-fast-tag-insert "Current" current c-face)
14467 (org-set-current-tags-overlay current ov-prefix)
14468 (while (re-search-forward
14469 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14470 (setq tg (match-string 1))
14471 (add-text-properties
14472 (match-beginning 1) (match-end 1)
14473 (list 'face
14474 (cond
14475 ((member tg current) c-face)
14476 ((member tg inherited) i-face)
14477 (t (get-text-property (match-beginning 1) 'face))))))
14478 (goto-char (point-min)))))
14479 (org-detach-overlay org-tags-overlay)
14480 (if rtn
14481 (mapconcat 'identity current ":")
14482 nil))))
14484 (defun org-get-tags-string ()
14485 "Get the TAGS string in the current headline."
14486 (unless (org-at-heading-p t)
14487 (error "Not on a heading"))
14488 (save-excursion
14489 (beginning-of-line 1)
14490 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14491 (org-match-string-no-properties 1)
14492 "")))
14494 (defun org-get-tags ()
14495 "Get the list of tags specified in the current headline."
14496 (org-split-string (org-get-tags-string) ":"))
14498 (defun org-get-buffer-tags ()
14499 "Get a table of all tags used in the buffer, for completion."
14500 (let (tags)
14501 (save-excursion
14502 (goto-char (point-min))
14503 (while (re-search-forward
14504 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14505 (when (equal (char-after (point-at-bol 0)) ?*)
14506 (mapc (lambda (x) (add-to-list 'tags x))
14507 (org-split-string (org-match-string-no-properties 1) ":")))))
14508 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14509 (mapcar 'list tags)))
14511 ;;;; The mapping API
14513 (defun org-map-entries (func &optional match scope &rest skip)
14514 "Call FUNC at each headline selected by MATCH in SCOPE.
14516 FUNC is a function or a lisp form. The function will be called without
14517 arguments, with the cursor positioned at the beginning of the headline.
14518 The return values of all calls to the function will be collected and
14519 returned as a list.
14521 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14522 does not need to preserve point. After evaluation, the cursor will be
14523 moved to the end of the line (presumably of the headline of the
14524 processed entry) and search continues from there. Under some
14525 circumstances, this may not produce the wanted results. For example,
14526 if you have removed (e.g. archived) the current (sub)tree it could
14527 mean that the next entry will be skipped entirely. In such cases, you
14528 can specify the position from where search should continue by making
14529 FUNC set the variable `org-map-continue-from' to the desired buffer
14530 position.
14532 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14533 Only headlines that are matched by this query will be considered during
14534 the iteration. When MATCH is nil or t, all headlines will be
14535 visited by the iteration.
14537 SCOPE determines the scope of this command. It can be any of:
14539 nil The current buffer, respecting the restriction if any
14540 tree The subtree started with the entry at point
14541 region The entries within the active region, if any
14542 region-start-level
14543 The entries within the active region, but only those at
14544 the same level than the first one.
14545 file The current buffer, without restriction
14546 file-with-archives
14547 The current buffer, and any archives associated with it
14548 agenda All agenda files
14549 agenda-with-archives
14550 All agenda files with any archive files associated with them
14551 \(file1 file2 ...)
14552 If this is a list, all files in the list will be scanned
14554 The remaining args are treated as settings for the skipping facilities of
14555 the scanner. The following items can be given here:
14557 archive skip trees with the archive tag
14558 comment skip trees with the COMMENT keyword
14559 function or Emacs Lisp form:
14560 will be used as value for `org-agenda-skip-function', so
14561 whenever the function returns a position, FUNC will not be
14562 called for that entry and search will continue from the
14563 position returned
14565 If your function needs to retrieve the tags including inherited tags
14566 at the *current* entry, you can use the value of the variable
14567 `org-scanner-tags' which will be much faster than getting the value
14568 with `org-get-tags-at'. If your function gets properties with
14569 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14570 to t around the call to `org-entry-properties' to get the same speedup.
14571 Note that if your function moves around to retrieve tags and properties at
14572 a *different* entry, you cannot use these techniques."
14573 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14574 (not (org-region-active-p)))
14575 (let* ((org-agenda-archives-mode nil) ; just to make sure
14576 (org-agenda-skip-archived-trees (memq 'archive skip))
14577 (org-agenda-skip-comment-trees (memq 'comment skip))
14578 (org-agenda-skip-function
14579 (car (org-delete-all '(comment archive) skip)))
14580 (org-tags-match-list-sublevels t)
14581 (start-level (eq scope 'region-start-level))
14582 matcher file res
14583 org-todo-keywords-for-agenda
14584 org-done-keywords-for-agenda
14585 org-todo-keyword-alist-for-agenda
14586 org-drawers-for-agenda
14587 org-tag-alist-for-agenda
14588 todo-only)
14590 (cond
14591 ((eq match t) (setq matcher t))
14592 ((eq match nil) (setq matcher t))
14593 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14595 (save-excursion
14596 (save-restriction
14597 (cond ((eq scope 'tree)
14598 (org-back-to-heading t)
14599 (org-narrow-to-subtree)
14600 (setq scope nil))
14601 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14602 (org-region-active-p))
14603 ;; If needed, set start-level to a string like "2"
14604 (when start-level
14605 (save-excursion
14606 (goto-char (region-beginning))
14607 (unless (org-at-heading-p) (outline-next-heading))
14608 (setq start-level (org-current-level))))
14609 (narrow-to-region (region-beginning)
14610 (save-excursion
14611 (goto-char (region-end))
14612 (unless (and (bolp) (org-at-heading-p))
14613 (outline-next-heading))
14614 (point)))
14615 (setq scope nil)))
14617 (if (not scope)
14618 (progn
14619 (org-agenda-prepare-buffers
14620 (list (buffer-file-name (current-buffer))))
14621 (setq res (org-scan-tags func matcher todo-only start-level)))
14622 ;; Get the right scope
14623 (cond
14624 ((and scope (listp scope) (symbolp (car scope)))
14625 (setq scope (eval scope)))
14626 ((eq scope 'agenda)
14627 (setq scope (org-agenda-files t)))
14628 ((eq scope 'agenda-with-archives)
14629 (setq scope (org-agenda-files t))
14630 (setq scope (org-add-archive-files scope)))
14631 ((eq scope 'file)
14632 (setq scope (list (buffer-file-name))))
14633 ((eq scope 'file-with-archives)
14634 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14635 (org-agenda-prepare-buffers scope)
14636 (while (setq file (pop scope))
14637 (with-current-buffer (org-find-base-buffer-visiting file)
14638 (save-excursion
14639 (save-restriction
14640 (widen)
14641 (goto-char (point-min))
14642 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14643 res)))
14645 ;;;; Properties
14647 ;;; Setting and retrieving properties
14649 (defconst org-special-properties
14650 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14651 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14652 "The special properties valid in Org-mode.
14654 These are properties that are not defined in the property drawer,
14655 but in some other way.")
14657 (defconst org-default-properties
14658 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14659 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14660 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14661 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14662 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14663 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14664 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14665 "Some properties that are used by Org-mode for various purposes.
14666 Being in this list makes sure that they are offered for completion.")
14668 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14669 "Regular expression matching the first line of a property drawer.")
14671 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14672 "Regular expression matching the last line of a property drawer.")
14674 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14675 "Regular expression matching the first line of a property drawer.")
14677 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14678 "Regular expression matching the first line of a property drawer.")
14680 (defconst org-property-drawer-re
14681 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14682 org-property-end-re "\\)\n?")
14683 "Matches an entire property drawer.")
14685 (defconst org-clock-drawer-re
14686 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14687 org-property-end-re "\\)\n?")
14688 "Matches an entire clock drawer.")
14690 (defsubst org-re-property (property)
14691 "Return a regexp matching a PROPERTY line.
14692 Match group 1 will be set to the value."
14693 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14695 (defsubst org-re-property-keyword (property)
14696 "Return a regexp matching a PROPERTY line, possibly with no
14697 value for the property."
14698 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14700 (defun org-property-action ()
14701 "Do an action on properties."
14702 (interactive)
14703 (let (c)
14704 (org-at-property-p)
14705 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14706 (setq c (read-char-exclusive))
14707 (cond
14708 ((equal c ?s)
14709 (call-interactively 'org-set-property))
14710 ((equal c ?d)
14711 (call-interactively 'org-delete-property))
14712 ((equal c ?D)
14713 (call-interactively 'org-delete-property-globally))
14714 ((equal c ?c)
14715 (call-interactively 'org-compute-property-at-point))
14716 (t (error "No such property action %c" c)))))
14718 (defun org-inc-effort ()
14719 "Increment the value of the effort property in the current entry."
14720 (interactive)
14721 (org-set-effort nil t))
14723 (defvar org-clock-effort) ;; Defined in org-clock.el
14724 (defvar org-clock-current-task) ;; Defined in org-clock.el
14725 (defun org-set-effort (&optional value increment)
14726 "Set the effort property of the current entry.
14727 With numerical prefix arg, use the nth allowed value, 0 stands for the
14728 10th allowed value.
14730 When INCREMENT is non-nil, set the property to the next allowed value."
14731 (interactive "P")
14732 (if (equal value 0) (setq value 10))
14733 (let* ((completion-ignore-case t)
14734 (prop org-effort-property)
14735 (cur (org-entry-get nil prop))
14736 (allowed (org-property-get-allowed-values nil prop 'table))
14737 (existing (mapcar 'list (org-property-values prop)))
14738 (heading (nth 4 (org-heading-components)))
14740 (val (cond
14741 ((stringp value) value)
14742 ((and allowed (integerp value))
14743 (or (car (nth (1- value) allowed))
14744 (car (org-last allowed))))
14745 ((and allowed increment)
14746 (or (caadr (member (list cur) allowed))
14747 (error "Allowed effort values are not set")))
14748 (allowed
14749 (message "Select 1-9,0, [RET%s]: %s"
14750 (if cur (concat "=" cur) "")
14751 (mapconcat 'car allowed " "))
14752 (setq rpl (read-char-exclusive))
14753 (if (equal rpl ?\r)
14755 (setq rpl (- rpl ?0))
14756 (if (equal rpl 0) (setq rpl 10))
14757 (if (and (> rpl 0) (<= rpl (length allowed)))
14758 (car (nth (1- rpl) allowed))
14759 (org-completing-read "Effort: " allowed nil))))
14761 (let (org-completion-use-ido org-completion-use-iswitchb)
14762 (org-completing-read
14763 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14764 (concat "[" cur "]") "")
14765 ": ")
14766 existing nil nil "" nil cur))))))
14767 (unless (equal (org-entry-get nil prop) val)
14768 (org-entry-put nil prop val))
14769 (save-excursion
14770 (org-back-to-heading t)
14771 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14772 (when (string= heading org-clock-current-task)
14773 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14774 (org-clock-update-mode-line))
14775 (message "%s is now %s" prop val)))
14777 (defun org-at-property-p ()
14778 "Is cursor inside a property drawer?"
14779 (save-excursion
14780 (beginning-of-line 1)
14781 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14782 (save-match-data ;; Used by calling procedures
14783 (let ((p (point))
14784 (range (unless (org-before-first-heading-p)
14785 (org-get-property-block))))
14786 (and range (<= (car range) p) (< p (cdr range))))))))
14788 (defun org-get-property-block (&optional beg end force)
14789 "Return the (beg . end) range of the body of the property drawer.
14790 BEG and END are the beginning and end of the current subtree, or of
14791 the part before the first headline. If they are not given, they will
14792 be found. If the drawer does not exist and FORCE is non-nil, create
14793 the drawer."
14794 (catch 'exit
14795 (save-excursion
14796 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14797 (progn (org-back-to-heading t) (point))))
14798 (end (or end (and (not (outline-next-heading)) (point-max))
14799 (point))))
14800 (goto-char beg)
14801 (if (re-search-forward org-property-start-re end t)
14802 (setq beg (1+ (match-end 0)))
14803 (if force
14804 (save-excursion
14805 (org-insert-property-drawer)
14806 (setq end (progn (outline-next-heading) (point))))
14807 (throw 'exit nil))
14808 (goto-char beg)
14809 (if (re-search-forward org-property-start-re end t)
14810 (setq beg (1+ (match-end 0)))))
14811 (if (re-search-forward org-property-end-re end t)
14812 (setq end (match-beginning 0))
14813 (or force (throw 'exit nil))
14814 (goto-char beg)
14815 (setq end beg)
14816 (org-indent-line)
14817 (insert ":END:\n"))
14818 (cons beg end)))))
14820 (defun org-entry-properties (&optional pom which specific)
14821 "Get all properties of the entry at point-or-marker POM.
14822 This includes the TODO keyword, the tags, time strings for deadline,
14823 scheduled, and clocking, and any additional properties defined in the
14824 entry. The return value is an alist, keys may occur multiple times
14825 if the property key was used several times.
14826 POM may also be nil, in which case the current entry is used.
14827 If WHICH is nil or `all', get all properties. If WHICH is
14828 `special' or `standard', only get that subclass. If WHICH
14829 is a string only get exactly this property. SPECIFIC can be a string, the
14830 specific property we are interested in. Specifying it can speed
14831 things up because then unnecessary parsing is avoided."
14832 (setq which (or which 'all))
14833 (org-with-point-at pom
14834 (let ((clockstr (substring org-clock-string 0 -1))
14835 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14836 (case-fold-search nil)
14837 beg end range props sum-props key key1 value string clocksum clocksumt)
14838 (save-excursion
14839 (when (condition-case nil
14840 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14841 (error nil))
14842 (setq beg (point))
14843 (setq sum-props (get-text-property (point) 'org-summaries))
14844 (setq clocksum (get-text-property (point) :org-clock-minutes)
14845 clocksumt (get-text-property (point) :org-clock-minutes-today))
14846 (outline-next-heading)
14847 (setq end (point))
14848 (when (memq which '(all special))
14849 ;; Get the special properties, like TODO and tags
14850 (goto-char beg)
14851 (when (and (or (not specific) (string= specific "TODO"))
14852 (looking-at org-todo-line-regexp) (match-end 2))
14853 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14854 (when (and (or (not specific) (string= specific "PRIORITY"))
14855 (looking-at org-priority-regexp))
14856 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14857 (when (or (not specific) (string= specific "FILE"))
14858 (push (cons "FILE" buffer-file-name) props))
14859 (when (and (or (not specific) (string= specific "TAGS"))
14860 (setq value (org-get-tags-string))
14861 (string-match "\\S-" value))
14862 (push (cons "TAGS" value) props))
14863 (when (and (or (not specific) (string= specific "ALLTAGS"))
14864 (setq value (org-get-tags-at)))
14865 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14866 ":"))
14867 props))
14868 (when (or (not specific) (string= specific "BLOCKED"))
14869 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14870 (when (or (not specific)
14871 (member specific
14872 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14873 "TIMESTAMP" "TIMESTAMP_IA")))
14874 (catch 'match
14875 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14876 (setq key (if (match-end 1)
14877 (substring (org-match-string-no-properties 1)
14878 0 -1))
14879 string (if (equal key clockstr)
14880 (org-trim
14881 (buffer-substring-no-properties
14882 (match-beginning 3) (goto-char
14883 (point-at-eol))))
14884 (substring (org-match-string-no-properties 3)
14885 1 -1)))
14886 ;; Get the correct property name from the key. This is
14887 ;; necessary if the user has configured time keywords.
14888 (setq key1 (concat key ":"))
14889 (cond
14890 ((not key)
14891 (setq key
14892 (if (= (char-after (match-beginning 3)) ?\[)
14893 "TIMESTAMP_IA" "TIMESTAMP")))
14894 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14895 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14896 ((equal key1 org-closed-string) (setq key "CLOSED"))
14897 ((equal key1 org-clock-string) (setq key "CLOCK")))
14898 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14899 (progn
14900 (push (cons key string) props)
14901 ;; no need to search further if match is found
14902 (throw 'match t))
14903 (when (or (equal key "CLOCK") (not (assoc key props)))
14904 (push (cons key string) props)))))))
14906 (when (memq which '(all standard))
14907 ;; Get the standard properties, like :PROP: ...
14908 (setq range (org-get-property-block beg end))
14909 (when range
14910 (goto-char (car range))
14911 (while (re-search-forward
14912 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14913 (cdr range) t)
14914 (setq key (org-match-string-no-properties 1)
14915 value (org-trim (or (org-match-string-no-properties 2) "")))
14916 (unless (member key excluded)
14917 (push (cons key (or value "")) props)))))
14918 (if clocksum
14919 (push (cons "CLOCKSUM"
14920 (org-columns-number-to-string (/ (float clocksum) 60.)
14921 'add_times))
14922 props))
14923 (if clocksumt
14924 (push (cons "CLOCKSUM_T"
14925 (org-columns-number-to-string (/ (float clocksumt) 60.)
14926 'add_times))
14927 props))
14928 (unless (assoc "CATEGORY" props)
14929 (push (cons "CATEGORY" (org-get-category)) props))
14930 (append sum-props (nreverse props)))))))
14932 (defun org-entry-get (pom property &optional inherit literal-nil)
14933 "Get value of PROPERTY for entry or content at point-or-marker POM.
14934 If INHERIT is non-nil and the entry does not have the property,
14935 then also check higher levels of the hierarchy.
14936 If INHERIT is the symbol `selective', use inheritance only if the setting
14937 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14938 If the property is present but empty, the return value is the empty string.
14939 If the property is not present at all, nil is returned.
14941 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14942 do not interpret it as the list atom nil. This is used for inheritance
14943 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14944 (org-with-point-at pom
14945 (if (and inherit (if (eq inherit 'selective)
14946 (org-property-inherit-p property)
14948 (org-entry-get-with-inheritance property literal-nil)
14949 (if (member property org-special-properties)
14950 ;; We need a special property. Use `org-entry-properties' to
14951 ;; retrieve it, but specify the wanted property
14952 (cdr (assoc property (org-entry-properties nil 'special property)))
14953 (let ((range (org-get-property-block)))
14954 (when (and range (not (eq (car range) (cdr range))))
14955 (let* ((props (list (or (assoc property org-file-properties)
14956 (assoc property org-global-properties)
14957 (assoc property org-global-properties-fixed))))
14958 (ap (lambda (key)
14959 (when (re-search-forward
14960 (org-re-property key) (cdr range) t)
14961 (setq props
14962 (org-update-property-plist
14964 (if (match-end 1)
14965 (org-match-string-no-properties 1) "")
14966 props)))))
14967 val)
14968 (goto-char (car range))
14969 (funcall ap property)
14970 (goto-char (car range))
14971 (while (funcall ap (concat property "+")))
14972 (setq val (cdr (assoc property props)))
14973 (when val (if literal-nil val (org-not-nil val))))))))))
14975 (defun org-property-or-variable-value (var &optional inherit)
14976 "Check if there is a property fixing the value of VAR.
14977 If yes, return this value. If not, return the current value of the variable."
14978 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14979 (if (and prop (stringp prop) (string-match "\\S-" prop))
14980 (read prop)
14981 (symbol-value var))))
14983 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14984 "Delete the property PROPERTY from entry at point-or-marker POM.
14985 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14986 an empty drawer to delete."
14987 (org-with-point-at pom
14988 (if (member property org-special-properties)
14989 nil ; cannot delete these properties.
14990 (let ((range (org-get-property-block)))
14991 (if (and range
14992 (goto-char (car range))
14993 (re-search-forward
14994 (org-re-property property)
14995 (cdr range) t))
14996 (progn
14997 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14998 (and delete-empty-drawer
14999 (org-remove-empty-drawer-at
15000 delete-empty-drawer (car range)))
15002 nil)))))
15004 ;; Multi-values properties are properties that contain multiple values
15005 ;; These values are assumed to be single words, separated by whitespace.
15006 (defun org-entry-add-to-multivalued-property (pom property value)
15007 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15008 (let* ((old (org-entry-get pom property))
15009 (values (and old (org-split-string old "[ \t]"))))
15010 (setq value (org-entry-protect-space value))
15011 (unless (member value values)
15012 (setq values (cons value values))
15013 (org-entry-put pom property
15014 (mapconcat 'identity values " ")))))
15016 (defun org-entry-remove-from-multivalued-property (pom property value)
15017 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15018 (let* ((old (org-entry-get pom property))
15019 (values (and old (org-split-string old "[ \t]"))))
15020 (setq value (org-entry-protect-space value))
15021 (when (member value values)
15022 (setq values (delete value values))
15023 (org-entry-put pom property
15024 (mapconcat 'identity values " ")))))
15026 (defun org-entry-member-in-multivalued-property (pom property value)
15027 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15028 (let* ((old (org-entry-get pom property))
15029 (values (and old (org-split-string old "[ \t]"))))
15030 (setq value (org-entry-protect-space value))
15031 (member value values)))
15033 (defun org-entry-get-multivalued-property (pom property)
15034 "Return a list of values in a multivalued property."
15035 (let* ((value (org-entry-get pom property))
15036 (values (and value (org-split-string value "[ \t]"))))
15037 (mapcar 'org-entry-restore-space values)))
15039 (defun org-entry-put-multivalued-property (pom property &rest values)
15040 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15041 VALUES should be a list of strings. Spaces will be protected."
15042 (org-entry-put pom property
15043 (mapconcat 'org-entry-protect-space values " "))
15044 (let* ((value (org-entry-get pom property))
15045 (values (and value (org-split-string value "[ \t]"))))
15046 (mapcar 'org-entry-restore-space values)))
15048 (defun org-entry-protect-space (s)
15049 "Protect spaces and newline in string S."
15050 (while (string-match " " s)
15051 (setq s (replace-match "%20" t t s)))
15052 (while (string-match "\n" s)
15053 (setq s (replace-match "%0A" t t s)))
15056 (defun org-entry-restore-space (s)
15057 "Restore spaces and newline in string S."
15058 (while (string-match "%20" s)
15059 (setq s (replace-match " " t t s)))
15060 (while (string-match "%0A" s)
15061 (setq s (replace-match "\n" t t s)))
15064 (defvar org-entry-property-inherited-from (make-marker)
15065 "Marker pointing to the entry from where a property was inherited.
15066 Each call to `org-entry-get-with-inheritance' will set this marker to the
15067 location of the entry where the inheritance search matched. If there was
15068 no match, the marker will point nowhere.
15069 Note that also `org-entry-get' calls this function, if the INHERIT flag
15070 is set.")
15072 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15073 "Get PROPERTY of entry or content at point, search higher levels if needed.
15074 The search will stop at the first ancestor which has the property defined.
15075 If the value found is \"nil\", return nil to show that the property
15076 should be considered as undefined (this is the meaning of nil here).
15077 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15078 (move-marker org-entry-property-inherited-from nil)
15079 (let (tmp)
15080 (save-excursion
15081 (save-restriction
15082 (widen)
15083 (catch 'ex
15084 (while t
15085 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15086 (or (ignore-errors (org-back-to-heading t))
15087 (goto-char (point-min)))
15088 (move-marker org-entry-property-inherited-from (point))
15089 (throw 'ex tmp))
15090 (or (ignore-errors (org-up-heading-safe))
15091 (throw 'ex nil))))))
15092 (setq tmp (or tmp
15093 (cdr (assoc property org-file-properties))
15094 (cdr (assoc property org-global-properties))
15095 (cdr (assoc property org-global-properties-fixed))))
15096 (if literal-nil tmp (org-not-nil tmp))))
15098 (defvar org-property-changed-functions nil
15099 "Hook called when the value of a property has changed.
15100 Each hook function should accept two arguments, the name of the property
15101 and the new value.")
15103 (defun org-entry-put (pom property value)
15104 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15105 (org-with-point-at pom
15106 (org-back-to-heading t)
15107 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15108 range)
15109 (cond
15110 ((equal property "TODO")
15111 (when (and (stringp value) (string-match "\\S-" value)
15112 (not (member value org-todo-keywords-1)))
15113 (error "\"%s\" is not a valid TODO state" value))
15114 (if (or (not value)
15115 (not (string-match "\\S-" value)))
15116 (setq value 'none))
15117 (org-todo value)
15118 (org-set-tags nil 'align))
15119 ((equal property "PRIORITY")
15120 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15121 (string-to-char value) ?\ ))
15122 (org-set-tags nil 'align))
15123 ((equal property "CLOCKSUM")
15124 (if (not (re-search-forward
15125 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15126 (error "Cannot find a clock log")
15127 (goto-char (- (match-end 1) 2))
15128 (cond
15129 ((eq value 'earlier) (org-timestamp-down))
15130 ((eq value 'later) (org-timestamp-up)))
15131 (org-clock-sum-current-item)))
15132 ((equal property "SCHEDULED")
15133 (if (re-search-forward org-scheduled-time-regexp end t)
15134 (cond
15135 ((eq value 'earlier) (org-timestamp-change -1 'day))
15136 ((eq value 'later) (org-timestamp-change 1 'day))
15137 (t (call-interactively 'org-schedule)))
15138 (call-interactively 'org-schedule)))
15139 ((equal property "DEADLINE")
15140 (if (re-search-forward org-deadline-time-regexp end t)
15141 (cond
15142 ((eq value 'earlier) (org-timestamp-change -1 'day))
15143 ((eq value 'later) (org-timestamp-change 1 'day))
15144 (t (call-interactively 'org-deadline)))
15145 (call-interactively 'org-deadline)))
15146 ((member property org-special-properties)
15147 (error "The %s property can not yet be set with `org-entry-put'"
15148 property))
15149 (t ; a non-special property
15150 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15151 (setq range (org-get-property-block beg end 'force))
15152 (goto-char (car range))
15153 (if (re-search-forward
15154 (org-re-property-keyword property) (cdr range) t)
15155 (progn
15156 (delete-region (match-beginning 0) (match-end 0))
15157 (goto-char (match-beginning 0)))
15158 (goto-char (cdr range))
15159 (insert "\n")
15160 (backward-char 1)
15161 (org-indent-line))
15162 (insert ":" property ":")
15163 (and value (insert " " value))
15164 (org-indent-line)))))
15165 (run-hook-with-args 'org-property-changed-functions property value)))
15167 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15168 "Get all property keys in the current buffer.
15169 With INCLUDE-SPECIALS, also list the special properties that reflect things
15170 like tags and TODO state.
15171 With INCLUDE-DEFAULTS, also include properties that has special meaning
15172 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15173 and others.
15174 With INCLUDE-COLUMNS, also include property names given in COLUMN
15175 formats in the current buffer."
15176 (let (rtn range cfmt s p)
15177 (save-excursion
15178 (save-restriction
15179 (widen)
15180 (goto-char (point-min))
15181 (while (re-search-forward org-property-start-re nil t)
15182 (setq range (org-get-property-block))
15183 (goto-char (car range))
15184 (while (re-search-forward
15185 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15186 (cdr range) t)
15187 (add-to-list 'rtn (org-match-string-no-properties 1)))
15188 (outline-next-heading))))
15190 (when include-specials
15191 (setq rtn (append org-special-properties rtn)))
15193 (when include-defaults
15194 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15195 (add-to-list 'rtn org-effort-property))
15197 (when include-columns
15198 (save-excursion
15199 (save-restriction
15200 (widen)
15201 (goto-char (point-min))
15202 (while (re-search-forward
15203 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15204 nil t)
15205 (setq cfmt (match-string 2) s 0)
15206 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15207 cfmt s)
15208 (setq s (match-end 0)
15209 p (match-string 1 cfmt))
15210 (unless (or (equal p "ITEM")
15211 (member p org-special-properties))
15212 (add-to-list 'rtn (match-string 1 cfmt))))))))
15214 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15216 (defun org-property-values (key)
15217 "Return a list of all values of property KEY in the current buffer."
15218 (save-excursion
15219 (save-restriction
15220 (widen)
15221 (goto-char (point-min))
15222 (let ((re (org-re-property key))
15223 values)
15224 (while (re-search-forward re nil t)
15225 (add-to-list 'values (org-trim (match-string 1))))
15226 (delete "" values)))))
15228 (defun org-insert-property-drawer ()
15229 "Insert a property drawer into the current entry."
15230 (org-back-to-heading t)
15231 (looking-at org-outline-regexp)
15232 (let ((indent (if org-adapt-indentation
15233 (- (match-end 0) (match-beginning 0))
15235 (beg (point))
15236 (re (concat "^[ \t]*" org-keyword-time-regexp))
15237 end hiddenp)
15238 (outline-next-heading)
15239 (setq end (point))
15240 (goto-char beg)
15241 (while (re-search-forward re end t))
15242 (setq hiddenp (outline-invisible-p))
15243 (end-of-line 1)
15244 (and (equal (char-after) ?\n) (forward-char 1))
15245 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15246 (if (member (match-string 1) '("CLOCK:" ":END:"))
15247 ;; just skip this line
15248 (beginning-of-line 2)
15249 ;; Drawer start, find the end
15250 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15251 (beginning-of-line 1)))
15252 (org-skip-over-state-notes)
15253 (skip-chars-backward " \t\n\r")
15254 (if (eq (char-before) ?*) (forward-char 1))
15255 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15256 (beginning-of-line 0)
15257 (org-indent-to-column indent)
15258 (beginning-of-line 2)
15259 (org-indent-to-column indent)
15260 (beginning-of-line 0)
15261 (if hiddenp
15262 (save-excursion
15263 (org-back-to-heading t)
15264 (hide-entry))
15265 (org-flag-drawer t))))
15267 (defun org-insert-drawer (&optional arg drawer)
15268 "Insert a drawer at point.
15270 Optional argument DRAWER, when non-nil, is a string representing
15271 drawer's name. Otherwise, the user is prompted for a name.
15273 If a region is active, insert the drawer around that region
15274 instead.
15276 Point is left between drawer's boundaries."
15277 (interactive "P")
15278 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15279 "LOGBOOK"))
15280 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15281 ;; internally by Org. They are meant to be inserted
15282 ;; automatically.
15283 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15284 ;; Remove system drawers from list. Note: For some reason,
15285 ;; `org-completing-read' ignores the predicate while
15286 ;; `completing-read' handles it fine.
15287 (drawer (if arg "PROPERTIES"
15288 (or drawer
15289 (completing-read
15290 "Drawer: " org-drawers
15291 (lambda (d) (not (member d system-drawers))))))))
15292 (cond
15293 ;; With C-u, fall back on `org-insert-property-drawer'
15294 (arg (org-insert-property-drawer))
15295 ;; With an active region, insert a drawer at point.
15296 ((not (org-region-active-p))
15297 (progn
15298 (unless (bolp) (insert "\n"))
15299 (insert (format ":%s:\n\n:END:\n" drawer))
15300 (forward-line -2)))
15301 ;; Otherwise, insert the drawer at point
15303 (let ((rbeg (region-beginning))
15304 (rend (copy-marker (region-end))))
15305 (unwind-protect
15306 (progn
15307 (goto-char rbeg)
15308 (beginning-of-line)
15309 (when (save-excursion
15310 (re-search-forward org-outline-regexp-bol rend t))
15311 (error "Drawers cannot contain headlines"))
15312 ;; Position point at the beginning of the first
15313 ;; non-blank line in region. Insert drawer's opening
15314 ;; there, then indent it.
15315 (org-skip-whitespace)
15316 (beginning-of-line)
15317 (insert ":" drawer ":\n")
15318 (forward-line -1)
15319 (indent-for-tab-command)
15320 ;; Move point to the beginning of the first blank line
15321 ;; after the last non-blank line in region. Insert
15322 ;; drawer's closing, then indent it.
15323 (goto-char rend)
15324 (skip-chars-backward " \r\t\n")
15325 (insert "\n:END:")
15326 (deactivate-mark t)
15327 (indent-for-tab-command)
15328 (unless (eolp) (insert "\n")))
15329 ;; Clear marker, whatever the outcome of insertion is.
15330 (set-marker rend nil)))))))
15332 (defvar org-property-set-functions-alist nil
15333 "Property set function alist.
15334 Each entry should have the following format:
15336 (PROPERTY . READ-FUNCTION)
15338 The read function will be called with the same argument as
15339 `org-completing-read'.")
15341 (defun org-set-property-function (property)
15342 "Get the function that should be used to set PROPERTY.
15343 This is computed according to `org-property-set-functions-alist'."
15344 (or (cdr (assoc property org-property-set-functions-alist))
15345 'org-completing-read))
15347 (defun org-read-property-value (property)
15348 "Read PROPERTY value from user."
15349 (let* ((completion-ignore-case t)
15350 (allowed (org-property-get-allowed-values nil property 'table))
15351 (cur (org-entry-get nil property))
15352 (prompt (concat property " value"
15353 (if (and cur (string-match "\\S-" cur))
15354 (concat " [" cur "]") "") ": "))
15355 (set-function (org-set-property-function property))
15356 (val (if allowed
15357 (funcall set-function prompt allowed nil
15358 (not (get-text-property 0 'org-unrestricted
15359 (caar allowed))))
15360 (let (org-completion-use-ido org-completion-use-iswitchb)
15361 (funcall set-function prompt
15362 (mapcar 'list (org-property-values property))
15363 nil nil "" nil cur)))))
15364 (if (equal val "")
15366 val)))
15368 (defvar org-last-set-property nil)
15369 (defvar org-last-set-property-value nil)
15370 (defun org-read-property-name ()
15371 "Read a property name."
15372 (let* ((completion-ignore-case t)
15373 (keys (org-buffer-property-keys nil t t))
15374 (default-prop (or (save-excursion
15375 (save-match-data
15376 (beginning-of-line)
15377 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15378 (null (string= (match-string 1) "END"))
15379 (match-string 1))))
15380 org-last-set-property))
15381 (property (org-icompleting-read
15382 (concat "Property"
15383 (if default-prop (concat " [" default-prop "]") "")
15384 ": ")
15385 (mapcar 'list keys)
15386 nil nil nil nil
15387 default-prop)))
15388 (if (member property keys)
15389 property
15390 (or (cdr (assoc (downcase property)
15391 (mapcar (lambda (x) (cons (downcase x) x))
15392 keys)))
15393 property))))
15395 (defun org-set-property-and-value (use-last)
15396 "Allow to set [PROPERTY]: [value] direction from prompt.
15397 When use-default, don't even ask, just use the last
15398 \"[PROPERTY]: [value]\" string from the history."
15399 (interactive "P")
15400 (let* ((completion-ignore-case t)
15401 (pv (or (and use-last org-last-set-property-value)
15402 (org-completing-read
15403 "Enter a \"[Property]: [value]\" pair: "
15404 nil nil nil nil nil
15405 org-last-set-property-value)))
15406 prop val)
15407 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15408 (setq prop (match-string 1 pv)
15409 val (match-string 2 pv))
15410 (org-set-property prop val))))
15412 (defun org-set-property (property value)
15413 "In the current entry, set PROPERTY to VALUE.
15414 When called interactively, this will prompt for a property name, offering
15415 completion on existing and default properties. And then it will prompt
15416 for a value, offering completion either on allowed values (via an inherited
15417 xxx_ALL property) or on existing values in other instances of this property
15418 in the current file."
15419 (interactive (list nil nil))
15420 (let* ((property (or property (org-read-property-name)))
15421 (value (or value (org-read-property-value property)))
15422 (fn (cdr (assoc property org-properties-postprocess-alist))))
15423 (setq org-last-set-property property)
15424 (setq org-last-set-property-value (concat property ": " value))
15425 ;; Possibly postprocess the inserted value:
15426 (when fn (setq value (funcall fn value)))
15427 (unless (equal (org-entry-get nil property) value)
15428 (org-entry-put nil property value))))
15430 (defun org-delete-property (property &optional delete-empty-drawer)
15431 "In the current entry, delete PROPERTY.
15432 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15433 an empty drawer to delete."
15434 (interactive
15435 (let* ((completion-ignore-case t)
15436 (prop (org-icompleting-read "Property: "
15437 (org-entry-properties nil 'standard))))
15438 (list prop)))
15439 (message "Property %s %s" property
15440 (if (org-entry-delete nil property delete-empty-drawer)
15441 "deleted"
15442 "was not present in the entry")))
15444 (defun org-delete-property-globally (property)
15445 "Remove PROPERTY globally, from all entries."
15446 (interactive
15447 (let* ((completion-ignore-case t)
15448 (prop (org-icompleting-read
15449 "Globally remove property: "
15450 (mapcar 'list (org-buffer-property-keys)))))
15451 (list prop)))
15452 (save-excursion
15453 (save-restriction
15454 (widen)
15455 (goto-char (point-min))
15456 (let ((cnt 0))
15457 (while (re-search-forward
15458 (org-re-property property)
15459 nil t)
15460 (setq cnt (1+ cnt))
15461 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15462 (message "Property \"%s\" removed from %d entries" property cnt)))))
15464 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15466 (defun org-compute-property-at-point ()
15467 "Compute the property at point.
15468 This looks for an enclosing column format, extracts the operator and
15469 then applies it to the property in the column format's scope."
15470 (interactive)
15471 (unless (org-at-property-p)
15472 (error "Not at a property"))
15473 (let ((prop (org-match-string-no-properties 2)))
15474 (org-columns-get-format-and-top-level)
15475 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15476 (error "No operator defined for property %s" prop))
15477 (org-columns-compute prop)))
15479 (defvar org-property-allowed-value-functions nil
15480 "Hook for functions supplying allowed values for a specific property.
15481 The functions must take a single argument, the name of the property, and
15482 return a flat list of allowed values. If \":ETC\" is one of
15483 the values, this means that these values are intended as defaults for
15484 completion, but that other values should be allowed too.
15485 The functions must return nil if they are not responsible for this
15486 property.")
15488 (defun org-property-get-allowed-values (pom property &optional table)
15489 "Get allowed values for the property PROPERTY.
15490 When TABLE is non-nil, return an alist that can directly be used for
15491 completion."
15492 (let (vals)
15493 (cond
15494 ((equal property "TODO")
15495 (setq vals (org-with-point-at pom
15496 (append org-todo-keywords-1 '("")))))
15497 ((equal property "PRIORITY")
15498 (let ((n org-lowest-priority))
15499 (while (>= n org-highest-priority)
15500 (push (char-to-string n) vals)
15501 (setq n (1- n)))))
15502 ((member property org-special-properties))
15503 ((setq vals (run-hook-with-args-until-success
15504 'org-property-allowed-value-functions property)))
15506 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15507 (when (and vals (string-match "\\S-" vals))
15508 (setq vals (car (read-from-string (concat "(" vals ")"))))
15509 (setq vals (mapcar (lambda (x)
15510 (cond ((stringp x) x)
15511 ((numberp x) (number-to-string x))
15512 ((symbolp x) (symbol-name x))
15513 (t "???")))
15514 vals)))))
15515 (when (member ":ETC" vals)
15516 (setq vals (remove ":ETC" vals))
15517 (org-add-props (car vals) '(org-unrestricted t)))
15518 (if table (mapcar 'list vals) vals)))
15520 (defun org-property-previous-allowed-value (&optional previous)
15521 "Switch to the next allowed value for this property."
15522 (interactive)
15523 (org-property-next-allowed-value t))
15525 (defun org-property-next-allowed-value (&optional previous)
15526 "Switch to the next allowed value for this property."
15527 (interactive)
15528 (unless (org-at-property-p)
15529 (error "Not at a property"))
15530 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15531 (key (match-string 2))
15532 (value (match-string 3))
15533 (allowed (or (org-property-get-allowed-values (point) key)
15534 (and (member value '("[ ]" "[-]" "[X]"))
15535 '("[ ]" "[X]"))))
15536 (heading (save-match-data (nth 4 (org-heading-components))))
15537 nval)
15538 (unless allowed
15539 (error "Allowed values for this property have not been defined"))
15540 (if previous (setq allowed (reverse allowed)))
15541 (if (member value allowed)
15542 (setq nval (car (cdr (member value allowed)))))
15543 (setq nval (or nval (car allowed)))
15544 (if (equal nval value)
15545 (error "Only one allowed value for this property"))
15546 (org-at-property-p)
15547 (replace-match (concat " :" key ": " nval) t t)
15548 (org-indent-line)
15549 (beginning-of-line 1)
15550 (skip-chars-forward " \t")
15551 (when (equal prop org-effort-property)
15552 (save-excursion
15553 (org-back-to-heading t)
15554 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15555 (when (string= org-clock-current-task heading)
15556 (setq org-clock-effort nval)
15557 (org-clock-update-mode-line)))
15558 (run-hook-with-args 'org-property-changed-functions key nval)))
15560 (defun org-find-olp (path &optional this-buffer)
15561 "Return a marker pointing to the entry at outline path OLP.
15562 If anything goes wrong, throw an error.
15563 You can wrap this call to catch the error like this:
15565 (condition-case msg
15566 (org-mobile-locate-entry (match-string 4))
15567 (error (nth 1 msg)))
15569 The return value will then be either a string with the error message,
15570 or a marker if everything is OK.
15572 If THIS-BUFFER is set, the outline path does not contain a file,
15573 only headings."
15574 (let* ((file (if this-buffer buffer-file-name (pop path)))
15575 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15576 (level 1)
15577 (lmin 1)
15578 (lmax 1)
15579 limit re end found pos heading cnt flevel)
15580 (unless buffer (error "File not found :%s" file))
15581 (with-current-buffer buffer
15582 (save-excursion
15583 (save-restriction
15584 (widen)
15585 (setq limit (point-max))
15586 (goto-char (point-min))
15587 (while (setq heading (pop path))
15588 (setq re (format org-complex-heading-regexp-format
15589 (regexp-quote heading)))
15590 (setq cnt 0 pos (point))
15591 (while (re-search-forward re end t)
15592 (setq level (- (match-end 1) (match-beginning 1)))
15593 (if (and (>= level lmin) (<= level lmax))
15594 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15595 (when (= cnt 0) (error "Heading not found on level %d: %s"
15596 lmax heading))
15597 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15598 lmax heading))
15599 (goto-char found)
15600 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15601 (setq end (save-excursion (org-end-of-subtree t t))))
15602 (when (org-at-heading-p)
15603 (point-marker)))))))
15605 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15606 "Find node HEADING in BUFFER.
15607 Return a marker to the heading if it was found, or nil if not.
15608 If POS-ONLY is set, return just the position instead of a marker.
15610 The heading text must match exact, but it may have a TODO keyword,
15611 a priority cookie and tags in the standard locations."
15612 (with-current-buffer (or buffer (current-buffer))
15613 (save-excursion
15614 (save-restriction
15615 (widen)
15616 (goto-char (point-min))
15617 (let (case-fold-search)
15618 (if (re-search-forward
15619 (format org-complex-heading-regexp-format
15620 (regexp-quote heading)) nil t)
15621 (if pos-only
15622 (match-beginning 0)
15623 (move-marker (make-marker) (match-beginning 0)))))))))
15625 (defun org-find-exact-heading-in-directory (heading &optional dir)
15626 "Find Org node headline HEADING in all .org files in directory DIR.
15627 When the target headline is found, return a marker to this location."
15628 (let ((files (directory-files (or dir default-directory)
15629 nil "\\`[^.#].*\\.org\\'"))
15630 file visiting m buffer)
15631 (catch 'found
15632 (while (setq file (pop files))
15633 (message "trying %s" file)
15634 (setq visiting (org-find-base-buffer-visiting file))
15635 (setq buffer (or visiting (find-file-noselect file)))
15636 (setq m (org-find-exact-headline-in-buffer
15637 heading buffer))
15638 (when (and (not m) (not visiting)) (kill-buffer buffer))
15639 (and m (throw 'found m))))))
15641 (defun org-find-entry-with-id (ident)
15642 "Locate the entry that contains the ID property with exact value IDENT.
15643 IDENT can be a string, a symbol or a number, this function will search for
15644 the string representation of it.
15645 Return the position where this entry starts, or nil if there is no such entry."
15646 (interactive "sID: ")
15647 (let ((id (cond
15648 ((stringp ident) ident)
15649 ((symbol-name ident) (symbol-name ident))
15650 ((numberp ident) (number-to-string ident))
15651 (t (error "IDENT %s must be a string, symbol or number" ident))))
15652 (case-fold-search nil))
15653 (save-excursion
15654 (save-restriction
15655 (widen)
15656 (goto-char (point-min))
15657 (when (re-search-forward
15658 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15659 nil t)
15660 (org-back-to-heading t)
15661 (point))))))
15663 ;;;; Timestamps
15665 (defvar org-last-changed-timestamp nil)
15666 (defvar org-last-inserted-timestamp nil
15667 "The last time stamp inserted with `org-insert-time-stamp'.")
15668 (defvar org-time-was-given) ; dynamically scoped parameter
15669 (defvar org-end-time-was-given) ; dynamically scoped parameter
15670 (defvar org-ts-what) ; dynamically scoped parameter
15672 (defun org-time-stamp (arg &optional inactive)
15673 "Prompt for a date/time and insert a time stamp.
15674 If the user specifies a time like HH:MM or if this command is
15675 called with at least one prefix argument, the time stamp contains
15676 the date and the time. Otherwise, only the date is be included.
15678 All parts of a date not specified by the user is filled in from
15679 the current date/time. So if you just press return without
15680 typing anything, the time stamp will represent the current
15681 date/time.
15683 If there is already a timestamp at the cursor, it will be
15684 modified.
15686 With two universal prefix arguments, insert an active timestamp
15687 with the current time without prompting the user."
15688 (interactive "P")
15689 (let* ((ts nil)
15690 (default-time
15691 ;; Default time is either today, or, when entering a range,
15692 ;; the range start.
15693 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15694 (save-excursion
15695 (re-search-backward
15696 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15697 (- (point) 20) t)))
15698 (apply 'encode-time (org-parse-time-string (match-string 1)))
15699 (current-time)))
15700 (default-input (and ts (org-get-compact-tod ts)))
15701 (repeater (save-excursion
15702 (save-match-data
15703 (beginning-of-line)
15704 (when (re-search-forward
15705 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15706 (save-excursion (progn (end-of-line) (point))) t)
15707 (match-string 0)))))
15708 org-time-was-given org-end-time-was-given time)
15709 (cond
15710 ((and (org-at-timestamp-p t)
15711 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15712 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15713 (insert "--")
15714 (setq time (let ((this-command this-command))
15715 (org-read-date arg 'totime nil nil
15716 default-time default-input inactive)))
15717 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15718 ((org-at-timestamp-p t)
15719 (setq time (let ((this-command this-command))
15720 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15721 (when (org-at-timestamp-p t) ; just to get the match data
15722 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15723 (replace-match "")
15724 (setq org-last-changed-timestamp
15725 (org-insert-time-stamp
15726 time (or org-time-was-given arg)
15727 inactive nil nil (list org-end-time-was-given)))
15728 (when repeater (goto-char (1- (point))) (insert " " repeater)
15729 (setq org-last-changed-timestamp
15730 (concat (substring org-last-inserted-timestamp 0 -1)
15731 " " repeater ">"))))
15732 (message "Timestamp updated"))
15733 ((equal arg '(16))
15734 (org-insert-time-stamp (current-time) t))
15736 (setq time (let ((this-command this-command))
15737 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15738 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15739 nil nil (list org-end-time-was-given))))))
15741 ;; FIXME: can we use this for something else, like computing time differences?
15742 (defun org-get-compact-tod (s)
15743 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15744 (let* ((t1 (match-string 1 s))
15745 (h1 (string-to-number (match-string 2 s)))
15746 (m1 (string-to-number (match-string 3 s)))
15747 (t2 (and (match-end 4) (match-string 5 s)))
15748 (h2 (and t2 (string-to-number (match-string 6 s))))
15749 (m2 (and t2 (string-to-number (match-string 7 s))))
15750 dh dm)
15751 (if (not t2)
15753 (setq dh (- h2 h1) dm (- m2 m1))
15754 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15755 (concat t1 "+" (number-to-string dh)
15756 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15758 (defun org-time-stamp-inactive (&optional arg)
15759 "Insert an inactive time stamp.
15760 An inactive time stamp is enclosed in square brackets instead of angle
15761 brackets. It is inactive in the sense that it does not trigger agenda entries,
15762 does not link to the calendar and cannot be changed with the S-cursor keys.
15763 So these are more for recording a certain time/date."
15764 (interactive "P")
15765 (org-time-stamp arg 'inactive))
15767 (defvar org-date-ovl (make-overlay 1 1))
15768 (overlay-put org-date-ovl 'face 'org-date-selected)
15769 (org-detach-overlay org-date-ovl)
15771 (defvar org-ans1) ; dynamically scoped parameter
15772 (defvar org-ans2) ; dynamically scoped parameter
15774 (defvar org-plain-time-of-day-regexp) ; defined below
15776 (defvar org-overriding-default-time nil) ; dynamically scoped
15777 (defvar org-read-date-overlay nil)
15778 (defvar org-dcst nil) ; dynamically scoped
15779 (defvar org-read-date-history nil)
15780 (defvar org-read-date-final-answer nil)
15781 (defvar org-read-date-analyze-futurep nil)
15782 (defvar org-read-date-analyze-forced-year nil)
15783 (defvar org-read-date-inactive)
15785 (defvar org-read-date-minibuffer-local-map
15786 (let ((map (make-sparse-keymap)))
15787 (set-keymap-parent map minibuffer-local-map)
15788 (org-defkey map (kbd ".")
15789 (lambda () (interactive)
15790 (org-eval-in-calendar '(calendar-goto-today))))
15791 (org-defkey map [(meta shift left)]
15792 (lambda () (interactive)
15793 (org-eval-in-calendar '(calendar-backward-month 1))))
15794 (org-defkey map [(meta shift right)]
15795 (lambda () (interactive)
15796 (org-eval-in-calendar '(calendar-forward-month 1))))
15797 (org-defkey map [(meta shift up)]
15798 (lambda () (interactive)
15799 (org-eval-in-calendar '(calendar-backward-year 1))))
15800 (org-defkey map [(meta shift down)]
15801 (lambda () (interactive)
15802 (org-eval-in-calendar '(calendar-forward-year 1))))
15803 (org-defkey map [?\e (shift left)]
15804 (lambda () (interactive)
15805 (org-eval-in-calendar '(calendar-backward-month 1))))
15806 (org-defkey map [?\e (shift right)]
15807 (lambda () (interactive)
15808 (org-eval-in-calendar '(calendar-forward-month 1))))
15809 (org-defkey map [?\e (shift up)]
15810 (lambda () (interactive)
15811 (org-eval-in-calendar '(calendar-backward-year 1))))
15812 (org-defkey map [?\e (shift down)]
15813 (lambda () (interactive)
15814 (org-eval-in-calendar '(calendar-forward-year 1))))
15815 (org-defkey map [(shift up)]
15816 (lambda () (interactive)
15817 (org-eval-in-calendar '(calendar-backward-week 1))))
15818 (org-defkey map [(shift down)]
15819 (lambda () (interactive)
15820 (org-eval-in-calendar '(calendar-forward-week 1))))
15821 (org-defkey map [(shift left)]
15822 (lambda () (interactive)
15823 (org-eval-in-calendar '(calendar-backward-day 1))))
15824 (org-defkey map [(shift right)]
15825 (lambda () (interactive)
15826 (org-eval-in-calendar '(calendar-forward-day 1))))
15827 (org-defkey map "!"
15828 (lambda () (interactive)
15829 (org-eval-in-calendar '(diary-view-entries))
15830 (message "")))
15831 (org-defkey map ">"
15832 (lambda () (interactive)
15833 (org-eval-in-calendar '(scroll-calendar-left 1))))
15834 (org-defkey map "<"
15835 (lambda () (interactive)
15836 (org-eval-in-calendar '(scroll-calendar-right 1))))
15837 (org-defkey map "\C-v"
15838 (lambda () (interactive)
15839 (org-eval-in-calendar
15840 '(calendar-scroll-left-three-months 1))))
15841 (org-defkey map "\M-v"
15842 (lambda () (interactive)
15843 (org-eval-in-calendar
15844 '(calendar-scroll-right-three-months 1))))
15845 map)
15846 "Keymap for minibuffer commands when using `org-read-date'.")
15848 (defun org-read-date (&optional org-with-time to-time from-string prompt
15849 default-time default-input inactive)
15850 "Read a date, possibly a time, and make things smooth for the user.
15851 The prompt will suggest to enter an ISO date, but you can also enter anything
15852 which will at least partially be understood by `parse-time-string'.
15853 Unrecognized parts of the date will default to the current day, month, year,
15854 hour and minute. If this command is called to replace a timestamp at point,
15855 or to enter the second timestamp of a range, the default time is taken
15856 from the existing stamp. Furthermore, the command prefers the future,
15857 so if you are giving a date where the year is not given, and the day-month
15858 combination is already past in the current year, it will assume you
15859 mean next year. For details, see the manual. A few examples:
15861 3-2-5 --> 2003-02-05
15862 feb 15 --> currentyear-02-15
15863 2/15 --> currentyear-02-15
15864 sep 12 9 --> 2009-09-12
15865 12:45 --> today 12:45
15866 22 sept 0:34 --> currentyear-09-22 0:34
15867 12 --> currentyear-currentmonth-12
15868 Fri --> nearest Friday (today or later)
15869 etc.
15871 Furthermore you can specify a relative date by giving, as the *first* thing
15872 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15873 change in days weeks, months, years.
15874 With a single plus or minus, the date is relative to today. With a double
15875 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15876 +4d --> four days from today
15877 +4 --> same as above
15878 +2w --> two weeks from today
15879 ++5 --> five days from default date
15881 The function understands only English month and weekday abbreviations.
15883 While prompting, a calendar is popped up - you can also select the
15884 date with the mouse (button 1). The calendar shows a period of three
15885 months. To scroll it to other months, use the keys `>' and `<'.
15886 If you don't like the calendar, turn it off with
15887 \(setq org-read-date-popup-calendar nil)
15889 With optional argument TO-TIME, the date will immediately be converted
15890 to an internal time.
15891 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15892 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15893 still enter a time, and this function will inform the calling routine
15894 about this change. The calling routine may then choose to change the
15895 format used to insert the time stamp into the buffer to include the time.
15896 With optional argument FROM-STRING, read from this string instead from
15897 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15898 the time/date that is used for everything that is not specified by the
15899 user."
15900 (require 'parse-time)
15901 (let* ((org-time-stamp-rounding-minutes
15902 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15903 (org-dcst org-display-custom-times)
15904 (ct (org-current-time))
15905 (org-def (or org-overriding-default-time default-time ct))
15906 (org-defdecode (decode-time org-def))
15907 (dummy (progn
15908 (when (< (nth 2 org-defdecode) org-extend-today-until)
15909 (setcar (nthcdr 2 org-defdecode) -1)
15910 (setcar (nthcdr 1 org-defdecode) 59)
15911 (setq org-def (apply 'encode-time org-defdecode)
15912 org-defdecode (decode-time org-def)))))
15913 (mouse-autoselect-window nil) ; Don't let the mouse jump
15914 (calendar-frame-setup nil)
15915 (calendar-setup nil)
15916 (calendar-move-hook nil)
15917 (calendar-view-diary-initially-flag nil)
15918 (calendar-view-holidays-initially-flag nil)
15919 (timestr (format-time-string
15920 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15921 (prompt (concat (if prompt (concat prompt " ") "")
15922 (format "Date+time [%s]: " timestr)))
15923 ans (org-ans0 "") org-ans1 org-ans2 final)
15925 (cond
15926 (from-string (setq ans from-string))
15927 (org-read-date-popup-calendar
15928 (save-excursion
15929 (save-window-excursion
15930 (calendar)
15931 (org-eval-in-calendar '(setq cursor-type nil) t)
15932 (unwind-protect
15933 (progn
15934 (calendar-forward-day (- (time-to-days org-def)
15935 (calendar-absolute-from-gregorian
15936 (calendar-current-date))))
15937 (org-eval-in-calendar nil t)
15938 (let* ((old-map (current-local-map))
15939 (map (copy-keymap calendar-mode-map))
15940 (minibuffer-local-map
15941 (copy-keymap org-read-date-minibuffer-local-map)))
15942 (org-defkey map (kbd "RET") 'org-calendar-select)
15943 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15944 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15945 (unwind-protect
15946 (progn
15947 (use-local-map map)
15948 (setq org-read-date-inactive inactive)
15949 (add-hook 'post-command-hook 'org-read-date-display)
15950 (setq org-ans0 (read-string prompt default-input
15951 'org-read-date-history nil))
15952 ;; org-ans0: from prompt
15953 ;; org-ans1: from mouse click
15954 ;; org-ans2: from calendar motion
15955 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15956 (remove-hook 'post-command-hook 'org-read-date-display)
15957 (use-local-map old-map)
15958 (when org-read-date-overlay
15959 (delete-overlay org-read-date-overlay)
15960 (setq org-read-date-overlay nil)))))
15961 (bury-buffer "*Calendar*")))))
15963 (t ; Naked prompt only
15964 (unwind-protect
15965 (setq ans (read-string prompt default-input
15966 'org-read-date-history timestr))
15967 (when org-read-date-overlay
15968 (delete-overlay org-read-date-overlay)
15969 (setq org-read-date-overlay nil)))))
15971 (setq final (org-read-date-analyze ans org-def org-defdecode))
15973 (when org-read-date-analyze-forced-year
15974 (message "Year was forced into %s"
15975 (if org-read-date-force-compatible-dates
15976 "compatible range (1970-2037)"
15977 "range representable on this machine"))
15978 (ding))
15980 ;; One round trip to get rid of 34th of August and stuff like that....
15981 (setq final (decode-time (apply 'encode-time final)))
15983 (setq org-read-date-final-answer ans)
15985 (if to-time
15986 (apply 'encode-time final)
15987 (if (and (boundp 'org-time-was-given) org-time-was-given)
15988 (format "%04d-%02d-%02d %02d:%02d"
15989 (nth 5 final) (nth 4 final) (nth 3 final)
15990 (nth 2 final) (nth 1 final))
15991 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15993 (defvar org-def)
15994 (defvar org-defdecode)
15995 (defvar org-with-time)
15996 (defun org-read-date-display ()
15997 "Display the current date prompt interpretation in the minibuffer."
15998 (when org-read-date-display-live
15999 (when org-read-date-overlay
16000 (delete-overlay org-read-date-overlay))
16001 (when (minibufferp (current-buffer))
16002 (save-excursion
16003 (end-of-line 1)
16004 (while (not (equal (buffer-substring
16005 (max (point-min) (- (point) 4)) (point))
16006 " "))
16007 (insert " ")))
16008 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16009 " " (or org-ans1 org-ans2)))
16010 (org-end-time-was-given nil)
16011 (f (org-read-date-analyze ans org-def org-defdecode))
16012 (fmts (if org-dcst
16013 org-time-stamp-custom-formats
16014 org-time-stamp-formats))
16015 (fmt (if (or org-with-time
16016 (and (boundp 'org-time-was-given) org-time-was-given))
16017 (cdr fmts)
16018 (car fmts)))
16019 (txt (format-time-string fmt (apply 'encode-time f)))
16020 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16021 (txt (concat "=> " txt)))
16022 (when (and org-end-time-was-given
16023 (string-match org-plain-time-of-day-regexp txt))
16024 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16025 org-end-time-was-given
16026 (substring txt (match-end 0)))))
16027 (when org-read-date-analyze-futurep
16028 (setq txt (concat txt " (=>F)")))
16029 (setq org-read-date-overlay
16030 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16031 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16033 (defun org-read-date-analyze (ans org-def org-defdecode)
16034 "Analyze the combined answer of the date prompt."
16035 ;; FIXME: cleanup and comment
16036 (let ((nowdecode (decode-time (current-time)))
16037 delta deltan deltaw deltadef year month day
16038 hour minute second wday pm h2 m2 tl wday1
16039 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16040 (setq org-read-date-analyze-futurep nil
16041 org-read-date-analyze-forced-year nil)
16042 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16043 (setq ans "+0"))
16045 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16046 (setq ans (replace-match "" t t ans)
16047 deltan (car delta)
16048 deltaw (nth 1 delta)
16049 deltadef (nth 2 delta)))
16051 ;; Check if there is an iso week date in there. If yes, store the
16052 ;; info and postpone interpreting it until the rest of the parsing
16053 ;; is done.
16054 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16055 (setq iso-year (if (match-end 1)
16056 (org-small-year-to-year
16057 (string-to-number (match-string 1 ans))))
16058 iso-weekday (if (match-end 3)
16059 (string-to-number (match-string 3 ans)))
16060 iso-week (string-to-number (match-string 2 ans)))
16061 (setq ans (replace-match "" t t ans)))
16063 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16064 (when (string-match
16065 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16066 (setq year (if (match-end 2)
16067 (string-to-number (match-string 2 ans))
16068 (progn (setq kill-year t)
16069 (string-to-number (format-time-string "%Y"))))
16070 month (string-to-number (match-string 3 ans))
16071 day (string-to-number (match-string 4 ans)))
16072 (if (< year 100) (setq year (+ 2000 year)))
16073 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16074 t nil ans)))
16076 ;; Help matching dotted european dates
16077 (when (string-match
16078 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16079 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16080 (setq kill-year t)
16081 (string-to-number (format-time-string "%Y")))
16082 day (string-to-number (match-string 1 ans))
16083 month (string-to-number (match-string 2 ans))
16084 ans (replace-match (format "%04d-%02d-%02d" year month day)
16085 t nil ans)))
16087 ;; Help matching american dates, like 5/30 or 5/30/7
16088 (when (string-match
16089 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16090 (setq year (if (match-end 4)
16091 (string-to-number (match-string 4 ans))
16092 (progn (setq kill-year t)
16093 (string-to-number (format-time-string "%Y"))))
16094 month (string-to-number (match-string 1 ans))
16095 day (string-to-number (match-string 2 ans)))
16096 (if (< year 100) (setq year (+ 2000 year)))
16097 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16098 t nil ans)))
16099 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16100 ;; If there is a time with am/pm, and *no* time without it, we convert
16101 ;; so that matching will be successful.
16102 (loop for i from 1 to 2 do ; twice, for end time as well
16103 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16104 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16105 (setq hour (string-to-number (match-string 1 ans))
16106 minute (if (match-end 3)
16107 (string-to-number (match-string 3 ans))
16109 pm (equal ?p
16110 (string-to-char (downcase (match-string 4 ans)))))
16111 (if (and (= hour 12) (not pm))
16112 (setq hour 0)
16113 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16114 (setq ans (replace-match (format "%02d:%02d" hour minute)
16115 t t ans))))
16117 ;; Check if a time range is given as a duration
16118 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16119 (setq hour (string-to-number (match-string 1 ans))
16120 h2 (+ hour (string-to-number (match-string 3 ans)))
16121 minute (string-to-number (match-string 2 ans))
16122 m2 (+ minute (if (match-end 5) (string-to-number
16123 (match-string 5 ans))0)))
16124 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16125 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16126 t t ans)))
16128 ;; Check if there is a time range
16129 (when (boundp 'org-end-time-was-given)
16130 (setq org-time-was-given nil)
16131 (when (and (string-match org-plain-time-of-day-regexp ans)
16132 (match-end 8))
16133 (setq org-end-time-was-given (match-string 8 ans))
16134 (setq ans (concat (substring ans 0 (match-beginning 7))
16135 (substring ans (match-end 7))))))
16137 (setq tl (parse-time-string ans)
16138 day (or (nth 3 tl) (nth 3 org-defdecode))
16139 month (or (nth 4 tl)
16140 (if (and org-read-date-prefer-future
16141 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16142 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16143 (nth 4 org-defdecode)))
16144 year (or (and (not kill-year) (nth 5 tl))
16145 (if (and org-read-date-prefer-future
16146 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16147 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16148 (nth 5 org-defdecode)))
16149 hour (or (nth 2 tl) (nth 2 org-defdecode))
16150 minute (or (nth 1 tl) (nth 1 org-defdecode))
16151 second (or (nth 0 tl) 0)
16152 wday (nth 6 tl))
16154 (when (and (eq org-read-date-prefer-future 'time)
16155 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16156 (equal day (nth 3 nowdecode))
16157 (equal month (nth 4 nowdecode))
16158 (equal year (nth 5 nowdecode))
16159 (nth 2 tl)
16160 (or (< (nth 2 tl) (nth 2 nowdecode))
16161 (and (= (nth 2 tl) (nth 2 nowdecode))
16162 (nth 1 tl)
16163 (< (nth 1 tl) (nth 1 nowdecode)))))
16164 (setq day (1+ day)
16165 futurep t))
16167 ;; Special date definitions below
16168 (cond
16169 (iso-week
16170 ;; There was an iso week
16171 (require 'cal-iso)
16172 (setq futurep nil)
16173 (setq year (or iso-year year)
16174 day (or iso-weekday wday 1)
16175 wday nil ; to make sure that the trigger below does not match
16176 iso-date (calendar-gregorian-from-absolute
16177 (calendar-absolute-from-iso
16178 (list iso-week day year))))
16179 ; FIXME: Should we also push ISO weeks into the future?
16180 ; (when (and org-read-date-prefer-future
16181 ; (not iso-year)
16182 ; (< (calendar-absolute-from-gregorian iso-date)
16183 ; (time-to-days (current-time))))
16184 ; (setq year (1+ year)
16185 ; iso-date (calendar-gregorian-from-absolute
16186 ; (calendar-absolute-from-iso
16187 ; (list iso-week day year)))))
16188 (setq month (car iso-date)
16189 year (nth 2 iso-date)
16190 day (nth 1 iso-date)))
16191 (deltan
16192 (setq futurep nil)
16193 (unless deltadef
16194 (let ((now (decode-time (current-time))))
16195 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16196 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16197 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16198 ((equal deltaw "m") (setq month (+ month deltan)))
16199 ((equal deltaw "y") (setq year (+ year deltan)))))
16200 ((and wday (not (nth 3 tl)))
16201 ;; Weekday was given, but no day, so pick that day in the week
16202 ;; on or after the derived date.
16203 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16204 (unless (equal wday wday1)
16205 (setq day (+ day (% (- wday wday1 -7) 7))))))
16206 (if (and (boundp 'org-time-was-given)
16207 (nth 2 tl))
16208 (setq org-time-was-given t))
16209 (if (< year 100) (setq year (+ 2000 year)))
16210 ;; Check of the date is representable
16211 (if org-read-date-force-compatible-dates
16212 (progn
16213 (if (< year 1970)
16214 (setq year 1970 org-read-date-analyze-forced-year t))
16215 (if (> year 2037)
16216 (setq year 2037 org-read-date-analyze-forced-year t)))
16217 (condition-case nil
16218 (ignore (encode-time second minute hour day month year))
16219 (error
16220 (setq year (nth 5 org-defdecode))
16221 (setq org-read-date-analyze-forced-year t))))
16222 (setq org-read-date-analyze-futurep futurep)
16223 (list second minute hour day month year)))
16225 (defvar parse-time-weekdays)
16226 (defun org-read-date-get-relative (s today default)
16227 "Check string S for special relative date string.
16228 TODAY and DEFAULT are internal times, for today and for a default.
16229 Return shift list (N what def-flag)
16230 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16231 N is the number of WHATs to shift.
16232 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16233 the DEFAULT date rather than TODAY."
16234 (require 'parse-time)
16235 (when (and
16236 (string-match
16237 (concat
16238 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16239 "\\([0-9]+\\)?"
16240 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16241 "\\([ \t]\\|$\\)") s)
16242 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16243 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16244 (string-to-char (substring (match-string 1 s) -1))
16245 ?+))
16246 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16247 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16248 (what (if (match-end 3) (match-string 3 s) "d"))
16249 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16250 (date (if rel default today))
16251 (wday (nth 6 (decode-time date)))
16252 delta)
16253 (if wday1
16254 (progn
16255 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16256 (if (= dir ?-) (setq delta (- delta 7)))
16257 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16258 (list delta "d" rel))
16259 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16261 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16262 "Turn a user-specified date into the internal representation.
16263 The internal representation needed by the calendar is (month day year).
16264 This is a wrapper to handle the brain-dead convention in calendar that
16265 user function argument order change dependent on argument order."
16266 (if (boundp 'calendar-date-style)
16267 (cond
16268 ((eq calendar-date-style 'american)
16269 (list arg1 arg2 arg3))
16270 ((eq calendar-date-style 'european)
16271 (list arg2 arg1 arg3))
16272 ((eq calendar-date-style 'iso)
16273 (list arg2 arg3 arg1)))
16274 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16275 (if (org-bound-and-true-p european-calendar-style)
16276 (list arg2 arg1 arg3)
16277 (list arg1 arg2 arg3)))))
16279 (defun org-eval-in-calendar (form &optional keepdate)
16280 "Eval FORM in the calendar window and return to current window.
16281 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16282 otherwise stick to the current value of `org-ans2'."
16283 (let ((sf (selected-frame))
16284 (sw (selected-window)))
16285 (select-window (get-buffer-window "*Calendar*" t))
16286 (eval form)
16287 (when (and (not keepdate) (calendar-cursor-to-date))
16288 (let* ((date (calendar-cursor-to-date))
16289 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16290 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16291 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16292 (select-window sw)
16293 (org-select-frame-set-input-focus sf)))
16295 (defun org-calendar-select ()
16296 "Return to `org-read-date' with the date currently selected.
16297 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16298 (interactive)
16299 (when (calendar-cursor-to-date)
16300 (let* ((date (calendar-cursor-to-date))
16301 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16302 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16303 (if (active-minibuffer-window) (exit-minibuffer))))
16305 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16306 "Insert a date stamp for the date given by the internal TIME.
16307 WITH-HM means use the stamp format that includes the time of the day.
16308 INACTIVE means use square brackets instead of angular ones, so that the
16309 stamp will not contribute to the agenda.
16310 PRE and POST are optional strings to be inserted before and after the
16311 stamp.
16312 The command returns the inserted time stamp."
16313 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16314 stamp)
16315 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16316 (insert-before-markers (or pre ""))
16317 (when (listp extra)
16318 (setq extra (car extra))
16319 (if (and (stringp extra)
16320 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16321 (setq extra (format "-%02d:%02d"
16322 (string-to-number (match-string 1 extra))
16323 (string-to-number (match-string 2 extra))))
16324 (setq extra nil)))
16325 (when extra
16326 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16327 (insert-before-markers (setq stamp (format-time-string fmt time)))
16328 (insert-before-markers (or post ""))
16329 (setq org-last-inserted-timestamp stamp)))
16331 (defun org-toggle-time-stamp-overlays ()
16332 "Toggle the use of custom time stamp formats."
16333 (interactive)
16334 (setq org-display-custom-times (not org-display-custom-times))
16335 (unless org-display-custom-times
16336 (let ((p (point-min)) (bmp (buffer-modified-p)))
16337 (while (setq p (next-single-property-change p 'display))
16338 (if (and (get-text-property p 'display)
16339 (eq (get-text-property p 'face) 'org-date))
16340 (remove-text-properties
16341 p (setq p (next-single-property-change p 'display))
16342 '(display t))))
16343 (set-buffer-modified-p bmp)))
16344 (if (featurep 'xemacs)
16345 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16346 (org-restart-font-lock)
16347 (setq org-table-may-need-update t)
16348 (if org-display-custom-times
16349 (message "Time stamps are overlaid with custom format")
16350 (message "Time stamp overlays removed")))
16352 (defun org-display-custom-time (beg end)
16353 "Overlay modified time stamp format over timestamp between BEG and END."
16354 (let* ((ts (buffer-substring beg end))
16355 t1 w1 with-hm tf time str w2 (off 0))
16356 (save-match-data
16357 (setq t1 (org-parse-time-string ts t))
16358 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16359 (setq off (- (match-end 0) (match-beginning 0)))))
16360 (setq end (- end off))
16361 (setq w1 (- end beg)
16362 with-hm (and (nth 1 t1) (nth 2 t1))
16363 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16364 time (org-fix-decoded-time t1)
16365 str (org-add-props
16366 (format-time-string
16367 (substring tf 1 -1) (apply 'encode-time time))
16368 nil 'mouse-face 'highlight)
16369 w2 (length str))
16370 (if (not (= w2 w1))
16371 (add-text-properties (1+ beg) (+ 2 beg)
16372 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16373 (if (featurep 'xemacs)
16374 (progn
16375 (put-text-property beg end 'invisible t)
16376 (put-text-property beg end 'end-glyph (make-glyph str)))
16377 (put-text-property beg end 'display str))))
16379 (defun org-translate-time (string)
16380 "Translate all timestamps in STRING to custom format.
16381 But do this only if the variable `org-display-custom-times' is set."
16382 (when org-display-custom-times
16383 (save-match-data
16384 (let* ((start 0)
16385 (re org-ts-regexp-both)
16386 t1 with-hm inactive tf time str beg end)
16387 (while (setq start (string-match re string start))
16388 (setq beg (match-beginning 0)
16389 end (match-end 0)
16390 t1 (save-match-data
16391 (org-parse-time-string (substring string beg end) t))
16392 with-hm (and (nth 1 t1) (nth 2 t1))
16393 inactive (equal (substring string beg (1+ beg)) "[")
16394 tf (funcall (if with-hm 'cdr 'car)
16395 org-time-stamp-custom-formats)
16396 time (org-fix-decoded-time t1)
16397 str (format-time-string
16398 (concat
16399 (if inactive "[" "<") (substring tf 1 -1)
16400 (if inactive "]" ">"))
16401 (apply 'encode-time time))
16402 string (replace-match str t t string)
16403 start (+ start (length str)))))))
16404 string)
16406 (defun org-fix-decoded-time (time)
16407 "Set 0 instead of nil for the first 6 elements of time.
16408 Don't touch the rest."
16409 (let ((n 0))
16410 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16412 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16414 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16415 "Difference between TIMESTAMP-STRING and now in days.
16416 If SECONDS is non-nil, return the difference in seconds."
16417 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16418 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16419 (funcall fdiff (current-time)))))
16421 (defun org-deadline-close (timestamp-string &optional ndays)
16422 "Is the time in TIMESTAMP-STRING close to the current date?"
16423 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16424 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16425 (not (org-entry-is-done-p))))
16427 (defun org-get-wdays (ts &optional delay zero-delay)
16428 "Get the deadline lead time appropriate for timestring TS.
16429 When DELAY is non-nil, get the delay time for scheduled items
16430 instead of the deadline lead time. When ZERO-DELAY is non-nil
16431 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16432 don't try to find the delay cookie in the scheduled timestamp."
16433 (let ((tv (if delay org-scheduled-delay-days
16434 org-deadline-warning-days)))
16435 (cond
16436 ((or (and delay (< tv 0))
16437 (and delay zero-delay (<= tv 0))
16438 (and (not delay) (<= tv 0)))
16439 ;; Enforce this value no matter what
16440 (- tv))
16441 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16442 ;; lead time is specified.
16443 (floor (* (string-to-number (match-string 1 ts))
16444 (cdr (assoc (match-string 2 ts)
16445 '(("d" . 1) ("w" . 7)
16446 ("m" . 30.4) ("y" . 365.25)
16447 ("h" . 0.041667)))))))
16448 ;; go for the default.
16449 (t tv))))
16451 (defun org-calendar-select-mouse (ev)
16452 "Return to `org-read-date' with the date currently selected.
16453 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16454 (interactive "e")
16455 (mouse-set-point ev)
16456 (when (calendar-cursor-to-date)
16457 (let* ((date (calendar-cursor-to-date))
16458 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16459 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16460 (if (active-minibuffer-window) (exit-minibuffer))))
16462 (defun org-check-deadlines (ndays)
16463 "Check if there are any deadlines due or past due.
16464 A deadline is considered due if it happens within `org-deadline-warning-days'
16465 days from today's date. If the deadline appears in an entry marked DONE,
16466 it is not shown. The prefix arg NDAYS can be used to test that many
16467 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16468 (interactive "P")
16469 (let* ((org-warn-days
16470 (cond
16471 ((equal ndays '(4)) 100000)
16472 (ndays (prefix-numeric-value ndays))
16473 (t (abs org-deadline-warning-days))))
16474 (case-fold-search nil)
16475 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16476 (callback
16477 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16479 (message "%d deadlines past-due or due within %d days"
16480 (org-occur regexp nil callback)
16481 org-warn-days)))
16483 (defsubst org-re-timestamp (type)
16484 "Return a regexp for timestamp TYPE.
16485 Allowed values for TYPE are:
16487 all: all timestamps
16488 active: only active timestamps (<...>)
16489 inactive: only inactive timestamps ([...])
16490 scheduled: only scheduled timestamps
16491 deadline: only deadline timestamps
16493 When TYPE is nil, fall back on returning a regexp that matches
16494 both scheduled and deadline timestamps."
16495 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16496 ((eq type 'active) org-ts-regexp)
16497 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16498 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16499 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16500 ((eq type 'scheduled-or-deadline)
16501 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16503 (defun org-check-before-date (date)
16504 "Check if there are deadlines or scheduled entries before DATE."
16505 (interactive (list (org-read-date)))
16506 (let ((case-fold-search nil)
16507 (regexp (org-re-timestamp org-ts-type))
16508 (callback
16509 (lambda () (time-less-p
16510 (org-time-string-to-time (match-string 1))
16511 (org-time-string-to-time date)))))
16512 (message "%d entries before %s"
16513 (org-occur regexp nil callback) date)))
16515 (defun org-check-after-date (date)
16516 "Check if there are deadlines or scheduled entries after DATE."
16517 (interactive (list (org-read-date)))
16518 (let ((case-fold-search nil)
16519 (regexp (org-re-timestamp org-ts-type))
16520 (callback
16521 (lambda () (not
16522 (time-less-p
16523 (org-time-string-to-time (match-string 1))
16524 (org-time-string-to-time date))))))
16525 (message "%d entries after %s"
16526 (org-occur regexp nil callback) date)))
16528 (defun org-check-dates-range (start-date end-date)
16529 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16530 (interactive (list (org-read-date nil nil nil "Range starts")
16531 (org-read-date nil nil nil "Range end")))
16532 (let ((case-fold-search nil)
16533 (regexp (org-re-timestamp org-ts-type))
16534 (callback
16535 (lambda ()
16536 (let ((match (match-string 1)))
16537 (and
16538 (not (time-less-p
16539 (org-time-string-to-time match)
16540 (org-time-string-to-time start-date)))
16541 (time-less-p
16542 (org-time-string-to-time match)
16543 (org-time-string-to-time end-date)))))))
16544 (message "%d entries between %s and %s"
16545 (org-occur regexp nil callback) start-date end-date)))
16547 (defun org-evaluate-time-range (&optional to-buffer)
16548 "Evaluate a time range by computing the difference between start and end.
16549 Normally the result is just printed in the echo area, but with prefix arg
16550 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16551 If the time range is actually in a table, the result is inserted into the
16552 next column.
16553 For time difference computation, a year is assumed to be exactly 365
16554 days in order to avoid rounding problems."
16555 (interactive "P")
16557 (org-clock-update-time-maybe)
16558 (save-excursion
16559 (unless (org-at-date-range-p t)
16560 (goto-char (point-at-bol))
16561 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16562 (if (not (org-at-date-range-p t))
16563 (error "Not at a time-stamp range, and none found in current line")))
16564 (let* ((ts1 (match-string 1))
16565 (ts2 (match-string 2))
16566 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16567 (match-end (match-end 0))
16568 (time1 (org-time-string-to-time ts1))
16569 (time2 (org-time-string-to-time ts2))
16570 (t1 (org-float-time time1))
16571 (t2 (org-float-time time2))
16572 (diff (abs (- t2 t1)))
16573 (negative (< (- t2 t1) 0))
16574 ;; (ys (floor (* 365 24 60 60)))
16575 (ds (* 24 60 60))
16576 (hs (* 60 60))
16577 (fy "%dy %dd %02d:%02d")
16578 (fy1 "%dy %dd")
16579 (fd "%dd %02d:%02d")
16580 (fd1 "%dd")
16581 (fh "%02d:%02d")
16582 y d h m align)
16583 (if havetime
16584 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16586 d (floor (/ diff ds)) diff (mod diff ds)
16587 h (floor (/ diff hs)) diff (mod diff hs)
16588 m (floor (/ diff 60)))
16589 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16591 d (floor (+ (/ diff ds) 0.5))
16592 h 0 m 0))
16593 (if (not to-buffer)
16594 (message "%s" (org-make-tdiff-string y d h m))
16595 (if (org-at-table-p)
16596 (progn
16597 (goto-char match-end)
16598 (setq align t)
16599 (and (looking-at " *|") (goto-char (match-end 0))))
16600 (goto-char match-end))
16601 (if (looking-at
16602 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16603 (replace-match ""))
16604 (if negative (insert " -"))
16605 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16606 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16607 (insert " " (format fh h m))))
16608 (if align (org-table-align))
16609 (message "Time difference inserted")))))
16611 (defun org-make-tdiff-string (y d h m)
16612 (let ((fmt "")
16613 (l nil))
16614 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16615 l (push y l)))
16616 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16617 l (push d l)))
16618 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16619 l (push h l)))
16620 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16621 l (push m l)))
16622 (apply 'format fmt (nreverse l))))
16624 (defun org-time-string-to-time (s &optional buffer pos)
16625 "Convert a timestamp string into internal time."
16626 (condition-case errdata
16627 (apply 'encode-time (org-parse-time-string s))
16628 (error (error "Bad timestamp `%s'%s\nError was: %s"
16629 s (if (not (and buffer pos))
16631 (format " at %d in buffer `%s'" pos buffer))
16632 (cdr errdata)))))
16634 (defun org-time-string-to-seconds (s)
16635 "Convert a timestamp string to a number of seconds."
16636 (org-float-time (org-time-string-to-time s)))
16638 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16639 "Convert a time stamp to an absolute day number.
16640 If there is a specifier for a cyclic time stamp, get the closest
16641 date to DAYNR.
16642 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16643 The variable date is bound by the calendar when this is called."
16644 (cond
16645 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16646 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16647 daynr
16648 (+ daynr 1000)))
16649 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16650 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16651 (time-to-days (current-time))) (match-string 0 s)
16652 prefer show-all))
16653 (t (time-to-days
16654 (condition-case errdata
16655 (apply 'encode-time (org-parse-time-string s))
16656 (error (error "Bad timestamp `%s'%s\nError was: %s"
16657 s (if (not (and buffer pos))
16659 (format " at %d in buffer `%s'" pos buffer))
16660 (cdr errdata))))))))
16662 (defun org-days-to-iso-week (days)
16663 "Return the iso week number."
16664 (require 'cal-iso)
16665 (car (calendar-iso-from-absolute days)))
16667 (defun org-small-year-to-year (year)
16668 "Convert 2-digit years into 4-digit years.
16669 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16670 The year 2000 cannot be abbreviated. Any year larger than 99
16671 is returned unchanged."
16672 (if (< year 38)
16673 (setq year (+ 2000 year))
16674 (if (< year 100)
16675 (setq year (+ 1900 year))))
16676 year)
16678 (defun org-time-from-absolute (d)
16679 "Return the time corresponding to date D.
16680 D may be an absolute day number, or a calendar-type list (month day year)."
16681 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16682 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16684 (defun org-calendar-holiday ()
16685 "List of holidays, for Diary display in Org-mode."
16686 (require 'holidays)
16687 (let ((hl (funcall
16688 (if (fboundp 'calendar-check-holidays)
16689 'calendar-check-holidays 'check-calendar-holidays) date)))
16690 (if hl (mapconcat 'identity hl "; "))))
16692 (defun org-diary-sexp-entry (sexp entry date)
16693 "Process a SEXP diary ENTRY for DATE."
16694 (require 'diary-lib)
16695 (let ((result (if calendar-debug-sexp
16696 (let ((stack-trace-on-error t))
16697 (eval (car (read-from-string sexp))))
16698 (condition-case nil
16699 (eval (car (read-from-string sexp)))
16700 (error
16701 (beep)
16702 (message "Bad sexp at line %d in %s: %s"
16703 (org-current-line)
16704 (buffer-file-name) sexp)
16705 (sleep-for 2))))))
16706 (cond ((stringp result) (split-string result "; "))
16707 ((and (consp result)
16708 (not (consp (cdr result)))
16709 (stringp (cdr result))) (cdr result))
16710 ((and (consp result)
16711 (stringp (car result))) result)
16712 (result entry))))
16714 (defun org-diary-to-ical-string (frombuf)
16715 "Get iCalendar entries from diary entries in buffer FROMBUF.
16716 This uses the icalendar.el library."
16717 (let* ((tmpdir (if (featurep 'xemacs)
16718 (temp-directory)
16719 temporary-file-directory))
16720 (tmpfile (make-temp-name
16721 (expand-file-name "orgics" tmpdir)))
16722 buf rtn b e)
16723 (with-current-buffer frombuf
16724 (icalendar-export-region (point-min) (point-max) tmpfile)
16725 (setq buf (find-buffer-visiting tmpfile))
16726 (set-buffer buf)
16727 (goto-char (point-min))
16728 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16729 (setq b (match-beginning 0)))
16730 (goto-char (point-max))
16731 (if (re-search-backward "^END:VEVENT" nil t)
16732 (setq e (match-end 0)))
16733 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16734 (kill-buffer buf)
16735 (delete-file tmpfile)
16736 rtn))
16738 (defun org-closest-date (start current change prefer show-all)
16739 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16740 When PREFER is `past', return a date that is either CURRENT or past.
16741 When PREFER is `future', return a date that is either CURRENT or future.
16742 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16743 ;; Make the proper lists from the dates
16744 (catch 'exit
16745 (let ((a1 '(("h" . hour)
16746 ("d" . day)
16747 ("w" . week)
16748 ("m" . month)
16749 ("y" . year)))
16750 (shour (nth 2 (org-parse-time-string start)))
16751 dn dw sday cday n1 n2 n0
16752 d m y y1 y2 date1 date2 nmonths nm ny m2)
16754 (setq start (org-date-to-gregorian start)
16755 current (org-date-to-gregorian
16756 (if show-all
16757 current
16758 (time-to-days (current-time))))
16759 sday (calendar-absolute-from-gregorian start)
16760 cday (calendar-absolute-from-gregorian current))
16762 (if (<= cday sday) (throw 'exit sday))
16764 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16765 (setq dn (string-to-number (match-string 1 change))
16766 dw (cdr (assoc (match-string 2 change) a1)))
16767 (error "Invalid change specifier: %s" change))
16768 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16769 (cond
16770 ((eq dw 'hour)
16771 (let ((missing-hours
16772 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16773 dn)))
16774 (setq n1 (if (zerop missing-hours) cday
16775 (- cday (1+ (floor (/ missing-hours 24)))))
16776 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16777 ((eq dw 'day)
16778 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16779 n2 (+ n1 dn)))
16780 ((eq dw 'year)
16781 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16782 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16783 (setq date1 (list m d y1)
16784 n1 (calendar-absolute-from-gregorian date1)
16785 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16786 n2 (calendar-absolute-from-gregorian date2)))
16787 ((eq dw 'month)
16788 ;; approx number of month between the two dates
16789 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16790 ;; How often does dn fit in there?
16791 (setq d (nth 1 start) m (car start) y (nth 2 start)
16792 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16793 m (+ m nm)
16794 ny (floor (/ m 12))
16795 y (+ y ny)
16796 m (- m (* ny 12)))
16797 (while (> m 12) (setq m (- m 12) y (1+ y)))
16798 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16799 (setq m2 (+ m dn) y2 y)
16800 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16801 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16802 (while (<= n2 cday)
16803 (setq n1 n2 m m2 y y2)
16804 (setq m2 (+ m dn) y2 y)
16805 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16806 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16807 ;; Make sure n1 is the earlier date
16808 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16809 (if show-all
16810 (cond
16811 ((eq prefer 'past) (if (= cday n2) n2 n1))
16812 ((eq prefer 'future) (if (= cday n1) n1 n2))
16813 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16814 (cond
16815 ((eq prefer 'past) (if (= cday n2) n2 n1))
16816 ((eq prefer 'future) (if (= cday n1) n1 n2))
16817 (t (if (= cday n1) n1 n2)))))))
16819 (defun org-date-to-gregorian (date)
16820 "Turn any specification of DATE into a Gregorian date for the calendar."
16821 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16822 ((and (listp date) (= (length date) 3)) date)
16823 ((stringp date)
16824 (setq date (org-parse-time-string date))
16825 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16826 ((listp date)
16827 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16829 (defun org-parse-time-string (s &optional nodefault)
16830 "Parse the standard Org-mode time string.
16831 This should be a lot faster than the normal `parse-time-string'.
16832 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16833 hour and minute fields will be nil if not given."
16834 (cond ((string-match org-ts-regexp0 s)
16835 (list 0
16836 (if (or (match-beginning 8) (not nodefault))
16837 (string-to-number (or (match-string 8 s) "0")))
16838 (if (or (match-beginning 7) (not nodefault))
16839 (string-to-number (or (match-string 7 s) "0")))
16840 (string-to-number (match-string 4 s))
16841 (string-to-number (match-string 3 s))
16842 (string-to-number (match-string 2 s))
16843 nil nil nil))
16844 ((string-match "^<[^>]+>$" s)
16845 (decode-time (seconds-to-time (org-matcher-time s))))
16846 (t (error "Not a standard Org-mode time string: %s" s))))
16848 (defun org-timestamp-up (&optional arg)
16849 "Increase the date item at the cursor by one.
16850 If the cursor is on the year, change the year. If it is on the month,
16851 the day or the time, change that.
16852 With prefix ARG, change by that many units."
16853 (interactive "p")
16854 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16856 (defun org-timestamp-down (&optional arg)
16857 "Decrease the date item at the cursor by one.
16858 If the cursor is on the year, change the year. If it is on the month,
16859 the day or the time, change that.
16860 With prefix ARG, change by that many units."
16861 (interactive "p")
16862 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16864 (defun org-timestamp-up-day (&optional arg)
16865 "Increase the date in the time stamp by one day.
16866 With prefix ARG, change that many days."
16867 (interactive "p")
16868 (if (and (not (org-at-timestamp-p t))
16869 (org-at-heading-p))
16870 (org-todo 'up)
16871 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16873 (defun org-timestamp-down-day (&optional arg)
16874 "Decrease the date in the time stamp by one day.
16875 With prefix ARG, change that many days."
16876 (interactive "p")
16877 (if (and (not (org-at-timestamp-p t))
16878 (org-at-heading-p))
16879 (org-todo 'down)
16880 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16882 (defun org-at-timestamp-p (&optional inactive-ok)
16883 "Determine if the cursor is in or at a timestamp."
16884 (interactive)
16885 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16886 (pos (point))
16887 (ans (or (looking-at tsr)
16888 (save-excursion
16889 (skip-chars-backward "^[<\n\r\t")
16890 (if (> (point) (point-min)) (backward-char 1))
16891 (and (looking-at tsr)
16892 (> (- (match-end 0) pos) -1))))))
16893 (and ans
16894 (boundp 'org-ts-what)
16895 (setq org-ts-what
16896 (cond
16897 ((= pos (match-beginning 0)) 'bracket)
16898 ;; Point is considered to be "on the bracket" whether
16899 ;; it's really on it or right after it.
16900 ((= pos (1- (match-end 0))) 'bracket)
16901 ((= pos (match-end 0)) 'after)
16902 ((org-pos-in-match-range pos 2) 'year)
16903 ((org-pos-in-match-range pos 3) 'month)
16904 ((org-pos-in-match-range pos 7) 'hour)
16905 ((org-pos-in-match-range pos 8) 'minute)
16906 ((or (org-pos-in-match-range pos 4)
16907 (org-pos-in-match-range pos 5)) 'day)
16908 ((and (> pos (or (match-end 8) (match-end 5)))
16909 (< pos (match-end 0)))
16910 (- pos (or (match-end 8) (match-end 5))))
16911 (t 'day))))
16912 ans))
16914 (defun org-toggle-timestamp-type ()
16915 "Toggle the type (<active> or [inactive]) of a time stamp."
16916 (interactive)
16917 (when (org-at-timestamp-p t)
16918 (let ((beg (match-beginning 0)) (end (match-end 0))
16919 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16920 (save-excursion
16921 (goto-char beg)
16922 (while (re-search-forward "[][<>]" end t)
16923 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16924 t t)))
16925 (message "Timestamp is now %sactive"
16926 (if (equal (char-after beg) ?<) "" "in")))))
16928 (defun org-at-clock-log-p nil
16929 "Is the cursor on the clock log line?"
16930 (save-excursion
16931 (move-beginning-of-line 1)
16932 (looking-at "^[ \t]*CLOCK:")))
16934 (defvar org-clock-history) ; defined in org-clock.el
16935 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16936 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16937 "Change the date in the time stamp at point.
16938 The date will be changed by N times WHAT. WHAT can be `day', `month',
16939 `year', `minute', `second'. If WHAT is not given, the cursor position
16940 in the timestamp determines what will be changed.
16941 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16942 (let ((origin (point)) origin-cat
16943 with-hm inactive
16944 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16945 org-ts-what
16946 extra rem
16947 ts time time0 fixnext clrgx)
16948 (if (not (org-at-timestamp-p t))
16949 (error "Not at a timestamp"))
16950 (if (and (not what) (eq org-ts-what 'bracket))
16951 (org-toggle-timestamp-type)
16952 ;; Point isn't on brackets. Remember the part of the time-stamp
16953 ;; the point was in. Indeed, size of time-stamps may change,
16954 ;; but point must be kept in the same category nonetheless.
16955 (setq origin-cat org-ts-what)
16956 (if (and (not what) (not (eq org-ts-what 'day))
16957 org-display-custom-times
16958 (get-text-property (point) 'display)
16959 (not (get-text-property (1- (point)) 'display)))
16960 (setq org-ts-what 'day))
16961 (setq org-ts-what (or what org-ts-what)
16962 inactive (= (char-after (match-beginning 0)) ?\[)
16963 ts (match-string 0))
16964 (replace-match "")
16965 (when (string-match
16966 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16968 (setq extra (match-string 1 ts))
16969 (if suppress-tmp-delay
16970 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16971 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16972 (setq with-hm t))
16973 (setq time0 (org-parse-time-string ts))
16974 (when (and updown
16975 (eq org-ts-what 'minute)
16976 (not current-prefix-arg))
16977 ;; This looks like s-up and s-down. Change by one rounding step.
16978 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16979 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16980 (setcar (cdr time0) (+ (nth 1 time0)
16981 (if (> n 0) (- rem) (- dm rem))))))
16982 (setq time
16983 (encode-time (or (car time0) 0)
16984 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16985 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16986 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16987 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16988 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16989 (nthcdr 6 time0)))
16990 (when (and (member org-ts-what '(hour minute))
16991 extra
16992 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16993 (setq extra (org-modify-ts-extra
16994 extra
16995 (if (eq org-ts-what 'hour) 2 5)
16996 n dm)))
16997 (when (integerp org-ts-what)
16998 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16999 (if (eq what 'calendar)
17000 (let ((cal-date (org-get-date-from-calendar)))
17001 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17002 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17003 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17004 (setcar time0 (or (car time0) 0))
17005 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17006 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17007 (setq time (apply 'encode-time time0))))
17008 ;; Insert the new time-stamp, and ensure point stays in the same
17009 ;; category as before (i.e. not after the last position in that
17010 ;; category).
17011 (let ((pos (point)))
17012 ;; Stay before inserted string. `save-excursion' is of no use.
17013 (setq org-last-changed-timestamp
17014 (org-insert-time-stamp time with-hm inactive nil nil extra))
17015 (goto-char pos))
17016 (save-match-data
17017 (looking-at org-ts-regexp3)
17018 (goto-char (cond
17019 ;; `day' category ends before `hour' if any, or at
17020 ;; the end of the day name.
17021 ((eq origin-cat 'day)
17022 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17023 ((eq origin-cat 'hour) (min (match-end 7) origin))
17024 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17025 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17026 ;; `year' and `month' have both fixed size: point
17027 ;; couldn't have moved into another part.
17028 (t origin))))
17029 ;; Update clock if on a CLOCK line.
17030 (org-clock-update-time-maybe)
17031 ;; Maybe adjust the closest clock in `org-clock-history'
17032 (when org-clock-adjust-closest
17033 (if (not (and (org-at-clock-log-p)
17034 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17035 org-clock-history))))))
17036 (message "No clock to adjust")
17037 (cond ((save-excursion ; fix previous clock?
17038 (re-search-backward org-ts-regexp0 nil t)
17039 (org-looking-back (concat org-clock-string " \\[")))
17040 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17041 ((save-excursion ; fix next clock?
17042 (re-search-backward org-ts-regexp0 nil t)
17043 (looking-at (concat org-ts-regexp0 "\\] =>")))
17044 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17045 (save-window-excursion
17046 ;; Find closest clock to point, adjust the previous/next one in history
17047 (let* ((p (save-excursion (org-back-to-heading t)))
17048 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17049 (clfixnth
17050 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17051 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17052 (if (not clfixpos)
17053 (message "No clock to adjust")
17054 (save-excursion
17055 (org-goto-marker-or-bmk clfixpos)
17056 (org-show-subtree)
17057 (when (re-search-forward clrgx nil t)
17058 (goto-char (match-beginning 1))
17059 (let (org-clock-adjust-closest)
17060 (org-timestamp-change n org-ts-what updown))
17061 (message "Clock adjusted in %s for heading: %s"
17062 (file-name-nondirectory (buffer-file-name))
17063 (org-get-heading t t)))))))))
17064 ;; Try to recenter the calendar window, if any.
17065 (if (and org-calendar-follow-timestamp-change
17066 (get-buffer-window "*Calendar*" t)
17067 (memq org-ts-what '(day month year)))
17068 (org-recenter-calendar (time-to-days time))))))
17070 (defun org-modify-ts-extra (s pos n dm)
17071 "Change the different parts of the lead-time and repeat fields in timestamp."
17072 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17073 ng h m new rem)
17074 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17075 (cond
17076 ((or (org-pos-in-match-range pos 2)
17077 (org-pos-in-match-range pos 3))
17078 (setq m (string-to-number (match-string 3 s))
17079 h (string-to-number (match-string 2 s)))
17080 (if (org-pos-in-match-range pos 2)
17081 (setq h (+ h n))
17082 (setq n (* dm (org-no-warnings (signum n))))
17083 (when (not (= 0 (setq rem (% m dm))))
17084 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17085 (setq m (+ m n)))
17086 (if (< m 0) (setq m (+ m 60) h (1- h)))
17087 (if (> m 59) (setq m (- m 60) h (1+ h)))
17088 (setq h (min 24 (max 0 h)))
17089 (setq ng 1 new (format "-%02d:%02d" h m)))
17090 ((org-pos-in-match-range pos 6)
17091 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17092 ((org-pos-in-match-range pos 5)
17093 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17095 ((org-pos-in-match-range pos 9)
17096 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17097 ((org-pos-in-match-range pos 8)
17098 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17100 (when ng
17101 (setq s (concat
17102 (substring s 0 (match-beginning ng))
17104 (substring s (match-end ng))))))
17107 (defun org-recenter-calendar (date)
17108 "If the calendar is visible, recenter it to DATE."
17109 (let ((cwin (get-buffer-window "*Calendar*" t)))
17110 (when cwin
17111 (let ((calendar-move-hook nil))
17112 (with-selected-window cwin
17113 (calendar-goto-date (if (listp date) date
17114 (calendar-gregorian-from-absolute date))))))))
17116 (defun org-goto-calendar (&optional arg)
17117 "Go to the Emacs calendar at the current date.
17118 If there is a time stamp in the current line, go to that date.
17119 A prefix ARG can be used to force the current date."
17120 (interactive "P")
17121 (let ((tsr org-ts-regexp) diff
17122 (calendar-move-hook nil)
17123 (calendar-view-holidays-initially-flag nil)
17124 (calendar-view-diary-initially-flag nil))
17125 (if (or (org-at-timestamp-p)
17126 (save-excursion
17127 (beginning-of-line 1)
17128 (looking-at (concat ".*" tsr))))
17129 (let ((d1 (time-to-days (current-time)))
17130 (d2 (time-to-days
17131 (org-time-string-to-time (match-string 1)))))
17132 (setq diff (- d2 d1))))
17133 (calendar)
17134 (calendar-goto-today)
17135 (if (and diff (not arg)) (calendar-forward-day diff))))
17137 (defun org-get-date-from-calendar ()
17138 "Return a list (month day year) of date at point in calendar."
17139 (with-current-buffer "*Calendar*"
17140 (save-match-data
17141 (calendar-cursor-to-date))))
17143 (defun org-date-from-calendar ()
17144 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17145 If there is already a time stamp at the cursor position, update it."
17146 (interactive)
17147 (if (org-at-timestamp-p t)
17148 (org-timestamp-change 0 'calendar)
17149 (let ((cal-date (org-get-date-from-calendar)))
17150 (org-insert-time-stamp
17151 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17153 (defcustom org-effort-durations
17154 `(("h" . 60)
17155 ("d" . ,(* 60 8))
17156 ("w" . ,(* 60 8 5))
17157 ("m" . ,(* 60 8 5 4))
17158 ("y" . ,(* 60 8 5 40)))
17159 "Conversion factor to minutes for an effort modifier.
17161 Each entry has the form (MODIFIER . MINUTES).
17163 In an effort string, a number followed by MODIFIER is multiplied
17164 by the specified number of MINUTES to obtain an effort in
17165 minutes.
17167 For example, if the value of this variable is ((\"hours\" . 60)), then an
17168 effort string \"2hours\" is equivalent to 120 minutes."
17169 :group 'org-agenda
17170 :version "24.1"
17171 :type '(alist :key-type (string :tag "Modifier")
17172 :value-type (number :tag "Minutes")))
17174 (defun org-minutes-to-clocksum-string (m)
17175 "Format number of minutes as a clocksum string.
17176 The format is determined by `org-time-clocksum-format',
17177 `org-time-clocksum-use-fractional' and
17178 `org-time-clocksum-fractional-format' and
17179 `org-time-clocksum-use-effort-durations'."
17180 (let ((clocksum "") h d w mo y fmt n)
17181 (setq h (if org-time-clocksum-use-effort-durations
17182 (cdr (assoc "h" org-effort-durations)) 60)
17183 d (if org-time-clocksum-use-effort-durations
17184 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17185 w (if org-time-clocksum-use-effort-durations
17186 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17187 mo (if org-time-clocksum-use-effort-durations
17188 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17189 y (if org-time-clocksum-use-effort-durations
17190 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17191 ;; fractional format
17192 (if org-time-clocksum-use-fractional
17193 (cond
17194 ;; single format string
17195 ((stringp org-time-clocksum-fractional-format)
17196 (format org-time-clocksum-fractional-format (/ m (float h))))
17197 ;; choice of fractional formats for different time units
17198 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17199 (> (/ (truncate m) (* y d h)) 0))
17200 (format fmt (/ m (* y d (float h)))))
17201 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17202 (> (/ (truncate m) (* mo d h)) 0))
17203 (format fmt (/ m (* mo d (float h)))))
17204 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17205 (> (/ (truncate m) (* w d h)) 0))
17206 (format fmt (/ m (* w d (float h)))))
17207 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17208 (> (/ (truncate m) (* d h)) 0))
17209 (format fmt (/ m (* d (float h)))))
17210 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17211 (> (/ (truncate m) h) 0))
17212 (format fmt (/ m (float h))))
17213 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17214 (format fmt m))
17215 ;; fall back to smallest time unit with a format
17216 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17217 (format fmt (/ m (float h))))
17218 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17219 (format fmt (/ m (* d (float h)))))
17220 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17221 (format fmt (/ m (* w d (float h)))))
17222 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17223 (format fmt (/ m (* mo d (float h)))))
17224 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17225 (format fmt (/ m (* y d (float h))))))
17226 ;; standard (non-fractional) format, with single format string
17227 (if (stringp org-time-clocksum-format)
17228 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17229 ;; separate formats components
17230 (and (setq fmt (plist-get org-time-clocksum-format :years))
17231 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17232 (plist-get org-time-clocksum-format :require-years))
17233 (setq clocksum (concat clocksum (format fmt n))
17234 m (- m (* n y d h))))
17235 (and (setq fmt (plist-get org-time-clocksum-format :months))
17236 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17237 (plist-get org-time-clocksum-format :require-months))
17238 (setq clocksum (concat clocksum (format fmt n))
17239 m (- m (* n mo d h))))
17240 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17241 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17242 (plist-get org-time-clocksum-format :require-weeks))
17243 (setq clocksum (concat clocksum (format fmt n))
17244 m (- m (* n w d h))))
17245 (and (setq fmt (plist-get org-time-clocksum-format :days))
17246 (or (> (setq n (/ (truncate m) (* d h))) 0)
17247 (plist-get org-time-clocksum-format :require-days))
17248 (setq clocksum (concat clocksum (format fmt n))
17249 m (- m (* n d h))))
17250 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17251 (or (> (setq n (/ (truncate m) h)) 0)
17252 (plist-get org-time-clocksum-format :require-hours))
17253 (setq clocksum (concat clocksum (format fmt n))
17254 m (- m (* n h))))
17255 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17256 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17257 (setq clocksum (concat clocksum (format fmt m))))
17258 ;; return formatted time duration
17259 clocksum))))
17261 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17262 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17263 "Org mode version 8.0")
17265 (defun org-hours-to-clocksum-string (n)
17266 (org-minutes-to-clocksum-string (* n 60)))
17268 (defun org-hh:mm-string-to-minutes (s)
17269 "Convert a string H:MM to a number of minutes.
17270 If the string is just a number, interpret it as minutes.
17271 In fact, the first hh:mm or number in the string will be taken,
17272 there can be extra stuff in the string.
17273 If no number is found, the return value is 0."
17274 (cond
17275 ((integerp s) s)
17276 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17277 (+ (* (string-to-number (match-string 1 s)) 60)
17278 (string-to-number (match-string 2 s))))
17279 ((string-match "\\([0-9]+\\)" s)
17280 (string-to-number (match-string 1 s)))
17281 (t 0)))
17283 (defcustom org-image-actual-width t
17284 "Should we use the actual width of images when inlining them?
17286 When set to `t', always use the image width.
17288 When set to a number, use imagemagick (when available) to set
17289 the image's width to this value.
17291 When set to a number in a list, try to get the width from the
17292 #+ATTR.* keyword if it matches a width specification like
17293 width=\"[0-9]+\", and fall back on that number if none is found.
17295 When set to nil, try to get the width from an #+ATTR.* keyword
17296 and fall back on the original width if none is found.
17298 This requires Emacs >= 24.1, build with imagemagick support."
17299 :group 'org-appearance
17300 :version "24.4"
17301 :package-version '(Org . "8.0")
17302 :type '(choice
17303 (const :tag "Use the image width" t)
17304 (integer :tag "Use a number of pixels")
17305 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17306 (const :tag "Use #+ATTR* or don't resize" nil)))
17308 (defcustom org-agenda-inhibit-startup t
17309 "Inhibit startup when preparing agenda buffers.
17310 When this variable is `t' (the default), the initialization of
17311 the Org agenda buffers is inhibited: e.g. the visibility state
17312 is not set, the tables are not re-aligned, etc."
17313 :type 'boolean
17314 :version "24.3"
17315 :group 'org-agenda)
17317 (defun org-duration-string-to-minutes (s &optional output-to-string)
17318 "Convert a duration string S to minutes.
17320 A bare number is interpreted as minutes, modifiers can be set by
17321 customizing `org-effort-durations' (which see).
17323 Entries containing a colon are interpreted as H:MM by
17324 `org-hh:mm-string-to-minutes'."
17325 (let ((result 0)
17326 (re (concat "\\([0-9.]+\\) *\\("
17327 (regexp-opt (mapcar 'car org-effort-durations))
17328 "\\)")))
17329 (while (string-match re s)
17330 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17331 (string-to-number (match-string 1 s))))
17332 (setq s (replace-match "" nil t s)))
17333 (setq result (floor result))
17334 (incf result (org-hh:mm-string-to-minutes s))
17335 (if output-to-string (number-to-string result) result)))
17337 ;;;; Files
17339 (defun org-save-all-org-buffers ()
17340 "Save all Org-mode buffers without user confirmation."
17341 (interactive)
17342 (message "Saving all Org-mode buffers...")
17343 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17344 (when (featurep 'org-id) (org-id-locations-save))
17345 (message "Saving all Org-mode buffers... done"))
17347 (defun org-revert-all-org-buffers ()
17348 "Revert all Org-mode buffers.
17349 Prompt for confirmation when there are unsaved changes.
17350 Be sure you know what you are doing before letting this function
17351 overwrite your changes.
17353 This function is useful in a setup where one tracks org files
17354 with a version control system, to revert on one machine after pulling
17355 changes from another. I believe the procedure must be like this:
17357 1. M-x org-save-all-org-buffers
17358 2. Pull changes from the other machine, resolve conflicts
17359 3. M-x org-revert-all-org-buffers"
17360 (interactive)
17361 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17362 (error "Abort"))
17363 (save-excursion
17364 (save-window-excursion
17365 (mapc
17366 (lambda (b)
17367 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17368 (with-current-buffer b buffer-file-name))
17369 (org-pop-to-buffer-same-window b)
17370 (revert-buffer t 'no-confirm)))
17371 (buffer-list))
17372 (when (and (featurep 'org-id) org-id-track-globally)
17373 (org-id-locations-load)))))
17375 ;;;; Agenda files
17377 ;;;###autoload
17378 (defun org-switchb (&optional arg)
17379 "Switch between Org buffers.
17380 With one prefix argument, restrict available buffers to files.
17381 With two prefix arguments, restrict available buffers to agenda files.
17383 Defaults to `iswitchb' for buffer name completion.
17384 Set `org-completion-use-ido' to make it use ido instead."
17385 (interactive "P")
17386 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17387 ((equal arg '(16)) (org-buffer-list 'agenda))
17388 (t (org-buffer-list))))
17389 (org-completion-use-iswitchb org-completion-use-iswitchb)
17390 (org-completion-use-ido org-completion-use-ido))
17391 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17392 (setq org-completion-use-iswitchb t))
17393 (org-pop-to-buffer-same-window
17394 (org-icompleting-read "Org buffer: "
17395 (mapcar 'list (mapcar 'buffer-name blist))
17396 nil t))))
17398 ;;; Define some older names previously used for this functionality
17399 ;;;###autoload
17400 (defalias 'org-ido-switchb 'org-switchb)
17401 ;;;###autoload
17402 (defalias 'org-iswitchb 'org-switchb)
17404 (defun org-buffer-list (&optional predicate exclude-tmp)
17405 "Return a list of Org buffers.
17406 PREDICATE can be `export', `files' or `agenda'.
17408 export restrict the list to Export buffers.
17409 files restrict the list to buffers visiting Org files.
17410 agenda restrict the list to buffers visiting agenda files.
17412 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17413 (let* ((bfn nil)
17414 (agenda-files (and (eq predicate 'agenda)
17415 (mapcar 'file-truename (org-agenda-files t))))
17416 (filter
17417 (cond
17418 ((eq predicate 'files)
17419 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17420 ((eq predicate 'export)
17421 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17422 ((eq predicate 'agenda)
17423 (lambda (b)
17424 (with-current-buffer b
17425 (and (derived-mode-p 'org-mode)
17426 (setq bfn (buffer-file-name b))
17427 (member (file-truename bfn) agenda-files)))))
17428 (t (lambda (b) (with-current-buffer b
17429 (or (derived-mode-p 'org-mode)
17430 (string-match "\*Org .*Export"
17431 (buffer-name b)))))))))
17432 (delq nil
17433 (mapcar
17434 (lambda(b)
17435 (if (and (funcall filter b)
17436 (or (not exclude-tmp)
17437 (not (string-match "tmp" (buffer-name b)))))
17439 nil))
17440 (buffer-list)))))
17442 (defun org-agenda-files (&optional unrestricted archives)
17443 "Get the list of agenda files.
17444 Optional UNRESTRICTED means return the full list even if a restriction
17445 is currently in place.
17446 When ARCHIVES is t, include all archive files that are really being
17447 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17448 `org-agenda-archives-mode' is t."
17449 (let ((files
17450 (cond
17451 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17452 ((stringp org-agenda-files) (org-read-agenda-file-list))
17453 ((listp org-agenda-files) org-agenda-files)
17454 (t (error "Invalid value of `org-agenda-files'")))))
17455 (setq files (apply 'append
17456 (mapcar (lambda (f)
17457 (if (file-directory-p f)
17458 (directory-files
17459 f t org-agenda-file-regexp)
17460 (list f)))
17461 files)))
17462 (when org-agenda-skip-unavailable-files
17463 (setq files (delq nil
17464 (mapcar (function
17465 (lambda (file)
17466 (and (file-readable-p file) file)))
17467 files))))
17468 (when (or (eq archives t)
17469 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17470 (setq files (org-add-archive-files files)))
17471 files))
17473 (defun org-agenda-file-p (&optional file)
17474 "Return non-nil, if FILE is an agenda file.
17475 If FILE is omitted, use the file associated with the current
17476 buffer."
17477 (member (or file (buffer-file-name))
17478 (org-agenda-files t)))
17480 (defun org-edit-agenda-file-list ()
17481 "Edit the list of agenda files.
17482 Depending on setup, this either uses customize to edit the variable
17483 `org-agenda-files', or it visits the file that is holding the list. In the
17484 latter case, the buffer is set up in a way that saving it automatically kills
17485 the buffer and restores the previous window configuration."
17486 (interactive)
17487 (if (stringp org-agenda-files)
17488 (let ((cw (current-window-configuration)))
17489 (find-file org-agenda-files)
17490 (org-set-local 'org-window-configuration cw)
17491 (org-add-hook 'after-save-hook
17492 (lambda ()
17493 (set-window-configuration
17494 (prog1 org-window-configuration
17495 (kill-buffer (current-buffer))))
17496 (org-install-agenda-files-menu)
17497 (message "New agenda file list installed"))
17498 nil 'local)
17499 (message "%s" (substitute-command-keys
17500 "Edit list and finish with \\[save-buffer]")))
17501 (customize-variable 'org-agenda-files)))
17503 (defun org-store-new-agenda-file-list (list)
17504 "Set new value for the agenda file list and save it correctly."
17505 (if (stringp org-agenda-files)
17506 (let ((fe (org-read-agenda-file-list t)) b u)
17507 (while (setq b (find-buffer-visiting org-agenda-files))
17508 (kill-buffer b))
17509 (with-temp-file org-agenda-files
17510 (insert
17511 (mapconcat
17512 (lambda (f) ;; Keep un-expanded entries.
17513 (if (setq u (assoc f fe))
17514 (cdr u)
17516 list "\n")
17517 "\n")))
17518 (let ((org-mode-hook nil) (org-inhibit-startup t)
17519 (org-insert-mode-line-in-empty-file nil))
17520 (setq org-agenda-files list)
17521 (customize-save-variable 'org-agenda-files org-agenda-files))))
17523 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17524 "Read the list of agenda files from a file.
17525 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17526 filenames, used by `org-store-new-agenda-file-list' to write back
17527 un-expanded file names."
17528 (when (file-directory-p org-agenda-files)
17529 (error "`org-agenda-files' cannot be a single directory"))
17530 (when (stringp org-agenda-files)
17531 (with-temp-buffer
17532 (insert-file-contents org-agenda-files)
17533 (mapcar
17534 (lambda (f)
17535 (let ((e (expand-file-name (substitute-in-file-name f)
17536 org-directory)))
17537 (if pair-with-expansion
17538 (cons e f)
17539 e)))
17540 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17542 ;;;###autoload
17543 (defun org-cycle-agenda-files ()
17544 "Cycle through the files in `org-agenda-files'.
17545 If the current buffer visits an agenda file, find the next one in the list.
17546 If the current buffer does not, find the first agenda file."
17547 (interactive)
17548 (let* ((fs (org-agenda-files t))
17549 (files (append fs (list (car fs))))
17550 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17551 file)
17552 (unless files (error "No agenda files"))
17553 (catch 'exit
17554 (while (setq file (pop files))
17555 (if (equal (file-truename file) tcf)
17556 (when (car files)
17557 (find-file (car files))
17558 (throw 'exit t))))
17559 (find-file (car fs)))
17560 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17562 (defun org-agenda-file-to-front (&optional to-end)
17563 "Move/add the current file to the top of the agenda file list.
17564 If the file is not present in the list, it is added to the front. If it is
17565 present, it is moved there. With optional argument TO-END, add/move to the
17566 end of the list."
17567 (interactive "P")
17568 (let ((org-agenda-skip-unavailable-files nil)
17569 (file-alist (mapcar (lambda (x)
17570 (cons (file-truename x) x))
17571 (org-agenda-files t)))
17572 (ctf (file-truename
17573 (or buffer-file-name
17574 (error "Please save the current buffer to a file"))))
17575 x had)
17576 (setq x (assoc ctf file-alist) had x)
17578 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17579 (if to-end
17580 (setq file-alist (append (delq x file-alist) (list x)))
17581 (setq file-alist (cons x (delq x file-alist))))
17582 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17583 (org-install-agenda-files-menu)
17584 (message "File %s to %s of agenda file list"
17585 (if had "moved" "added") (if to-end "end" "front"))))
17587 (defun org-remove-file (&optional file)
17588 "Remove current file from the list of files in variable `org-agenda-files'.
17589 These are the files which are being checked for agenda entries.
17590 Optional argument FILE means use this file instead of the current."
17591 (interactive)
17592 (let* ((org-agenda-skip-unavailable-files nil)
17593 (file (or file buffer-file-name
17594 (error "Current buffer does not visit a file")))
17595 (true-file (file-truename file))
17596 (afile (abbreviate-file-name file))
17597 (files (delq nil (mapcar
17598 (lambda (x)
17599 (if (equal true-file
17600 (file-truename x))
17601 nil x))
17602 (org-agenda-files t)))))
17603 (if (not (= (length files) (length (org-agenda-files t))))
17604 (progn
17605 (org-store-new-agenda-file-list files)
17606 (org-install-agenda-files-menu)
17607 (message "Removed file: %s" afile))
17608 (message "File was not in list: %s (not removed)" afile))))
17610 (defun org-file-menu-entry (file)
17611 (vector file (list 'find-file file) t))
17613 (defun org-check-agenda-file (file)
17614 "Make sure FILE exists. If not, ask user what to do."
17615 (when (not (file-exists-p file))
17616 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17617 (abbreviate-file-name file))
17618 (let ((r (downcase (read-char-exclusive))))
17619 (cond
17620 ((equal r ?r)
17621 (org-remove-file file)
17622 (throw 'nextfile t))
17623 (t (error "Abort"))))))
17625 (defun org-get-agenda-file-buffer (file)
17626 "Get a buffer visiting FILE. If the buffer needs to be created, add
17627 it to the list of buffers which might be released later."
17628 (let ((buf (org-find-base-buffer-visiting file)))
17629 (if buf
17630 buf ; just return it
17631 ;; Make a new buffer and remember it
17632 (setq buf (find-file-noselect file))
17633 (if buf (push buf org-agenda-new-buffers))
17634 buf)))
17636 (defun org-release-buffers (blist)
17637 "Release all buffers in list, asking the user for confirmation when needed.
17638 When a buffer is unmodified, it is just killed. When modified, it is saved
17639 \(if the user agrees) and then killed."
17640 (let (buf file)
17641 (while (setq buf (pop blist))
17642 (setq file (buffer-file-name buf))
17643 (when (and (buffer-modified-p buf)
17644 file
17645 (y-or-n-p (format "Save file %s? " file)))
17646 (with-current-buffer buf (save-buffer)))
17647 (kill-buffer buf))))
17649 (defun org-agenda-prepare-buffers (files)
17650 "Create buffers for all agenda files, protect archived trees and comments."
17651 (interactive)
17652 (let ((pa '(:org-archived t))
17653 (pc '(:org-comment t))
17654 (pall '(:org-archived t :org-comment t))
17655 (inhibit-read-only t)
17656 (org-inhibit-startup org-agenda-inhibit-startup)
17657 (rea (concat ":" org-archive-tag ":"))
17658 file re)
17659 (save-excursion
17660 (save-restriction
17661 (while (setq file (pop files))
17662 (catch 'nextfile
17663 (if (bufferp file)
17664 (set-buffer file)
17665 (org-check-agenda-file file)
17666 (set-buffer (org-get-agenda-file-buffer file)))
17667 (widen)
17668 (org-refresh-category-properties)
17669 (org-refresh-properties org-effort-property 'org-effort)
17670 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17671 (setq org-todo-keywords-for-agenda
17672 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17673 (setq org-done-keywords-for-agenda
17674 (append org-done-keywords-for-agenda org-done-keywords))
17675 (setq org-todo-keyword-alist-for-agenda
17676 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17677 (setq org-drawers-for-agenda
17678 (append org-drawers-for-agenda org-drawers))
17679 (setq org-tag-alist-for-agenda
17680 (append org-tag-alist-for-agenda org-tag-alist))
17681 (org-with-silent-modifications
17682 (save-excursion
17683 (remove-text-properties (point-min) (point-max) pall)
17684 (when org-agenda-skip-archived-trees
17685 (goto-char (point-min))
17686 (while (re-search-forward rea nil t)
17687 (if (org-at-heading-p t)
17688 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17689 (goto-char (point-min))
17690 (setq re (format org-heading-keyword-regexp-format
17691 org-comment-string))
17692 (while (re-search-forward re nil t)
17693 (add-text-properties
17694 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17695 (setq org-todo-keywords-for-agenda
17696 (org-uniquify org-todo-keywords-for-agenda))
17697 (setq org-todo-keyword-alist-for-agenda
17698 (org-uniquify org-todo-keyword-alist-for-agenda)
17699 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17702 ;;;; CDLaTeX minor mode
17704 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17705 "Keymap for the minor `org-cdlatex-mode'.")
17707 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17708 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17709 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17710 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17711 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17713 (defvar org-cdlatex-texmathp-advice-is-done nil
17714 "Flag remembering if we have applied the advice to texmathp already.")
17716 (define-minor-mode org-cdlatex-mode
17717 "Toggle the minor `org-cdlatex-mode'.
17718 This mode supports entering LaTeX environment and math in LaTeX fragments
17719 in Org-mode.
17720 \\{org-cdlatex-mode-map}"
17721 nil " OCDL" nil
17722 (when org-cdlatex-mode
17723 (require 'cdlatex)
17724 (run-hooks 'cdlatex-mode-hook)
17725 (cdlatex-compute-tables))
17726 (unless org-cdlatex-texmathp-advice-is-done
17727 (setq org-cdlatex-texmathp-advice-is-done t)
17728 (defadvice texmathp (around org-math-always-on activate)
17729 "Always return t in org-mode buffers.
17730 This is because we want to insert math symbols without dollars even outside
17731 the LaTeX math segments. If Orgmode thinks that point is actually inside
17732 an embedded LaTeX fragment, let texmathp do its job.
17733 \\[org-cdlatex-mode-map]"
17734 (interactive)
17735 (let (p)
17736 (cond
17737 ((not (derived-mode-p 'org-mode)) ad-do-it)
17738 ((eq this-command 'cdlatex-math-symbol)
17739 (setq ad-return-value t
17740 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17742 (let ((p (org-inside-LaTeX-fragment-p)))
17743 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17744 (setq ad-return-value t
17745 texmathp-why '("Org-mode embedded math" . 0))
17746 (if p ad-do-it)))))))))
17748 (defun turn-on-org-cdlatex ()
17749 "Unconditionally turn on `org-cdlatex-mode'."
17750 (org-cdlatex-mode 1))
17752 (defun org-try-cdlatex-tab ()
17753 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17754 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17755 - inside a LaTeX fragment, or
17756 - after the first word in a line, where an abbreviation expansion could
17757 insert a LaTeX environment."
17758 (when org-cdlatex-mode
17759 (cond
17760 ;; Before any word on the line: No expansion possible.
17761 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17762 ;; Just after first word on the line: Expand it. Make sure it
17763 ;; cannot happen on headlines, though.
17764 ((save-excursion
17765 (skip-chars-backward "a-zA-Z0-9*")
17766 (skip-chars-backward " \t")
17767 (and (bolp) (not (org-at-heading-p))))
17768 (cdlatex-tab) t)
17769 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17771 (defun org-cdlatex-underscore-caret (&optional arg)
17772 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17773 Revert to the normal definition outside of these fragments."
17774 (interactive "P")
17775 (if (org-inside-LaTeX-fragment-p)
17776 (call-interactively 'cdlatex-sub-superscript)
17777 (let (org-cdlatex-mode)
17778 (call-interactively (key-binding (vector last-input-event))))))
17780 (defun org-cdlatex-math-modify (&optional arg)
17781 "Execute `cdlatex-math-modify' in LaTeX fragments.
17782 Revert to the normal definition outside of these fragments."
17783 (interactive "P")
17784 (if (org-inside-LaTeX-fragment-p)
17785 (call-interactively 'cdlatex-math-modify)
17786 (let (org-cdlatex-mode)
17787 (call-interactively (key-binding (vector last-input-event))))))
17791 ;;;; LaTeX fragments
17793 (defvar org-latex-regexps
17794 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17795 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17796 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17797 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17798 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17799 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17800 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17801 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17802 "Regular expressions for matching embedded LaTeX.")
17804 (defun org-inside-LaTeX-fragment-p ()
17805 "Test if point is inside a LaTeX fragment.
17806 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17807 sequence appearing also before point.
17808 Even though the matchers for math are configurable, this function assumes
17809 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17810 delimiters are skipped when they have been removed by customization.
17811 The return value is nil, or a cons cell with the delimiter and the
17812 position of this delimiter.
17814 This function does a reasonably good job, but can locally be fooled by
17815 for example currency specifications. For example it will assume being in
17816 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17817 fragments that are properly closed, but during editing, we have to live
17818 with the uncertainty caused by missing closing delimiters. This function
17819 looks only before point, not after."
17820 (catch 'exit
17821 (let ((pos (point))
17822 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17823 (lim (progn
17824 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17825 (point)))
17826 dd-on str (start 0) m re)
17827 (goto-char pos)
17828 (when dodollar
17829 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17830 re (nth 1 (assoc "$" org-latex-regexps)))
17831 (while (string-match re str start)
17832 (cond
17833 ((= (match-end 0) (length str))
17834 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17835 ((= (match-end 0) (- (length str) 5))
17836 (throw 'exit nil))
17837 (t (setq start (match-end 0))))))
17838 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17839 (goto-char pos)
17840 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17841 (and (match-beginning 2) (throw 'exit nil))
17842 ;; count $$
17843 (while (re-search-backward "\\$\\$" lim t)
17844 (setq dd-on (not dd-on)))
17845 (goto-char pos)
17846 (if dd-on (cons "$$" m))))))
17848 (defun org-inside-latex-macro-p ()
17849 "Is point inside a LaTeX macro or its arguments?"
17850 (save-match-data
17851 (org-in-regexp
17852 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17854 (defvar org-latex-fragment-image-overlays nil
17855 "List of overlays carrying the images of latex fragments.")
17856 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17858 (defun org-remove-latex-fragment-image-overlays ()
17859 "Remove all overlays with LaTeX fragment images in current buffer."
17860 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17861 (setq org-latex-fragment-image-overlays nil))
17863 (defun org-preview-latex-fragment (&optional subtree)
17864 "Preview the LaTeX fragment at point, or all locally or globally.
17865 If the cursor is in a LaTeX fragment, create the image and overlay
17866 it over the source code. If there is no fragment at point, display
17867 all fragments in the current text, from one headline to the next. With
17868 prefix SUBTREE, display all fragments in the current subtree. With a
17869 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17870 the cursor is before the first headline,
17871 display all fragments in the buffer.
17872 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17873 (interactive "P")
17874 (unless buffer-file-name
17875 (error "Can't preview LaTeX fragment in a non-file buffer"))
17876 (org-remove-latex-fragment-image-overlays)
17877 (save-excursion
17878 (save-restriction
17879 (let (beg end at msg)
17880 (cond
17881 ((or (equal subtree '(16))
17882 (not (save-excursion
17883 (re-search-backward org-outline-regexp-bol nil t))))
17884 (setq beg (point-min) end (point-max)
17885 msg "Creating images for buffer...%s"))
17886 ((equal subtree '(4))
17887 (org-back-to-heading)
17888 (setq beg (point) end (org-end-of-subtree t)
17889 msg "Creating images for subtree...%s"))
17891 (if (setq at (org-inside-LaTeX-fragment-p))
17892 (goto-char (max (point-min) (- (cdr at) 2)))
17893 (org-back-to-heading))
17894 (setq beg (point) end (progn (outline-next-heading) (point))
17895 msg (if at "Creating image...%s"
17896 "Creating images for entry...%s"))))
17897 (message msg "")
17898 (narrow-to-region beg end)
17899 (goto-char beg)
17900 (org-format-latex
17901 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17902 (file-name-nondirectory
17903 buffer-file-name)))
17904 default-directory 'overlays msg at 'forbuffer
17905 org-latex-create-formula-image-program)
17906 (message msg "done. Use `C-c C-c' to remove images.")))))
17908 (defun org-format-latex (prefix &optional dir overlays msg at
17909 forbuffer processing-type)
17910 "Replace LaTeX fragments with links to an image, and produce images.
17911 Some of the options can be changed using the variable
17912 `org-format-latex-options'."
17913 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17914 (let* ((prefixnodir (file-name-nondirectory prefix))
17915 (absprefix (expand-file-name prefix dir))
17916 (todir (file-name-directory absprefix))
17917 (opt org-format-latex-options)
17918 (optnew org-format-latex-options)
17919 (matchers (plist-get opt :matchers))
17920 (re-list org-latex-regexps)
17921 (cnt 0) txt hash link beg end re e checkdir
17922 string
17923 m n block-type block linkfile movefile ov)
17924 ;; Check the different regular expressions
17925 (while (setq e (pop re-list))
17926 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17927 block (if block-type "\n\n" ""))
17928 (when (member m matchers)
17929 (goto-char (point-min))
17930 (while (re-search-forward re nil t)
17931 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17932 (or (not overlays)
17933 (not (eq (get-char-property (match-beginning n)
17934 'org-overlay-type)
17935 'org-latex-overlay))))
17936 (cond
17937 ((eq processing-type 'verbatim))
17938 ((eq processing-type 'mathjax)
17939 ;; Prepare for MathJax processing.
17940 (setq string (match-string n))
17941 (when (member m '("$" "$1"))
17942 (save-excursion
17943 (delete-region (match-beginning n) (match-end n))
17944 (goto-char (match-beginning n))
17945 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17946 ((or (eq processing-type 'dvipng)
17947 (eq processing-type 'imagemagick))
17948 ;; Process to an image.
17949 (setq txt (match-string n)
17950 beg (match-beginning n) end (match-end n)
17951 cnt (1+ cnt))
17952 (let ((face (face-at-point))
17953 (fg (plist-get opt :foreground))
17954 (bg (plist-get opt :background))
17955 ;; Ensure full list is printed.
17956 print-length print-level)
17957 (when forbuffer
17958 ;; Get the colors from the face at point.
17959 (goto-char beg)
17960 (when (eq fg 'auto)
17961 (setq fg (face-attribute face :foreground nil 'default)))
17962 (when (eq bg 'auto)
17963 (setq bg (face-attribute face :background nil 'default)))
17964 (setq optnew (copy-sequence opt))
17965 (plist-put optnew :foreground fg)
17966 (plist-put optnew :background bg))
17967 (setq hash (sha1 (prin1-to-string
17968 (list org-format-latex-header
17969 org-latex-default-packages-alist
17970 org-latex-packages-alist
17971 org-format-latex-options
17972 forbuffer txt fg bg)))
17973 linkfile (format "%s_%s.png" prefix hash)
17974 movefile (format "%s_%s.png" absprefix hash)))
17975 (setq link (concat block "[[file:" linkfile "]]" block))
17976 (if msg (message msg cnt))
17977 (goto-char beg)
17978 (unless checkdir ; Ensure the directory exists.
17979 (setq checkdir t)
17980 (or (file-directory-p todir) (make-directory todir t)))
17981 (unless (file-exists-p movefile)
17982 (org-create-formula-image
17983 txt movefile optnew forbuffer processing-type))
17984 (if overlays
17985 (progn
17986 (mapc (lambda (o)
17987 (if (eq (overlay-get o 'org-overlay-type)
17988 'org-latex-overlay)
17989 (delete-overlay o)))
17990 (overlays-in beg end))
17991 (setq ov (make-overlay beg end))
17992 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17993 (if (featurep 'xemacs)
17994 (progn
17995 (overlay-put ov 'invisible t)
17996 (overlay-put
17997 ov 'end-glyph
17998 (make-glyph (vector 'png :file movefile))))
17999 (overlay-put
18000 ov 'display
18001 (list 'image :type 'png :file movefile :ascent 'center)))
18002 (push ov org-latex-fragment-image-overlays)
18003 (goto-char end))
18004 (delete-region beg end)
18005 (insert (org-add-props link
18006 (list 'org-latex-src
18007 (replace-regexp-in-string
18008 "\"" "" txt)
18009 'org-latex-src-embed-type
18010 (if block-type 'paragraph 'character))))))
18011 ((eq processing-type 'mathml)
18012 ;; Process to MathML
18013 (unless (save-match-data (org-format-latex-mathml-available-p))
18014 (error "LaTeX to MathML converter not configured"))
18015 (setq txt (match-string n)
18016 beg (match-beginning n) end (match-end n)
18017 cnt (1+ cnt))
18018 (if msg (message msg cnt))
18019 (goto-char beg)
18020 (delete-region beg end)
18021 (insert (org-format-latex-as-mathml
18022 txt block-type prefix dir)))
18024 (error "Unknown conversion type %s for latex fragments"
18025 processing-type)))))))))
18027 (defun org-create-math-formula (latex-frag &optional mathml-file)
18028 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18029 Use `org-latex-to-mathml-convert-command'. If the conversion is
18030 sucessful, return the portion between \"<math...> </math>\"
18031 elements otherwise return nil. When MATHML-FILE is specified,
18032 write the results in to that file. When invoked as an
18033 interactive command, prompt for LATEX-FRAG, with initial value
18034 set to the current active region and echo the results for user
18035 inspection."
18036 (interactive (list (let ((frag (when (org-region-active-p)
18037 (buffer-substring-no-properties
18038 (region-beginning) (region-end)))))
18039 (read-string "LaTeX Fragment: " frag nil frag))))
18040 (unless latex-frag (error "Invalid latex-frag"))
18041 (let* ((tmp-in-file (file-relative-name
18042 (make-temp-name (expand-file-name "ltxmathml-in"))))
18043 (ignore (write-region latex-frag nil tmp-in-file))
18044 (tmp-out-file (file-relative-name
18045 (make-temp-name (expand-file-name "ltxmathml-out"))))
18046 (cmd (format-spec
18047 org-latex-to-mathml-convert-command
18048 `((?j . ,(shell-quote-argument
18049 (expand-file-name org-latex-to-mathml-jar-file)))
18050 (?I . ,(shell-quote-argument tmp-in-file))
18051 (?o . ,(shell-quote-argument tmp-out-file)))))
18052 mathml shell-command-output)
18053 (when (org-called-interactively-p 'any)
18054 (unless (org-format-latex-mathml-available-p)
18055 (error "LaTeX to MathML converter not configured")))
18056 (message "Running %s" cmd)
18057 (setq shell-command-output (shell-command-to-string cmd))
18058 (setq mathml
18059 (when (file-readable-p tmp-out-file)
18060 (with-current-buffer (find-file-noselect tmp-out-file t)
18061 (goto-char (point-min))
18062 (when (re-search-forward
18063 (concat
18064 (regexp-quote
18065 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18066 "\\(.\\|\n\\)*"
18067 (regexp-quote "</math>")) nil t)
18068 (prog1 (match-string 0) (kill-buffer))))))
18069 (cond
18070 (mathml
18071 (setq mathml
18072 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18073 (when mathml-file
18074 (write-region mathml nil mathml-file))
18075 (when (org-called-interactively-p 'any)
18076 (message mathml)))
18077 ((message "LaTeX to MathML conversion failed")
18078 (message shell-command-output)))
18079 (delete-file tmp-in-file)
18080 (when (file-exists-p tmp-out-file)
18081 (delete-file tmp-out-file))
18082 mathml))
18084 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18085 prefix &optional dir)
18086 "Use `org-create-math-formula' but check local cache first."
18087 (let* ((absprefix (expand-file-name prefix dir))
18088 (print-length nil) (print-level nil)
18089 (formula-id (concat
18090 "formula-"
18091 (sha1
18092 (prin1-to-string
18093 (list latex-frag
18094 org-latex-to-mathml-convert-command)))))
18095 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18096 (formula-cache-dir (file-name-directory formula-cache)))
18098 (unless (file-directory-p formula-cache-dir)
18099 (make-directory formula-cache-dir t))
18101 (unless (file-exists-p formula-cache)
18102 (org-create-math-formula latex-frag formula-cache))
18104 (if (file-exists-p formula-cache)
18105 ;; Successful conversion. Return the link to MathML file.
18106 (org-add-props
18107 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18108 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18109 'org-latex-src-embed-type (if latex-frag-type
18110 'paragraph 'character)))
18111 ;; Failed conversion. Return the LaTeX fragment verbatim
18112 latex-frag)))
18114 (defun org-create-formula-image (string tofile options buffer &optional type)
18115 "Create an image from LaTeX source using dvipng or convert.
18116 This function calls either `org-create-formula-image-with-dvipng'
18117 or `org-create-formula-image-with-imagemagick' depending on the
18118 value of `org-latex-create-formula-image-program' or on the value
18119 of the optional TYPE variable.
18121 Note: ultimately these two function should be combined as they
18122 share a good deal of logic."
18123 (org-check-external-command
18124 "latex" "needed to convert LaTeX fragments to images")
18125 (funcall
18126 (case (or type org-latex-create-formula-image-program)
18127 ('dvipng
18128 (org-check-external-command
18129 "dvipng" "needed to convert LaTeX fragments to images")
18130 #'org-create-formula-image-with-dvipng)
18131 ('imagemagick
18132 (org-check-external-command
18133 "convert" "you need to install imagemagick")
18134 #'org-create-formula-image-with-imagemagick)
18135 (t (error
18136 "invalid value of `org-latex-create-formula-image-program'")))
18137 string tofile options buffer))
18139 (declare-function org-export--get-global-options "ox" (&optional backend))
18140 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18141 (defun org-create-formula--latex-header ()
18142 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18143 (org-latex-guess-inputenc
18144 (org-splice-latex-header
18145 org-format-latex-header
18146 org-latex-default-packages-alist
18147 org-latex-packages-alist t
18148 (plist-get
18149 (org-combine-plists
18150 (org-export--get-global-options 'latex)
18151 (org-export--get-inbuffer-options 'latex))
18152 :latex-header-extra))))
18154 ;; This function borrows from Ganesh Swami's latex2png.el
18155 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18156 "This calls dvipng."
18157 (require 'ox-latex)
18158 (let* ((tmpdir (if (featurep 'xemacs)
18159 (temp-directory)
18160 temporary-file-directory))
18161 (texfilebase (make-temp-name
18162 (expand-file-name "orgtex" tmpdir)))
18163 (texfile (concat texfilebase ".tex"))
18164 (dvifile (concat texfilebase ".dvi"))
18165 (pngfile (concat texfilebase ".png"))
18166 (fnh (if (featurep 'xemacs)
18167 (font-height (face-font 'default))
18168 (face-attribute 'default :height nil)))
18169 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18170 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18171 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18172 "Black"))
18173 (bg (or (plist-get options (if buffer :background :html-background))
18174 "Transparent")))
18175 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18176 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18177 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18178 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18179 (let ((latex-header (org-create-formula--latex-header)))
18180 (with-temp-file texfile
18181 (insert latex-header)
18182 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18183 (let ((dir default-directory))
18184 (condition-case nil
18185 (progn
18186 (cd tmpdir)
18187 (call-process "latex" nil nil nil texfile))
18188 (error nil))
18189 (cd dir))
18190 (if (not (file-exists-p dvifile))
18191 (progn (message "Failed to create dvi file from %s" texfile) nil)
18192 (condition-case nil
18193 (if (featurep 'xemacs)
18194 (call-process "dvipng" nil nil nil
18195 "-fg" fg "-bg" bg
18196 "-T" "tight"
18197 "-o" pngfile
18198 dvifile)
18199 (call-process "dvipng" nil nil nil
18200 "-fg" fg "-bg" bg
18201 "-D" dpi
18202 ;;"-x" scale "-y" scale
18203 "-T" "tight"
18204 "-o" pngfile
18205 dvifile))
18206 (error nil))
18207 (if (not (file-exists-p pngfile))
18208 (if org-format-latex-signal-error
18209 (error "Failed to create png file from %s" texfile)
18210 (message "Failed to create png file from %s" texfile)
18211 nil)
18212 ;; Use the requested file name and clean up
18213 (copy-file pngfile tofile 'replace)
18214 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18215 (if (file-exists-p (concat texfilebase e))
18216 (delete-file (concat texfilebase e))))
18217 pngfile))))
18219 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18220 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18221 "This calls convert, which is included into imagemagick."
18222 (require 'ox-latex)
18223 (let* ((tmpdir (if (featurep 'xemacs)
18224 (temp-directory)
18225 temporary-file-directory))
18226 (texfilebase (make-temp-name
18227 (expand-file-name "orgtex" tmpdir)))
18228 (texfile (concat texfilebase ".tex"))
18229 (pdffile (concat texfilebase ".pdf"))
18230 (pngfile (concat texfilebase ".png"))
18231 (fnh (if (featurep 'xemacs)
18232 (font-height (face-font 'default))
18233 (face-attribute 'default :height nil)))
18234 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18235 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18236 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18237 "black"))
18238 (bg (or (plist-get options (if buffer :background :html-background))
18239 "white")))
18240 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18241 (setq fg (org-latex-color-format fg)))
18242 (if (eq bg 'default) (setq bg (org-latex-color :background))
18243 (setq bg (org-latex-color-format
18244 (if (string= bg "Transparent") "white" bg))))
18245 (let ((latex-header (org-create-formula--latex-header)))
18246 (with-temp-file texfile
18247 (insert latex-header)
18248 (insert "\n\\begin{document}\n"
18249 "\\definecolor{fg}{rgb}{" fg "}\n"
18250 "\\definecolor{bg}{rgb}{" bg "}\n"
18251 "\n\\pagecolor{bg}\n"
18252 "\n{\\color{fg}\n"
18253 string
18254 "\n}\n"
18255 "\n\\end{document}\n")))
18256 (org-latex-compile texfile t)
18257 (if (not (file-exists-p pdffile))
18258 (progn (message "Failed to create pdf file from %s" texfile) nil)
18259 (condition-case nil
18260 (if (featurep 'xemacs)
18261 (call-process "convert" nil nil nil
18262 "-density" "96"
18263 "-trim"
18264 "-antialias"
18265 pdffile
18266 "-quality" "100"
18267 ;; "-sharpen" "0x1.0"
18268 pngfile)
18269 (call-process "convert" nil nil nil
18270 "-density" dpi
18271 "-trim"
18272 "-antialias"
18273 pdffile
18274 "-quality" "100"
18275 ;; "-sharpen" "0x1.0"
18276 pngfile))
18277 (error nil))
18278 (if (not (file-exists-p pngfile))
18279 (if org-format-latex-signal-error
18280 (error "Failed to create png file from %s" texfile)
18281 (message "Failed to create png file from %s" texfile)
18282 nil)
18283 ;; Use the requested file name and clean up
18284 (copy-file pngfile tofile 'replace)
18285 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18286 (if (file-exists-p (concat texfilebase e))
18287 (delete-file (concat texfilebase e))))
18288 pngfile))))
18290 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18291 "Fill a LaTeX header template TPL.
18292 In the template, the following place holders will be recognized:
18294 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18295 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18296 [PACKAGES] \\usepackage statements for PKG
18297 [NO-PACKAGES] do not include PKG
18298 [EXTRA] the string EXTRA
18299 [NO-EXTRA] do not include EXTRA
18301 For backward compatibility, if both the positive and the negative place
18302 holder is missing, the positive one (without the \"NO-\") will be
18303 assumed to be present at the end of the template.
18304 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18305 EXTRA is a string.
18306 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18307 (let (rpl (end ""))
18308 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18309 (setq rpl (if (or (match-end 1) (not def-pkg))
18310 "" (org-latex-packages-to-string def-pkg snippets-p t))
18311 tpl (replace-match rpl t t tpl))
18312 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18314 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18315 (setq rpl (if (or (match-end 1) (not pkg))
18316 "" (org-latex-packages-to-string pkg snippets-p t))
18317 tpl (replace-match rpl t t tpl))
18318 (if pkg (setq end
18319 (concat end "\n"
18320 (org-latex-packages-to-string pkg snippets-p)))))
18322 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18323 (setq rpl (if (or (match-end 1) (not extra))
18324 "" (concat extra "\n"))
18325 tpl (replace-match rpl t t tpl))
18326 (if (and extra (string-match "\\S-" extra))
18327 (setq end (concat end "\n" extra))))
18329 (if (string-match "\\S-" end)
18330 (concat tpl "\n" end)
18331 tpl)))
18333 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18334 "Turn an alist of packages into a string with the \\usepackage macros."
18335 (setq pkg (mapconcat (lambda(p)
18336 (cond
18337 ((stringp p) p)
18338 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18339 (format "%% Package %s omitted" (cadr p)))
18340 ((equal "" (car p))
18341 (format "\\usepackage{%s}" (cadr p)))
18343 (format "\\usepackage[%s]{%s}"
18344 (car p) (cadr p)))))
18346 "\n"))
18347 (if newline (concat pkg "\n") pkg))
18349 (defun org-dvipng-color (attr)
18350 "Return a RGB color specification for dvipng."
18351 (apply 'format "rgb %s %s %s"
18352 (mapcar 'org-normalize-color
18353 (if (featurep 'xemacs)
18354 (color-rgb-components
18355 (face-property 'default
18356 (cond ((eq attr :foreground) 'foreground)
18357 ((eq attr :background) 'background))))
18358 (color-values (face-attribute 'default attr nil))))))
18360 (defun org-dvipng-color-format (color-name)
18361 "Convert COLOR-NAME to a RGB color value for dvipng."
18362 (apply 'format "rgb %s %s %s"
18363 (mapcar 'org-normalize-color
18364 (color-values color-name))))
18366 (defun org-latex-color (attr)
18367 "Return a RGB color for the LaTeX color package."
18368 (apply 'format "%s,%s,%s"
18369 (mapcar 'org-normalize-color
18370 (if (featurep 'xemacs)
18371 (color-rgb-components
18372 (face-property 'default
18373 (cond ((eq attr :foreground) 'foreground)
18374 ((eq attr :background) 'background))))
18375 (color-values (face-attribute 'default attr nil))))))
18377 (defun org-latex-color-format (color-name)
18378 "Convert COLOR-NAME to a RGB color value."
18379 (apply 'format "%s,%s,%s"
18380 (mapcar 'org-normalize-color
18381 (color-values color-name))))
18383 (defun org-normalize-color (value)
18384 "Return string to be used as color value for an RGB component."
18385 (format "%g" (/ value 65535.0)))
18389 ;; Image display
18391 (defvar org-inline-image-overlays nil)
18392 (make-variable-buffer-local 'org-inline-image-overlays)
18394 (defun org-toggle-inline-images (&optional include-linked)
18395 "Toggle the display of inline images.
18396 INCLUDE-LINKED is passed to `org-display-inline-images'."
18397 (interactive "P")
18398 (if org-inline-image-overlays
18399 (progn
18400 (org-remove-inline-images)
18401 (message "Inline image display turned off"))
18402 (org-display-inline-images include-linked)
18403 (if (and (org-called-interactively-p)
18404 org-inline-image-overlays)
18405 (message "%d images displayed inline"
18406 (length org-inline-image-overlays))
18407 (message "No images to display inline"))))
18409 (defun org-redisplay-inline-images ()
18410 "Refresh the display of inline images."
18411 (interactive)
18412 (if (not org-inline-image-overlays)
18413 (org-toggle-inline-images)
18414 (org-toggle-inline-images)
18415 (org-toggle-inline-images)))
18417 (defun org-display-inline-images (&optional include-linked refresh beg end)
18418 "Display inline images.
18419 Normally only links without a description part are inlined, because this
18420 is how it will work for export. When INCLUDE-LINKED is set, also links
18421 with a description part will be inlined. This can be nice for a quick
18422 look at those images, but it does not reflect what exported files will look
18423 like.
18424 When REFRESH is set, refresh existing images between BEG and END.
18425 This will create new image displays only if necessary.
18426 BEG and END default to the buffer boundaries."
18427 (interactive "P")
18428 (unless refresh
18429 (org-remove-inline-images)
18430 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18431 (save-excursion
18432 (save-restriction
18433 (widen)
18434 (setq beg (or beg (point-min)) end (or end (point-max)))
18435 (goto-char beg)
18436 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18437 (substring (org-image-file-name-regexp) 0 -2)
18438 "\\)\\]" (if include-linked "" "\\]")))
18439 old file ov img type attrwidth width)
18440 (while (re-search-forward re end t)
18441 (setq old (get-char-property-and-overlay (match-beginning 1)
18442 'org-image-overlay)
18443 file (expand-file-name
18444 (concat (or (match-string 3) "") (match-string 4))))
18445 (when (image-type-available-p 'imagemagick)
18446 (setq attrwidth (if (or (listp org-image-actual-width)
18447 (null org-image-actual-width))
18448 (save-excursion
18449 (save-match-data
18450 (when (re-search-backward
18451 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18452 (save-excursion
18453 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18454 (string-to-number (match-string 1))))))
18455 width (cond ((eq org-image-actual-width t) nil)
18456 ((null org-image-actual-width) attrwidth)
18457 ((numberp org-image-actual-width)
18458 org-image-actual-width)
18459 ((listp org-image-actual-width)
18460 (or attrwidth (car org-image-actual-width))))
18461 type (if width 'imagemagick)))
18462 (when (file-exists-p file)
18463 (if (and (car-safe old) refresh)
18464 (image-refresh (overlay-get (cdr old) 'display))
18465 (setq img (save-match-data (create-image file type nil :width width)))
18466 (when img
18467 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18468 (overlay-put ov 'display img)
18469 (overlay-put ov 'face 'default)
18470 (overlay-put ov 'org-image-overlay t)
18471 (overlay-put ov 'modification-hooks
18472 (list 'org-display-inline-remove-overlay))
18473 (push ov org-inline-image-overlays)))))))))
18475 (define-obsolete-function-alias
18476 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18478 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18479 "Remove inline-display overlay if a corresponding region is modified."
18480 (let ((inhibit-modification-hooks t))
18481 (when (and ov after)
18482 (delete ov org-inline-image-overlays)
18483 (delete-overlay ov))))
18485 (defun org-remove-inline-images ()
18486 "Remove inline display of images."
18487 (interactive)
18488 (mapc 'delete-overlay org-inline-image-overlays)
18489 (setq org-inline-image-overlays nil))
18491 ;;;; Key bindings
18493 ;; Outline functions from `outline-mode-prefix-map'
18494 ;; that can be remapped in Org:
18495 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18496 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18497 (define-key org-mode-map [remap outline-forward-same-level]
18498 'org-forward-heading-same-level)
18499 (define-key org-mode-map [remap outline-backward-same-level]
18500 'org-backward-heading-same-level)
18501 (define-key org-mode-map [remap show-branches]
18502 'org-kill-note-or-show-branches)
18503 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18504 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18505 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18507 ;; Outline functions from `outline-mode-prefix-map' that can not
18508 ;; be remapped in Org:
18510 ;; - the column "key binding" shows whether the Outline function is still
18511 ;; available in Org mode on the same key that it has been bound to in
18512 ;; Outline mode:
18513 ;; - "overridden": key used for a different functionality in Org mode
18514 ;; - else: key still bound to the same Outline function in Org mode
18516 ;; | Outline function | key binding | Org replacement |
18517 ;; |------------------------------------+-------------+-----------------------|
18518 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18519 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18520 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18521 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18522 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18523 ;; | `show-entry' | overridden | no replacement |
18524 ;; | `show-children' | `C-c C-i' | visibility cycling |
18525 ;; | `show-branches' | `C-c C-k' | still same function |
18526 ;; | `show-subtree' | overridden | visibility cycling |
18527 ;; | `show-all' | overridden | no replacement |
18528 ;; | `hide-subtree' | overridden | visibility cycling |
18529 ;; | `hide-body' | overridden | no replacement |
18530 ;; | `hide-entry' | overridden | visibility cycling |
18531 ;; | `hide-leaves' | overridden | no replacement |
18532 ;; | `hide-sublevels' | overridden | no replacement |
18533 ;; | `hide-other' | overridden | no replacement |
18535 ;; Make `C-c C-x' a prefix key
18536 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18538 ;; TAB key with modifiers
18539 (org-defkey org-mode-map "\C-i" 'org-cycle)
18540 (org-defkey org-mode-map [(tab)] 'org-cycle)
18541 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18542 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18543 ;; The following line is necessary under Suse GNU/Linux
18544 (unless (featurep 'xemacs)
18545 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18546 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18547 (define-key org-mode-map [backtab] 'org-shifttab)
18549 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18550 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18551 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18553 ;; Cursor keys with modifiers
18554 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18555 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18556 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18557 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18559 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18560 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18561 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18562 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18564 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18565 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18566 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18567 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18569 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18570 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18571 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18572 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18574 ;; Babel keys
18575 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18576 (mapc (lambda (pair)
18577 (define-key org-babel-map (car pair) (cdr pair)))
18578 org-babel-key-bindings)
18580 ;;; Extra keys for tty access.
18581 ;; We only set them when really needed because otherwise the
18582 ;; menus don't show the simple keys
18584 (when (or org-use-extra-keys
18585 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18586 (not window-system))
18587 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18588 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18589 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18590 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18591 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18592 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18593 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18594 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18595 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18596 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18597 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18598 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18599 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18600 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18601 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18602 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18603 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18604 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18605 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18606 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18607 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18608 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18609 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18610 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18611 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18612 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18613 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18614 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18616 ;; All the other keys
18618 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18619 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18620 (if (boundp 'narrow-map)
18621 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18622 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18623 (if (boundp 'narrow-map)
18624 (org-defkey narrow-map "b" 'org-narrow-to-block)
18625 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18626 (if (boundp 'narrow-map)
18627 (org-defkey narrow-map "e" 'org-narrow-to-element)
18628 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18629 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18630 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18631 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18632 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18633 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18634 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18635 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18636 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18637 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18638 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18639 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18640 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18641 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18642 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18643 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18644 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18645 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18646 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18647 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18648 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18649 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18650 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18651 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18652 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18653 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18654 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18655 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18656 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18657 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18658 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18659 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18660 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18661 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18662 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18663 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18664 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18665 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18666 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18667 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18668 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18669 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18670 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18671 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18672 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18673 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18674 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18675 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18676 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18677 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18678 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18679 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18680 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18681 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18682 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18683 (org-defkey org-mode-map "\C-c^" 'org-sort)
18684 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18685 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18686 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18687 (org-defkey org-mode-map "\C-m" 'org-return)
18688 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18689 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18690 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18691 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18692 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18693 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18694 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18695 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18696 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18697 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18698 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18699 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18700 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18701 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18702 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18703 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18704 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18705 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18706 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18707 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18708 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18709 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18710 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18712 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18713 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18714 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18716 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18717 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18718 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18719 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18720 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18721 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18722 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18723 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18724 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18725 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18726 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18727 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18728 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18729 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18730 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18731 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18732 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18733 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18734 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18735 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18736 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18737 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18738 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18740 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18741 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18742 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18743 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18744 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18746 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18748 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18750 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18751 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18753 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18756 (when (featurep 'xemacs)
18757 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18760 (defconst org-speed-commands-default
18762 ("Outline Navigation")
18763 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18764 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18765 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18766 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18767 ("F" . org-next-block)
18768 ("B" . org-previous-block)
18769 ("u" . (org-speed-move-safe 'outline-up-heading))
18770 ("j" . org-goto)
18771 ("g" . (org-refile t))
18772 ("Outline Visibility")
18773 ("c" . org-cycle)
18774 ("C" . org-shifttab)
18775 (" " . org-display-outline-path)
18776 ("=" . org-columns)
18777 ("Outline Structure Editing")
18778 ("U" . org-shiftmetaup)
18779 ("D" . org-shiftmetadown)
18780 ("r" . org-metaright)
18781 ("l" . org-metaleft)
18782 ("R" . org-shiftmetaright)
18783 ("L" . org-shiftmetaleft)
18784 ("i" . (progn (forward-char 1) (call-interactively
18785 'org-insert-heading-respect-content)))
18786 ("^" . org-sort)
18787 ("w" . org-refile)
18788 ("a" . org-archive-subtree-default-with-confirmation)
18789 ("@" . org-mark-subtree)
18790 ("#" . org-toggle-comment)
18791 ("Clock Commands")
18792 ("I" . org-clock-in)
18793 ("O" . org-clock-out)
18794 ("Meta Data Editing")
18795 ("t" . org-todo)
18796 ("," . (org-priority))
18797 ("0" . (org-priority ?\ ))
18798 ("1" . (org-priority ?A))
18799 ("2" . (org-priority ?B))
18800 ("3" . (org-priority ?C))
18801 (":" . org-set-tags-command)
18802 ("e" . org-set-effort)
18803 ("E" . org-inc-effort)
18804 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18805 (org-entry-put (point) "APPT_WARNTIME" m)))
18806 ("Agenda Views etc")
18807 ("v" . org-agenda)
18808 ("/" . org-sparse-tree)
18809 ("Misc")
18810 ("o" . org-open-at-point)
18811 ("?" . org-speed-command-help)
18812 ("<" . (org-agenda-set-restriction-lock 'subtree))
18813 (">" . (org-agenda-remove-restriction-lock))
18815 "The default speed commands.")
18817 (defun org-print-speed-command (e)
18818 (if (> (length (car e)) 1)
18819 (progn
18820 (princ "\n")
18821 (princ (car e))
18822 (princ "\n")
18823 (princ (make-string (length (car e)) ?-))
18824 (princ "\n"))
18825 (princ (car e))
18826 (princ " ")
18827 (if (symbolp (cdr e))
18828 (princ (symbol-name (cdr e)))
18829 (prin1 (cdr e)))
18830 (princ "\n")))
18832 (defun org-speed-command-help ()
18833 "Show the available speed commands."
18834 (interactive)
18835 (if (not org-use-speed-commands)
18836 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18837 (with-output-to-temp-buffer "*Help*"
18838 (princ "User-defined Speed commands\n===========================\n")
18839 (mapc 'org-print-speed-command org-speed-commands-user)
18840 (princ "\n")
18841 (princ "Built-in Speed commands\n=======================\n")
18842 (mapc 'org-print-speed-command org-speed-commands-default))
18843 (with-current-buffer "*Help*"
18844 (setq truncate-lines t))))
18846 (defun org-speed-move-safe (cmd)
18847 "Execute CMD, but make sure that the cursor always ends up in a headline.
18848 If not, return to the original position and throw an error."
18849 (interactive)
18850 (let ((pos (point)))
18851 (call-interactively cmd)
18852 (unless (and (bolp) (org-at-heading-p))
18853 (goto-char pos)
18854 (error "Boundary reached while executing %s" cmd))))
18856 (defvar org-self-insert-command-undo-counter 0)
18858 (defvar org-table-auto-blank-field) ; defined in org-table.el
18859 (defvar org-speed-command nil)
18861 (define-obsolete-function-alias
18862 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18864 (defun org-speed-command-activate (keys)
18865 "Hook for activating single-letter speed commands.
18866 `org-speed-commands-default' specifies a minimal command set.
18867 Use `org-speed-commands-user' for further customization."
18868 (when (or (and (bolp) (looking-at org-outline-regexp))
18869 (and (functionp org-use-speed-commands)
18870 (funcall org-use-speed-commands)))
18871 (cdr (assoc keys (append org-speed-commands-user
18872 org-speed-commands-default)))))
18874 (define-obsolete-function-alias
18875 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18877 (defun org-babel-speed-command-activate (keys)
18878 "Hook for activating single-letter code block commands."
18879 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18880 (cdr (assoc keys org-babel-key-bindings))))
18882 (defcustom org-speed-command-hook
18883 '(org-speed-command-default-hook org-babel-speed-command-hook)
18884 "Hook for activating speed commands at strategic locations.
18885 Hook functions are called in sequence until a valid handler is
18886 found.
18888 Each hook takes a single argument, a user-pressed command key
18889 which is also a `self-insert-command' from the global map.
18891 Within the hook, examine the cursor position and the command key
18892 and return nil or a valid handler as appropriate. Handler could
18893 be one of an interactive command, a function, or a form.
18895 Set `org-use-speed-commands' to non-nil value to enable this
18896 hook. The default setting is `org-speed-command-activate'."
18897 :group 'org-structure
18898 :version "24.1"
18899 :type 'hook)
18901 (defun org-self-insert-command (N)
18902 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18903 If the cursor is in a table looking at whitespace, the whitespace is
18904 overwritten, and the table is not marked as requiring realignment."
18905 (interactive "p")
18906 (org-check-before-invisible-edit 'insert)
18907 (cond
18908 ((and org-use-speed-commands
18909 (setq org-speed-command
18910 (run-hook-with-args-until-success
18911 'org-speed-command-hook (this-command-keys))))
18912 (cond
18913 ((commandp org-speed-command)
18914 (setq this-command org-speed-command)
18915 (call-interactively org-speed-command))
18916 ((functionp org-speed-command)
18917 (funcall org-speed-command))
18918 ((and org-speed-command (listp org-speed-command))
18919 (eval org-speed-command))
18920 (t (let (org-use-speed-commands)
18921 (call-interactively 'org-self-insert-command)))))
18922 ((and
18923 (org-table-p)
18924 (progn
18925 ;; check if we blank the field, and if that triggers align
18926 (and (featurep 'org-table) org-table-auto-blank-field
18927 (member last-command
18928 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18929 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18930 ;; got extra space, this field does not determine column width
18931 (let (org-table-may-need-update) (org-table-blank-field))
18932 ;; no extra space, this field may determine column width
18933 (org-table-blank-field)))
18935 (eq N 1)
18936 (looking-at "[^|\n]* |"))
18937 (let (org-table-may-need-update)
18938 (goto-char (1- (match-end 0)))
18939 (backward-delete-char 1)
18940 (goto-char (match-beginning 0))
18941 (self-insert-command N)))
18943 (setq org-table-may-need-update t)
18944 (self-insert-command N)
18945 (org-fix-tags-on-the-fly)
18946 (if org-self-insert-cluster-for-undo
18947 (if (not (eq last-command 'org-self-insert-command))
18948 (setq org-self-insert-command-undo-counter 1)
18949 (if (>= org-self-insert-command-undo-counter 20)
18950 (setq org-self-insert-command-undo-counter 1)
18951 (and (> org-self-insert-command-undo-counter 0)
18952 buffer-undo-list (listp buffer-undo-list)
18953 (not (cadr buffer-undo-list)) ; remove nil entry
18954 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18955 (setq org-self-insert-command-undo-counter
18956 (1+ org-self-insert-command-undo-counter))))))))
18958 (defun org-check-before-invisible-edit (kind)
18959 "Check is editing if kind KIND would be dangerous with invisible text around.
18960 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18961 ;; First, try to get out of here as quickly as possible, to reduce overhead
18962 (if (and org-catch-invisible-edits
18963 (or (not (boundp 'visible-mode)) (not visible-mode))
18964 (or (get-char-property (point) 'invisible)
18965 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18966 ;; OK, we need to take a closer look
18967 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18968 (invisible-before-point (if (bobp) nil (get-char-property
18969 (1- (point)) 'invisible)))
18970 (border-and-ok-direction
18972 ;; Check if we are acting predictably before invisible text
18973 (and invisible-at-point (not invisible-before-point)
18974 (memq kind '(insert delete-backward)))
18975 ;; Check if we are acting predictably after invisible text
18976 ;; This works not well, and I have turned it off. It seems
18977 ;; better to always show and stop after invisible text.
18978 ;; (and (not invisible-at-point) invisible-before-point
18979 ;; (memq kind '(insert delete)))
18981 (when (or (memq invisible-at-point '(outline org-hide-block t))
18982 (memq invisible-before-point '(outline org-hide-block t)))
18983 (if (eq org-catch-invisible-edits 'error)
18984 (error "Editing in invisible areas is prohibited - make visible first"))
18985 (if (and org-custom-properties-overlays
18986 (y-or-n-p "Display invisible properties in this buffer? "))
18987 (org-toggle-custom-properties-visibility)
18988 ;; Make the area visible
18989 (save-excursion
18990 (if invisible-before-point
18991 (goto-char (previous-single-char-property-change
18992 (point) 'invisible)))
18993 (org-cycle))
18994 (cond
18995 ((eq org-catch-invisible-edits 'show)
18996 ;; That's it, we do the edit after showing
18997 (message
18998 "Unfolding invisible region around point before editing")
18999 (sit-for 1))
19000 ((and (eq org-catch-invisible-edits 'smart)
19001 border-and-ok-direction)
19002 (message "Unfolding invisible region around point before editing"))
19004 ;; Don't do the edit, make the user repeat it in full visibility
19005 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19007 (defun org-fix-tags-on-the-fly ()
19008 (when (and (equal (char-after (point-at-bol)) ?*)
19009 (org-at-heading-p))
19010 (org-align-tags-here org-tags-column)))
19012 (defun org-delete-backward-char (N)
19013 "Like `delete-backward-char', insert whitespace at field end in tables.
19014 When deleting backwards, in tables this function will insert whitespace in
19015 front of the next \"|\" separator, to keep the table aligned. The table will
19016 still be marked for re-alignment if the field did fill the entire column,
19017 because, in this case the deletion might narrow the column."
19018 (interactive "p")
19019 (save-match-data
19020 (org-check-before-invisible-edit 'delete-backward)
19021 (if (and (org-table-p)
19022 (eq N 1)
19023 (string-match "|" (buffer-substring (point-at-bol) (point)))
19024 (looking-at ".*?|"))
19025 (let ((pos (point))
19026 (noalign (looking-at "[^|\n\r]* |"))
19027 (c org-table-may-need-update))
19028 (backward-delete-char N)
19029 (if (not overwrite-mode)
19030 (progn
19031 (skip-chars-forward "^|")
19032 (insert " ")
19033 (goto-char (1- pos))))
19034 ;; noalign: if there were two spaces at the end, this field
19035 ;; does not determine the width of the column.
19036 (if noalign (setq org-table-may-need-update c)))
19037 (backward-delete-char N)
19038 (org-fix-tags-on-the-fly))))
19040 (defun org-delete-char (N)
19041 "Like `delete-char', but insert whitespace at field end in tables.
19042 When deleting characters, in tables this function will insert whitespace in
19043 front of the next \"|\" separator, to keep the table aligned. The table will
19044 still be marked for re-alignment if the field did fill the entire column,
19045 because, in this case the deletion might narrow the column."
19046 (interactive "p")
19047 (save-match-data
19048 (org-check-before-invisible-edit 'delete)
19049 (if (and (org-table-p)
19050 (not (bolp))
19051 (not (= (char-after) ?|))
19052 (eq N 1))
19053 (if (looking-at ".*?|")
19054 (let ((pos (point))
19055 (noalign (looking-at "[^|\n\r]* |"))
19056 (c org-table-may-need-update))
19057 (replace-match (concat
19058 (substring (match-string 0) 1 -1)
19059 " |"))
19060 (goto-char pos)
19061 ;; noalign: if there were two spaces at the end, this field
19062 ;; does not determine the width of the column.
19063 (if noalign (setq org-table-may-need-update c)))
19064 (delete-char N))
19065 (delete-char N)
19066 (org-fix-tags-on-the-fly))))
19068 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19069 (put 'org-self-insert-command 'delete-selection t)
19070 (put 'orgtbl-self-insert-command 'delete-selection t)
19071 (put 'org-delete-char 'delete-selection 'supersede)
19072 (put 'org-delete-backward-char 'delete-selection 'supersede)
19073 (put 'org-yank 'delete-selection 'yank)
19075 ;; Make `flyspell-mode' delay after some commands
19076 (put 'org-self-insert-command 'flyspell-delayed t)
19077 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19078 (put 'org-delete-char 'flyspell-delayed t)
19079 (put 'org-delete-backward-char 'flyspell-delayed t)
19081 ;; Make pabbrev-mode expand after org-mode commands
19082 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19083 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19085 ;; How to do this: Measure non-white length of current string
19086 ;; If equal to column width, we should realign.
19088 (defun org-remap (map &rest commands)
19089 "In MAP, remap the functions given in COMMANDS.
19090 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19091 (let (new old)
19092 (while commands
19093 (setq old (pop commands) new (pop commands))
19094 (if (fboundp 'command-remapping)
19095 (org-defkey map (vector 'remap old) new)
19096 (substitute-key-definition old new map global-map)))))
19098 (defun org-transpose-words ()
19099 "Transpose words for Org.
19100 This uses the `org-mode-transpose-word-syntax-table' syntax
19101 table, which interprets characters in `org-emphasis-alist' as
19102 word constituants."
19103 (interactive)
19104 (with-syntax-table org-mode-transpose-word-syntax-table
19105 (call-interactively 'transpose-words)))
19106 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19108 (when (eq org-enable-table-editor 'optimized)
19109 ;; If the user wants maximum table support, we need to hijack
19110 ;; some standard editing functions
19111 (org-remap org-mode-map
19112 'self-insert-command 'org-self-insert-command
19113 'delete-char 'org-delete-char
19114 'delete-backward-char 'org-delete-backward-char)
19115 (org-defkey org-mode-map "|" 'org-force-self-insert))
19117 (defvar org-ctrl-c-ctrl-c-hook nil
19118 "Hook for functions attaching themselves to `C-c C-c'.
19120 This can be used to add additional functionality to the C-c C-c
19121 key which executes context-dependent commands. This hook is run
19122 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19123 run after the last test.
19125 Each function will be called with no arguments. The function
19126 must check if the context is appropriate for it to act. If yes,
19127 it should do its thing and then return a non-nil value. If the
19128 context is wrong, just do nothing and return nil.")
19130 (defvar org-ctrl-c-ctrl-c-final-hook nil
19131 "Hook for functions attaching themselves to `C-c C-c'.
19133 This can be used to add additional functionality to the C-c C-c
19134 key which executes context-dependent commands. This hook is run
19135 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19136 before the first test.
19138 Each function will be called with no arguments. The function
19139 must check if the context is appropriate for it to act. If yes,
19140 it should do its thing and then return a non-nil value. If the
19141 context is wrong, just do nothing and return nil.")
19143 (defvar org-tab-first-hook nil
19144 "Hook for functions to attach themselves to TAB.
19145 See `org-ctrl-c-ctrl-c-hook' for more information.
19146 This hook runs as the first action when TAB is pressed, even before
19147 `org-cycle' messes around with the `outline-regexp' to cater for
19148 inline tasks and plain list item folding.
19149 If any function in this hook returns t, any other actions that
19150 would have been caused by TAB (such as table field motion or visibility
19151 cycling) will not occur.")
19153 (defvar org-tab-after-check-for-table-hook nil
19154 "Hook for functions to attach themselves to TAB.
19155 See `org-ctrl-c-ctrl-c-hook' for more information.
19156 This hook runs after it has been established that the cursor is not in a
19157 table, but before checking if the cursor is in a headline or if global cycling
19158 should be done.
19159 If any function in this hook returns t, not other actions like visibility
19160 cycling will be done.")
19162 (defvar org-tab-after-check-for-cycling-hook nil
19163 "Hook for functions to attach themselves to TAB.
19164 See `org-ctrl-c-ctrl-c-hook' for more information.
19165 This hook runs after it has been established that not table field motion and
19166 not visibility should be done because of current context. This is probably
19167 the place where a package like yasnippets can hook in.")
19169 (defvar org-tab-before-tab-emulation-hook nil
19170 "Hook for functions to attach themselves to TAB.
19171 See `org-ctrl-c-ctrl-c-hook' for more information.
19172 This hook runs after every other options for TAB have been exhausted, but
19173 before indentation and \t insertion takes place.")
19175 (defvar org-metaleft-hook nil
19176 "Hook for functions attaching themselves to `M-left'.
19177 See `org-ctrl-c-ctrl-c-hook' for more information.")
19178 (defvar org-metaright-hook nil
19179 "Hook for functions attaching themselves to `M-right'.
19180 See `org-ctrl-c-ctrl-c-hook' for more information.")
19181 (defvar org-metaup-hook nil
19182 "Hook for functions attaching themselves to `M-up'.
19183 See `org-ctrl-c-ctrl-c-hook' for more information.")
19184 (defvar org-metadown-hook nil
19185 "Hook for functions attaching themselves to `M-down'.
19186 See `org-ctrl-c-ctrl-c-hook' for more information.")
19187 (defvar org-shiftmetaleft-hook nil
19188 "Hook for functions attaching themselves to `M-S-left'.
19189 See `org-ctrl-c-ctrl-c-hook' for more information.")
19190 (defvar org-shiftmetaright-hook nil
19191 "Hook for functions attaching themselves to `M-S-right'.
19192 See `org-ctrl-c-ctrl-c-hook' for more information.")
19193 (defvar org-shiftmetaup-hook nil
19194 "Hook for functions attaching themselves to `M-S-up'.
19195 See `org-ctrl-c-ctrl-c-hook' for more information.")
19196 (defvar org-shiftmetadown-hook nil
19197 "Hook for functions attaching themselves to `M-S-down'.
19198 See `org-ctrl-c-ctrl-c-hook' for more information.")
19199 (defvar org-metareturn-hook nil
19200 "Hook for functions attaching themselves to `M-RET'.
19201 See `org-ctrl-c-ctrl-c-hook' for more information.")
19202 (defvar org-shiftup-hook nil
19203 "Hook for functions attaching themselves to `S-up'.
19204 See `org-ctrl-c-ctrl-c-hook' for more information.")
19205 (defvar org-shiftup-final-hook nil
19206 "Hook for functions attaching themselves to `S-up'.
19207 This one runs after all other options except shift-select have been excluded.
19208 See `org-ctrl-c-ctrl-c-hook' for more information.")
19209 (defvar org-shiftdown-hook nil
19210 "Hook for functions attaching themselves to `S-down'.
19211 See `org-ctrl-c-ctrl-c-hook' for more information.")
19212 (defvar org-shiftdown-final-hook nil
19213 "Hook for functions attaching themselves to `S-down'.
19214 This one runs after all other options except shift-select have been excluded.
19215 See `org-ctrl-c-ctrl-c-hook' for more information.")
19216 (defvar org-shiftleft-hook nil
19217 "Hook for functions attaching themselves to `S-left'.
19218 See `org-ctrl-c-ctrl-c-hook' for more information.")
19219 (defvar org-shiftleft-final-hook nil
19220 "Hook for functions attaching themselves to `S-left'.
19221 This one runs after all other options except shift-select have been excluded.
19222 See `org-ctrl-c-ctrl-c-hook' for more information.")
19223 (defvar org-shiftright-hook nil
19224 "Hook for functions attaching themselves to `S-right'.
19225 See `org-ctrl-c-ctrl-c-hook' for more information.")
19226 (defvar org-shiftright-final-hook nil
19227 "Hook for functions attaching themselves to `S-right'.
19228 This one runs after all other options except shift-select have been excluded.
19229 See `org-ctrl-c-ctrl-c-hook' for more information.")
19231 (defun org-modifier-cursor-error ()
19232 "Throw an error, a modified cursor command was applied in wrong context."
19233 (error "This command is active in special context like tables, headlines or items"))
19235 (defun org-shiftselect-error ()
19236 "Throw an error because Shift-Cursor command was applied in wrong context."
19237 (if (and (boundp 'shift-select-mode) shift-select-mode)
19238 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19239 (error "This command works only in special context like headlines or timestamps")))
19241 (defun org-call-for-shift-select (cmd)
19242 (let ((this-command-keys-shift-translated t))
19243 (call-interactively cmd)))
19245 (defun org-shifttab (&optional arg)
19246 "Global visibility cycling or move to previous table field.
19247 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19248 on context.
19249 See the individual commands for more information."
19250 (interactive "P")
19251 (cond
19252 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19253 ((integerp arg)
19254 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19255 (message "Content view to level: %d" arg)
19256 (org-content (prefix-numeric-value arg2))
19257 (setq org-cycle-global-status 'overview)))
19258 (t (call-interactively 'org-global-cycle))))
19260 (defun org-shiftmetaleft ()
19261 "Promote subtree or delete table column.
19262 Calls `org-promote-subtree', `org-outdent-item-tree', or
19263 `org-table-delete-column', depending on context. See the
19264 individual commands for more information."
19265 (interactive)
19266 (cond
19267 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19268 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19269 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19270 ((if (not (org-region-active-p)) (org-at-item-p)
19271 (save-excursion (goto-char (region-beginning))
19272 (org-at-item-p)))
19273 (call-interactively 'org-outdent-item-tree))
19274 (t (org-modifier-cursor-error))))
19276 (defun org-shiftmetaright ()
19277 "Demote subtree or insert table column.
19278 Calls `org-demote-subtree', `org-indent-item-tree', or
19279 `org-table-insert-column', depending on context. See the
19280 individual commands for more information."
19281 (interactive)
19282 (cond
19283 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19284 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19285 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19286 ((if (not (org-region-active-p)) (org-at-item-p)
19287 (save-excursion (goto-char (region-beginning))
19288 (org-at-item-p)))
19289 (call-interactively 'org-indent-item-tree))
19290 (t (org-modifier-cursor-error))))
19292 (defun org-shiftmetaup (&optional arg)
19293 "Move subtree up or kill table row.
19294 Calls `org-move-subtree-up' or `org-table-kill-row' or
19295 `org-move-item-up' or `org-timestamp-up', depending on context.
19296 See the individual commands for more information."
19297 (interactive "P")
19298 (cond
19299 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19300 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19301 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19302 ((org-at-item-p) (call-interactively 'org-move-item-up))
19303 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19304 (call-interactively 'org-timestamp-up)))
19305 (t (call-interactively 'org-drag-line-backward))))
19307 (defun org-shiftmetadown (&optional arg)
19308 "Move subtree down or insert table row.
19309 Calls `org-move-subtree-down' or `org-table-insert-row' or
19310 `org-move-item-down' or `org-timestamp-up', depending on context.
19311 See the individual commands for more information."
19312 (interactive "P")
19313 (cond
19314 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19315 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19316 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19317 ((org-at-item-p) (call-interactively 'org-move-item-down))
19318 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19319 (call-interactively 'org-timestamp-down)))
19320 (t (call-interactively 'org-drag-line-forward))))
19322 (defsubst org-hidden-tree-error ()
19323 (error
19324 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19326 (defun org-metaleft (&optional arg)
19327 "Promote heading or move table column to left.
19328 Calls `org-do-promote' or `org-table-move-column', depending on context.
19329 With no specific context, calls the Emacs default `backward-word'.
19330 See the individual commands for more information."
19331 (interactive "P")
19332 (cond
19333 ((run-hook-with-args-until-success 'org-metaleft-hook))
19334 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19335 ((org-with-limited-levels
19336 (or (org-at-heading-p)
19337 (and (org-region-active-p)
19338 (save-excursion
19339 (goto-char (region-beginning))
19340 (org-at-heading-p)))))
19341 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19342 (call-interactively 'org-do-promote))
19343 ;; At an inline task.
19344 ((org-at-heading-p)
19345 (call-interactively 'org-inlinetask-promote))
19346 ((or (org-at-item-p)
19347 (and (org-region-active-p)
19348 (save-excursion
19349 (goto-char (region-beginning))
19350 (org-at-item-p))))
19351 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19352 (call-interactively 'org-outdent-item))
19353 (t (call-interactively 'backward-word))))
19355 (defun org-metaright (&optional arg)
19356 "Demote a subtree, a list item or move table column to right.
19357 In front of a drawer or a block keyword, indent it correctly.
19358 With no specific context, calls the Emacs default `forward-word'.
19359 See the individual commands for more information."
19360 (interactive "P")
19361 (cond
19362 ((run-hook-with-args-until-success 'org-metaright-hook))
19363 ((org-at-table-p) (call-interactively 'org-table-move-column))
19364 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19365 ((org-at-block-p) (call-interactively 'org-indent-block))
19366 ((org-with-limited-levels
19367 (or (org-at-heading-p)
19368 (and (org-region-active-p)
19369 (save-excursion
19370 (goto-char (region-beginning))
19371 (org-at-heading-p)))))
19372 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19373 (call-interactively 'org-do-demote))
19374 ;; At an inline task.
19375 ((org-at-heading-p)
19376 (call-interactively 'org-inlinetask-demote))
19377 ((or (org-at-item-p)
19378 (and (org-region-active-p)
19379 (save-excursion
19380 (goto-char (region-beginning))
19381 (org-at-item-p))))
19382 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19383 (call-interactively 'org-indent-item))
19384 (t (call-interactively 'forward-word))))
19386 (defun org-check-for-hidden (what)
19387 "Check if there are hidden headlines/items in the current visual line.
19388 WHAT can be either `headlines' or `items'. If the current line is
19389 an outline or item heading and it has a folded subtree below it,
19390 this function returns t, nil otherwise."
19391 (let ((re (cond
19392 ((eq what 'headlines) org-outline-regexp-bol)
19393 ((eq what 'items) (org-item-beginning-re))
19394 (t (error "This should not happen"))))
19395 beg end)
19396 (save-excursion
19397 (catch 'exit
19398 (unless (org-region-active-p)
19399 (setq beg (point-at-bol))
19400 (beginning-of-line 2)
19401 (while (and (not (eobp)) ;; this is like `next-line'
19402 (get-char-property (1- (point)) 'invisible))
19403 (beginning-of-line 2))
19404 (setq end (point))
19405 (goto-char beg)
19406 (goto-char (point-at-eol))
19407 (setq end (max end (point)))
19408 (while (re-search-forward re end t)
19409 (if (get-char-property (match-beginning 0) 'invisible)
19410 (throw 'exit t))))
19411 nil))))
19413 (defun org-metaup (&optional arg)
19414 "Move subtree up or move table row up.
19415 Calls `org-move-subtree-up' or `org-table-move-row' or
19416 `org-move-item-up', depending on context. See the individual commands
19417 for more information."
19418 (interactive "P")
19419 (cond
19420 ((run-hook-with-args-until-success 'org-metaup-hook))
19421 ((org-region-active-p)
19422 (let* ((a (min (region-beginning) (region-end)))
19423 (b (1- (max (region-beginning) (region-end))))
19424 (c (save-excursion (goto-char a)
19425 (move-beginning-of-line 0)))
19426 (d (save-excursion (goto-char a)
19427 (move-end-of-line 0) (point))))
19428 (transpose-regions a b c d)
19429 (goto-char c)))
19430 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19431 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19432 ((org-at-item-p) (call-interactively 'org-move-item-up))
19433 (t (org-drag-element-backward))))
19435 (defun org-metadown (&optional arg)
19436 "Move subtree down or move table row down.
19437 Calls `org-move-subtree-down' or `org-table-move-row' or
19438 `org-move-item-down', depending on context. See the individual
19439 commands for more information."
19440 (interactive "P")
19441 (cond
19442 ((run-hook-with-args-until-success 'org-metadown-hook))
19443 ((org-region-active-p)
19444 (let* ((a (min (region-beginning) (region-end)))
19445 (b (max (region-beginning) (region-end)))
19446 (c (save-excursion (goto-char b)
19447 (move-beginning-of-line 1)))
19448 (d (save-excursion (goto-char b)
19449 (move-end-of-line 1) (1+ (point)))))
19450 (transpose-regions a b c d)
19451 (goto-char d)))
19452 ((org-at-table-p) (call-interactively 'org-table-move-row))
19453 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19454 ((org-at-item-p) (call-interactively 'org-move-item-down))
19455 (t (org-drag-element-forward))))
19457 (defun org-shiftup (&optional arg)
19458 "Increase item in timestamp or increase priority of current headline.
19459 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19460 depending on context. See the individual commands for more information."
19461 (interactive "P")
19462 (cond
19463 ((run-hook-with-args-until-success 'org-shiftup-hook))
19464 ((and org-support-shift-select (org-region-active-p))
19465 (org-call-for-shift-select 'previous-line))
19466 ((org-at-timestamp-p t)
19467 (call-interactively (if org-edit-timestamp-down-means-later
19468 'org-timestamp-down 'org-timestamp-up)))
19469 ((and (not (eq org-support-shift-select 'always))
19470 org-enable-priority-commands
19471 (org-at-heading-p))
19472 (call-interactively 'org-priority-up))
19473 ((and (not org-support-shift-select) (org-at-item-p))
19474 (call-interactively 'org-previous-item))
19475 ((org-clocktable-try-shift 'up arg))
19476 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19477 (org-support-shift-select
19478 (org-call-for-shift-select 'previous-line))
19479 (t (org-shiftselect-error))))
19481 (defun org-shiftdown (&optional arg)
19482 "Decrease item in timestamp or decrease priority of current headline.
19483 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19484 depending on context. See the individual commands for more information."
19485 (interactive "P")
19486 (cond
19487 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19488 ((and org-support-shift-select (org-region-active-p))
19489 (org-call-for-shift-select 'next-line))
19490 ((org-at-timestamp-p t)
19491 (call-interactively (if org-edit-timestamp-down-means-later
19492 'org-timestamp-up 'org-timestamp-down)))
19493 ((and (not (eq org-support-shift-select 'always))
19494 org-enable-priority-commands
19495 (org-at-heading-p))
19496 (call-interactively 'org-priority-down))
19497 ((and (not org-support-shift-select) (org-at-item-p))
19498 (call-interactively 'org-next-item))
19499 ((org-clocktable-try-shift 'down arg))
19500 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19501 (org-support-shift-select
19502 (org-call-for-shift-select 'next-line))
19503 (t (org-shiftselect-error))))
19505 (defun org-shiftright (&optional arg)
19506 "Cycle the thing at point or in the current line, depending on context.
19507 Depending on context, this does one of the following:
19509 - switch a timestamp at point one day into the future
19510 - on a headline, switch to the next TODO keyword.
19511 - on an item, switch entire list to the next bullet type
19512 - on a property line, switch to the next allowed value
19513 - on a clocktable definition line, move time block into the future"
19514 (interactive "P")
19515 (cond
19516 ((run-hook-with-args-until-success 'org-shiftright-hook))
19517 ((and org-support-shift-select (org-region-active-p))
19518 (org-call-for-shift-select 'forward-char))
19519 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19520 ((and (not (eq org-support-shift-select 'always))
19521 (org-at-heading-p))
19522 (let ((org-inhibit-logging
19523 (not org-treat-S-cursor-todo-selection-as-state-change))
19524 (org-inhibit-blocking
19525 (not org-treat-S-cursor-todo-selection-as-state-change)))
19526 (org-call-with-arg 'org-todo 'right)))
19527 ((or (and org-support-shift-select
19528 (not (eq org-support-shift-select 'always))
19529 (org-at-item-bullet-p))
19530 (and (not org-support-shift-select) (org-at-item-p)))
19531 (org-call-with-arg 'org-cycle-list-bullet nil))
19532 ((and (not (eq org-support-shift-select 'always))
19533 (org-at-property-p))
19534 (call-interactively 'org-property-next-allowed-value))
19535 ((org-clocktable-try-shift 'right arg))
19536 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19537 (org-support-shift-select
19538 (org-call-for-shift-select 'forward-char))
19539 (t (org-shiftselect-error))))
19541 (defun org-shiftleft (&optional arg)
19542 "Cycle the thing at point or in the current line, depending on context.
19543 Depending on context, this does one of the following:
19545 - switch a timestamp at point one day into the past
19546 - on a headline, switch to the previous TODO keyword.
19547 - on an item, switch entire list to the previous bullet type
19548 - on a property line, switch to the previous allowed value
19549 - on a clocktable definition line, move time block into the past"
19550 (interactive "P")
19551 (cond
19552 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19553 ((and org-support-shift-select (org-region-active-p))
19554 (org-call-for-shift-select 'backward-char))
19555 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19556 ((and (not (eq org-support-shift-select 'always))
19557 (org-at-heading-p))
19558 (let ((org-inhibit-logging
19559 (not org-treat-S-cursor-todo-selection-as-state-change))
19560 (org-inhibit-blocking
19561 (not org-treat-S-cursor-todo-selection-as-state-change)))
19562 (org-call-with-arg 'org-todo 'left)))
19563 ((or (and org-support-shift-select
19564 (not (eq org-support-shift-select 'always))
19565 (org-at-item-bullet-p))
19566 (and (not org-support-shift-select) (org-at-item-p)))
19567 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19568 ((and (not (eq org-support-shift-select 'always))
19569 (org-at-property-p))
19570 (call-interactively 'org-property-previous-allowed-value))
19571 ((org-clocktable-try-shift 'left arg))
19572 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19573 (org-support-shift-select
19574 (org-call-for-shift-select 'backward-char))
19575 (t (org-shiftselect-error))))
19577 (defun org-shiftcontrolright ()
19578 "Switch to next TODO set."
19579 (interactive)
19580 (cond
19581 ((and org-support-shift-select (org-region-active-p))
19582 (org-call-for-shift-select 'forward-word))
19583 ((and (not (eq org-support-shift-select 'always))
19584 (org-at-heading-p))
19585 (org-call-with-arg 'org-todo 'nextset))
19586 (org-support-shift-select
19587 (org-call-for-shift-select 'forward-word))
19588 (t (org-shiftselect-error))))
19590 (defun org-shiftcontrolleft ()
19591 "Switch to previous TODO set."
19592 (interactive)
19593 (cond
19594 ((and org-support-shift-select (org-region-active-p))
19595 (org-call-for-shift-select 'backward-word))
19596 ((and (not (eq org-support-shift-select 'always))
19597 (org-at-heading-p))
19598 (org-call-with-arg 'org-todo 'previousset))
19599 (org-support-shift-select
19600 (org-call-for-shift-select 'backward-word))
19601 (t (org-shiftselect-error))))
19603 (defun org-shiftcontrolup (&optional n)
19604 "Change timestamps synchronously up in CLOCK log lines.
19605 Optional argument N tells to change by that many units."
19606 (interactive "P")
19607 (cond ((and (not org-support-shift-select)
19608 (org-at-clock-log-p)
19609 (org-at-timestamp-p t))
19610 (org-clock-timestamps-up n))
19611 (t (org-shiftselect-error))))
19613 (defun org-shiftcontroldown (&optional n)
19614 "Change timestamps synchronously down in CLOCK log lines.
19615 Optional argument N tells to change by that many units."
19616 (interactive "P")
19617 (cond ((and (not org-support-shift-select)
19618 (org-at-clock-log-p)
19619 (org-at-timestamp-p t))
19620 (org-clock-timestamps-down n))
19621 (t (org-shiftselect-error))))
19623 (defun org-ctrl-c-ret ()
19624 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19625 (interactive)
19626 (cond
19627 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19628 (t (call-interactively 'org-insert-heading))))
19630 (defun org-find-visible ()
19631 (let ((s (point)))
19632 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19633 (get-char-property s 'invisible)))
19635 (defun org-find-invisible ()
19636 (let ((s (point)))
19637 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19638 (not (get-char-property s 'invisible))))
19641 (defun org-copy-visible (beg end)
19642 "Copy the visible parts of the region."
19643 (interactive "r")
19644 (let (snippets s)
19645 (save-excursion
19646 (save-restriction
19647 (narrow-to-region beg end)
19648 (setq s (goto-char (point-min)))
19649 (while (not (= (point) (point-max)))
19650 (goto-char (org-find-invisible))
19651 (push (buffer-substring s (point)) snippets)
19652 (setq s (goto-char (org-find-visible))))))
19653 (kill-new (apply 'concat (nreverse snippets)))))
19655 (defun org-copy-special ()
19656 "Copy region in table or copy current subtree.
19657 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19658 See the individual commands for more information."
19659 (interactive)
19660 (call-interactively
19661 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19663 (defun org-cut-special ()
19664 "Cut region in table or cut current subtree.
19665 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19666 See the individual commands for more information."
19667 (interactive)
19668 (call-interactively
19669 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19671 (defun org-paste-special (arg)
19672 "Paste rectangular region into table, or past subtree relative to level.
19673 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19674 See the individual commands for more information."
19675 (interactive "P")
19676 (if (org-at-table-p)
19677 (org-table-paste-rectangle)
19678 (org-paste-subtree arg)))
19680 (defsubst org-in-fixed-width-region-p ()
19681 "Is point in a fixed-width region?"
19682 (save-match-data
19683 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19685 (defun org-edit-special (&optional arg)
19686 "Call a special editor for the element at point.
19687 When at a table, call the formula editor with `org-table-edit-formulas'.
19688 When in a source code block, call `org-edit-src-code'.
19689 When in a fixed-width region, call `org-edit-fixed-width-region'.
19690 When at an #+INCLUDE keyword, visit the included file.
19691 On a link, call `ffap' to visit the link at point.
19692 Otherwise, return a user error."
19693 (interactive)
19694 (let ((element (org-element-at-point)))
19695 (assert (not buffer-read-only) nil
19696 "Buffer is read-only: %s" (buffer-name))
19697 (case (org-element-type element)
19698 (src-block
19699 (if (not arg) (org-edit-src-code)
19700 (let* ((info (org-babel-get-src-block-info))
19701 (lang (nth 0 info))
19702 (params (nth 2 info))
19703 (session (cdr (assq :session params))))
19704 (if (not session) (org-edit-src-code)
19705 ;; At a src-block with a session and function called with
19706 ;; an ARG: switch to the buffer related to the inferior
19707 ;; process.
19708 (funcall (intern (concat "org-babel-prep-session:" lang))
19709 session params)))))
19710 (keyword
19711 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19712 (find-file
19713 (org-remove-double-quotes
19714 (car (org-split-string (org-element-property :value element)))))
19715 (user-error "No special environment to edit here")))
19716 (table
19717 (if (eq (org-element-property :type element) 'table.el)
19718 (org-edit-src-code)
19719 (call-interactively 'org-table-edit-formulas)))
19720 ;; Only Org tables contain `table-row' type elements.
19721 (table-row (call-interactively 'org-table-edit-formulas))
19722 ((example-block export-block) (org-edit-src-code))
19723 (fixed-width (org-edit-fixed-width-region))
19724 (otherwise
19725 ;; No notable element at point. Though, we may be at a link,
19726 ;; which is an object. Thus, scan deeper.
19727 (if (eq (org-element-type (org-element-context element)) 'link)
19728 (call-interactively 'ffap)
19729 (user-error "No special environment to edit here"))))))
19731 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19732 (defun org-ctrl-c-ctrl-c (&optional arg)
19733 "Set tags in headline, or update according to changed information at point.
19735 This command does many different things, depending on context:
19737 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19738 this is what we do.
19740 - If the cursor is on a statistics cookie, update it.
19742 - If the cursor is in a headline, prompt for tags and insert them
19743 into the current line, aligned to `org-tags-column'. When called
19744 with prefix arg, realign all tags in the current buffer.
19746 - If the cursor is in one of the special #+KEYWORD lines, this
19747 triggers scanning the buffer for these lines and updating the
19748 information.
19750 - If the cursor is inside a table, realign the table. This command
19751 works even if the automatic table editor has been turned off.
19753 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19754 the entire table.
19756 - If the cursor is at a footnote reference or definition, jump to
19757 the corresponding definition or references, respectively.
19759 - If the cursor is a the beginning of a dynamic block, update it.
19761 - If the current buffer is a capture buffer, close note and file it.
19763 - If the cursor is on a <<<target>>>, update radio targets and
19764 corresponding links in this buffer.
19766 - If the cursor is on a numbered item in a plain list, renumber the
19767 ordered list.
19769 - If the cursor is on a checkbox, toggle it.
19771 - If the cursor is on a code block, evaluate it. The variable
19772 `org-confirm-babel-evaluate' can be used to control prompting
19773 before code block evaluation, by default every code block
19774 evaluation requires confirmation. Code block evaluation can be
19775 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19776 (interactive "P")
19777 (cond
19778 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19779 org-occur-highlights
19780 org-latex-fragment-image-overlays)
19781 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19782 (org-remove-occur-highlights)
19783 (org-remove-latex-fragment-image-overlays)
19784 (message "Temporary highlights/overlays removed from current buffer"))
19785 ((and (local-variable-p 'org-finish-function (current-buffer))
19786 (fboundp org-finish-function))
19787 (funcall org-finish-function))
19788 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19790 (let* ((context (org-element-context)) (type (org-element-type context)))
19791 ;; Test if point is within a blank line.
19792 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19793 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19794 (user-error "C-c C-c can do nothing useful at this location"))
19795 ;; For convenience: at the first line of a paragraph on the
19796 ;; same line as an item, apply function on that item instead.
19797 (when (eq type 'paragraph)
19798 (let ((parent (org-element-property :parent context)))
19799 (when (and (eq (org-element-type parent) 'item)
19800 (= (point-at-bol) (org-element-property :begin parent)))
19801 (setq context parent type 'item))))
19802 ;; Act according to type of element or object at point.
19803 (case type
19804 (clock (org-clock-update-time-maybe))
19805 (dynamic-block
19806 (save-excursion
19807 (goto-char (org-element-property :post-affiliated context))
19808 (org-update-dblock)))
19809 (footnote-definition
19810 (goto-char (org-element-property :post-affiliated context))
19811 (call-interactively 'org-footnote-action))
19812 (footnote-reference (call-interactively 'org-footnote-action))
19813 ((headline inlinetask)
19814 (save-excursion (goto-char (org-element-property :begin context))
19815 (call-interactively 'org-set-tags)))
19816 (item
19817 ;; At an item: a double C-u set checkbox to "[-]"
19818 ;; unconditionally, whereas a single one will toggle its
19819 ;; presence. Without an universal argument, if the item
19820 ;; has a checkbox, toggle it. Otherwise repair the list.
19821 (let* ((box (org-element-property :checkbox context))
19822 (struct (org-element-property :structure context))
19823 (old-struct (copy-tree struct))
19824 (parents (org-list-parents-alist struct))
19825 (prevs (org-list-prevs-alist struct))
19826 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19827 (org-list-set-checkbox
19828 (org-element-property :begin context) struct
19829 (cond ((equal arg '(16)) "[-]")
19830 ((and (not box) (equal arg '(4))) "[ ]")
19831 ((or (not box) (equal arg '(4))) nil)
19832 ((eq box 'on) "[ ]")
19833 (t "[X]")))
19834 ;; Mimic `org-list-write-struct' but with grabbing
19835 ;; a return value from `org-list-struct-fix-box'.
19836 (org-list-struct-fix-ind struct parents 2)
19837 (org-list-struct-fix-item-end struct)
19838 (org-list-struct-fix-bul struct prevs)
19839 (org-list-struct-fix-ind struct parents)
19840 (let ((block-item
19841 (org-list-struct-fix-box struct parents prevs orderedp)))
19842 (if (and box (equal struct old-struct))
19843 (if (equal arg '(16))
19844 (message "Checkboxes already reset")
19845 (user-error "Cannot toggle this checkbox: %s"
19846 (if (eq box 'on)
19847 "all subitems checked"
19848 "unchecked subitems")))
19849 (org-list-struct-apply-struct struct old-struct)
19850 (org-update-checkbox-count-maybe))
19851 (when block-item
19852 (message "Checkboxes were removed due to empty box at line %d"
19853 (org-current-line block-item))))))
19854 (keyword
19855 (let ((org-inhibit-startup-visibility-stuff t)
19856 (org-startup-align-all-tables nil))
19857 (when (boundp 'org-table-coordinate-overlays)
19858 (mapc 'delete-overlay org-table-coordinate-overlays)
19859 (setq org-table-coordinate-overlays nil))
19860 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19861 (message "Local setup has been refreshed"))
19862 (plain-list
19863 ;; At a plain list, with a double C-u argument, set
19864 ;; checkboxes of each item to "[-]", whereas a single one
19865 ;; will toggle their presence according to the state of the
19866 ;; first item in the list. Without an argument, repair the
19867 ;; list.
19868 (let* ((begin (org-element-property :contents-begin context))
19869 (struct (org-element-property :structure context))
19870 (old-struct (copy-tree struct))
19871 (first-box (save-excursion
19872 (goto-char begin)
19873 (looking-at org-list-full-item-re)
19874 (match-string-no-properties 3)))
19875 (new-box (cond ((equal arg '(16)) "[-]")
19876 ((equal arg '(4)) (unless first-box "[ ]"))
19877 ((equal first-box "[X]") "[ ]")
19878 (t "[X]"))))
19879 (cond
19880 (arg
19881 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19882 (org-list-get-all-items
19883 begin struct (org-list-prevs-alist struct))))
19884 ((and first-box (eq (point) begin))
19885 ;; For convenience, when point is at bol on the first
19886 ;; item of the list and no argument is provided, simply
19887 ;; toggle checkbox of that item, if any.
19888 (org-list-set-checkbox begin struct new-box)))
19889 (org-list-write-struct
19890 struct (org-list-parents-alist struct) old-struct)
19891 (org-update-checkbox-count-maybe)
19892 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19893 ((property-drawer node-property)
19894 (call-interactively 'org-property-action))
19895 ((radio-target target)
19896 (call-interactively 'org-update-radio-target-regexp))
19897 (statistics-cookie
19898 (call-interactively 'org-update-statistics-cookies))
19899 ((table table-cell table-row)
19900 ;; At a table, recalculate every field and align it. Also
19901 ;; send the table if necessary. If the table has
19902 ;; a `table.el' type, just give up. At a table row or
19903 ;; cell, maybe recalculate line but always align table.
19904 (if (eq (org-element-property :type context) 'table.el)
19905 (message "Use C-c ' to edit table.el tables")
19906 (let ((org-enable-table-editor t))
19907 (if (or (eq type 'table)
19908 ;; Check if point is at a TBLFM line.
19909 (and (eq type 'table-row)
19910 (= (point) (org-element-property :end context))))
19911 (save-excursion
19912 (goto-char (org-element-property :contents-begin context))
19913 (org-call-with-arg 'org-table-recalculate (or arg t))
19914 (orgtbl-send-table 'maybe))
19915 (org-table-maybe-eval-formula)
19916 (cond (arg (call-interactively 'org-table-recalculate))
19917 ((org-table-maybe-recalculate-line))
19918 (t (org-table-align)))))))
19919 (timestamp (org-timestamp-change 0 'day))
19920 (otherwise
19921 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19922 (user-error
19923 "C-c C-c can do nothing useful at this location")))))))))
19925 (defun org-mode-restart ()
19926 "Restart Org-mode, to scan again for special lines.
19927 Also updates the keyword regular expressions."
19928 (interactive)
19929 (org-mode)
19930 (message "Org-mode restarted"))
19932 (defun org-kill-note-or-show-branches ()
19933 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19934 (interactive)
19935 (if (not org-finish-function)
19936 (progn
19937 (hide-subtree)
19938 (call-interactively 'show-branches))
19939 (let ((org-note-abort t))
19940 (funcall org-finish-function))))
19942 (defun org-return (&optional indent)
19943 "Goto next table row or insert a newline.
19944 Calls `org-table-next-row' or `newline', depending on context.
19945 See the individual commands for more information."
19946 (interactive)
19947 (let (org-ts-what)
19948 (cond
19949 ((or (bobp) (org-in-src-block-p))
19950 (if indent (newline-and-indent) (newline)))
19951 ((org-at-table-p)
19952 (org-table-justify-field-maybe)
19953 (call-interactively 'org-table-next-row))
19954 ;; when `newline-and-indent' is called within a list, make sure
19955 ;; text moved stays inside the item.
19956 ((and (org-in-item-p) indent)
19957 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19958 (progn
19959 (save-match-data (newline))
19960 (org-indent-line-to (length (match-string 0))))
19961 (let ((ind (org-get-indentation)))
19962 (newline)
19963 (if (org-looking-back org-list-end-re)
19964 (org-indent-line)
19965 (org-indent-line-to ind)))))
19966 ((and org-return-follows-link
19967 (org-at-timestamp-p t)
19968 (not (eq org-ts-what 'after)))
19969 (org-follow-timestamp-link))
19970 ((and org-return-follows-link
19971 (let ((tprop (get-text-property (point) 'face)))
19972 (or (eq tprop 'org-link)
19973 (and (listp tprop) (memq 'org-link tprop)))))
19974 (call-interactively 'org-open-at-point))
19975 ((and (org-at-heading-p)
19976 (looking-at
19977 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19978 (org-show-entry)
19979 (end-of-line 1)
19980 (newline))
19981 (t (if indent (newline-and-indent) (newline))))))
19983 (defun org-return-indent ()
19984 "Goto next table row or insert a newline and indent.
19985 Calls `org-table-next-row' or `newline-and-indent', depending on
19986 context. See the individual commands for more information."
19987 (interactive)
19988 (org-return t))
19990 (defun org-ctrl-c-star ()
19991 "Compute table, or change heading status of lines.
19992 Calls `org-table-recalculate' or `org-toggle-heading',
19993 depending on context."
19994 (interactive)
19995 (cond
19996 ((org-at-table-p)
19997 (call-interactively 'org-table-recalculate))
19999 ;; Convert all lines in region to list items
20000 (call-interactively 'org-toggle-heading))))
20002 (defun org-ctrl-c-minus ()
20003 "Insert separator line in table or modify bullet status of line.
20004 Also turns a plain line or a region of lines into list items.
20005 Calls `org-table-insert-hline', `org-toggle-item', or
20006 `org-cycle-list-bullet', depending on context."
20007 (interactive)
20008 (cond
20009 ((org-at-table-p)
20010 (call-interactively 'org-table-insert-hline))
20011 ((org-region-active-p)
20012 (call-interactively 'org-toggle-item))
20013 ((org-in-item-p)
20014 (call-interactively 'org-cycle-list-bullet))
20016 (call-interactively 'org-toggle-item))))
20018 (defun org-toggle-item (arg)
20019 "Convert headings or normal lines to items, items to normal lines.
20020 If there is no active region, only the current line is considered.
20022 If the first non blank line in the region is a headline, convert
20023 all headlines to items, shifting text accordingly.
20025 If it is an item, convert all items to normal lines.
20027 If it is normal text, change region into an item. With a prefix
20028 argument ARG, change each line in region into an item."
20029 (interactive "P")
20030 (let ((shift-text
20031 (function
20032 ;; Shift text in current section to IND, from point to END.
20033 ;; The function leaves point to END line.
20034 (lambda (ind end)
20035 (let ((min-i 1000) (end (copy-marker end)))
20036 ;; First determine the minimum indentation (MIN-I) of
20037 ;; the text.
20038 (save-excursion
20039 (catch 'exit
20040 (while (< (point) end)
20041 (let ((i (org-get-indentation)))
20042 (cond
20043 ;; Skip blank lines and inline tasks.
20044 ((looking-at "^[ \t]*$"))
20045 ((looking-at org-outline-regexp-bol))
20046 ;; We can't find less than 0 indentation.
20047 ((zerop i) (throw 'exit (setq min-i 0)))
20048 ((< i min-i) (setq min-i i))))
20049 (forward-line))))
20050 ;; Then indent each line so that a line indented to
20051 ;; MIN-I becomes indented to IND. Ignore blank lines
20052 ;; and inline tasks in the process.
20053 (let ((delta (- ind min-i)))
20054 (while (< (point) end)
20055 (unless (or (looking-at "^[ \t]*$")
20056 (looking-at org-outline-regexp-bol))
20057 (org-indent-line-to (+ (org-get-indentation) delta)))
20058 (forward-line)))))))
20059 (skip-blanks
20060 (function
20061 ;; Return beginning of first non-blank line, starting from
20062 ;; line at POS.
20063 (lambda (pos)
20064 (save-excursion
20065 (goto-char pos)
20066 (skip-chars-forward " \r\t\n")
20067 (point-at-bol)))))
20068 beg end)
20069 ;; Determine boundaries of changes.
20070 (if (org-region-active-p)
20071 (setq beg (funcall skip-blanks (region-beginning))
20072 end (copy-marker (region-end)))
20073 (setq beg (funcall skip-blanks (point-at-bol))
20074 end (copy-marker (point-at-eol))))
20075 ;; Depending on the starting line, choose an action on the text
20076 ;; between BEG and END.
20077 (org-with-limited-levels
20078 (save-excursion
20079 (goto-char beg)
20080 (cond
20081 ;; Case 1. Start at an item: de-itemize. Note that it only
20082 ;; happens when a region is active: `org-ctrl-c-minus'
20083 ;; would call `org-cycle-list-bullet' otherwise.
20084 ((org-at-item-p)
20085 (while (< (point) end)
20086 (when (org-at-item-p)
20087 (skip-chars-forward " \t")
20088 (delete-region (point) (match-end 0)))
20089 (forward-line)))
20090 ;; Case 2. Start at an heading: convert to items.
20091 ((org-at-heading-p)
20092 (let* ((bul (org-list-bullet-string "-"))
20093 (bul-len (length bul))
20094 ;; Indentation of the first heading. It should be
20095 ;; relative to the indentation of its parent, if any.
20096 (start-ind (save-excursion
20097 (cond
20098 ((not org-adapt-indentation) 0)
20099 ((not (outline-previous-heading)) 0)
20100 (t (length (match-string 0))))))
20101 ;; Level of first heading. Further headings will be
20102 ;; compared to it to determine hierarchy in the list.
20103 (ref-level (org-reduced-level (org-outline-level))))
20104 (while (< (point) end)
20105 (let* ((level (org-reduced-level (org-outline-level)))
20106 (delta (max 0 (- level ref-level))))
20107 ;; If current headline is less indented than the first
20108 ;; one, set it as reference, in order to preserve
20109 ;; subtrees.
20110 (when (< level ref-level) (setq ref-level level))
20111 (replace-match bul t t)
20112 (org-indent-line-to (+ start-ind (* delta bul-len)))
20113 ;; Ensure all text down to END (or SECTION-END) belongs
20114 ;; to the newly created item.
20115 (let ((section-end (save-excursion
20116 (or (outline-next-heading) (point)))))
20117 (forward-line)
20118 (funcall shift-text
20119 (+ start-ind (* (1+ delta) bul-len))
20120 (min end section-end)))))))
20121 ;; Case 3. Normal line with ARG: turn each non-item line into
20122 ;; an item.
20123 (arg
20124 (while (< (point) end)
20125 (unless (or (org-at-heading-p) (org-at-item-p))
20126 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20127 (replace-match
20128 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20129 (forward-line)))
20130 ;; Case 4. Normal line without ARG: make the first line of
20131 ;; region an item, and shift indentation of others
20132 ;; lines to set them as item's body.
20133 (t (let* ((bul (org-list-bullet-string "-"))
20134 (bul-len (length bul))
20135 (ref-ind (org-get-indentation)))
20136 (skip-chars-forward " \t")
20137 (insert bul)
20138 (forward-line)
20139 (while (< (point) end)
20140 ;; Ensure that lines less indented than first one
20141 ;; still get included in item body.
20142 (funcall shift-text
20143 (+ ref-ind bul-len)
20144 (min end (save-excursion (or (outline-next-heading)
20145 (point)))))
20146 (forward-line)))))))))
20148 (defun org-toggle-heading (&optional nstars)
20149 "Convert headings to normal text, or items or text to headings.
20150 If there is no active region, only the current line is considered.
20152 With a \\[universal-argument] prefix, convert the whole list at
20153 point into heading.
20155 In a region:
20157 - If the first non blank line is a headline, remove the stars
20158 from all headlines in the region.
20160 - If it is a normal line turn each and every normal line (i.e. not an
20161 heading or an item) in the region into a heading.
20163 - If it is a plain list item, turn all plain list items into headings.
20165 When converting a line into a heading, the number of stars is chosen
20166 such that the lines become children of the current entry. However,
20167 when a prefix argument is given, its value determines the number of
20168 stars to add."
20169 (interactive "P")
20170 (let ((skip-blanks
20171 (function
20172 ;; Return beginning of first non-blank line, starting from
20173 ;; line at POS.
20174 (lambda (pos)
20175 (save-excursion
20176 (goto-char pos)
20177 (while (org-at-comment-p) (forward-line))
20178 (skip-chars-forward " \r\t\n")
20179 (point-at-bol)))))
20180 beg end toggled)
20181 ;; Determine boundaries of changes. If a universal prefix has
20182 ;; been given, put the list in a region. If region ends at a bol,
20183 ;; do not consider the last line to be in the region.
20185 (when (and current-prefix-arg (org-at-item-p))
20186 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20187 (org-mark-element))
20189 (if (org-region-active-p)
20190 (setq beg (funcall skip-blanks (region-beginning))
20191 end (copy-marker (save-excursion
20192 (goto-char (region-end))
20193 (if (bolp) (point) (point-at-eol)))))
20194 (setq beg (funcall skip-blanks (point-at-bol))
20195 end (copy-marker (point-at-eol))))
20196 ;; Ensure inline tasks don't count as headings.
20197 (org-with-limited-levels
20198 (save-excursion
20199 (goto-char beg)
20200 (cond
20201 ;; Case 1. Started at an heading: de-star headings.
20202 ((org-at-heading-p)
20203 (while (< (point) end)
20204 (when (org-at-heading-p t)
20205 (looking-at org-outline-regexp) (replace-match "")
20206 (setq toggled t))
20207 (forward-line)))
20208 ;; Case 2. Started at an item: change items into headlines.
20209 ;; One star will be added by `org-list-to-subtree'.
20210 ((org-at-item-p)
20211 (let* ((stars (make-string
20212 (if nstars
20213 ;; subtract the star that will be added again by
20214 ;; `org-list-to-subtree'
20215 (1- (prefix-numeric-value current-prefix-arg))
20216 (or (org-current-level) 0))
20217 ?*))
20218 (add-stars
20219 (cond (nstars "") ; stars from prefix only
20220 ((equal stars "") "") ; before first heading
20221 (org-odd-levels-only "*") ; inside heading, odd
20222 (t "")))) ; inside heading, oddeven
20223 (while (< (point) end)
20224 (when (org-at-item-p)
20225 ;; Pay attention to cases when region ends before list.
20226 (let* ((struct (org-list-struct))
20227 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20228 (save-restriction
20229 (narrow-to-region (point) list-end)
20230 (insert
20231 (org-list-to-subtree
20232 (org-list-parse-list t)
20233 '(:istart (concat stars add-stars (funcall get-stars depth))
20234 :icount (concat stars add-stars (funcall get-stars depth)))))))
20235 (setq toggled t))
20236 (forward-line))))
20237 ;; Case 3. Started at normal text: make every line an heading,
20238 ;; skipping headlines and items.
20239 (t (let* ((stars (make-string
20240 (if nstars
20241 (prefix-numeric-value current-prefix-arg)
20242 (or (org-current-level) 0))
20243 ?*))
20244 (add-stars
20245 (cond (nstars "") ; stars from prefix only
20246 ((equal stars "") "*") ; before first heading
20247 (org-odd-levels-only "**") ; inside heading, odd
20248 (t "*"))) ; inside heading, oddeven
20249 (rpl (concat stars add-stars " ")))
20250 (while (< (point) end)
20251 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20252 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20253 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20254 (forward-line)))))))
20255 (unless toggled (message "Cannot toggle heading from here"))))
20257 (defun org-meta-return (&optional arg)
20258 "Insert a new heading or wrap a region in a table.
20259 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20260 See the individual commands for more information."
20261 (interactive "P")
20262 (cond
20263 ((run-hook-with-args-until-success 'org-metareturn-hook))
20264 ((or (org-at-drawer-p) (org-at-property-p))
20265 (newline-and-indent))
20266 ((org-at-table-p)
20267 (call-interactively 'org-table-wrap-region))
20268 (t (call-interactively 'org-insert-heading))))
20270 ;;; Menu entries
20272 (defsubst org-in-subtree-not-table-p ()
20273 "Are we in a subtree and not in a table?"
20274 (and (not (org-before-first-heading-p))
20275 (not (org-at-table-p))))
20277 ;; Define the Org-mode menus
20278 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20279 '("Tbl"
20280 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20281 ["Next Field" org-cycle (org-at-table-p)]
20282 ["Previous Field" org-shifttab (org-at-table-p)]
20283 ["Next Row" org-return (org-at-table-p)]
20284 "--"
20285 ["Blank Field" org-table-blank-field (org-at-table-p)]
20286 ["Edit Field" org-table-edit-field (org-at-table-p)]
20287 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20288 "--"
20289 ("Column"
20290 ["Move Column Left" org-metaleft (org-at-table-p)]
20291 ["Move Column Right" org-metaright (org-at-table-p)]
20292 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20293 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20294 ("Row"
20295 ["Move Row Up" org-metaup (org-at-table-p)]
20296 ["Move Row Down" org-metadown (org-at-table-p)]
20297 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20298 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20299 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20300 "--"
20301 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20302 ("Rectangle"
20303 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20304 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20305 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20306 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20307 "--"
20308 ("Calculate"
20309 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20310 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20311 ["Edit Formulas" org-edit-special (org-at-table-p)]
20312 "--"
20313 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20314 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20315 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20316 "--"
20317 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20318 "--"
20319 ["Sum Column/Rectangle" org-table-sum
20320 (or (org-at-table-p) (org-region-active-p))]
20321 ["Which Column?" org-table-current-column (org-at-table-p)])
20322 ["Debug Formulas"
20323 org-table-toggle-formula-debugger
20324 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20325 ["Show Col/Row Numbers"
20326 org-table-toggle-coordinate-overlays
20327 :style toggle
20328 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20329 "--"
20330 ["Create" org-table-create (and (not (org-at-table-p))
20331 org-enable-table-editor)]
20332 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20333 ["Import from File" org-table-import (not (org-at-table-p))]
20334 ["Export to File" org-table-export (org-at-table-p)]
20335 "--"
20336 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20338 (easy-menu-define org-org-menu org-mode-map "Org menu"
20339 '("Org"
20340 ("Show/Hide"
20341 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20342 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20343 ["Sparse Tree..." org-sparse-tree t]
20344 ["Reveal Context" org-reveal t]
20345 ["Show All" show-all t]
20346 "--"
20347 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20348 "--"
20349 ["New Heading" org-insert-heading t]
20350 ("Navigate Headings"
20351 ["Up" outline-up-heading t]
20352 ["Next" outline-next-visible-heading t]
20353 ["Previous" outline-previous-visible-heading t]
20354 ["Next Same Level" outline-forward-same-level t]
20355 ["Previous Same Level" outline-backward-same-level t]
20356 "--"
20357 ["Jump" org-goto t])
20358 ("Edit Structure"
20359 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20360 "--"
20361 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20362 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20363 "--"
20364 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20365 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20366 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20367 "--"
20368 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20369 "--"
20370 ["Copy visible text" org-copy-visible t]
20371 "--"
20372 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20373 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20374 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20375 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20376 "--"
20377 ["Sort Region/Children" org-sort t]
20378 "--"
20379 ["Convert to odd levels" org-convert-to-odd-levels t]
20380 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20381 ("Editing"
20382 ["Emphasis..." org-emphasize t]
20383 ["Edit Source Example" org-edit-special t]
20384 "--"
20385 ["Footnote new/jump" org-footnote-action t]
20386 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20387 ("Archive"
20388 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20389 "--"
20390 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20391 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20392 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20394 "--"
20395 ("Hyperlinks"
20396 ["Store Link (Global)" org-store-link t]
20397 ["Find existing link to here" org-occur-link-in-agenda-files t]
20398 ["Insert Link" org-insert-link t]
20399 ["Follow Link" org-open-at-point t]
20400 "--"
20401 ["Next link" org-next-link t]
20402 ["Previous link" org-previous-link t]
20403 "--"
20404 ["Descriptive Links"
20405 org-toggle-link-display
20406 :style radio
20407 :selected org-descriptive-links
20409 ["Literal Links"
20410 org-toggle-link-display
20411 :style radio
20412 :selected (not org-descriptive-links)])
20413 "--"
20414 ("TODO Lists"
20415 ["TODO/DONE/-" org-todo t]
20416 ("Select keyword"
20417 ["Next keyword" org-shiftright (org-at-heading-p)]
20418 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20419 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20420 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20421 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20422 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20423 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20424 "--"
20425 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20426 :selected org-enforce-todo-dependencies :style toggle :active t]
20427 "Settings for tree at point"
20428 ["Do Children sequentially" org-toggle-ordered-property :style radio
20429 :selected (org-entry-get nil "ORDERED")
20430 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20431 ["Do Children parallel" org-toggle-ordered-property :style radio
20432 :selected (not (org-entry-get nil "ORDERED"))
20433 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20434 "--"
20435 ["Set Priority" org-priority t]
20436 ["Priority Up" org-shiftup t]
20437 ["Priority Down" org-shiftdown t]
20438 "--"
20439 ["Get news from all feeds" org-feed-update-all t]
20440 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20441 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20442 ("TAGS and Properties"
20443 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20444 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20445 "--"
20446 ["Set property" org-set-property (not (org-before-first-heading-p))]
20447 ["Column view of properties" org-columns t]
20448 ["Insert Column View DBlock" org-insert-columns-dblock t])
20449 ("Dates and Scheduling"
20450 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20451 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20452 ("Change Date"
20453 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20454 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20455 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20456 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20457 ["Compute Time Range" org-evaluate-time-range t]
20458 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20459 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20460 "--"
20461 ["Custom time format" org-toggle-time-stamp-overlays
20462 :style radio :selected org-display-custom-times]
20463 "--"
20464 ["Goto Calendar" org-goto-calendar t]
20465 ["Date from Calendar" org-date-from-calendar t]
20466 "--"
20467 ["Start/Restart Timer" org-timer-start t]
20468 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20469 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20470 ["Insert Timer String" org-timer t]
20471 ["Insert Timer Item" org-timer-item t])
20472 ("Logging work"
20473 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20474 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20475 ["Clock out" org-clock-out t]
20476 ["Clock cancel" org-clock-cancel t]
20477 "--"
20478 ["Mark as default task" org-clock-mark-default-task t]
20479 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20480 ["Goto running clock" org-clock-goto t]
20481 "--"
20482 ["Display times" org-clock-display t]
20483 ["Create clock table" org-clock-report t]
20484 "--"
20485 ["Record DONE time"
20486 (progn (setq org-log-done (not org-log-done))
20487 (message "Switching to %s will %s record a timestamp"
20488 (car org-done-keywords)
20489 (if org-log-done "automatically" "not")))
20490 :style toggle :selected org-log-done])
20491 "--"
20492 ["Agenda Command..." org-agenda t]
20493 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20494 ("File List for Agenda")
20495 ("Special views current file"
20496 ["TODO Tree" org-show-todo-tree t]
20497 ["Check Deadlines" org-check-deadlines t]
20498 ["Timeline" org-timeline t]
20499 ["Tags/Property tree" org-match-sparse-tree t])
20500 "--"
20501 ["Export/Publish..." org-export-dispatch t]
20502 ("LaTeX"
20503 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20504 :selected org-cdlatex-mode]
20505 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20506 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20507 ["Modify math symbol" org-cdlatex-math-modify
20508 (org-inside-LaTeX-fragment-p)]
20509 ["Insert citation" org-reftex-citation t]
20510 "--"
20511 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20512 "--"
20513 ("MobileOrg"
20514 ["Push Files and Views" org-mobile-push t]
20515 ["Get Captured and Flagged" org-mobile-pull t]
20516 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20517 "--"
20518 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20519 "--"
20520 ("Documentation"
20521 ["Show Version" org-version t]
20522 ["Info Documentation" org-info t])
20523 ("Customize"
20524 ["Browse Org Group" org-customize t]
20525 "--"
20526 ["Expand This Menu" org-create-customize-menu
20527 (fboundp 'customize-menu-create)])
20528 ["Send bug report" org-submit-bug-report t]
20529 "--"
20530 ("Refresh/Reload"
20531 ["Refresh setup current buffer" org-mode-restart t]
20532 ["Reload Org (after update)" org-reload t]
20533 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20536 (defun org-info (&optional node)
20537 "Read documentation for Org-mode in the info system.
20538 With optional NODE, go directly to that node."
20539 (interactive)
20540 (info (format "(org)%s" (or node ""))))
20542 ;;;###autoload
20543 (defun org-submit-bug-report ()
20544 "Submit a bug report on Org-mode via mail.
20546 Don't hesitate to report any problems or inaccurate documentation.
20548 If you don't have setup sending mail from (X)Emacs, please copy the
20549 output buffer into your mail program, as it gives us important
20550 information about your Org-mode version and configuration."
20551 (interactive)
20552 (require 'reporter)
20553 (org-load-modules-maybe)
20554 (org-require-autoloaded-modules)
20555 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20556 (reporter-submit-bug-report
20557 "emacs-orgmode@gnu.org"
20558 (org-version nil 'full)
20559 (let (list)
20560 (save-window-excursion
20561 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20562 (delete-other-windows)
20563 (erase-buffer)
20564 (insert "You are about to submit a bug report to the Org-mode mailing list.
20566 We would like to add your full Org-mode and Outline configuration to the
20567 bug report. This greatly simplifies the work of the maintainer and
20568 other experts on the mailing list.
20570 HOWEVER, some variables you have customized may contain private
20571 information. The names of customers, colleagues, or friends, might
20572 appear in the form of file names, tags, todo states, or search strings.
20573 If you answer yes to the prompt, you might want to check and remove
20574 such private information before sending the email.")
20575 (add-text-properties (point-min) (point-max) '(face org-warning))
20576 (when (yes-or-no-p "Include your Org-mode configuration ")
20577 (mapatoms
20578 (lambda (v)
20579 (and (boundp v)
20580 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20581 (or (and (symbol-value v)
20582 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20583 (and
20584 (get v 'custom-type) (get v 'standard-value)
20585 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20586 (push v list)))))
20587 (kill-buffer (get-buffer "*Warn about privacy*"))
20588 list))
20589 nil nil
20590 "Remember to cover the basics, that is, what you expected to happen and
20591 what in fact did happen. You don't know how to make a good report? See
20593 http://orgmode.org/manual/Feedback.html#Feedback
20595 Your bug report will be posted to the Org-mode mailing list.
20596 ------------------------------------------------------------------------")
20597 (save-excursion
20598 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20599 (replace-match "\\1Bug: \\3 [\\2]")))))
20602 (defun org-install-agenda-files-menu ()
20603 (let ((bl (buffer-list)))
20604 (save-excursion
20605 (while bl
20606 (set-buffer (pop bl))
20607 (if (derived-mode-p 'org-mode) (setq bl nil)))
20608 (when (derived-mode-p 'org-mode)
20609 (easy-menu-change
20610 '("Org") "File List for Agenda"
20611 (append
20612 (list
20613 ["Edit File List" (org-edit-agenda-file-list) t]
20614 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20615 ["Remove Current File from List" org-remove-file t]
20616 ["Cycle through agenda files" org-cycle-agenda-files t]
20617 ["Occur in all agenda files" org-occur-in-agenda-files t]
20618 "--")
20619 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20621 ;;;; Documentation
20623 (defun org-require-autoloaded-modules ()
20624 (interactive)
20625 (mapc 'require
20626 '(org-agenda org-archive org-attach org-clock org-colview org-id
20627 org-remember org-table org-timer)))
20629 ;;;###autoload
20630 (defun org-reload (&optional uncompiled)
20631 "Reload all org lisp files.
20632 With prefix arg UNCOMPILED, load the uncompiled versions."
20633 (interactive "P")
20634 (require 'loadhist)
20635 (let* ((org-dir (org-find-library-dir "org"))
20636 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20637 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20638 (remove-re (mapconcat 'identity
20639 (mapcar (lambda (f) (concat "^" f "$"))
20640 (list (if (featurep 'xemacs)
20641 "org-colview"
20642 "org-colview-xemacs")
20643 "org" "org-loaddefs" "org-version"))
20644 "\\|"))
20645 (feats (delete-dups
20646 (mapcar 'file-name-sans-extension
20647 (mapcar 'file-name-nondirectory
20648 (delq nil
20649 (mapcar 'feature-file
20650 features))))))
20651 (lfeat (append
20652 (sort
20653 (setq feats
20654 (delq nil (mapcar
20655 (lambda (f)
20656 (if (and (string-match feature-re f)
20657 (not (string-match remove-re f)))
20658 f nil))
20659 feats)))
20660 'string-lessp)
20661 (list "org-version" "org")))
20662 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20663 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20664 load-uncore load-misses)
20665 (setq load-misses
20666 (delq 't
20667 (mapcar (lambda (f)
20668 (or (org-load-noerror-mustsuffix (concat org-dir f))
20669 (and (string= org-dir contrib-dir)
20670 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20671 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20672 (add-to-list 'load-uncore f 'append)
20675 lfeat)))
20676 (if load-uncore
20677 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20678 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20679 (if load-misses
20680 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20681 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20682 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20684 ;;;###autoload
20685 (defun org-customize ()
20686 "Call the customize function with org as argument."
20687 (interactive)
20688 (org-load-modules-maybe)
20689 (org-require-autoloaded-modules)
20690 (customize-browse 'org))
20692 (defun org-create-customize-menu ()
20693 "Create a full customization menu for Org-mode, insert it into the menu."
20694 (interactive)
20695 (org-load-modules-maybe)
20696 (org-require-autoloaded-modules)
20697 (if (fboundp 'customize-menu-create)
20698 (progn
20699 (easy-menu-change
20700 '("Org") "Customize"
20701 `(["Browse Org group" org-customize t]
20702 "--"
20703 ,(customize-menu-create 'org)
20704 ["Set" Custom-set t]
20705 ["Save" Custom-save t]
20706 ["Reset to Current" Custom-reset-current t]
20707 ["Reset to Saved" Custom-reset-saved t]
20708 ["Reset to Standard Settings" Custom-reset-standard t]))
20709 (message "\"Org\"-menu now contains full customization menu"))
20710 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20712 ;;;; Miscellaneous stuff
20714 ;;; Generally useful functions
20716 (defun org-get-at-bol (property)
20717 "Get text property PROPERTY at beginning of line."
20718 (get-text-property (point-at-bol) property))
20720 (defun org-find-text-property-in-string (prop s)
20721 "Return the first non-nil value of property PROP in string S."
20722 (or (get-text-property 0 prop s)
20723 (get-text-property (or (next-single-property-change 0 prop s) 0)
20724 prop s)))
20726 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20727 "Display the given MESSAGE as a warning."
20728 (if (fboundp 'display-warning)
20729 (display-warning 'org message
20730 (if (featurep 'xemacs) 'warning :warning))
20731 (let ((buf (get-buffer-create "*Org warnings*")))
20732 (with-current-buffer buf
20733 (goto-char (point-max))
20734 (insert "Warning (Org): " message)
20735 (unless (bolp)
20736 (newline)))
20737 (display-buffer buf)
20738 (sit-for 0))))
20740 (defun org-eval (form)
20741 "Eval FORM and return result."
20742 (condition-case error
20743 (eval form)
20744 (error (format "%%![Error: %s]" error))))
20746 (defun org-in-clocktable-p ()
20747 "Check if the cursor is in a clocktable."
20748 (let ((pos (point)) start)
20749 (save-excursion
20750 (end-of-line 1)
20751 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20752 (setq start (match-beginning 0))
20753 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20754 (>= (match-end 0) pos)
20755 start))))
20757 (defun org-in-commented-line ()
20758 "Is point in a line starting with `#'?"
20759 (equal (char-after (point-at-bol)) ?#))
20761 (defun org-in-indented-comment-line ()
20762 "Is point in a line starting with `#' after some white space?"
20763 (save-excursion
20764 (save-match-data
20765 (goto-char (point-at-bol))
20766 (looking-at "[ \t]*#"))))
20768 (defun org-in-verbatim-emphasis ()
20769 (save-match-data
20770 (and (org-in-regexp org-emph-re 2)
20771 (>= (point) (match-beginning 3))
20772 (<= (point) (match-end 4))
20773 (member (match-string 3) '("=" "~")))))
20775 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20776 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20777 (if (and marker (marker-buffer marker)
20778 (buffer-live-p (marker-buffer marker)))
20779 (progn
20780 (org-pop-to-buffer-same-window (marker-buffer marker))
20781 (if (or (> marker (point-max)) (< marker (point-min)))
20782 (widen))
20783 (goto-char marker)
20784 (org-show-context 'org-goto))
20785 (if bookmark
20786 (bookmark-jump bookmark)
20787 (error "Cannot find location"))))
20789 (defun org-quote-csv-field (s)
20790 "Quote field for inclusion in CSV material."
20791 (if (string-match "[\",]" s)
20792 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20795 (defun org-force-self-insert (N)
20796 "Needed to enforce self-insert under remapping."
20797 (interactive "p")
20798 (self-insert-command N))
20800 (defun org-string-width (s)
20801 "Compute width of string, ignoring invisible characters.
20802 This ignores character with invisibility property `org-link', and also
20803 characters with property `org-cwidth', because these will become invisible
20804 upon the next fontification round."
20805 (let (b l)
20806 (when (or (eq t buffer-invisibility-spec)
20807 (assq 'org-link buffer-invisibility-spec))
20808 (while (setq b (text-property-any 0 (length s)
20809 'invisible 'org-link s))
20810 (setq s (concat (substring s 0 b)
20811 (substring s (or (next-single-property-change
20812 b 'invisible s) (length s)))))))
20813 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20814 (setq s (concat (substring s 0 b)
20815 (substring s (or (next-single-property-change
20816 b 'org-cwidth s) (length s))))))
20817 (setq l (string-width s) b -1)
20818 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20819 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20822 (defun org-shorten-string (s maxlength)
20823 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20824 If the string is shorter or has length MAXLENGTH, just return the
20825 original string. If it is longer, the functions finds a space in the
20826 string, breaks this string off at that locations and adds three dots
20827 as ellipsis. Including the ellipsis, the string will not be longer
20828 than MAXLENGTH. If finding a good breaking point in the string does
20829 not work, the string is just chopped off in the middle of a word
20830 if necessary."
20831 (if (<= (length s) maxlength)
20833 (let* ((n (max (- maxlength 4) 1))
20834 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20835 (if (string-match re s)
20836 (concat (match-string 1 s) "...")
20837 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20839 (defun org-get-indentation (&optional line)
20840 "Get the indentation of the current line, interpreting tabs.
20841 When LINE is given, assume it represents a line and compute its indentation."
20842 (if line
20843 (if (string-match "^ *" (org-remove-tabs line))
20844 (match-end 0))
20845 (save-excursion
20846 (beginning-of-line 1)
20847 (skip-chars-forward " \t")
20848 (current-column))))
20850 (defun org-get-string-indentation (s)
20851 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20852 (let ((n -1) (i 0) (w tab-width) c)
20853 (catch 'exit
20854 (while (< (setq n (1+ n)) (length s))
20855 (setq c (aref s n))
20856 (cond ((= c ?\ ) (setq i (1+ i)))
20857 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20858 (t (throw 'exit t)))))
20861 (defun org-remove-tabs (s &optional width)
20862 "Replace tabulators in S with spaces.
20863 Assumes that s is a single line, starting in column 0."
20864 (setq width (or width tab-width))
20865 (while (string-match "\t" s)
20866 (setq s (replace-match
20867 (make-string
20868 (- (* width (/ (+ (match-beginning 0) width) width))
20869 (match-beginning 0)) ?\ )
20870 t t s)))
20873 (defun org-fix-indentation (line ind)
20874 "Fix indentation in LINE.
20875 IND is a cons cell with target and minimum indentation.
20876 If the current indentation in LINE is smaller than the minimum,
20877 leave it alone. If it is larger than ind, set it to the target."
20878 (let* ((l (org-remove-tabs line))
20879 (i (org-get-indentation l))
20880 (i1 (car ind)) (i2 (cdr ind)))
20881 (if (>= i i2) (setq l (substring line i2)))
20882 (if (> i1 0)
20883 (concat (make-string i1 ?\ ) l)
20884 l)))
20886 (defun org-remove-indentation (code &optional n)
20887 "Remove the maximum common indentation from the lines in CODE.
20888 N may optionally be the number of spaces to remove."
20889 (with-temp-buffer
20890 (insert code)
20891 (org-do-remove-indentation n)
20892 (buffer-string)))
20894 (defun org-do-remove-indentation (&optional n)
20895 "Remove the maximum common indentation from the buffer."
20896 (untabify (point-min) (point-max))
20897 (let ((min 10000) re)
20898 (if n
20899 (setq min n)
20900 (goto-char (point-min))
20901 (while (re-search-forward "^ *[^ \n]" nil t)
20902 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20903 (unless (or (= min 0) (= min 10000))
20904 (setq re (format "^ \\{%d\\}" min))
20905 (goto-char (point-min))
20906 (while (re-search-forward re nil t)
20907 (replace-match "")
20908 (end-of-line 1))
20909 min)))
20911 (defun org-fill-template (template alist)
20912 "Find each %key of ALIST in TEMPLATE and replace it."
20913 (let ((case-fold-search nil)
20914 entry key value)
20915 (setq alist (sort (copy-sequence alist)
20916 (lambda (a b) (< (length (car a)) (length (car b))))))
20917 (while (setq entry (pop alist))
20918 (setq template
20919 (replace-regexp-in-string
20920 (concat "%" (regexp-quote (car entry)))
20921 (or (cdr entry) "") template t t)))
20922 template))
20924 (defun org-base-buffer (buffer)
20925 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20926 (if (not buffer)
20927 buffer
20928 (or (buffer-base-buffer buffer)
20929 buffer)))
20931 (defun org-trim (s)
20932 "Remove whitespace at beginning and end of string."
20933 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20934 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20937 (defun org-wrap (string &optional width lines)
20938 "Wrap string to either a number of lines, or a width in characters.
20939 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20940 that costs. If there is a word longer than WIDTH, the text is actually
20941 wrapped to the length of that word.
20942 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20943 many lines, whatever width that takes.
20944 The return value is a list of lines, without newlines at the end."
20945 (let* ((words (org-split-string string "[ \t\n]+"))
20946 (maxword (apply 'max (mapcar 'org-string-width words)))
20947 w ll)
20948 (cond (width
20949 (org-do-wrap words (max maxword width)))
20950 (lines
20951 (setq w maxword)
20952 (setq ll (org-do-wrap words maxword))
20953 (if (<= (length ll) lines)
20955 (setq ll words)
20956 (while (> (length ll) lines)
20957 (setq w (1+ w))
20958 (setq ll (org-do-wrap words w)))
20959 ll))
20960 (t (error "Cannot wrap this")))))
20962 (defun org-do-wrap (words width)
20963 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20964 (let (lines line)
20965 (while words
20966 (setq line (pop words))
20967 (while (and words (< (+ (length line) (length (car words))) width))
20968 (setq line (concat line " " (pop words))))
20969 (setq lines (push line lines)))
20970 (nreverse lines)))
20972 (defun org-split-string (string &optional separators)
20973 "Splits STRING into substrings at SEPARATORS.
20974 No empty strings are returned if there are matches at the beginning
20975 and end of string."
20976 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20977 (start 0)
20978 notfirst
20979 (list nil))
20980 (while (and (string-match rexp string
20981 (if (and notfirst
20982 (= start (match-beginning 0))
20983 (< start (length string)))
20984 (1+ start) start))
20985 (< (match-beginning 0) (length string)))
20986 (setq notfirst t)
20987 (or (eq (match-beginning 0) 0)
20988 (and (eq (match-beginning 0) (match-end 0))
20989 (eq (match-beginning 0) start))
20990 (setq list
20991 (cons (substring string start (match-beginning 0))
20992 list)))
20993 (setq start (match-end 0)))
20994 (or (eq start (length string))
20995 (setq list
20996 (cons (substring string start)
20997 list)))
20998 (nreverse list)))
21000 (defun org-quote-vert (s)
21001 "Replace \"|\" with \"\\vert\"."
21002 (while (string-match "|" s)
21003 (setq s (replace-match "\\vert" t t s)))
21006 (defun org-uuidgen-p (s)
21007 "Is S an ID created by UUIDGEN?"
21008 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21010 (defun org-in-src-block-p (&optional inside)
21011 "Whether point is in a code source block.
21012 When INSIDE is non-nil, don't consider we are within a src block
21013 when point is at #+BEGIN_SRC or #+END_SRC."
21014 (let ((case-fold-search t) ov)
21015 (or (and (setq ov (overlays-at (point)))
21016 (memq 'org-block-background
21017 (overlay-properties (car ov))))
21018 (and (not inside)
21019 (save-match-data
21020 (save-excursion
21021 (beginning-of-line)
21022 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21024 (defun org-context ()
21025 "Return a list of contexts of the current cursor position.
21026 If several contexts apply, all are returned.
21027 Each context entry is a list with a symbol naming the context, and
21028 two positions indicating start and end of the context. Possible
21029 contexts are:
21031 :headline anywhere in a headline
21032 :headline-stars on the leading stars in a headline
21033 :todo-keyword on a TODO keyword (including DONE) in a headline
21034 :tags on the TAGS in a headline
21035 :priority on the priority cookie in a headline
21036 :item on the first line of a plain list item
21037 :item-bullet on the bullet/number of a plain list item
21038 :checkbox on the checkbox in a plain list item
21039 :table in an org-mode table
21040 :table-special on a special filed in a table
21041 :table-table in a table.el table
21042 :clocktable in a clocktable
21043 :src-block in a source block
21044 :link on a hyperlink
21045 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21046 :target on a <<target>>
21047 :radio-target on a <<<radio-target>>>
21048 :latex-fragment on a LaTeX fragment
21049 :latex-preview on a LaTeX fragment with overlaid preview image
21051 This function expects the position to be visible because it uses font-lock
21052 faces as a help to recognize the following contexts: :table-special, :link,
21053 and :keyword."
21054 (let* ((f (get-text-property (point) 'face))
21055 (faces (if (listp f) f (list f)))
21056 (case-fold-search t)
21057 (p (point)) clist o)
21058 ;; First the large context
21059 (cond
21060 ((org-at-heading-p t)
21061 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21062 (when (progn
21063 (beginning-of-line 1)
21064 (looking-at org-todo-line-tags-regexp))
21065 (push (org-point-in-group p 1 :headline-stars) clist)
21066 (push (org-point-in-group p 2 :todo-keyword) clist)
21067 (push (org-point-in-group p 4 :tags) clist))
21068 (goto-char p)
21069 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21070 (if (looking-at "\\[#[A-Z0-9]\\]")
21071 (push (org-point-in-group p 0 :priority) clist)))
21073 ((org-at-item-p)
21074 (push (org-point-in-group p 2 :item-bullet) clist)
21075 (push (list :item (point-at-bol)
21076 (save-excursion (org-end-of-item) (point)))
21077 clist)
21078 (and (org-at-item-checkbox-p)
21079 (push (org-point-in-group p 0 :checkbox) clist)))
21081 ((org-at-table-p)
21082 (push (list :table (org-table-begin) (org-table-end)) clist)
21083 (if (memq 'org-formula faces)
21084 (push (list :table-special
21085 (previous-single-property-change p 'face)
21086 (next-single-property-change p 'face)) clist)))
21087 ((org-at-table-p 'any)
21088 (push (list :table-table) clist)))
21089 (goto-char p)
21091 (let ((case-fold-search t))
21092 ;; New the "medium" contexts: clocktables, source blocks
21093 (cond ((org-in-clocktable-p)
21094 (push (list :clocktable
21095 (and (or (looking-at "#\\+BEGIN: clocktable")
21096 (search-backward "#+BEGIN: clocktable" nil t))
21097 (match-beginning 0))
21098 (and (re-search-forward "#\\+END:?" nil t)
21099 (match-end 0))) clist))
21100 ((org-in-src-block-p)
21101 (push (list :src-block
21102 (and (or (looking-at "#\\+BEGIN_SRC")
21103 (search-backward "#+BEGIN_SRC" nil t))
21104 (match-beginning 0))
21105 (and (search-forward "#+END_SRC" nil t)
21106 (match-beginning 0))) clist))))
21107 (goto-char p)
21109 ;; Now the small context
21110 (cond
21111 ((org-at-timestamp-p)
21112 (push (org-point-in-group p 0 :timestamp) clist))
21113 ((memq 'org-link faces)
21114 (push (list :link
21115 (previous-single-property-change p 'face)
21116 (next-single-property-change p 'face)) clist))
21117 ((memq 'org-special-keyword faces)
21118 (push (list :keyword
21119 (previous-single-property-change p 'face)
21120 (next-single-property-change p 'face)) clist))
21121 ((org-at-target-p)
21122 (push (org-point-in-group p 0 :target) clist)
21123 (goto-char (1- (match-beginning 0)))
21124 (if (looking-at org-radio-target-regexp)
21125 (push (org-point-in-group p 0 :radio-target) clist))
21126 (goto-char p))
21127 ((setq o (car (delq nil
21128 (mapcar
21129 (lambda (x)
21130 (if (memq x org-latex-fragment-image-overlays) x))
21131 (overlays-at (point))))))
21132 (push (list :latex-fragment
21133 (overlay-start o) (overlay-end o)) clist)
21134 (push (list :latex-preview
21135 (overlay-start o) (overlay-end o)) clist))
21136 ((org-inside-LaTeX-fragment-p)
21137 ;; FIXME: positions wrong.
21138 (push (list :latex-fragment (point) (point)) clist)))
21140 (setq clist (nreverse (delq nil clist)))
21141 clist))
21143 ;; FIXME: Compare with at-regexp-p Do we need both?
21144 (defun org-in-regexp (re &optional nlines visually)
21145 "Check if point is inside a match of regexp.
21146 Normally only the current line is checked, but you can include NLINES extra
21147 lines both before and after point into the search.
21148 If VISUALLY is set, require that the cursor is not after the match but
21149 really on, so that the block visually is on the match."
21150 (catch 'exit
21151 (let ((pos (point))
21152 (eol (point-at-eol (+ 1 (or nlines 0))))
21153 (inc (if visually 1 0)))
21154 (save-excursion
21155 (beginning-of-line (- 1 (or nlines 0)))
21156 (while (re-search-forward re eol t)
21157 (if (and (<= (match-beginning 0) pos)
21158 (>= (+ inc (match-end 0)) pos))
21159 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21161 (defun org-at-regexp-p (regexp)
21162 "Is point inside a match of REGEXP in the current line?"
21163 (catch 'exit
21164 (save-excursion
21165 (let ((pos (point)) (end (point-at-eol)))
21166 (beginning-of-line 1)
21167 (while (re-search-forward regexp end t)
21168 (if (and (<= (match-beginning 0) pos)
21169 (>= (match-end 0) pos))
21170 (throw 'exit t)))
21171 nil))))
21173 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21174 "Non-nil when point is between matches of START-RE and END-RE.
21176 Also return a non-nil value when point is on one of the matches.
21178 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21179 buffer positions. Default values are the positions of headlines
21180 surrounding the point.
21182 The functions returns a cons cell whose car (resp. cdr) is the
21183 position before START-RE (resp. after END-RE)."
21184 (save-match-data
21185 (let ((pos (point))
21186 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21187 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21188 beg end)
21189 (save-excursion
21190 ;; Point is on a block when on START-RE or if START-RE can be
21191 ;; found before it...
21192 (and (or (org-at-regexp-p start-re)
21193 (re-search-backward start-re limit-up t))
21194 (setq beg (match-beginning 0))
21195 ;; ... and END-RE after it...
21196 (goto-char (match-end 0))
21197 (re-search-forward end-re limit-down t)
21198 (> (setq end (match-end 0)) pos)
21199 ;; ... without another START-RE in-between.
21200 (goto-char (match-beginning 0))
21201 (not (re-search-backward start-re (1+ beg) t))
21202 ;; Return value.
21203 (cons beg end))))))
21205 (defun org-in-block-p (names)
21206 "Non-nil when point belongs to a block whose name belongs to NAMES.
21208 NAMES is a list of strings containing names of blocks.
21210 Return first block name matched, or nil. Beware that in case of
21211 nested blocks, the returned name may not belong to the closest
21212 block from point."
21213 (save-match-data
21214 (catch 'exit
21215 (let ((case-fold-search t)
21216 (lim-up (save-excursion (outline-previous-heading)))
21217 (lim-down (save-excursion (outline-next-heading))))
21218 (mapc (lambda (name)
21219 (let ((n (regexp-quote name)))
21220 (when (org-between-regexps-p
21221 (concat "^[ \t]*#\\+begin_" n)
21222 (concat "^[ \t]*#\\+end_" n)
21223 lim-up lim-down)
21224 (throw 'exit n))))
21225 names))
21226 nil)))
21228 (defun org-occur-in-agenda-files (regexp &optional nlines)
21229 "Call `multi-occur' with buffers for all agenda files."
21230 (interactive "sOrg-files matching: \np")
21231 (let* ((files (org-agenda-files))
21232 (tnames (mapcar 'file-truename files))
21233 (extra org-agenda-text-search-extra-files)
21235 (when (eq (car extra) 'agenda-archives)
21236 (setq extra (cdr extra))
21237 (setq files (org-add-archive-files files)))
21238 (while (setq f (pop extra))
21239 (unless (member (file-truename f) tnames)
21240 (add-to-list 'files f 'append)
21241 (add-to-list 'tnames (file-truename f) 'append)))
21242 (multi-occur
21243 (mapcar (lambda (x)
21244 (with-current-buffer
21245 (or (get-file-buffer x) (find-file-noselect x))
21246 (widen)
21247 (current-buffer)))
21248 files)
21249 regexp)))
21251 (if (boundp 'occur-mode-find-occurrence-hook)
21252 ;; Emacs 23
21253 (add-hook 'occur-mode-find-occurrence-hook
21254 (lambda ()
21255 (when (derived-mode-p 'org-mode)
21256 (org-reveal))))
21257 ;; Emacs 22
21258 (defadvice occur-mode-goto-occurrence
21259 (after org-occur-reveal activate)
21260 (and (derived-mode-p 'org-mode) (org-reveal)))
21261 (defadvice occur-mode-goto-occurrence-other-window
21262 (after org-occur-reveal activate)
21263 (and (derived-mode-p 'org-mode) (org-reveal)))
21264 (defadvice occur-mode-display-occurrence
21265 (after org-occur-reveal activate)
21266 (when (derived-mode-p 'org-mode)
21267 (let ((pos (occur-mode-find-occurrence)))
21268 (with-current-buffer (marker-buffer pos)
21269 (save-excursion
21270 (goto-char pos)
21271 (org-reveal)))))))
21273 (defun org-occur-link-in-agenda-files ()
21274 "Create a link and search for it in the agendas.
21275 The link is not stored in `org-stored-links', it is just created
21276 for the search purpose."
21277 (interactive)
21278 (let ((link (condition-case nil
21279 (org-store-link nil)
21280 (error "Unable to create a link to here"))))
21281 (org-occur-in-agenda-files (regexp-quote link))))
21283 (defun org-reverse-string (string)
21284 "Return the reverse of STRING."
21285 (apply 'string (reverse (string-to-list string))))
21287 (defun org-uniquify (list)
21288 "Remove duplicate elements from LIST."
21289 (let (res)
21290 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21291 res))
21293 (defun org-delete-all (elts list)
21294 "Remove all elements in ELTS from LIST."
21295 (while elts
21296 (setq list (delete (pop elts) list)))
21297 list)
21299 (defun org-count (cl-item cl-seq)
21300 "Count the number of occurrences of ITEM in SEQ.
21301 Taken from `count' in cl-seq.el with all keyword arguments removed."
21302 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21303 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21304 (while (< cl-start cl-end)
21305 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21306 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21307 (setq cl-start (1+ cl-start)))
21308 cl-count))
21310 (defun org-remove-if (predicate seq)
21311 "Remove everything from SEQ that fulfills PREDICATE."
21312 (let (res e)
21313 (while seq
21314 (setq e (pop seq))
21315 (if (not (funcall predicate e)) (push e res)))
21316 (nreverse res)))
21318 (defun org-remove-if-not (predicate seq)
21319 "Remove everything from SEQ that does not fulfill PREDICATE."
21320 (let (res e)
21321 (while seq
21322 (setq e (pop seq))
21323 (if (funcall predicate e) (push e res)))
21324 (nreverse res)))
21326 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21327 "Reduce two-argument FUNCTION across SEQ.
21328 Taken from `reduce' in cl-seq.el with all keyword arguments but
21329 \":initial-value\" removed."
21330 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21331 (cadr (memq :initial-value cl-keys)))
21332 (cl-seq (pop cl-seq))
21333 (t (funcall cl-func)))))
21334 (while cl-seq
21335 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21336 cl-accum))
21338 (defun org-back-over-empty-lines ()
21339 "Move backwards over whitespace, to the beginning of the first empty line.
21340 Returns the number of empty lines passed."
21341 (let ((pos (point)))
21342 (if (cdr (assoc 'heading org-blank-before-new-entry))
21343 (skip-chars-backward " \t\n\r")
21344 (unless (eobp)
21345 (forward-line -1)))
21346 (beginning-of-line 2)
21347 (goto-char (min (point) pos))
21348 (count-lines (point) pos)))
21350 (defun org-skip-whitespace ()
21351 (skip-chars-forward " \t\n\r"))
21353 (defun org-point-in-group (point group &optional context)
21354 "Check if POINT is in match-group GROUP.
21355 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21356 match. If the match group does not exist or point is not inside it,
21357 return nil."
21358 (and (match-beginning group)
21359 (>= point (match-beginning group))
21360 (<= point (match-end group))
21361 (if context
21362 (list context (match-beginning group) (match-end group))
21363 t)))
21365 (defun org-switch-to-buffer-other-window (&rest args)
21366 "Switch to buffer in a second window on the current frame.
21367 In particular, do not allow pop-up frames.
21368 Returns the newly created buffer."
21369 (org-no-popups
21370 (apply 'switch-to-buffer-other-window args)))
21372 (defun org-combine-plists (&rest plists)
21373 "Create a single property list from all plists in PLISTS.
21374 The process starts by copying the first list, and then setting properties
21375 from the other lists. Settings in the last list are the most significant
21376 ones and overrule settings in the other lists."
21377 (let ((rtn (copy-sequence (pop plists)))
21378 p v ls)
21379 (while plists
21380 (setq ls (pop plists))
21381 (while ls
21382 (setq p (pop ls) v (pop ls))
21383 (setq rtn (plist-put rtn p v))))
21384 rtn))
21386 (defun org-replace-escapes (string table)
21387 "Replace %-escapes in STRING with values in TABLE.
21388 TABLE is an association list with keys like \"%a\" and string values.
21389 The sequences in STRING may contain normal field width and padding information,
21390 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21391 so values can contain further %-escapes if they are define later in TABLE."
21392 (let ((tbl (copy-alist table))
21393 (case-fold-search nil)
21394 (pchg 0)
21395 e re rpl)
21396 (while (setq e (pop tbl))
21397 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21398 (when (and (cdr e) (string-match re (cdr e)))
21399 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21400 (safe "SREF"))
21401 (add-text-properties 0 3 (list 'sref sref) safe)
21402 (setcdr e (replace-match safe t t (cdr e)))))
21403 (while (string-match re string)
21404 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21405 (cdr e)))
21406 (setq string (replace-match rpl t t string))))
21407 (while (setq pchg (next-property-change pchg string))
21408 (let ((sref (get-text-property pchg 'sref string)))
21409 (when (and sref (string-match "SREF" string pchg))
21410 (setq string (replace-match sref t t string)))))
21411 string))
21413 (defun org-sublist (list start end)
21414 "Return a section of LIST, from START to END.
21415 Counting starts at 1."
21416 (let (rtn (c start))
21417 (setq list (nthcdr (1- start) list))
21418 (while (and list (<= c end))
21419 (push (pop list) rtn)
21420 (setq c (1+ c)))
21421 (nreverse rtn)))
21423 (defun org-find-base-buffer-visiting (file)
21424 "Like `find-buffer-visiting' but always return the base buffer and
21425 not an indirect buffer."
21426 (let ((buf (or (get-file-buffer file)
21427 (find-buffer-visiting file))))
21428 (if buf
21429 (or (buffer-base-buffer buf) buf)
21430 nil)))
21432 (defun org-image-file-name-regexp (&optional extensions)
21433 "Return regexp matching the file names of images.
21434 If EXTENSIONS is given, only match these."
21435 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21436 (image-file-name-regexp)
21437 (let ((image-file-name-extensions
21438 (or extensions
21439 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21440 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21441 (concat "\\."
21442 (regexp-opt (nconc (mapcar 'upcase
21443 image-file-name-extensions)
21444 image-file-name-extensions)
21446 "\\'"))))
21448 (defun org-file-image-p (file &optional extensions)
21449 "Return non-nil if FILE is an image."
21450 (save-match-data
21451 (string-match (org-image-file-name-regexp extensions) file)))
21453 (defun org-get-cursor-date (&optional with-time)
21454 "Return the date at cursor in as a time.
21455 This works in the calendar and in the agenda, anywhere else it just
21456 returns the current time.
21457 If WITH-TIME is non-nil, returns the time of the event at point (in
21458 the agenda) or the current time of the day."
21459 (let (date day defd tp tm hod mod)
21460 (when with-time
21461 (setq tp (get-text-property (point) 'time))
21462 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21463 (setq hod (string-to-number (match-string 1 tp))
21464 mod (string-to-number (match-string 2 tp))))
21465 (or tp (setq hod (nth 2 (decode-time (current-time)))
21466 mod (nth 1 (decode-time (current-time))))))
21467 (cond
21468 ((eq major-mode 'calendar-mode)
21469 (setq date (calendar-cursor-to-date)
21470 defd (encode-time 0 (or mod 0) (or hod 0)
21471 (nth 1 date) (nth 0 date) (nth 2 date))))
21472 ((eq major-mode 'org-agenda-mode)
21473 (setq day (get-text-property (point) 'day))
21474 (if day
21475 (setq date (calendar-gregorian-from-absolute day)
21476 defd (encode-time 0 (or mod 0) (or hod 0)
21477 (nth 1 date) (nth 0 date) (nth 2 date))))))
21478 (or defd (current-time))))
21480 (defun org-mark-subtree (&optional up)
21481 "Mark the current subtree.
21482 This puts point at the start of the current subtree, and mark at
21483 the end. If a numeric prefix UP is given, move up into the
21484 hierarchy of headlines by UP levels before marking the subtree."
21485 (interactive "P")
21486 (org-with-limited-levels
21487 (cond ((org-at-heading-p) (beginning-of-line))
21488 ((org-before-first-heading-p) (error "Not in a subtree"))
21489 (t (outline-previous-visible-heading 1))))
21490 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21491 (if (org-called-interactively-p 'any)
21492 (call-interactively 'org-mark-element)
21493 (org-mark-element)))
21496 ;;; Indentation
21498 (defun org-indent-line ()
21499 "Indent line depending on context."
21500 (interactive)
21501 (let* ((pos (point))
21502 (itemp (org-at-item-p))
21503 (case-fold-search t)
21504 (org-drawer-regexp (or org-drawer-regexp "\000"))
21505 (inline-task-p (and (featurep 'org-inlinetask)
21506 (org-inlinetask-in-task-p)))
21507 (inline-re (and inline-task-p
21508 (org-inlinetask-outline-regexp)))
21509 column)
21510 (if (and orgstruct-is-++ (eq pos (point)))
21511 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21512 (indent-according-to-mode))
21513 (beginning-of-line 1)
21514 (cond
21515 ;; Headings
21516 ((looking-at org-outline-regexp) (setq column 0))
21517 ;; Footnote definition
21518 ((looking-at org-footnote-definition-re) (setq column 0))
21519 ;; Literal examples
21520 ((looking-at "[ \t]*:\\( \\|$\\)")
21521 (setq column (org-get-indentation))) ; do nothing
21522 ;; Lists
21523 ((ignore-errors (goto-char (org-in-item-p)))
21524 (setq column (if itemp
21525 (org-get-indentation)
21526 (org-list-item-body-column (point))))
21527 (goto-char pos))
21528 ;; Drawers
21529 ((and (looking-at "[ \t]*:END:")
21530 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21531 (save-excursion
21532 (goto-char (1- (match-beginning 1)))
21533 (setq column (current-column))))
21534 ;; Special blocks
21535 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21536 (save-excursion
21537 (re-search-backward
21538 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21539 (setq column (org-get-indentation (match-string 0))))
21540 ((and (not (looking-at "[ \t]*#\\+begin_"))
21541 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21542 (save-excursion
21543 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21544 (setq column
21545 (cond ((equal (downcase (match-string 1)) "src")
21546 ;; src blocks: let `org-edit-src-exit' handle them
21547 (org-get-indentation))
21548 ((equal (downcase (match-string 1)) "example")
21549 (max (org-get-indentation)
21550 (org-get-indentation (match-string 0))))
21552 (org-get-indentation (match-string 0))))))
21553 ;; This line has nothing special, look at the previous relevant
21554 ;; line to compute indentation
21556 (beginning-of-line 0)
21557 (while (and (not (bobp))
21558 (not (looking-at org-table-line-regexp))
21559 (not (looking-at org-drawer-regexp))
21560 ;; When point started in an inline task, do not move
21561 ;; above task starting line.
21562 (not (and inline-task-p (looking-at inline-re)))
21563 ;; Skip drawers, blocks, empty lines, verbatim,
21564 ;; comments, tables, footnotes definitions, lists,
21565 ;; inline tasks.
21566 (or (and (looking-at "[ \t]*:END:")
21567 (re-search-backward org-drawer-regexp nil t))
21568 (and (looking-at "[ \t]*#\\+end_")
21569 (re-search-backward "[ \t]*#\\+begin_"nil t))
21570 (looking-at "[ \t]*[\n:#|]")
21571 (looking-at org-footnote-definition-re)
21572 (and (ignore-errors (goto-char (org-in-item-p)))
21573 (goto-char
21574 (org-list-get-top-point (org-list-struct))))
21575 (and (not inline-task-p)
21576 (featurep 'org-inlinetask)
21577 (org-inlinetask-in-task-p)
21578 (or (org-inlinetask-goto-beginning) t))))
21579 (beginning-of-line 0))
21580 (cond
21581 ;; There was an heading above.
21582 ((looking-at "\\*+[ \t]+")
21583 (if (not org-adapt-indentation)
21584 (setq column 0)
21585 (goto-char (match-end 0))
21586 (setq column (current-column))))
21587 ;; A drawer had started and is unfinished
21588 ((looking-at org-drawer-regexp)
21589 (goto-char (1- (match-beginning 1)))
21590 (setq column (current-column)))
21591 ;; Else, nothing noticeable found: get indentation and go on.
21592 (t (setq column (org-get-indentation))))))
21593 ;; Now apply indentation and move cursor accordingly
21594 (goto-char pos)
21595 (if (<= (current-column) (current-indentation))
21596 (org-indent-line-to column)
21597 (save-excursion (org-indent-line-to column)))
21598 ;; Special polishing for properties, see `org-property-format'
21599 (setq column (current-column))
21600 (beginning-of-line 1)
21601 (if (looking-at
21602 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21603 (replace-match (concat (match-string 1)
21604 (format org-property-format
21605 (match-string 2) (match-string 3)))
21606 t t))
21607 (org-move-to-column column))))
21609 (defun org-indent-drawer ()
21610 "Indent the drawer at point."
21611 (interactive)
21612 (let ((p (point))
21613 (e (and (save-excursion (re-search-forward ":END:" nil t))
21614 (match-end 0)))
21615 (folded
21616 (save-excursion
21617 (end-of-line)
21618 (when (overlays-at (point))
21619 (member 'invisible (overlay-properties
21620 (car (overlays-at (point)))))))))
21621 (when folded (org-cycle))
21622 (indent-for-tab-command)
21623 (while (and (move-beginning-of-line 2) (< (point) e))
21624 (indent-for-tab-command))
21625 (goto-char p)
21626 (when folded (org-cycle)))
21627 (message "Drawer at point indented"))
21629 (defun org-indent-block ()
21630 "Indent the block at point."
21631 (interactive)
21632 (let ((p (point))
21633 (case-fold-search t)
21634 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21635 (match-end 0)))
21636 (folded
21637 (save-excursion
21638 (end-of-line)
21639 (when (overlays-at (point))
21640 (member 'invisible (overlay-properties
21641 (car (overlays-at (point)))))))))
21642 (when folded (org-cycle))
21643 (indent-for-tab-command)
21644 (while (and (move-beginning-of-line 2) (< (point) e))
21645 (indent-for-tab-command))
21646 (goto-char p)
21647 (when folded (org-cycle)))
21648 (message "Block at point indented"))
21650 (defun org-indent-region (start end)
21651 "Indent region."
21652 (interactive "r")
21653 (save-excursion
21654 (let ((line-end (org-current-line end)))
21655 (goto-char start)
21656 (while (< (org-current-line) line-end)
21657 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21658 (t (call-interactively 'org-indent-line)))
21659 (move-beginning-of-line 2)))))
21662 ;;; Filling
21664 ;; We use our own fill-paragraph and auto-fill functions.
21666 ;; `org-fill-paragraph' relies on adaptive filling and context
21667 ;; checking. Appropriate `fill-prefix' is computed with
21668 ;; `org-adaptive-fill-function'.
21670 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21671 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21672 ;; `org-adaptive-fill-function' value. Internally,
21673 ;; `org-comment-line-break-function' breaks the line.
21675 ;; `org-setup-filling' installs filling and auto-filling related
21676 ;; variables during `org-mode' initialization.
21678 (defun org-setup-filling ()
21679 (interactive)
21680 ;; Prevent auto-fill from inserting unwanted new items.
21681 (when (boundp 'fill-nobreak-predicate)
21682 (org-set-local
21683 'fill-nobreak-predicate
21684 (org-uniquify
21685 (append fill-nobreak-predicate
21686 '(org-fill-paragraph-separate-nobreak-p
21687 org-fill-line-break-nobreak-p
21688 org-fill-paragraph-with-timestamp-nobreak-p)))))
21689 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21690 (org-set-local 'auto-fill-inhibit-regexp nil)
21691 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21692 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21693 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21695 (defvar org-element-paragraph-separate) ; org-element.el
21696 (defun org-fill-paragraph-separate-nobreak-p ()
21697 "Non-nil when a line break at point would insert a new item."
21698 (looking-at (substring org-element-paragraph-separate 1)))
21700 (defun org-fill-line-break-nobreak-p ()
21701 "Non-nil when a line break at point would create an Org line break."
21702 (save-excursion
21703 (skip-chars-backward "[ \t]")
21704 (skip-chars-backward "\\\\")
21705 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21707 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21708 "Non-nil when a line break at point would insert a new item."
21709 (and (org-at-timestamp-p t)
21710 (not (looking-at org-ts-regexp-both))))
21712 (declare-function message-in-body-p "message" ())
21713 (defvar orgtbl-line-start-regexp) ; From org-table.el
21714 (defun org-adaptive-fill-function ()
21715 "Compute a fill prefix for the current line.
21716 Return fill prefix, as a string, or nil if current line isn't
21717 meant to be filled."
21718 (let (prefix)
21719 (catch 'exit
21720 (when (derived-mode-p 'message-mode)
21721 (save-excursion
21722 (beginning-of-line)
21723 (cond ((or (not (message-in-body-p))
21724 (looking-at orgtbl-line-start-regexp))
21725 (throw 'exit nil))
21726 ((looking-at message-cite-prefix-regexp)
21727 (throw 'exit (match-string-no-properties 0)))
21728 ((looking-at org-outline-regexp)
21729 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21730 (org-with-wide-buffer
21731 (let* ((p (line-beginning-position))
21732 (element (save-excursion (beginning-of-line)
21733 (org-element-at-point)))
21734 (type (org-element-type element))
21735 (post-affiliated (org-element-property :post-affiliated element)))
21736 (unless (and post-affiliated (< p post-affiliated))
21737 (case type
21738 (comment (looking-at "[ \t]*# ?") (match-string 0))
21739 (footnote-definition "")
21740 ((item plain-list)
21741 (make-string (org-list-item-body-column
21742 (or post-affiliated
21743 (org-element-property :begin element)))
21744 ? ))
21745 (paragraph
21746 ;; Fill prefix is usually the same as the current line,
21747 ;; except if the paragraph is at the beginning of an item.
21748 (let ((parent (org-element-property :parent element)))
21749 (cond ((eq (org-element-type parent) 'item)
21750 (make-string (org-list-item-body-column
21751 (org-element-property :begin parent))
21752 ? ))
21753 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21754 (match-string 0))
21755 (t ""))))
21756 (comment-block
21757 ;; Only fill contents if P is within block boundaries.
21758 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21759 (forward-line)
21760 (point)))
21761 (cend (save-excursion
21762 (goto-char (org-element-property :end element))
21763 (skip-chars-backward " \r\t\n")
21764 (line-beginning-position))))
21765 (when (and (>= p cbeg) (< p cend))
21766 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21767 (match-string 0)
21768 "")))))))))))
21770 (declare-function message-goto-body "message" ())
21771 (defvar message-cite-prefix-regexp) ; From message.el
21772 (defun org-fill-paragraph (&optional justify)
21773 "Fill element at point, when applicable.
21775 This function only applies to comment blocks, comments, example
21776 blocks and paragraphs. Also, as a special case, re-align table
21777 when point is at one.
21779 If JUSTIFY is non-nil (interactively, with prefix argument),
21780 justify as well. If `sentence-end-double-space' is non-nil, then
21781 period followed by one space does not end a sentence, so don't
21782 break a line there. The variable `fill-column' controls the
21783 width for filling.
21785 For convenience, when point is at a plain list, an item or
21786 a footnote definition, try to fill the first paragraph within."
21787 (interactive)
21788 (if (and (derived-mode-p 'message-mode)
21789 (or (not (message-in-body-p))
21790 (save-excursion (move-beginning-of-line 1)
21791 (looking-at message-cite-prefix-regexp))))
21792 ;; First ensure filling is correct in message-mode.
21793 (let ((fill-paragraph-function
21794 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21795 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21796 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21797 (paragraph-separate
21798 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21799 (fill-paragraph nil))
21800 (with-syntax-table org-mode-transpose-word-syntax-table
21801 ;; Move to end of line in order to get the first paragraph
21802 ;; within a plain list or a footnote definition.
21803 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21804 ;; First check if point is in a blank line at the beginning of
21805 ;; the buffer. In that case, ignore filling.
21806 (case (org-element-type element)
21807 ;; Use major mode filling function is src blocks.
21808 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21809 ;; Align Org tables, leave table.el tables as-is.
21810 (table-row (org-table-align) t)
21811 (table
21812 (when (eq (org-element-property :type element) 'org)
21813 (org-table-align))
21815 (paragraph
21816 ;; Paragraphs may contain `line-break' type objects.
21817 (let ((beg (max (point-min)
21818 (org-element-property :contents-begin element)))
21819 (end (min (point-max)
21820 (org-element-property :contents-end element))))
21821 ;; Do nothing if point is at an affiliated keyword.
21822 (if (< (line-end-position) beg) t
21823 (when (derived-mode-p 'message-mode)
21824 ;; In `message-mode', do not fill following citation
21825 ;; in current paragraph nor text before message body.
21826 (let ((body-start (save-excursion (message-goto-body))))
21827 (when body-start (setq beg (max body-start beg))))
21828 (when (save-excursion
21829 (re-search-forward
21830 (concat "^" message-cite-prefix-regexp) end t))
21831 (setq end (match-beginning 0))))
21832 ;; Fill paragraph, taking line breaks into account.
21833 ;; For that, slice the paragraph using line breaks as
21834 ;; separators, and fill the parts in reverse order to
21835 ;; avoid messing with markers.
21836 (save-excursion
21837 (goto-char end)
21838 (mapc
21839 (lambda (pos)
21840 (fill-region-as-paragraph pos (point) justify)
21841 (goto-char pos))
21842 ;; Find the list of ending positions for line breaks
21843 ;; in the current paragraph. Add paragraph
21844 ;; beginning to include first slice.
21845 (nreverse
21846 (cons beg
21847 (org-element-map
21848 (org-element--parse-objects
21849 beg end nil (org-element-restriction 'paragraph))
21850 'line-break
21851 (lambda (lb) (org-element-property :end lb)))))))
21852 t)))
21853 ;; Contents of `comment-block' type elements should be
21854 ;; filled as plain text, but only if point is within block
21855 ;; markers.
21856 (comment-block
21857 (let* ((case-fold-search t)
21858 (beg (save-excursion
21859 (goto-char (org-element-property :begin element))
21860 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21861 (forward-line)
21862 (point)))
21863 (end (save-excursion
21864 (goto-char (org-element-property :end element))
21865 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21866 (line-beginning-position))))
21867 (when (and (>= (point) beg) (< (point) end))
21868 (fill-region-as-paragraph
21869 (save-excursion
21870 (end-of-line)
21871 (re-search-backward "^[ \t]*$" beg 'move)
21872 (line-beginning-position))
21873 (save-excursion
21874 (beginning-of-line)
21875 (re-search-forward "^[ \t]*$" end 'move)
21876 (line-beginning-position))
21877 justify)))
21879 ;; Fill comments.
21880 (comment (fill-comment-paragraph justify))
21881 ;; Ignore every other element.
21882 (otherwise t))))))
21884 (defun org-auto-fill-function ()
21885 "Auto-fill function."
21886 ;; Check if auto-filling is meaningful.
21887 (let ((fc (current-fill-column)))
21888 (when (and fc (> (current-column) fc))
21889 (let* ((fill-prefix (org-adaptive-fill-function))
21890 ;; Enforce empty fill prefix, if required. Otherwise, it
21891 ;; will be computed again.
21892 (adaptive-fill-mode (not (equal fill-prefix ""))))
21893 (when fill-prefix (do-auto-fill))))))
21895 (defun org-comment-line-break-function (&optional soft)
21896 "Break line at point and indent, continuing comment if within one.
21897 The inserted newline is marked hard if variable
21898 `use-hard-newlines' is true, unless optional argument SOFT is
21899 non-nil."
21900 (if soft (insert-and-inherit ?\n) (newline 1))
21901 (save-excursion (forward-char -1) (delete-horizontal-space))
21902 (delete-horizontal-space)
21903 (indent-to-left-margin)
21904 (insert-before-markers-and-inherit fill-prefix))
21907 ;;; Comments
21909 ;; Org comments syntax is quite complex. It requires the entire line
21910 ;; to be just a comment. Also, even with the right syntax at the
21911 ;; beginning of line, some some elements (i.e. verse-block or
21912 ;; example-block) don't accept comments. Usual Emacs comment commands
21913 ;; cannot cope with those requirements. Therefore, Org replaces them.
21915 ;; Org still relies on `comment-dwim', but cannot trust
21916 ;; `comment-only-p'. So, `comment-region-function' and
21917 ;; `uncomment-region-function' both point
21918 ;; to`org-comment-or-uncomment-region'. Eventually,
21919 ;; `org-insert-comment' takes care of insertion of comments at the
21920 ;; beginning of line.
21922 ;; `org-setup-comments-handling' install comments related variables
21923 ;; during `org-mode' initialization.
21925 (defun org-setup-comments-handling ()
21926 (interactive)
21927 (org-set-local 'comment-use-syntax nil)
21928 (org-set-local 'comment-start "# ")
21929 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21930 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21931 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21932 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21934 (defun org-insert-comment ()
21935 "Insert an empty comment above current line.
21936 If the line is empty, insert comment at its beginning."
21937 (beginning-of-line)
21938 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21939 (org-indent-line)
21940 (insert "# "))
21942 (defvar comment-empty-lines) ; From newcomment.el.
21943 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21944 "Comment or uncomment each non-blank line in the region.
21945 Uncomment each non-blank line between BEG and END if it only
21946 contains commented lines. Otherwise, comment them."
21947 (save-restriction
21948 ;; Restrict region
21949 (narrow-to-region (save-excursion (goto-char beg)
21950 (skip-chars-forward " \r\t\n" end)
21951 (line-beginning-position))
21952 (save-excursion (goto-char end)
21953 (skip-chars-backward " \r\t\n" beg)
21954 (line-end-position)))
21955 (let ((uncommentp
21956 ;; UNCOMMENTP is non-nil when every non blank line between
21957 ;; BEG and END is a comment.
21958 (save-excursion
21959 (goto-char (point-min))
21960 (while (and (not (eobp))
21961 (let ((element (org-element-at-point)))
21962 (and (eq (org-element-type element) 'comment)
21963 (goto-char (min (point-max)
21964 (org-element-property
21965 :end element)))))))
21966 (eobp))))
21967 (if uncommentp
21968 ;; Only blank lines and comments in region: uncomment it.
21969 (save-excursion
21970 (goto-char (point-min))
21971 (while (not (eobp))
21972 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21973 (replace-match "" nil nil nil 1))
21974 (forward-line)))
21975 ;; Comment each line in region.
21976 (let ((min-indent (point-max)))
21977 ;; First find the minimum indentation across all lines.
21978 (save-excursion
21979 (goto-char (point-min))
21980 (while (and (not (eobp)) (not (zerop min-indent)))
21981 (unless (looking-at "[ \t]*$")
21982 (setq min-indent (min min-indent (current-indentation))))
21983 (forward-line)))
21984 ;; Then loop over all lines.
21985 (save-excursion
21986 (goto-char (point-min))
21987 (while (not (eobp))
21988 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21989 (org-move-to-column min-indent t)
21990 (insert comment-start))
21991 (forward-line))))))))
21994 ;;; Planning
21996 ;; This section contains tools to operate on timestamp objects, as
21997 ;; returned by, e.g. `org-element-context'.
21999 (defun org-timestamp-has-time-p (timestamp)
22000 "Non-nil when TIMESTAMP has a time specified."
22001 (org-element-property :hour-start timestamp))
22003 (defun org-timestamp-format (timestamp format &optional end utc)
22004 "Format a TIMESTAMP element into a string.
22006 FORMAT is a format specifier to be passed to
22007 `format-time-string'.
22009 When optional argument END is non-nil, use end of date-range or
22010 time-range, if possible.
22012 When optional argument UTC is non-nil, time will be expressed as
22013 Universal Time."
22014 (format-time-string
22015 format
22016 (apply 'encode-time
22017 (cons 0
22018 (mapcar
22019 (lambda (prop) (or (org-element-property prop timestamp) 0))
22020 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22021 '(:minute-start :hour-start :day-start :month-start
22022 :year-start)))))
22023 utc))
22025 (defun org-timestamp-split-range (timestamp &optional end)
22026 "Extract a timestamp object from a date or time range.
22028 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22029 the end of the range. Otherwise, extract its start.
22031 Return a new timestamp object sharing the same parent as
22032 TIMESTAMP."
22033 (let ((type (org-element-property :type timestamp)))
22034 (if (memq type '(active inactive diary)) timestamp
22035 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22036 ;; Set new type.
22037 (org-element-put-property
22038 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22039 ;; Copy start properties over end properties if END is
22040 ;; non-nil. Otherwise, copy end properties over `start' ones.
22041 (let ((p-alist '((:minute-start . :minute-end)
22042 (:hour-start . :hour-end)
22043 (:day-start . :day-end)
22044 (:month-start . :month-end)
22045 (:year-start . :year-end))))
22046 (dolist (p-cell p-alist)
22047 (org-element-put-property
22048 split-ts
22049 (funcall (if end 'car 'cdr) p-cell)
22050 (org-element-property
22051 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22052 ;; Eventually refresh `:raw-value'.
22053 (org-element-put-property split-ts :raw-value nil)
22054 (org-element-put-property
22055 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22057 (defun org-timestamp-translate (timestamp &optional boundary)
22058 "Apply `org-translate-time' on a TIMESTAMP object.
22059 When optional argument BOUNDARY is non-nil, it is either the
22060 symbol `start' or `end'. In this case, only translate the
22061 starting or ending part of TIMESTAMP if it is a date or time
22062 range. Otherwise, translate both parts."
22063 (if (and (not boundary)
22064 (memq (org-element-property :type timestamp)
22065 '(active-range inactive-range)))
22066 (concat
22067 (org-translate-time
22068 (org-element-property :raw-value
22069 (org-timestamp-split-range timestamp)))
22070 "--"
22071 (org-translate-time
22072 (org-element-property :raw-value
22073 (org-timestamp-split-range timestamp t))))
22074 (org-translate-time
22075 (org-element-property
22076 :raw-value
22077 (if (not boundary) timestamp
22078 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22082 ;;; Other stuff.
22084 (defun org-toggle-fixed-width-section (arg)
22085 "Toggle the fixed-width export.
22086 If there is no active region, the QUOTE keyword at the current headline is
22087 inserted or removed. When present, it causes the text between this headline
22088 and the next to be exported as fixed-width text, and unmodified.
22089 If there is an active region, this command adds or removes a colon as the
22090 first character of this line. If the first character of a line is a colon,
22091 this line is also exported in fixed-width font."
22092 (interactive "P")
22093 (let* ((cc 0)
22094 (regionp (org-region-active-p))
22095 (beg (if regionp (region-beginning) (point)))
22096 (end (if regionp (region-end)))
22097 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22098 (case-fold-search nil)
22099 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22100 off)
22101 (if regionp
22102 (save-excursion
22103 (goto-char beg)
22104 (setq cc (current-column))
22105 (beginning-of-line 1)
22106 (setq off (looking-at re))
22107 (while (> nlines 0)
22108 (setq nlines (1- nlines))
22109 (beginning-of-line 1)
22110 (cond
22111 (arg
22112 (org-move-to-column cc t)
22113 (insert ": \n")
22114 (forward-line -1))
22115 ((and off (looking-at re))
22116 (replace-match "" t t nil 1))
22117 ((not off) (org-move-to-column cc t) (insert ": ")))
22118 (forward-line 1)))
22119 (save-excursion
22120 (org-back-to-heading)
22121 (cond
22122 ((looking-at (format org-heading-keyword-regexp-format
22123 org-quote-string))
22124 (goto-char (match-end 1))
22125 (looking-at (concat " +" org-quote-string))
22126 (replace-match "" t t)
22127 (when (eolp) (insert " ")))
22128 ((looking-at org-outline-regexp)
22129 (goto-char (match-end 0))
22130 (insert org-quote-string " ")))))))
22132 (defun org-reftex-citation ()
22133 "Use reftex-citation to insert a citation into the buffer.
22134 This looks for a line like
22136 #+BIBLIOGRAPHY: foo plain option:-d
22138 and derives from it that foo.bib is the bibliography file relevant
22139 for this document. It then installs the necessary environment for RefTeX
22140 to work in this buffer and calls `reftex-citation' to insert a citation
22141 into the buffer.
22143 Export of such citations to both LaTeX and HTML is handled by the contributed
22144 package org-exp-bibtex by Taru Karttunen."
22145 (interactive)
22146 (let ((reftex-docstruct-symbol 'rds)
22147 (reftex-cite-format "\\cite{%l}")
22148 rds bib)
22149 (save-excursion
22150 (save-restriction
22151 (widen)
22152 (let ((case-fold-search t)
22153 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22154 (if (not (save-excursion
22155 (or (re-search-forward re nil t)
22156 (re-search-backward re nil t))))
22157 (error "No bibliography defined in file")
22158 (setq bib (concat (match-string 1) ".bib")
22159 rds (list (list 'bib bib)))))))
22160 (call-interactively 'reftex-citation)))
22162 ;;;; Functions extending outline functionality
22164 (defun org-beginning-of-line (&optional arg)
22165 "Go to the beginning of the current line. If that is invisible, continue
22166 to a visible line beginning. This makes the function of C-a more intuitive.
22167 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22168 first attempt, and only move to after the tags when the cursor is already
22169 beyond the end of the headline."
22170 (interactive "P")
22171 (let ((pos (point))
22172 (special (if (consp org-special-ctrl-a/e)
22173 (car org-special-ctrl-a/e)
22174 org-special-ctrl-a/e))
22175 refpos)
22176 (if (org-bound-and-true-p visual-line-mode)
22177 (beginning-of-visual-line 1)
22178 (beginning-of-line 1))
22179 (if (and arg (fboundp 'move-beginning-of-line))
22180 (call-interactively 'move-beginning-of-line)
22181 (if (bobp)
22183 (backward-char 1)
22184 (if (org-truely-invisible-p)
22185 (while (and (not (bobp)) (org-truely-invisible-p))
22186 (backward-char 1)
22187 (beginning-of-line 1))
22188 (forward-char 1))))
22189 (when special
22190 (cond
22191 ((and (looking-at org-complex-heading-regexp)
22192 (= (char-after (match-end 1)) ?\ ))
22193 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22194 (point-at-eol)))
22195 (goto-char
22196 (if (eq special t)
22197 (cond ((> pos refpos) refpos)
22198 ((= pos (point)) refpos)
22199 (t (point)))
22200 (cond ((> pos (point)) (point))
22201 ((not (eq last-command this-command)) (point))
22202 (t refpos)))))
22203 ((org-at-item-p)
22204 ;; Being at an item and not looking at an the item means point
22205 ;; was previously moved to beginning of a visual line, which
22206 ;; doesn't contain the item. Therefore, do nothing special,
22207 ;; just stay here.
22208 (when (looking-at org-list-full-item-re)
22209 ;; Set special position at first white space character after
22210 ;; bullet, and check-box, if any.
22211 (let ((after-bullet
22212 (let ((box (match-end 3)))
22213 (if (not box) (match-end 1)
22214 (let ((after (char-after box)))
22215 (if (and after (= after ? )) (1+ box) box))))))
22216 ;; Special case: Move point to special position when
22217 ;; currently after it or at beginning of line.
22218 (if (eq special t)
22219 (when (or (> pos after-bullet) (= (point) pos))
22220 (goto-char after-bullet))
22221 ;; Reversed case: Move point to special position when
22222 ;; point was already at beginning of line and command is
22223 ;; repeated.
22224 (when (and (= (point) pos) (eq last-command this-command))
22225 (goto-char after-bullet))))))))
22226 (org-no-warnings
22227 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22229 (defun org-end-of-line (&optional arg)
22230 "Go to the end of the line.
22231 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22232 tags on the first attempt, and only move to after the tags when
22233 the cursor is already beyond the end of the headline."
22234 (interactive "P")
22235 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22236 org-special-ctrl-a/e))
22237 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22238 'end-of-visual-line)
22239 ((fboundp 'move-end-of-line) 'move-end-of-line)
22240 (t 'end-of-line))))
22241 (if (or (not special) arg) (call-interactively move-fun)
22242 (let* ((element (save-excursion (beginning-of-line)
22243 (org-element-at-point)))
22244 (type (org-element-type element)))
22245 (cond
22246 ((memq type '(headline inlinetask))
22247 (let ((pos (point)))
22248 (beginning-of-line 1)
22249 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22250 (if (eq special t)
22251 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22252 (goto-char (match-beginning 1))
22253 (goto-char (match-end 0)))
22254 (if (or (< pos (match-end 0))
22255 (not (eq this-command last-command)))
22256 (goto-char (match-end 0))
22257 (goto-char (match-beginning 1))))
22258 (call-interactively move-fun))))
22259 ((org-element-property :hiddenp element)
22260 ;; If element is hidden, `move-end-of-line' would put point
22261 ;; after it. Use `end-of-line' to stay on current line.
22262 (call-interactively 'end-of-line))
22263 (t (call-interactively move-fun)))))
22264 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22266 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22267 (define-key org-mode-map "\C-e" 'org-end-of-line)
22269 (defun org-backward-sentence (&optional arg)
22270 "Go to beginning of sentence, or beginning of table field.
22271 This will call `backward-sentence' or `org-table-beginning-of-field',
22272 depending on context."
22273 (interactive "P")
22274 (cond
22275 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22276 (t (call-interactively 'backward-sentence))))
22278 (defun org-forward-sentence (&optional arg)
22279 "Go to end of sentence, or end of table field.
22280 This will call `forward-sentence' or `org-table-end-of-field',
22281 depending on context."
22282 (interactive "P")
22283 (cond
22284 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22285 (t (call-interactively 'forward-sentence))))
22287 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22288 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22290 (defun org-kill-line (&optional arg)
22291 "Kill line, to tags or end of line."
22292 (interactive "P")
22293 (cond
22294 ((or (not org-special-ctrl-k)
22295 (bolp)
22296 (not (org-at-heading-p)))
22297 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22298 org-ctrl-k-protect-subtree)
22299 (if (or (eq org-ctrl-k-protect-subtree 'error)
22300 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22301 (error "C-k aborted - would kill hidden subtree")))
22302 (call-interactively
22303 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22304 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22305 (kill-region (point) (match-beginning 1))
22306 (org-set-tags nil t))
22307 (t (kill-region (point) (point-at-eol)))))
22309 (define-key org-mode-map "\C-k" 'org-kill-line)
22311 (defun org-yank (&optional arg)
22312 "Yank. If the kill is a subtree, treat it specially.
22313 This command will look at the current kill and check if is a single
22314 subtree, or a series of subtrees[1]. If it passes the test, and if the
22315 cursor is at the beginning of a line or after the stars of a currently
22316 empty headline, then the yank is handled specially. How exactly depends
22317 on the value of the following variables, both set by default.
22319 org-yank-folded-subtrees
22320 When set, the subtree(s) will be folded after insertion, but only
22321 if doing so would now swallow text after the yanked text.
22323 org-yank-adjusted-subtrees
22324 When set, the subtree will be promoted or demoted in order to
22325 fit into the local outline tree structure, which means that the level
22326 will be adjusted so that it becomes the smaller one of the two
22327 *visible* surrounding headings.
22329 Any prefix to this command will cause `yank' to be called directly with
22330 no special treatment. In particular, a simple \\[universal-argument] prefix \
22331 will just
22332 plainly yank the text as it is.
22334 \[1] The test checks if the first non-white line is a heading
22335 and if there are no other headings with fewer stars."
22336 (interactive "P")
22337 (org-yank-generic 'yank arg))
22339 (defun org-yank-generic (command arg)
22340 "Perform some yank-like command.
22342 This function implements the behavior described in the `org-yank'
22343 documentation. However, it has been generalized to work for any
22344 interactive command with similar behavior."
22346 ;; pretend to be command COMMAND
22347 (setq this-command command)
22349 (if arg
22350 (call-interactively command)
22352 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22353 (and (org-kill-is-subtree-p)
22354 (or (bolp)
22355 (and (looking-at "[ \t]*$")
22356 (string-match
22357 "\\`\\*+\\'"
22358 (buffer-substring (point-at-bol) (point)))))))
22359 swallowp)
22360 (cond
22361 ((and subtreep org-yank-folded-subtrees)
22362 (let ((beg (point))
22363 end)
22364 (if (and subtreep org-yank-adjusted-subtrees)
22365 (org-paste-subtree nil nil 'for-yank)
22366 (call-interactively command))
22368 (setq end (point))
22369 (goto-char beg)
22370 (when (and (bolp) subtreep
22371 (not (setq swallowp
22372 (org-yank-folding-would-swallow-text beg end))))
22373 (org-with-limited-levels
22374 (or (looking-at org-outline-regexp)
22375 (re-search-forward org-outline-regexp-bol end t))
22376 (while (and (< (point) end) (looking-at org-outline-regexp))
22377 (hide-subtree)
22378 (org-cycle-show-empty-lines 'folded)
22379 (condition-case nil
22380 (outline-forward-same-level 1)
22381 (error (goto-char end))))))
22382 (when swallowp
22383 (message
22384 "Inserted text not folded because that would swallow text"))
22386 (goto-char end)
22387 (skip-chars-forward " \t\n\r")
22388 (beginning-of-line 1)
22389 (push-mark beg 'nomsg)))
22390 ((and subtreep org-yank-adjusted-subtrees)
22391 (let ((beg (point-at-bol)))
22392 (org-paste-subtree nil nil 'for-yank)
22393 (push-mark beg 'nomsg)))
22395 (call-interactively command))))))
22397 (defun org-yank-folding-would-swallow-text (beg end)
22398 "Would hide-subtree at BEG swallow any text after END?"
22399 (let (level)
22400 (org-with-limited-levels
22401 (save-excursion
22402 (goto-char beg)
22403 (when (or (looking-at org-outline-regexp)
22404 (re-search-forward org-outline-regexp-bol end t))
22405 (setq level (org-outline-level)))
22406 (goto-char end)
22407 (skip-chars-forward " \t\r\n\v\f")
22408 (if (or (eobp)
22409 (and (bolp) (looking-at org-outline-regexp)
22410 (<= (org-outline-level) level)))
22411 nil ; Nothing would be swallowed
22412 t))))) ; something would swallow
22414 (define-key org-mode-map "\C-y" 'org-yank)
22416 (defun org-truely-invisible-p ()
22417 "Check if point is at a character currently not visible.
22418 This version does not only check the character property, but also
22419 `visible-mode'."
22420 ;; Early versions of noutline don't have `outline-invisible-p'.
22421 (if (org-bound-and-true-p visible-mode)
22423 (outline-invisible-p)))
22425 (defun org-invisible-p2 ()
22426 "Check if point is at a character currently not visible."
22427 (save-excursion
22428 (if (and (eolp) (not (bobp))) (backward-char 1))
22429 ;; Early versions of noutline don't have `outline-invisible-p'.
22430 (outline-invisible-p)))
22432 (defun org-back-to-heading (&optional invisible-ok)
22433 "Call `outline-back-to-heading', but provide a better error message."
22434 (condition-case nil
22435 (outline-back-to-heading invisible-ok)
22436 (error (error "Before first headline at position %d in buffer %s"
22437 (point) (current-buffer)))))
22439 (defun org-before-first-heading-p ()
22440 "Before first heading?"
22441 (save-excursion
22442 (end-of-line)
22443 (null (re-search-backward org-outline-regexp-bol nil t))))
22445 (defun org-at-heading-p (&optional ignored)
22446 (outline-on-heading-p t))
22447 ;; Compatibility alias with Org versions < 7.8.03
22448 (defalias 'org-on-heading-p 'org-at-heading-p)
22450 (defun org-at-comment-p nil
22451 "Is cursor in a line starting with a # character?"
22452 (save-excursion
22453 (beginning-of-line)
22454 (looking-at "^#")))
22456 (defun org-at-drawer-p nil
22457 "Is cursor at a drawer keyword?"
22458 (save-excursion
22459 (move-beginning-of-line 1)
22460 (looking-at org-drawer-regexp)))
22462 (defun org-at-block-p nil
22463 "Is cursor at a block keyword?"
22464 (save-excursion
22465 (move-beginning-of-line 1)
22466 (looking-at org-block-regexp)))
22468 (defun org-point-at-end-of-empty-headline ()
22469 "If point is at the end of an empty headline, return t, else nil.
22470 If the heading only contains a TODO keyword, it is still still considered
22471 empty."
22472 (and (looking-at "[ \t]*$")
22473 (when org-todo-line-regexp
22474 (save-excursion
22475 (beginning-of-line 1)
22476 (let ((case-fold-search nil))
22477 (looking-at org-todo-line-regexp)
22478 (string= (match-string 3) ""))))))
22480 (defun org-at-heading-or-item-p ()
22481 (or (org-at-heading-p) (org-at-item-p)))
22483 (defun org-at-target-p ()
22484 (or (org-in-regexp org-radio-target-regexp)
22485 (org-in-regexp org-target-regexp)))
22486 ;; Compatibility alias with Org versions < 7.8.03
22487 (defalias 'org-on-target-p 'org-at-target-p)
22489 (defun org-up-heading-all (arg)
22490 "Move to the heading line of which the present line is a subheading.
22491 This function considers both visible and invisible heading lines.
22492 With argument, move up ARG levels."
22493 (if (fboundp 'outline-up-heading-all)
22494 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22495 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22497 (defun org-up-heading-safe ()
22498 "Move to the heading line of which the present line is a subheading.
22499 This version will not throw an error. It will return the level of the
22500 headline found, or nil if no higher level is found.
22502 Also, this function will be a lot faster than `outline-up-heading',
22503 because it relies on stars being the outline starters. This can really
22504 make a significant difference in outlines with very many siblings."
22505 (let (start-level re)
22506 (org-back-to-heading t)
22507 (setq start-level (funcall outline-level))
22508 (if (equal start-level 1)
22510 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22511 (if (re-search-backward re nil t)
22512 (funcall outline-level)))))
22514 (defun org-first-sibling-p ()
22515 "Is this heading the first child of its parents?"
22516 (interactive)
22517 (let ((re org-outline-regexp-bol)
22518 level l)
22519 (unless (org-at-heading-p t)
22520 (error "Not at a heading"))
22521 (setq level (funcall outline-level))
22522 (save-excursion
22523 (if (not (re-search-backward re nil t))
22525 (setq l (funcall outline-level))
22526 (< l level)))))
22528 (defun org-goto-sibling (&optional previous)
22529 "Goto the next sibling, even if it is invisible.
22530 When PREVIOUS is set, go to the previous sibling instead. Returns t
22531 when a sibling was found. When none is found, return nil and don't
22532 move point."
22533 (let ((fun (if previous 're-search-backward 're-search-forward))
22534 (pos (point))
22535 (re org-outline-regexp-bol)
22536 level l)
22537 (when (condition-case nil (org-back-to-heading t) (error nil))
22538 (setq level (funcall outline-level))
22539 (catch 'exit
22540 (or previous (forward-char 1))
22541 (while (funcall fun re nil t)
22542 (setq l (funcall outline-level))
22543 (when (< l level) (goto-char pos) (throw 'exit nil))
22544 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22545 (goto-char pos)
22546 nil))))
22548 (defun org-show-siblings ()
22549 "Show all siblings of the current headline."
22550 (save-excursion
22551 (while (org-goto-sibling) (org-flag-heading nil)))
22552 (save-excursion
22553 (while (org-goto-sibling 'previous)
22554 (org-flag-heading nil))))
22556 (defun org-goto-first-child ()
22557 "Goto the first child, even if it is invisible.
22558 Return t when a child was found. Otherwise don't move point and
22559 return nil."
22560 (let (level (pos (point)) (re org-outline-regexp-bol))
22561 (when (condition-case nil (org-back-to-heading t) (error nil))
22562 (setq level (outline-level))
22563 (forward-char 1)
22564 (if (and (re-search-forward re nil t) (> (outline-level) level))
22565 (progn (goto-char (match-beginning 0)) t)
22566 (goto-char pos) nil))))
22568 (defun org-show-hidden-entry ()
22569 "Show an entry where even the heading is hidden."
22570 (save-excursion
22571 (org-show-entry)))
22573 (defun org-flag-heading (flag &optional entry)
22574 "Flag the current heading. FLAG non-nil means make invisible.
22575 When ENTRY is non-nil, show the entire entry."
22576 (save-excursion
22577 (org-back-to-heading t)
22578 ;; Check if we should show the entire entry
22579 (if entry
22580 (progn
22581 (org-show-entry)
22582 (save-excursion
22583 (and (outline-next-heading)
22584 (org-flag-heading nil))))
22585 (outline-flag-region (max (point-min) (1- (point)))
22586 (save-excursion (outline-end-of-heading) (point))
22587 flag))))
22589 (defun org-get-next-sibling ()
22590 "Move to next heading of the same level, and return point.
22591 If there is no such heading, return nil.
22592 This is like outline-next-sibling, but invisible headings are ok."
22593 (let ((level (funcall outline-level)))
22594 (outline-next-heading)
22595 (while (and (not (eobp)) (> (funcall outline-level) level))
22596 (outline-next-heading))
22597 (if (or (eobp) (< (funcall outline-level) level))
22599 (point))))
22601 (defun org-get-last-sibling ()
22602 "Move to previous heading of the same level, and return point.
22603 If there is no such heading, return nil."
22604 (let ((opoint (point))
22605 (level (funcall outline-level)))
22606 (outline-previous-heading)
22607 (when (and (/= (point) opoint) (outline-on-heading-p t))
22608 (while (and (> (funcall outline-level) level)
22609 (not (bobp)))
22610 (outline-previous-heading))
22611 (if (< (funcall outline-level) level)
22613 (point)))))
22615 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22616 "Goto to the end of a subtree."
22617 ;; This contains an exact copy of the original function, but it uses
22618 ;; `org-back-to-heading', to make it work also in invisible
22619 ;; trees. And is uses an invisible-ok argument.
22620 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22621 ;; Furthermore, when used inside Org, finding the end of a large subtree
22622 ;; with many children and grandchildren etc, this can be much faster
22623 ;; than the outline version.
22624 (org-back-to-heading invisible-ok)
22625 (let ((first t)
22626 (level (funcall outline-level)))
22627 (if (and (derived-mode-p 'org-mode) (< level 1000))
22628 ;; A true heading (not a plain list item), in Org-mode
22629 ;; This means we can easily find the end by looking
22630 ;; only for the right number of stars. Using a regexp to do
22631 ;; this is so much faster than using a Lisp loop.
22632 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22633 (forward-char 1)
22634 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22635 ;; something else, do it the slow way
22636 (while (and (not (eobp))
22637 (or first (> (funcall outline-level) level)))
22638 (setq first nil)
22639 (outline-next-heading)))
22640 (unless to-heading
22641 (if (memq (preceding-char) '(?\n ?\^M))
22642 (progn
22643 ;; Go to end of line before heading
22644 (forward-char -1)
22645 (if (memq (preceding-char) '(?\n ?\^M))
22646 ;; leave blank line before heading
22647 (forward-char -1))))))
22648 (point))
22650 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22651 "Use Org version in org-mode, for dramatic speed-up."
22652 (if (derived-mode-p 'org-mode)
22653 (progn
22654 (org-end-of-subtree nil t)
22655 (unless (eobp) (backward-char 1)))
22656 ad-do-it))
22658 (defun org-end-of-meta-data-and-drawers ()
22659 "Jump to the first text after meta data and drawers in the current entry.
22660 This will move over empty lines, lines with planning time stamps,
22661 clocking lines, and drawers."
22662 (org-back-to-heading t)
22663 (let ((end (save-excursion (outline-next-heading) (point)))
22664 (re (concat "\\(" org-drawer-regexp "\\)"
22665 "\\|" "[ \t]*" org-keyword-time-regexp)))
22666 (forward-line 1)
22667 (while (re-search-forward re end t)
22668 (if (not (match-end 1))
22669 ;; empty or planning line
22670 (forward-line 1)
22671 ;; a drawer, find the end
22672 (re-search-forward "^[ \t]*:END:" end 'move)
22673 (forward-line 1)))
22674 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22675 (point)))
22677 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22678 "Move forward to the ARG'th subheading at same level as this one.
22679 Stop at the first and last subheadings of a superior heading.
22680 Normally this only looks at visible headings, but when INVISIBLE-OK is
22681 non-nil it will also look at invisible ones."
22682 (interactive "p")
22683 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22684 (if (and arg (< arg 0))
22685 (goto-char (point-min))
22686 (outline-next-heading))
22687 (org-at-heading-p)
22688 (let ((level (- (match-end 0) (match-beginning 0) 1))
22689 (f (if (and arg (< arg 0))
22690 're-search-backward
22691 're-search-forward))
22692 (count (if arg (abs arg) 1))
22693 (result (point)))
22694 (forward-char (if (and arg (< arg 0)) -1 1))
22695 (while (and (> count 0)
22696 (funcall f org-outline-regexp-bol nil 'move))
22697 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22698 (cond ((< l level) (setq count 0))
22699 ((and (= l level)
22700 (or invisible-ok
22701 (progn
22702 (goto-char (line-beginning-position))
22703 (not (outline-invisible-p)))))
22704 (setq count (1- count))
22705 (when (eq l level)
22706 (setq result (point)))))))
22707 (goto-char result))
22708 (beginning-of-line 1)))
22710 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22711 "Move backward to the ARG'th subheading at same level as this one.
22712 Stop at the first and last subheadings of a superior heading."
22713 (interactive "p")
22714 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22716 (defun org-next-block (arg &optional backward block-regexp)
22717 "Jump to the next block.
22718 With a prefix argument ARG, jump forward ARG many source blocks.
22719 When BACKWARD is non-nil, jump to the previous block.
22720 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22721 (interactive "p")
22722 (let ((re (or block-regexp org-block-regexp))
22723 (re-search-fn (or (and backward 're-search-backward)
22724 're-search-forward)))
22725 (if (looking-at re) (forward-char 1))
22726 (condition-case nil
22727 (funcall re-search-fn re nil nil arg)
22728 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22729 (goto-char (match-beginning 0)) (org-show-context)))
22731 (defun org-previous-block (arg &optional block-regexp)
22732 "Jump to the previous block.
22733 With a prefix argument ARG, jump backward ARG many source blocks.
22734 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22735 (interactive "p")
22736 (org-next-block arg t block-regexp))
22738 (defun org-forward-element ()
22739 "Move forward by one element.
22740 Move to the next element at the same level, when possible."
22741 (interactive)
22742 (cond ((eobp) (user-error "Cannot move further down"))
22743 ((org-with-limited-levels (org-at-heading-p))
22744 (let ((origin (point)))
22745 (goto-char (org-end-of-subtree nil t))
22746 (unless (org-with-limited-levels (org-at-heading-p))
22747 (goto-char origin)
22748 (user-error "Cannot move further down"))))
22750 (let* ((elem (org-element-at-point))
22751 (end (org-element-property :end elem))
22752 (parent (org-element-property :parent elem)))
22753 (if (and parent (= (org-element-property :contents-end parent) end))
22754 (goto-char (org-element-property :end parent))
22755 (goto-char end))))))
22757 (defun org-backward-element ()
22758 "Move backward by one element.
22759 Move to the previous element at the same level, when possible."
22760 (interactive)
22761 (cond ((bobp) (user-error "Cannot move further up"))
22762 ((org-with-limited-levels (org-at-heading-p))
22763 ;; At a headline, move to the previous one, if any, or stay
22764 ;; here.
22765 (let ((origin (point)))
22766 (org-with-limited-levels (org-backward-heading-same-level 1))
22767 ;; When current headline has no sibling above, move to its
22768 ;; parent.
22769 (when (= (point) origin)
22770 (or (org-with-limited-levels (org-up-heading-safe))
22771 (progn (goto-char origin)
22772 (user-error "Cannot move further up"))))))
22774 (let* ((trail (org-element-at-point 'keep-trail))
22775 (elem (car trail))
22776 (prev-elem (nth 1 trail))
22777 (beg (org-element-property :begin elem)))
22778 (cond
22779 ;; Move to beginning of current element if point isn't
22780 ;; there already.
22781 ((/= (point) beg) (goto-char beg))
22782 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22783 ((org-before-first-heading-p) (goto-char (point-min)))
22784 (t (org-back-to-heading)))))))
22786 (defun org-up-element ()
22787 "Move to upper element."
22788 (interactive)
22789 (if (org-with-limited-levels (org-at-heading-p))
22790 (unless (org-up-heading-safe) (error "No surrounding element"))
22791 (let* ((elem (org-element-at-point))
22792 (parent (org-element-property :parent elem)))
22793 (if parent (goto-char (org-element-property :begin parent))
22794 (if (org-with-limited-levels (org-before-first-heading-p))
22795 (error "No surrounding element")
22796 (org-with-limited-levels (org-back-to-heading)))))))
22798 (defvar org-element-greater-elements)
22799 (defun org-down-element ()
22800 "Move to inner element."
22801 (interactive)
22802 (let ((element (org-element-at-point)))
22803 (cond
22804 ((memq (org-element-type element) '(plain-list table))
22805 (goto-char (org-element-property :contents-begin element))
22806 (forward-char))
22807 ((memq (org-element-type element) org-element-greater-elements)
22808 ;; If contents are hidden, first disclose them.
22809 (when (org-element-property :hiddenp element) (org-cycle))
22810 (goto-char (or (org-element-property :contents-begin element)
22811 (error "No content for this element"))))
22812 (t (error "No inner element")))))
22814 (defun org-drag-element-backward ()
22815 "Move backward element at point."
22816 (interactive)
22817 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22818 (let* ((trail (org-element-at-point 'keep-trail))
22819 (elem (car trail))
22820 (prev-elem (nth 1 trail)))
22821 ;; Error out if no previous element or previous element is
22822 ;; a parent of the current one.
22823 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22824 (error "Cannot drag element backward")
22825 (let ((pos (point)))
22826 (org-element-swap-A-B prev-elem elem)
22827 (goto-char (+ (org-element-property :begin prev-elem)
22828 (- pos (org-element-property :begin elem)))))))))
22830 (defun org-drag-element-forward ()
22831 "Move forward element at point."
22832 (interactive)
22833 (let* ((pos (point))
22834 (elem (org-element-at-point)))
22835 (when (= (point-max) (org-element-property :end elem))
22836 (error "Cannot drag element forward"))
22837 (goto-char (org-element-property :end elem))
22838 (let ((next-elem (org-element-at-point)))
22839 (when (or (org-element-nested-p elem next-elem)
22840 (and (eq (org-element-type next-elem) 'headline)
22841 (not (eq (org-element-type elem) 'headline))))
22842 (goto-char pos)
22843 (error "Cannot drag element forward"))
22844 ;; Compute new position of point: it's shifted by NEXT-ELEM
22845 ;; body's length (without final blanks) and by the length of
22846 ;; blanks between ELEM and NEXT-ELEM.
22847 (let ((size-next (- (save-excursion
22848 (goto-char (org-element-property :end next-elem))
22849 (skip-chars-backward " \r\t\n")
22850 (forward-line)
22851 ;; Small correction if buffer doesn't end
22852 ;; with a newline character.
22853 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22854 (org-element-property :begin next-elem)))
22855 (size-blank (- (org-element-property :end elem)
22856 (save-excursion
22857 (goto-char (org-element-property :end elem))
22858 (skip-chars-backward " \r\t\n")
22859 (forward-line)
22860 (point)))))
22861 (org-element-swap-A-B elem next-elem)
22862 (goto-char (+ pos size-next size-blank))))))
22864 (defun org-drag-line-forward (arg)
22865 "Drag the line at point ARG lines forward."
22866 (interactive "p")
22867 (dotimes (n (abs arg))
22868 (let ((c (current-column)))
22869 (if (< 0 arg)
22870 (progn
22871 (beginning-of-line 2)
22872 (transpose-lines 1)
22873 (beginning-of-line 0))
22874 (transpose-lines 1)
22875 (beginning-of-line -1))
22876 (org-move-to-column c))))
22878 (defun org-drag-line-backward (arg)
22879 "Drag the line at point ARG lines backward."
22880 (interactive "p")
22881 (org-drag-line-forward (- arg)))
22883 (defun org-mark-element ()
22884 "Put point at beginning of this element, mark at end.
22886 Interactively, if this command is repeated or (in Transient Mark
22887 mode) if the mark is active, it marks the next element after the
22888 ones already marked."
22889 (interactive)
22890 (let (deactivate-mark)
22891 (if (and (org-called-interactively-p 'any)
22892 (or (and (eq last-command this-command) (mark t))
22893 (and transient-mark-mode mark-active)))
22894 (set-mark
22895 (save-excursion
22896 (goto-char (mark))
22897 (goto-char (org-element-property :end (org-element-at-point)))))
22898 (let ((element (org-element-at-point)))
22899 (end-of-line)
22900 (push-mark (org-element-property :end element) t t)
22901 (goto-char (org-element-property :begin element))))))
22903 (defun org-narrow-to-element ()
22904 "Narrow buffer to current element."
22905 (interactive)
22906 (let ((elem (org-element-at-point)))
22907 (cond
22908 ((eq (car elem) 'headline)
22909 (narrow-to-region
22910 (org-element-property :begin elem)
22911 (org-element-property :end elem)))
22912 ((memq (car elem) org-element-greater-elements)
22913 (narrow-to-region
22914 (org-element-property :contents-begin elem)
22915 (org-element-property :contents-end elem)))
22917 (narrow-to-region
22918 (org-element-property :begin elem)
22919 (org-element-property :end elem))))))
22921 (defun org-transpose-element ()
22922 "Transpose current and previous elements, keeping blank lines between.
22923 Point is moved after both elements."
22924 (interactive)
22925 (org-skip-whitespace)
22926 (let ((end (org-element-property :end (org-element-at-point))))
22927 (org-drag-element-backward)
22928 (goto-char end)))
22930 (defun org-unindent-buffer ()
22931 "Un-indent the visible part of the buffer.
22932 Relative indentation (between items, inside blocks, etc.) isn't
22933 modified."
22934 (interactive)
22935 (unless (eq major-mode 'org-mode)
22936 (error "Cannot un-indent a buffer not in Org mode"))
22937 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22938 unindent-tree ; For byte-compiler.
22939 (unindent-tree
22940 (function
22941 (lambda (contents)
22942 (mapc
22943 (lambda (element)
22944 (if (memq (org-element-type element) '(headline section))
22945 (funcall unindent-tree (org-element-contents element))
22946 (save-excursion
22947 (save-restriction
22948 (narrow-to-region
22949 (org-element-property :begin element)
22950 (org-element-property :end element))
22951 (org-do-remove-indentation)))))
22952 (reverse contents))))))
22953 (funcall unindent-tree (org-element-contents parse-tree))))
22955 (defun org-show-subtree ()
22956 "Show everything after this heading at deeper levels."
22957 (interactive)
22958 (outline-flag-region
22959 (point)
22960 (save-excursion
22961 (org-end-of-subtree t t))
22962 nil))
22964 (defun org-show-entry ()
22965 "Show the body directly following this heading.
22966 Show the heading too, if it is currently invisible."
22967 (interactive)
22968 (save-excursion
22969 (condition-case nil
22970 (progn
22971 (org-back-to-heading t)
22972 (outline-flag-region
22973 (max (point-min) (1- (point)))
22974 (save-excursion
22975 (if (re-search-forward
22976 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22977 (match-beginning 1)
22978 (point-max)))
22979 nil)
22980 (org-cycle-hide-drawers 'children))
22981 (error nil))))
22983 (defun org-make-options-regexp (kwds &optional extra)
22984 "Make a regular expression for keyword lines."
22985 (concat
22986 "^#\\+\\("
22987 (mapconcat 'regexp-quote kwds "\\|")
22988 (if extra (concat "\\|" extra))
22989 "\\):[ \t]*\\(.*\\)"))
22991 ;; Make isearch reveal the necessary context
22992 (defun org-isearch-end ()
22993 "Reveal context after isearch exits."
22994 (when isearch-success ; only if search was successful
22995 (if (featurep 'xemacs)
22996 ;; Under XEmacs, the hook is run in the correct place,
22997 ;; we directly show the context.
22998 (org-show-context 'isearch)
22999 ;; In Emacs the hook runs *before* restoring the overlays.
23000 ;; So we have to use a one-time post-command-hook to do this.
23001 ;; (Emacs 22 has a special variable, see function `org-mode')
23002 (unless (and (boundp 'isearch-mode-end-hook-quit)
23003 isearch-mode-end-hook-quit)
23004 ;; Only when the isearch was not quitted.
23005 (org-add-hook 'post-command-hook 'org-isearch-post-command
23006 'append 'local)))
23007 (org-fix-ellipsis-at-bol)))
23009 (defun org-isearch-post-command ()
23010 "Remove self from hook, and show context."
23011 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23012 (org-show-context 'isearch))
23015 ;;;; Integration with and fixes for other packages
23017 ;;; Imenu support
23019 (defvar org-imenu-markers nil
23020 "All markers currently used by Imenu.")
23021 (make-variable-buffer-local 'org-imenu-markers)
23023 (defun org-imenu-new-marker (&optional pos)
23024 "Return a new marker for use by Imenu, and remember the marker."
23025 (let ((m (make-marker)))
23026 (move-marker m (or pos (point)))
23027 (push m org-imenu-markers)
23030 (defun org-imenu-get-tree ()
23031 "Produce the index for Imenu."
23032 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23033 (setq org-imenu-markers nil)
23034 (let* ((n org-imenu-depth)
23035 (re (concat "^" (org-get-limited-outline-regexp)))
23036 (subs (make-vector (1+ n) nil))
23037 (last-level 0)
23038 m level head0 head)
23039 (save-excursion
23040 (save-restriction
23041 (widen)
23042 (goto-char (point-max))
23043 (while (re-search-backward re nil t)
23044 (setq level (org-reduced-level (funcall outline-level)))
23045 (when (and (<= level n)
23046 (looking-at org-complex-heading-regexp)
23047 (setq head0 (org-match-string-no-properties 4)))
23048 (setq head (org-link-display-format head0)
23049 m (org-imenu-new-marker))
23050 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23051 (if (>= level last-level)
23052 (push (cons head m) (aref subs level))
23053 (push (cons head (aref subs (1+ level))) (aref subs level))
23054 (loop for i from (1+ level) to n do (aset subs i nil)))
23055 (setq last-level level)))))
23056 (aref subs 1)))
23058 (eval-after-load "imenu"
23059 '(progn
23060 (add-hook 'imenu-after-jump-hook
23061 (lambda ()
23062 (if (derived-mode-p 'org-mode)
23063 (org-show-context 'org-goto))))))
23065 (defun org-link-display-format (link)
23066 "Replace a link with either the description, or the link target
23067 if no description is present"
23068 (save-match-data
23069 (if (string-match org-bracket-link-analytic-regexp link)
23070 (replace-match (if (match-end 5)
23071 (match-string 5 link)
23072 (concat (match-string 1 link)
23073 (match-string 3 link)))
23074 nil t link)
23075 link)))
23077 (defun org-toggle-link-display ()
23078 "Toggle the literal or descriptive display of links."
23079 (interactive)
23080 (if org-descriptive-links
23081 (progn (org-remove-from-invisibility-spec '(org-link))
23082 (org-restart-font-lock)
23083 (setq org-descriptive-links nil))
23084 (progn (add-to-invisibility-spec '(org-link))
23085 (org-restart-font-lock)
23086 (setq org-descriptive-links t))))
23088 ;; Speedbar support
23090 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23091 "Overlay marking the agenda restriction line in speedbar.")
23092 (overlay-put org-speedbar-restriction-lock-overlay
23093 'face 'org-agenda-restriction-lock)
23094 (overlay-put org-speedbar-restriction-lock-overlay
23095 'help-echo "Agendas are currently limited to this item.")
23096 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23098 (defun org-speedbar-set-agenda-restriction ()
23099 "Restrict future agenda commands to the location at point in speedbar.
23100 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23101 (interactive)
23102 (require 'org-agenda)
23103 (let (p m tp np dir txt)
23104 (cond
23105 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23106 'org-imenu t))
23107 (setq m (get-text-property p 'org-imenu-marker))
23108 (with-current-buffer (marker-buffer m)
23109 (goto-char m)
23110 (org-agenda-set-restriction-lock 'subtree)))
23111 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23112 'speedbar-function 'speedbar-find-file))
23113 (setq tp (previous-single-property-change
23114 (1+ p) 'speedbar-function)
23115 np (next-single-property-change
23116 tp 'speedbar-function)
23117 dir (speedbar-line-directory)
23118 txt (buffer-substring-no-properties (or tp (point-min))
23119 (or np (point-max))))
23120 (with-current-buffer (find-file-noselect
23121 (let ((default-directory dir))
23122 (expand-file-name txt)))
23123 (unless (derived-mode-p 'org-mode)
23124 (error "Cannot restrict to non-Org-mode file"))
23125 (org-agenda-set-restriction-lock 'file)))
23126 (t (error "Don't know how to restrict Org-mode's agenda")))
23127 (move-overlay org-speedbar-restriction-lock-overlay
23128 (point-at-bol) (point-at-eol))
23129 (setq current-prefix-arg nil)
23130 (org-agenda-maybe-redo)))
23132 (eval-after-load "speedbar"
23133 '(progn
23134 (speedbar-add-supported-extension ".org")
23135 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23136 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23137 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23138 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23139 (add-hook 'speedbar-visiting-tag-hook
23140 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23142 ;;; Fixes and Hacks for problems with other packages
23144 ;; Make flyspell not check words in links, to not mess up our keymap
23145 (defvar org-element-affiliated-keywords) ; From org-element.el
23146 (defvar org-element-block-name-alist) ; From org-element.el
23147 (defun org-mode-flyspell-verify ()
23148 "Don't let flyspell put overlays at active buttons, or on
23149 {todo,all-time,additional-option-like}-keywords."
23150 (let ((pos (max (1- (point)) (point-min)))
23151 (word (thing-at-point 'word)))
23152 (and (not (get-text-property pos 'keymap))
23153 (not (get-text-property pos 'org-no-flyspell))
23154 (not (member word org-todo-keywords-1))
23155 (not (member word org-all-time-keywords))
23156 (not (member word org-options-keywords))
23157 (not (member word (mapcar 'car org-startup-options)))
23158 (not (member-ignore-case word org-element-affiliated-keywords))
23159 (not (member-ignore-case word (org-get-export-keywords)))
23160 (not (member-ignore-case
23161 word (mapcar 'car org-element-block-name-alist)))
23162 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23164 (defun org-remove-flyspell-overlays-in (beg end)
23165 "Remove flyspell overlays in region."
23166 (and (org-bound-and-true-p flyspell-mode)
23167 (fboundp 'flyspell-delete-region-overlays)
23168 (flyspell-delete-region-overlays beg end))
23169 (add-text-properties beg end '(org-no-flyspell t)))
23171 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23172 (eval-after-load "bookmark"
23173 '(if (boundp 'bookmark-after-jump-hook)
23174 ;; We can use the hook
23175 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23176 ;; Hook not available, use advice
23177 (defadvice bookmark-jump (after org-make-visible activate)
23178 "Make the position visible."
23179 (org-bookmark-jump-unhide))))
23181 ;; Make sure saveplace shows the location if it was hidden
23182 (eval-after-load "saveplace"
23183 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23184 "Make the position visible."
23185 (org-bookmark-jump-unhide)))
23187 ;; Make sure ecb shows the location if it was hidden
23188 (eval-after-load "ecb"
23189 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23190 "Make hierarchy visible when jumping into location from ECB tree buffer."
23191 (if (derived-mode-p 'org-mode)
23192 (org-show-context))))
23194 (defun org-bookmark-jump-unhide ()
23195 "Unhide the current position, to show the bookmark location."
23196 (and (derived-mode-p 'org-mode)
23197 (or (outline-invisible-p)
23198 (save-excursion (goto-char (max (point-min) (1- (point))))
23199 (outline-invisible-p)))
23200 (org-show-context 'bookmark-jump)))
23202 ;; Make session.el ignore our circular variable
23203 (eval-after-load "session"
23204 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23206 ;;;; Experimental code
23208 (defun org-closed-in-range ()
23209 "Sparse tree of items closed in a certain time range.
23210 Still experimental, may disappear in the future."
23211 (interactive)
23212 ;; Get the time interval from the user.
23213 (let* ((time1 (org-float-time
23214 (org-read-date nil 'to-time nil "Starting date: ")))
23215 (time2 (org-float-time
23216 (org-read-date nil 'to-time nil "End date:")))
23217 ;; callback function
23218 (callback (lambda ()
23219 (let ((time
23220 (org-float-time
23221 (apply 'encode-time
23222 (org-parse-time-string
23223 (match-string 1))))))
23224 ;; check if time in interval
23225 (and (>= time time1) (<= time time2))))))
23226 ;; make tree, check each match with the callback
23227 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23229 ;;;; Finish up
23231 (provide 'org)
23233 (run-hooks 'org-load-hook)
23235 ;;; org.el ends here