Fix commit 128e14b
[org-mode.git] / lisp / org.el
blob07fe8340dd955e0805732e86c7df4491813c465f
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-type "org-element" (element))
161 ;; load languages based on value of `org-babel-load-languages'
162 (defvar org-babel-load-languages)
164 ;;;###autoload
165 (defun org-babel-do-load-languages (sym value)
166 "Load the languages defined in `org-babel-load-languages'."
167 (set-default sym value)
168 (mapc (lambda (pair)
169 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
170 (if active
171 (progn
172 (require (intern (concat "ob-" lang))))
173 (progn
174 (funcall 'fmakunbound
175 (intern (concat "org-babel-execute:" lang)))
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-expand-body:" lang)))))))
178 org-babel-load-languages))
180 (defcustom org-babel-load-languages '((emacs-lisp . t))
181 "Languages which can be evaluated in Org-mode buffers.
182 This list can be used to load support for any of the languages
183 below, note that each language will depend on a different set of
184 system executables and/or Emacs modes. When a language is
185 \"loaded\", then code blocks in that language can be evaluated
186 with `org-babel-execute-src-block' bound by default to C-c
187 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
188 be set to remove code block evaluation from the C-c C-c
189 keybinding. By default only Emacs Lisp (which has no
190 requirements) is loaded."
191 :group 'org-babel
192 :set 'org-babel-do-load-languages
193 :version "24.1"
194 :type '(alist :tag "Babel Languages"
195 :key-type
196 (choice
197 (const :tag "Awk" awk)
198 (const :tag "C" C)
199 (const :tag "R" R)
200 (const :tag "Asymptote" asymptote)
201 (const :tag "Calc" calc)
202 (const :tag "Clojure" clojure)
203 (const :tag "CSS" css)
204 (const :tag "Ditaa" ditaa)
205 (const :tag "Dot" dot)
206 (const :tag "Emacs Lisp" emacs-lisp)
207 (const :tag "Fortran" fortran)
208 (const :tag "Gnuplot" gnuplot)
209 (const :tag "Haskell" haskell)
210 (const :tag "IO" io)
211 (const :tag "Java" java)
212 (const :tag "Javascript" js)
213 (const :tag "LaTeX" latex)
214 (const :tag "Ledger" ledger)
215 (const :tag "Lilypond" lilypond)
216 (const :tag "Lisp" lisp)
217 (const :tag "Makefile" makefile)
218 (const :tag "Maxima" maxima)
219 (const :tag "Matlab" matlab)
220 (const :tag "Mscgen" mscgen)
221 (const :tag "Ocaml" ocaml)
222 (const :tag "Octave" octave)
223 (const :tag "Org" org)
224 (const :tag "Perl" perl)
225 (const :tag "Pico Lisp" picolisp)
226 (const :tag "PlantUML" plantuml)
227 (const :tag "Python" python)
228 (const :tag "Ruby" ruby)
229 (const :tag "Sass" sass)
230 (const :tag "Scala" scala)
231 (const :tag "Scheme" scheme)
232 (const :tag "Screen" screen)
233 (const :tag "Shell Script" sh)
234 (const :tag "Shen" shen)
235 (const :tag "Sql" sql)
236 (const :tag "Sqlite" sqlite))
237 :value-type (boolean :tag "Activate" :value t)))
239 ;;;; Customization variables
240 (defcustom org-clone-delete-id nil
241 "Remove ID property of clones of a subtree.
242 When non-nil, clones of a subtree don't inherit the ID property.
243 Otherwise they inherit the ID property with a new unique
244 identifier."
245 :type 'boolean
246 :version "24.1"
247 :group 'org-id)
249 ;;; Version
250 (org-check-version)
252 ;;;###autoload
253 (defun org-version (&optional here full message)
254 "Show the org-mode version in the echo area.
255 With prefix argument HERE, insert it at point.
256 When FULL is non-nil, use a verbose version string.
257 When MESSAGE is non-nil, display a message with the version."
258 (interactive "P")
259 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
260 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
261 (load-suffixes (list ".el"))
262 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
263 (org-trash (or
264 (and (fboundp 'org-release) (fboundp 'org-git-version))
265 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
266 (load-suffixes save-load-suffixes)
267 (org-version (org-release))
268 (git-version (org-git-version))
269 (version (format "Org-mode version %s (%s @ %s)"
270 org-version
271 git-version
272 (if org-install-dir
273 (if (string= org-dir org-install-dir)
274 org-install-dir
275 (concat "mixed installation! " org-install-dir " and " org-dir))
276 "org-loaddefs.el can not be found!")))
277 (_version (if full version org-version)))
278 (if (org-called-interactively-p 'interactive)
279 (if here
280 (insert version)
281 (message version))
282 (if message (message _version))
283 _version)))
285 (defconst org-version (org-version))
287 ;;; Compatibility constants
289 ;;; The custom variables
291 (defgroup org nil
292 "Outline-based notes management and organizer."
293 :tag "Org"
294 :group 'outlines
295 :group 'calendar)
297 (defcustom org-mode-hook nil
298 "Mode hook for Org-mode, run after the mode was turned on."
299 :group 'org
300 :type 'hook)
302 (defcustom org-load-hook nil
303 "Hook that is run after org.el has been loaded."
304 :group 'org
305 :type 'hook)
307 (defcustom org-log-buffer-setup-hook nil
308 "Hook that is run after an Org log buffer is created."
309 :group 'org
310 :version "24.1"
311 :type 'hook)
313 (defvar org-modules) ; defined below
314 (defvar org-modules-loaded nil
315 "Have the modules been loaded already?")
317 (defun org-load-modules-maybe (&optional force)
318 "Load all extensions listed in `org-modules'."
319 (when (or force (not org-modules-loaded))
320 (mapc (lambda (ext)
321 (condition-case nil (require ext)
322 (error (message "Problems while trying to load feature `%s'" ext))))
323 org-modules)
324 (setq org-modules-loaded t)))
326 (defun org-set-modules (var value)
327 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
328 (set var value)
329 (when (featurep 'org)
330 (org-load-modules-maybe 'force)))
332 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
333 "Modules that should always be loaded together with org.el.
335 If a description starts with <C>, the file is not part of Emacs
336 and loading it will require that you have downloaded and properly
337 installed the Org mode distribution.
339 You can also use this system to load external packages (i.e. neither Org
340 core modules, nor modules from the CONTRIB directory). Just add symbols
341 to the end of the list. If the package is called org-xyz.el, then you need
342 to add the symbol `xyz', and the package must have a call to:
344 \(provide 'org-xyz)
346 For export specific modules, see also `org-export-backends'."
347 :group 'org
348 :set 'org-set-modules
349 :type
350 '(set :greedy t
351 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
352 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
353 (const :tag " crypt: Encryption of subtrees" org-crypt)
354 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
355 (const :tag " docview: Links to doc-view buffers" org-docview)
356 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
357 (const :tag " id: Global IDs for identifying entries" org-id)
358 (const :tag " info: Links to Info nodes" org-info)
359 (const :tag " habit: Track your consistency with habits" org-habit)
360 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
361 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
362 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
363 (const :tag " mew Links to Mew folders/messages" org-mew)
364 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
365 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
366 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
367 (const :tag " vm: Links to VM folders/messages" org-vm)
368 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
369 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
370 (const :tag " mouse: Additional mouse support" org-mouse)
372 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
373 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
374 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
375 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
376 (const :tag "C collector: Collect properties into tables" org-collector)
377 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
378 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
379 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
380 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
381 (const :tag "C eval: Include command output as text" org-eval)
382 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
383 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
384 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
385 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
386 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
388 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
390 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
391 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
392 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
393 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
394 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
395 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
396 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
397 (const :tag "C mtags: Support for muse-like tags" org-mtags)
398 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
399 (const :tag "C registry: A registry for Org-mode links" org-registry)
400 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
401 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
402 (const :tag "C secretary: Team management with org-mode" org-secretary)
403 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
404 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
405 (const :tag "C track: Keep up with Org-mode development" org-track)
406 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
407 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
408 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
410 (defvar org-export-registered-backends) ; From ox.el
411 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
412 (defcustom org-export-backends '(ascii html icalendar latex)
413 "List of export back-ends that should be always available.
415 If a description starts with <C>, the file is not part of Emacs
416 and loading it will require that you have downloaded and properly
417 installed the Org mode distribution.
419 Unlike to `org-modules', libraries in this list will not be
420 loaded along with Org, but only once the export framework is
421 needed.
423 This variable needs to be set before org.el is loaded. If you
424 need to make a change while Emacs is running, use the customize
425 interface or run the following code, where VALUE stands for the
426 new value of the variable, after updating it:
428 \(progn
429 \(setq org-export-registered-backends
430 \(org-remove-if-not
431 \(lambda (backend)
432 \(or (memq backend val)
433 \(catch 'parentp
434 \(mapc
435 \(lambda (b)
436 \(and (org-export-derived-backend-p b (car backend))
437 \(throw 'parentp t)))
438 val)
439 nil)))
440 org-export-registered-backends))
441 \(let ((new-list (mapcar 'car org-export-registered-backends)))
442 \(dolist (backend val)
443 \(cond
444 \((not (load (format \"ox-%s\" backend) t t))
445 \(message \"Problems while trying to load export back-end `%s'\"
446 backend))
447 \((not (memq backend new-list)) (push backend new-list))))
448 \(set-default var new-list)))
450 Adding a back-end to this list will also pull the back-end it
451 depends on, if any."
452 :group 'org
453 :group 'org-export
454 :set (lambda (var val)
455 (if (not (featurep 'ox)) (set-default var val)
456 ;; Any back-end not required anymore (not present in VAL and not
457 ;; a parent of any back-end in the new value) is removed from the
458 ;; list of registered back-ends.
459 (setq org-export-registered-backends
460 (org-remove-if-not
461 (lambda (backend)
462 (or (memq backend val)
463 (catch 'parentp
464 (mapc
465 (lambda (b)
466 (and (org-export-derived-backend-p b (car backend))
467 (throw 'parentp t)))
468 val)
469 nil)))
470 org-export-registered-backends))
471 ;; Now build NEW-LIST of both new back-ends and required
472 ;; parents.
473 (let ((new-list (mapcar 'car org-export-registered-backends)))
474 (dolist (backend val)
475 (cond
476 ((not (load (format "ox-%s" backend) t t))
477 (message "Problems while trying to load export back-end `%s'"
478 backend))
479 ((not (memq backend new-list)) (push backend new-list))))
480 ;; Set VAR to that list with fixed dependencies.
481 (set-default var new-list))))
482 :type '(set :greedy t
483 (const :tag " ascii Export buffer to ASCII format" ascii)
484 (const :tag " beamer Export buffer to Beamer presentation" beamer)
485 (const :tag " html Export buffer to HTML format" html)
486 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
487 (const :tag " latex Export buffer to LaTeX format" latex)
488 (const :tag " man Export buffer to MAN format" man)
489 (const :tag " md Export buffer to Markdown format" md)
490 (const :tag " odt Export buffer to ODT format" odt)
491 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
492 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
493 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
494 (const :tag "C groff Export buffer to Groff format" groff)
495 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
496 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything
591 By default, this option is ignored when Org opens agenda files
592 for the first time. If you want the agenda to honor the startup
593 option, set `org-agenda-inhibit-startup' to nil."
594 :group 'org-startup
595 :type '(choice
596 (const :tag "nofold: show all" nil)
597 (const :tag "fold: overview" t)
598 (const :tag "content: all headlines" content)
599 (const :tag "show everything, even drawers" showeverything)))
601 (defcustom org-startup-truncated t
602 "Non-nil means entering Org-mode will set `truncate-lines'.
603 This is useful since some lines containing links can be very long and
604 uninteresting. Also tables look terrible when wrapped."
605 :group 'org-startup
606 :type 'boolean)
608 (defcustom org-startup-indented nil
609 "Non-nil means turn on `org-indent-mode' on startup.
610 This can also be configured on a per-file basis by adding one of
611 the following lines anywhere in the buffer:
613 #+STARTUP: indent
614 #+STARTUP: noindent"
615 :group 'org-structure
616 :type '(choice
617 (const :tag "Not" nil)
618 (const :tag "Globally (slow on startup in large files)" t)))
620 (defcustom org-use-sub-superscripts t
621 "Non-nil means interpret \"_\" and \"^\" for display.
622 When this option is turned on, you can use TeX-like syntax for sub- and
623 superscripts. Several characters after \"_\" or \"^\" will be
624 considered as a single item - so grouping with {} is normally not
625 needed. For example, the following things will be parsed as single
626 sub- or superscripts.
628 10^24 or 10^tau several digits will be considered 1 item.
629 10^-12 or 10^-tau a leading sign with digits or a word
630 x^2-y^3 will be read as x^2 - y^3, because items are
631 terminated by almost any nonword/nondigit char.
632 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
634 Still, ambiguity is possible - so when in doubt use {} to enclose
635 the sub/superscript. If you set this variable to the symbol
636 `{}', the braces are *required* in order to trigger
637 interpretations as sub/superscript. This can be helpful in
638 documents that need \"_\" frequently in plain text."
639 :group 'org-startup
640 :version "24.1"
641 :type '(choice
642 (const :tag "Always interpret" t)
643 (const :tag "Only with braces" {})
644 (const :tag "Never interpret" nil)))
646 (defcustom org-startup-with-beamer-mode nil
647 "Non-nil means turn on `org-beamer-mode' on startup.
648 This can also be configured on a per-file basis by adding one of
649 the following lines anywhere in the buffer:
651 #+STARTUP: beamer"
652 :group 'org-startup
653 :version "24.1"
654 :type 'boolean)
656 (defcustom org-startup-align-all-tables nil
657 "Non-nil means align all tables when visiting a file.
658 This is useful when the column width in tables is forced with <N> cookies
659 in table fields. Such tables will look correct only after the first re-align.
660 This can also be configured on a per-file basis by adding one of
661 the following lines anywhere in the buffer:
662 #+STARTUP: align
663 #+STARTUP: noalign"
664 :group 'org-startup
665 :type 'boolean)
667 (defcustom org-startup-with-inline-images nil
668 "Non-nil means show inline images when loading a new Org file.
669 This can also be configured on a per-file basis by adding one of
670 the following lines anywhere in the buffer:
671 #+STARTUP: inlineimages
672 #+STARTUP: noinlineimages"
673 :group 'org-startup
674 :version "24.1"
675 :type 'boolean)
677 (defcustom org-startup-with-latex-preview nil
678 "Non-nil means preview LaTeX fragments when loading a new Org file.
680 This can also be configured on a per-file basis by adding one of
681 the followinglines anywhere in the buffer:
682 #+STARTUP: latexpreview
683 #+STARTUP: nolatexpreview"
684 :group 'org-startup
685 :version "24.4"
686 :package-version '(Org . "8.0")
687 :type 'boolean)
689 (defcustom org-insert-mode-line-in-empty-file nil
690 "Non-nil means insert the first line setting Org-mode in empty files.
691 When the function `org-mode' is called interactively in an empty file, this
692 normally means that the file name does not automatically trigger Org-mode.
693 To ensure that the file will always be in Org-mode in the future, a
694 line enforcing Org-mode will be inserted into the buffer, if this option
695 has been set."
696 :group 'org-startup
697 :type 'boolean)
699 (defcustom org-replace-disputed-keys nil
700 "Non-nil means use alternative key bindings for some keys.
701 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
702 These keys are also used by other packages like shift-selection-mode'
703 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
704 If you want to use Org-mode together with one of these other modes,
705 or more generally if you would like to move some Org-mode commands to
706 other keys, set this variable and configure the keys with the variable
707 `org-disputed-keys'.
709 This option is only relevant at load-time of Org-mode, and must be set
710 *before* org.el is loaded. Changing it requires a restart of Emacs to
711 become effective."
712 :group 'org-startup
713 :type 'boolean)
715 (defcustom org-use-extra-keys nil
716 "Non-nil means use extra key sequence definitions for certain commands.
717 This happens automatically if you run XEmacs or if `window-system'
718 is nil. This variable lets you do the same manually. You must
719 set it before loading org.
721 Example: on Carbon Emacs 22 running graphically, with an external
722 keyboard on a Powerbook, the default way of setting M-left might
723 not work for either Alt or ESC. Setting this variable will make
724 it work for ESC."
725 :group 'org-startup
726 :type 'boolean)
728 (if (fboundp 'defvaralias)
729 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
731 (defcustom org-disputed-keys
732 '(([(shift up)] . [(meta p)])
733 ([(shift down)] . [(meta n)])
734 ([(shift left)] . [(meta -)])
735 ([(shift right)] . [(meta +)])
736 ([(control shift right)] . [(meta shift +)])
737 ([(control shift left)] . [(meta shift -)]))
738 "Keys for which Org-mode and other modes compete.
739 This is an alist, cars are the default keys, second element specifies
740 the alternative to use when `org-replace-disputed-keys' is t.
742 Keys can be specified in any syntax supported by `define-key'.
743 The value of this option takes effect only at Org-mode's startup,
744 therefore you'll have to restart Emacs to apply it after changing."
745 :group 'org-startup
746 :type 'alist)
748 (defun org-key (key)
749 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
750 Or return the original if not disputed.
751 Also apply the translations defined in `org-xemacs-key-equivalents'."
752 (when org-replace-disputed-keys
753 (let* ((nkey (key-description key))
754 (x (org-find-if (lambda (x)
755 (equal (key-description (car x)) nkey))
756 org-disputed-keys)))
757 (setq key (if x (cdr x) key))))
758 (when (featurep 'xemacs)
759 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
760 key)
762 (defun org-find-if (predicate seq)
763 (catch 'exit
764 (while seq
765 (if (funcall predicate (car seq))
766 (throw 'exit (car seq))
767 (pop seq)))))
769 (defun org-defkey (keymap key def)
770 "Define a key, possibly translated, as returned by `org-key'."
771 (define-key keymap (org-key key) def))
773 (defcustom org-ellipsis nil
774 "The ellipsis to use in the Org-mode outline.
775 When nil, just use the standard three dots. When a string, use that instead,
776 When a face, use the standard 3 dots, but with the specified face.
777 The change affects only Org-mode (which will then use its own display table).
778 Changing this requires executing `M-x org-mode' in a buffer to become
779 effective."
780 :group 'org-startup
781 :type '(choice (const :tag "Default" nil)
782 (face :tag "Face" :value org-warning)
783 (string :tag "String" :value "...#")))
785 (defvar org-display-table nil
786 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
788 (defgroup org-keywords nil
789 "Keywords in Org-mode."
790 :tag "Org Keywords"
791 :group 'org)
793 (defcustom org-deadline-string "DEADLINE:"
794 "String to mark deadline entries.
795 A deadline is this string, followed by a time stamp. Should be a word,
796 terminated by a colon. You can insert a schedule keyword and
797 a timestamp with \\[org-deadline].
798 Changes become only effective after restarting Emacs."
799 :group 'org-keywords
800 :type 'string)
802 (defcustom org-scheduled-string "SCHEDULED:"
803 "String to mark scheduled TODO entries.
804 A schedule is this string, followed by a time stamp. Should be a word,
805 terminated by a colon. You can insert a schedule keyword and
806 a timestamp with \\[org-schedule].
807 Changes become only effective after restarting Emacs."
808 :group 'org-keywords
809 :type 'string)
811 (defcustom org-closed-string "CLOSED:"
812 "String used as the prefix for timestamps logging closing a TODO entry."
813 :group 'org-keywords
814 :type 'string)
816 (defcustom org-clock-string "CLOCK:"
817 "String used as prefix for timestamps clocking work hours on an item."
818 :group 'org-keywords
819 :type 'string)
821 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
822 org-scheduled-string "\\|"
823 org-deadline-string "\\|"
824 org-closed-string "\\|"
825 org-clock-string "\\)")
826 "Matches a line with planning or clock info.")
828 (defcustom org-comment-string "COMMENT"
829 "Entries starting with this keyword will never be exported.
830 An entry can be toggled between COMMENT and normal with
831 \\[org-toggle-comment].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-quote-string "QUOTE"
837 "Entries starting with this keyword will be exported in fixed-width font.
838 Quoting applies only to the text in the entry following the headline, and does
839 not extend beyond the next headline, even if that is lower level.
840 An entry can be toggled between QUOTE and normal with
841 \\[org-toggle-fixed-width-section]."
842 :group 'org-keywords
843 :type 'string)
845 (defconst org-repeat-re
846 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
847 "Regular expression for specifying repeated events.
848 After a match, group 1 contains the repeat expression.")
850 (defgroup org-structure nil
851 "Options concerning the general structure of Org-mode files."
852 :tag "Org Structure"
853 :group 'org)
855 (defgroup org-reveal-location nil
856 "Options about how to make context of a location visible."
857 :tag "Org Reveal Location"
858 :group 'org-structure)
860 (defconst org-context-choice
861 '(choice
862 (const :tag "Always" t)
863 (const :tag "Never" nil)
864 (repeat :greedy t :tag "Individual contexts"
865 (cons
866 (choice :tag "Context"
867 (const agenda)
868 (const org-goto)
869 (const occur-tree)
870 (const tags-tree)
871 (const link-search)
872 (const mark-goto)
873 (const bookmark-jump)
874 (const isearch)
875 (const default))
876 (boolean))))
877 "Contexts for the reveal options.")
879 (defcustom org-show-hierarchy-above '((default . t))
880 "Non-nil means show full hierarchy when revealing a location.
881 Org-mode often shows locations in an org-mode file which might have
882 been invisible before. When this is set, the hierarchy of headings
883 above the exposed location is shown.
884 Turning this off for example for sparse trees makes them very compact.
885 Instead of t, this can also be an alist specifying this option for different
886 contexts. Valid contexts are
887 agenda when exposing an entry from the agenda
888 org-goto when using the command `org-goto' on key C-c C-j
889 occur-tree when using the command `org-occur' on key C-c /
890 tags-tree when constructing a sparse tree based on tags matches
891 link-search when exposing search matches associated with a link
892 mark-goto when exposing the jump goal of a mark
893 bookmark-jump when exposing a bookmark location
894 isearch when exiting from an incremental search
895 default default for all contexts not set explicitly"
896 :group 'org-reveal-location
897 :type org-context-choice)
899 (defcustom org-show-following-heading '((default . nil))
900 "Non-nil means show following heading when revealing a location.
901 Org-mode often shows locations in an org-mode file which might have
902 been invisible before. When this is set, the heading following the
903 match is shown.
904 Turning this off for example for sparse trees makes them very compact,
905 but makes it harder to edit the location of the match. In such a case,
906 use the command \\[org-reveal] to show more context.
907 Instead of t, this can also be an alist specifying this option for different
908 contexts. See `org-show-hierarchy-above' for valid contexts."
909 :group 'org-reveal-location
910 :type org-context-choice)
912 (defcustom org-show-siblings '((default . nil) (isearch t))
913 "Non-nil means show all sibling heading when revealing a location.
914 Org-mode often shows locations in an org-mode file which might have
915 been invisible before. When this is set, the sibling of the current entry
916 heading are all made visible. If `org-show-hierarchy-above' is t,
917 the same happens on each level of the hierarchy above the current entry.
919 By default this is on for the isearch context, off for all other contexts.
920 Turning this off for example for sparse trees makes them very compact,
921 but makes it harder to edit the location of the match. In such a case,
922 use the command \\[org-reveal] to show more context.
923 Instead of t, this can also be an alist specifying this option for different
924 contexts. See `org-show-hierarchy-above' for valid contexts."
925 :group 'org-reveal-location
926 :type org-context-choice)
928 (defcustom org-show-entry-below '((default . nil))
929 "Non-nil means show the entry below a headline when revealing a location.
930 Org-mode often shows locations in an org-mode file which might have
931 been invisible before. When this is set, the text below the headline that is
932 exposed is also shown.
934 By default this is off for all contexts.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. See `org-show-hierarchy-above' for valid contexts."
937 :group 'org-reveal-location
938 :type org-context-choice)
940 (defcustom org-indirect-buffer-display 'other-window
941 "How should indirect tree buffers be displayed?
942 This applies to indirect buffers created with the commands
943 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
944 Valid values are:
945 current-window Display in the current window
946 other-window Just display in another window.
947 dedicated-frame Create one new frame, and re-use it each time.
948 new-frame Make a new frame each time. Note that in this case
949 previously-made indirect buffers are kept, and you need to
950 kill these buffers yourself."
951 :group 'org-structure
952 :group 'org-agenda-windows
953 :type '(choice
954 (const :tag "In current window" current-window)
955 (const :tag "In current frame, other window" other-window)
956 (const :tag "Each time a new frame" new-frame)
957 (const :tag "One dedicated frame" dedicated-frame)))
959 (defcustom org-use-speed-commands nil
960 "Non-nil means activate single letter commands at beginning of a headline.
961 This may also be a function to test for appropriate locations where speed
962 commands should be active."
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Never" nil)
966 (const :tag "At beginning of headline stars" t)
967 (function)))
969 (defcustom org-speed-commands-user nil
970 "Alist of additional speed commands.
971 This list will be checked before `org-speed-commands-default'
972 when the variable `org-use-speed-commands' is non-nil
973 and when the cursor is at the beginning of a headline.
974 The car if each entry is a string with a single letter, which must
975 be assigned to `self-insert-command' in the global map.
976 The cdr is either a command to be called interactively, a function
977 to be called, or a form to be evaluated.
978 An entry that is just a list with a single string will be interpreted
979 as a descriptive headline that will be added when listing the speed
980 commands in the Help buffer using the `?' speed command."
981 :group 'org-structure
982 :type '(repeat :value ("k" . ignore)
983 (choice :value ("k" . ignore)
984 (list :tag "Descriptive Headline" (string :tag "Headline"))
985 (cons :tag "Letter and Command"
986 (string :tag "Command letter")
987 (choice
988 (function)
989 (sexp))))))
991 (defgroup org-cycle nil
992 "Options concerning visibility cycling in Org-mode."
993 :tag "Org Cycle"
994 :group 'org-structure)
996 (defcustom org-cycle-skip-children-state-if-no-children t
997 "Non-nil means skip CHILDREN state in entries that don't have any."
998 :group 'org-cycle
999 :type 'boolean)
1001 (defcustom org-cycle-max-level nil
1002 "Maximum level which should still be subject to visibility cycling.
1003 Levels higher than this will, for cycling, be treated as text, not a headline.
1004 When `org-odd-levels-only' is set, a value of N in this variable actually
1005 means 2N-1 stars as the limiting headline.
1006 When nil, cycle all levels.
1007 Note that the limiting level of cycling is also influenced by
1008 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1009 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1010 than its value."
1011 :group 'org-cycle
1012 :type '(choice
1013 (const :tag "No limit" nil)
1014 (integer :tag "Maximum level")))
1016 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1017 "Names of drawers. Drawers are not opened by cycling on the headline above.
1018 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1019 this:
1020 :DRAWERNAME:
1021 .....
1022 :END:
1023 The drawer \"PROPERTIES\" is special for capturing properties through
1024 the property API.
1026 Drawers can be defined on the per-file basis with a line like:
1028 #+DRAWERS: HIDDEN STATE PROPERTIES"
1029 :group 'org-structure
1030 :group 'org-cycle
1031 :type '(repeat (string :tag "Drawer Name")))
1033 (defcustom org-hide-block-startup nil
1034 "Non-nil means entering Org-mode will fold all blocks.
1035 This can also be set in on a per-file basis with
1037 #+STARTUP: hideblocks
1038 #+STARTUP: showblocks"
1039 :group 'org-startup
1040 :group 'org-cycle
1041 :type 'boolean)
1043 (defcustom org-cycle-global-at-bob nil
1044 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1045 This makes it possible to do global cycling without having to use S-TAB or
1046 \\[universal-argument] TAB. For this special case to work, the first line
1047 of the buffer must not be a headline -- it may be empty or some other text.
1048 When used in this way, `org-cycle-hook' is disabled temporarily to make
1049 sure the cursor stays at the beginning of the buffer. When this option is
1050 nil, don't do anything special at the beginning of the buffer."
1051 :group 'org-cycle
1052 :type 'boolean)
1054 (defcustom org-cycle-level-after-item/entry-creation t
1055 "Non-nil means cycle entry level or item indentation in new empty entries.
1057 When the cursor is at the end of an empty headline, i.e., with only stars
1058 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1059 and then all possible ancestor states, before returning to the original state.
1060 This makes data entry extremely fast: M-RET to create a new headline,
1061 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1063 When the cursor is at the end of an empty plain list item, one TAB will
1064 make it a subitem, two or more tabs will back up to make this an item
1065 higher up in the item hierarchy."
1066 :group 'org-cycle
1067 :type 'boolean)
1069 (defcustom org-cycle-emulate-tab t
1070 "Where should `org-cycle' emulate TAB.
1071 nil Never
1072 white Only in completely white lines
1073 whitestart Only at the beginning of lines, before the first non-white char
1074 t Everywhere except in headlines
1075 exc-hl-bol Everywhere except at the start of a headline
1076 If TAB is used in a place where it does not emulate TAB, the current subtree
1077 visibility is cycled."
1078 :group 'org-cycle
1079 :type '(choice (const :tag "Never" nil)
1080 (const :tag "Only in completely white lines" white)
1081 (const :tag "Before first char in a line" whitestart)
1082 (const :tag "Everywhere except in headlines" t)
1083 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1086 (defcustom org-cycle-separator-lines 2
1087 "Number of empty lines needed to keep an empty line between collapsed trees.
1088 If you leave an empty line between the end of a subtree and the following
1089 headline, this empty line is hidden when the subtree is folded.
1090 Org-mode will leave (exactly) one empty line visible if the number of
1091 empty lines is equal or larger to the number given in this variable.
1092 So the default 2 means at least 2 empty lines after the end of a subtree
1093 are needed to produce free space between a collapsed subtree and the
1094 following headline.
1096 If the number is negative, and the number of empty lines is at least -N,
1097 all empty lines are shown.
1099 Special case: when 0, never leave empty lines in collapsed view."
1100 :group 'org-cycle
1101 :type 'integer)
1102 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1104 (defcustom org-pre-cycle-hook nil
1105 "Hook that is run before visibility cycling is happening.
1106 The function(s) in this hook must accept a single argument which indicates
1107 the new state that will be set right after running this hook. The
1108 argument is a symbol. Before a global state change, it can have the values
1109 `overview', `content', or `all'. Before a local state change, it can have
1110 the values `folded', `children', or `subtree'."
1111 :group 'org-cycle
1112 :type 'hook)
1114 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1115 org-cycle-hide-drawers
1116 org-cycle-hide-inline-tasks
1117 org-cycle-show-empty-lines
1118 org-optimize-window-after-visibility-change)
1119 "Hook that is run after `org-cycle' has changed the buffer visibility.
1120 The function(s) in this hook must accept a single argument which indicates
1121 the new state that was set by the most recent `org-cycle' command. The
1122 argument is a symbol. After a global state change, it can have the values
1123 `overview', `contents', or `all'. After a local state change, it can have
1124 the values `folded', `children', or `subtree'."
1125 :group 'org-cycle
1126 :type 'hook)
1128 (defgroup org-edit-structure nil
1129 "Options concerning structure editing in Org-mode."
1130 :tag "Org Edit Structure"
1131 :group 'org-structure)
1133 (defcustom org-odd-levels-only nil
1134 "Non-nil means skip even levels and only use odd levels for the outline.
1135 This has the effect that two stars are being added/taken away in
1136 promotion/demotion commands. It also influences how levels are
1137 handled by the exporters.
1138 Changing it requires restart of `font-lock-mode' to become effective
1139 for fontification also in regions already fontified.
1140 You may also set this on a per-file basis by adding one of the following
1141 lines to the buffer:
1143 #+STARTUP: odd
1144 #+STARTUP: oddeven"
1145 :group 'org-edit-structure
1146 :group 'org-appearance
1147 :type 'boolean)
1149 (defcustom org-adapt-indentation t
1150 "Non-nil means adapt indentation to outline node level.
1152 When this variable is set, Org assumes that you write outlines by
1153 indenting text in each node to align with the headline (after the stars).
1154 The following issues are influenced by this variable:
1156 - When this is set and the *entire* text in an entry is indented, the
1157 indentation is increased by one space in a demotion command, and
1158 decreased by one in a promotion command. If any line in the entry
1159 body starts with text at column 0, indentation is not changed at all.
1161 - Property drawers and planning information is inserted indented when
1162 this variable s set. When nil, they will not be indented.
1164 - TAB indents a line relative to context. The lines below a headline
1165 will be indented when this variable is set.
1167 Note that this is all about true indentation, by adding and removing
1168 space characters. See also `org-indent.el' which does level-dependent
1169 indentation in a virtual way, i.e. at display time in Emacs."
1170 :group 'org-edit-structure
1171 :type 'boolean)
1173 (defcustom org-special-ctrl-a/e nil
1174 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1176 When t, `C-a' will bring back the cursor to the beginning of the
1177 headline text, i.e. after the stars and after a possible TODO
1178 keyword. In an item, this will be the position after bullet and
1179 check-box, if any. When the cursor is already at that position,
1180 another `C-a' will bring it to the beginning of the line.
1182 `C-e' will jump to the end of the headline, ignoring the presence
1183 of tags in the headline. A second `C-e' will then jump to the
1184 true end of the line, after any tags. This also means that, when
1185 this variable is non-nil, `C-e' also will never jump beyond the
1186 end of the heading of a folded section, i.e. not after the
1187 ellipses.
1189 When set to the symbol `reversed', the first `C-a' or `C-e' works
1190 normally, going to the true line boundary first. Only a directly
1191 following, identical keypress will bring the cursor to the
1192 special positions.
1194 This may also be a cons cell where the behavior for `C-a' and
1195 `C-e' is set separately."
1196 :group 'org-edit-structure
1197 :type '(choice
1198 (const :tag "off" nil)
1199 (const :tag "on: after stars/bullet and before tags first" t)
1200 (const :tag "reversed: true line boundary first" reversed)
1201 (cons :tag "Set C-a and C-e separately"
1202 (choice :tag "Special C-a"
1203 (const :tag "off" nil)
1204 (const :tag "on: after stars/bullet first" t)
1205 (const :tag "reversed: before stars/bullet first" reversed))
1206 (choice :tag "Special C-e"
1207 (const :tag "off" nil)
1208 (const :tag "on: before tags first" t)
1209 (const :tag "reversed: after tags first" reversed)))))
1210 (if (fboundp 'defvaralias)
1211 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1213 (defcustom org-special-ctrl-k nil
1214 "Non-nil means `C-k' will behave specially in headlines.
1215 When nil, `C-k' will call the default `kill-line' command.
1216 When t, the following will happen while the cursor is in the headline:
1218 - When the cursor is at the beginning of a headline, kill the entire
1219 line and possible the folded subtree below the line.
1220 - When in the middle of the headline text, kill the headline up to the tags.
1221 - When after the headline text, kill the tags."
1222 :group 'org-edit-structure
1223 :type 'boolean)
1225 (defcustom org-ctrl-k-protect-subtree nil
1226 "Non-nil means, do not delete a hidden subtree with C-k.
1227 When set to the symbol `error', simply throw an error when C-k is
1228 used to kill (part-of) a headline that has hidden text behind it.
1229 Any other non-nil value will result in a query to the user, if it is
1230 OK to kill that hidden subtree. When nil, kill without remorse."
1231 :group 'org-edit-structure
1232 :version "24.1"
1233 :type '(choice
1234 (const :tag "Do not protect hidden subtrees" nil)
1235 (const :tag "Protect hidden subtrees with a security query" t)
1236 (const :tag "Never kill a hidden subtree with C-k" error)))
1238 (defcustom org-catch-invisible-edits nil
1239 "Check if in invisible region before inserting or deleting a character.
1240 Valid values are:
1242 nil Do not check, so just do invisible edits.
1243 error Throw an error and do nothing.
1244 show Make point visible, and do the requested edit.
1245 show-and-error Make point visible, then throw an error and abort the edit.
1246 smart Make point visible, and do insertion/deletion if it is
1247 adjacent to visible text and the change feels predictable.
1248 Never delete a previously invisible character or add in the
1249 middle or right after an invisible region. Basically, this
1250 allows insertion and backward-delete right before ellipses.
1251 FIXME: maybe in this case we should not even show?"
1252 :group 'org-edit-structure
1253 :version "24.1"
1254 :type '(choice
1255 (const :tag "Do not check" nil)
1256 (const :tag "Throw error when trying to edit" error)
1257 (const :tag "Unhide, but do not do the edit" show-and-error)
1258 (const :tag "Show invisible part and do the edit" show)
1259 (const :tag "Be smart and do the right thing" smart)))
1261 (defcustom org-yank-folded-subtrees t
1262 "Non-nil means when yanking subtrees, fold them.
1263 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1264 it starts with a heading and all other headings in it are either children
1265 or siblings, then fold all the subtrees. However, do this only if no
1266 text after the yank would be swallowed into a folded tree by this action."
1267 :group 'org-edit-structure
1268 :type 'boolean)
1270 (defcustom org-yank-adjusted-subtrees nil
1271 "Non-nil means when yanking subtrees, adjust the level.
1272 With this setting, `org-paste-subtree' is used to insert the subtree, see
1273 this function for details."
1274 :group 'org-edit-structure
1275 :type 'boolean)
1277 (defcustom org-M-RET-may-split-line '((default . t))
1278 "Non-nil means M-RET will split the line at the cursor position.
1279 When nil, it will go to the end of the line before making a
1280 new line.
1281 You may also set this option in a different way for different
1282 contexts. Valid contexts are:
1284 headline when creating a new headline
1285 item when creating a new item
1286 table in a table field
1287 default the value to be used for all contexts not explicitly
1288 customized"
1289 :group 'org-structure
1290 :group 'org-table
1291 :type '(choice
1292 (const :tag "Always" t)
1293 (const :tag "Never" nil)
1294 (repeat :greedy t :tag "Individual contexts"
1295 (cons
1296 (choice :tag "Context"
1297 (const headline)
1298 (const item)
1299 (const table)
1300 (const default))
1301 (boolean)))))
1304 (defcustom org-insert-heading-respect-content nil
1305 "Non-nil means insert new headings after the current subtree.
1306 When nil, the new heading is created directly after the current line.
1307 The commands \\[org-insert-heading-respect-content] and
1308 \\[org-insert-todo-heading-respect-content] turn this variable on
1309 for the duration of the command."
1310 :group 'org-structure
1311 :type 'boolean)
1313 (defcustom org-blank-before-new-entry '((heading . auto)
1314 (plain-list-item . auto))
1315 "Should `org-insert-heading' leave a blank line before new heading/item?
1316 The value is an alist, with `heading' and `plain-list-item' as CAR,
1317 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1318 which case Org will look at the surrounding headings/items and try to
1319 make an intelligent decision whether to insert a blank line or not.
1321 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1322 set, the setting here is ignored and no empty line is inserted, to avoid
1323 breaking the list structure."
1324 :group 'org-edit-structure
1325 :type '(list
1326 (cons (const heading)
1327 (choice (const :tag "Never" nil)
1328 (const :tag "Always" t)
1329 (const :tag "Auto" auto)))
1330 (cons (const plain-list-item)
1331 (choice (const :tag "Never" nil)
1332 (const :tag "Always" t)
1333 (const :tag "Auto" auto)))))
1335 (defcustom org-insert-heading-hook nil
1336 "Hook being run after inserting a new heading."
1337 :group 'org-edit-structure
1338 :type 'hook)
1340 (defcustom org-enable-fixed-width-editor t
1341 "Non-nil means lines starting with \":\" are treated as fixed-width.
1342 This currently only means they are never auto-wrapped.
1343 When nil, such lines will be treated like ordinary lines.
1344 See also the QUOTE keyword."
1345 :group 'org-edit-structure
1346 :type 'boolean)
1348 (defcustom org-goto-auto-isearch t
1349 "Non-nil means typing characters in `org-goto' starts incremental search.
1350 When nil, you can use these keybindings to navigate the buffer:
1352 q Quit the org-goto interface
1353 n Go to the next visible heading
1354 p Go to the previous visible heading
1355 f Go one heading forward on same level
1356 b Go one heading backward on same level
1357 u Go one heading up"
1358 :group 'org-edit-structure
1359 :type 'boolean)
1361 (defgroup org-sparse-trees nil
1362 "Options concerning sparse trees in Org-mode."
1363 :tag "Org Sparse Trees"
1364 :group 'org-structure)
1366 (defcustom org-highlight-sparse-tree-matches t
1367 "Non-nil means highlight all matches that define a sparse tree.
1368 The highlights will automatically disappear the next time the buffer is
1369 changed by an edit command."
1370 :group 'org-sparse-trees
1371 :type 'boolean)
1373 (defcustom org-remove-highlights-with-change t
1374 "Non-nil means any change to the buffer will remove temporary highlights.
1375 Such highlights are created by `org-occur' and `org-clock-display'.
1376 When nil, `C-c C-c needs to be used to get rid of the highlights.
1377 The highlights created by `org-preview-latex-fragment' always need
1378 `C-c C-c' to be removed."
1379 :group 'org-sparse-trees
1380 :group 'org-time
1381 :type 'boolean)
1384 (defcustom org-occur-hook '(org-first-headline-recenter)
1385 "Hook that is run after `org-occur' has constructed a sparse tree.
1386 This can be used to recenter the window to show as much of the structure
1387 as possible."
1388 :group 'org-sparse-trees
1389 :type 'hook)
1391 (defgroup org-imenu-and-speedbar nil
1392 "Options concerning imenu and speedbar in Org-mode."
1393 :tag "Org Imenu and Speedbar"
1394 :group 'org-structure)
1396 (defcustom org-imenu-depth 2
1397 "The maximum level for Imenu access to Org-mode headlines.
1398 This also applied for speedbar access."
1399 :group 'org-imenu-and-speedbar
1400 :type 'integer)
1402 (defgroup org-table nil
1403 "Options concerning tables in Org-mode."
1404 :tag "Org Table"
1405 :group 'org)
1407 (defcustom org-enable-table-editor 'optimized
1408 "Non-nil means lines starting with \"|\" are handled by the table editor.
1409 When nil, such lines will be treated like ordinary lines.
1411 When equal to the symbol `optimized', the table editor will be optimized to
1412 do the following:
1413 - Automatic overwrite mode in front of whitespace in table fields.
1414 This makes the structure of the table stay in tact as long as the edited
1415 field does not exceed the column width.
1416 - Minimize the number of realigns. Normally, the table is aligned each time
1417 TAB or RET are pressed to move to another field. With optimization this
1418 happens only if changes to a field might have changed the column width.
1419 Optimization requires replacing the functions `self-insert-command',
1420 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1421 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1422 very good at guessing when a re-align will be necessary, but you can always
1423 force one with \\[org-ctrl-c-ctrl-c].
1425 If you would like to use the optimized version in Org-mode, but the
1426 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1428 This variable can be used to turn on and off the table editor during a session,
1429 but in order to toggle optimization, a restart is required.
1431 See also the variable `org-table-auto-blank-field'."
1432 :group 'org-table
1433 :type '(choice
1434 (const :tag "off" nil)
1435 (const :tag "on" t)
1436 (const :tag "on, optimized" optimized)))
1438 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1439 (version<= emacs-version "24.1"))
1440 "Non-nil means cluster self-insert commands for undo when possible.
1441 If this is set, then, like in the Emacs command loop, 20 consecutive
1442 characters will be undone together.
1443 This is configurable, because there is some impact on typing performance."
1444 :group 'org-table
1445 :type 'boolean)
1447 (defcustom org-table-tab-recognizes-table.el t
1448 "Non-nil means TAB will automatically notice a table.el table.
1449 When it sees such a table, it moves point into it and - if necessary -
1450 calls `table-recognize-table'."
1451 :group 'org-table-editing
1452 :type 'boolean)
1454 (defgroup org-link nil
1455 "Options concerning links in Org-mode."
1456 :tag "Org Link"
1457 :group 'org)
1459 (defvar org-link-abbrev-alist-local nil
1460 "Buffer-local version of `org-link-abbrev-alist', which see.
1461 The value of this is taken from the #+LINK lines.")
1462 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1464 (defcustom org-link-abbrev-alist nil
1465 "Alist of link abbreviations.
1466 The car of each element is a string, to be replaced at the start of a link.
1467 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1468 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1470 [[linkkey:tag][description]]
1472 The 'linkkey' must be a word word, starting with a letter, followed
1473 by letters, numbers, '-' or '_'.
1475 If REPLACE is a string, the tag will simply be appended to create the link.
1476 If the string contains \"%s\", the tag will be inserted there. If the string
1477 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1478 at that point (see the function `url-hexify-string'). If the string contains
1479 the specifier \"%(my-function)\", then the custom function `my-function' will
1480 be invoked: this function takes the tag as its only argument and must return
1481 a string.
1483 REPLACE may also be a function that will be called with the tag as the
1484 only argument to create the link, which should be returned as a string.
1486 See the manual for examples."
1487 :group 'org-link
1488 :type '(repeat
1489 (cons
1490 (string :tag "Protocol")
1491 (choice
1492 (string :tag "Format")
1493 (function)))))
1495 (defcustom org-descriptive-links t
1496 "Non-nil means Org will display descriptive links.
1497 E.g. [[http://orgmode.org][Org website]] will be displayed as
1498 \"Org Website\", hiding the link itself and just displaying its
1499 description. When set to `nil', Org will display the full links
1500 literally.
1502 You can interactively set the value of this variable by calling
1503 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1504 :group 'org-link
1505 :type 'boolean)
1507 (defcustom org-link-file-path-type 'adaptive
1508 "How the path name in file links should be stored.
1509 Valid values are:
1511 relative Relative to the current directory, i.e. the directory of the file
1512 into which the link is being inserted.
1513 absolute Absolute path, if possible with ~ for home directory.
1514 noabbrev Absolute path, no abbreviation of home directory.
1515 adaptive Use relative path for files in the current directory and sub-
1516 directories of it. For other files, use an absolute path."
1517 :group 'org-link
1518 :type '(choice
1519 (const relative)
1520 (const absolute)
1521 (const noabbrev)
1522 (const adaptive)))
1524 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1525 "Types of links that should be activated in Org-mode files.
1526 This is a list of symbols, each leading to the activation of a certain link
1527 type. In principle, it does not hurt to turn on most link types - there may
1528 be a small gain when turning off unused link types. The types are:
1530 bracket The recommended [[link][description]] or [[link]] links with hiding.
1531 angle Links in angular brackets that may contain whitespace like
1532 <bbdb:Carsten Dominik>.
1533 plain Plain links in normal text, no whitespace, like http://google.com.
1534 radio Text that is matched by a radio target, see manual for details.
1535 tag Tag settings in a headline (link to tag search).
1536 date Time stamps (link to calendar).
1537 footnote Footnote labels.
1539 Changing this variable requires a restart of Emacs to become effective."
1540 :group 'org-link
1541 :type '(set :greedy t
1542 (const :tag "Double bracket links" bracket)
1543 (const :tag "Angular bracket links" angle)
1544 (const :tag "Plain text links" plain)
1545 (const :tag "Radio target matches" radio)
1546 (const :tag "Tags" tag)
1547 (const :tag "Timestamps" date)
1548 (const :tag "Footnotes" footnote)))
1550 (defcustom org-make-link-description-function nil
1551 "Function to use for generating link descriptions from links.
1552 When nil, the link location will be used. This function must take
1553 two parameters: the first one is the link, the second one is the
1554 description generated by `org-insert-link'. The function should
1555 return the description to use."
1556 :group 'org-link
1557 :type 'function)
1559 (defgroup org-link-store nil
1560 "Options concerning storing links in Org-mode."
1561 :tag "Org Store Link"
1562 :group 'org-link)
1564 (defcustom org-url-hexify-p t
1565 "When non-nil, hexify URL when creating a link."
1566 :type 'boolean
1567 :version "24.3"
1568 :group 'org-link-store)
1570 (defcustom org-email-link-description-format "Email %c: %.30s"
1571 "Format of the description part of a link to an email or usenet message.
1572 The following %-escapes will be replaced by corresponding information:
1574 %F full \"From\" field
1575 %f name, taken from \"From\" field, address if no name
1576 %T full \"To\" field
1577 %t first name in \"To\" field, address if no name
1578 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1579 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1580 %s subject
1581 %d date
1582 %m message-id.
1584 You may use normal field width specification between the % and the letter.
1585 This is for example useful to limit the length of the subject.
1587 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1588 :group 'org-link-store
1589 :type 'string)
1591 (defcustom org-from-is-user-regexp
1592 (let (r1 r2)
1593 (when (and user-mail-address (not (string= user-mail-address "")))
1594 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1595 (when (and user-full-name (not (string= user-full-name "")))
1596 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1597 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1598 "Regexp matched against the \"From:\" header of an email or usenet message.
1599 It should match if the message is from the user him/herself."
1600 :group 'org-link-store
1601 :type 'regexp)
1603 (defcustom org-context-in-file-links t
1604 "Non-nil means file links from `org-store-link' contain context.
1605 A search string will be added to the file name with :: as separator and
1606 used to find the context when the link is activated by the command
1607 `org-open-at-point'. When this option is t, the entire active region
1608 will be placed in the search string of the file link. If set to a
1609 positive integer, only the first n lines of context will be stored.
1611 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1612 negates this setting for the duration of the command."
1613 :group 'org-link-store
1614 :type '(choice boolean integer))
1616 (defcustom org-keep-stored-link-after-insertion nil
1617 "Non-nil means keep link in list for entire session.
1619 The command `org-store-link' adds a link pointing to the current
1620 location to an internal list. These links accumulate during a session.
1621 The command `org-insert-link' can be used to insert links into any
1622 Org-mode file (offering completion for all stored links). When this
1623 option is nil, every link which has been inserted once using \\[org-insert-link]
1624 will be removed from the list, to make completing the unused links
1625 more efficient."
1626 :group 'org-link-store
1627 :type 'boolean)
1629 (defgroup org-link-follow nil
1630 "Options concerning following links in Org-mode."
1631 :tag "Org Follow Link"
1632 :group 'org-link)
1634 (defcustom org-link-translation-function nil
1635 "Function to translate links with different syntax to Org syntax.
1636 This can be used to translate links created for example by the Planner
1637 or emacs-wiki packages to Org syntax.
1638 The function must accept two parameters, a TYPE containing the link
1639 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1640 which is everything after the link protocol. It should return a cons
1641 with possibly modified values of type and path.
1642 Org contains a function for this, so if you set this variable to
1643 `org-translate-link-from-planner', you should be able follow many
1644 links created by planner."
1645 :group 'org-link-follow
1646 :type 'function)
1648 (defcustom org-follow-link-hook nil
1649 "Hook that is run after a link has been followed."
1650 :group 'org-link-follow
1651 :type 'hook)
1653 (defcustom org-tab-follows-link nil
1654 "Non-nil means on links TAB will follow the link.
1655 Needs to be set before org.el is loaded.
1656 This really should not be used, it does not make sense, and the
1657 implementation is bad."
1658 :group 'org-link-follow
1659 :type 'boolean)
1661 (defcustom org-return-follows-link nil
1662 "Non-nil means on links RET will follow the link.
1663 In tables, the special behavior of RET has precedence."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-mouse-1-follows-link
1668 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1669 "Non-nil means mouse-1 on a link will follow the link.
1670 A longer mouse click will still set point. Does not work on XEmacs.
1671 Needs to be set before org.el is loaded."
1672 :group 'org-link-follow
1673 :type 'boolean)
1675 (defcustom org-mark-ring-length 4
1676 "Number of different positions to be recorded in the ring.
1677 Changing this requires a restart of Emacs to work correctly."
1678 :group 'org-link-follow
1679 :type 'integer)
1681 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1682 "Non-nil means internal links in Org files must exactly match a headline.
1683 When nil, the link search tries to match a phrase with all words
1684 in the search text."
1685 :group 'org-link-follow
1686 :version "24.1"
1687 :type '(choice
1688 (const :tag "Use fuzzy text search" nil)
1689 (const :tag "Match only exact headline" t)
1690 (const :tag "Match exact headline or query to create it"
1691 query-to-create)))
1693 (defcustom org-link-frame-setup
1694 '((vm . vm-visit-folder-other-frame)
1695 (vm-imap . vm-visit-imap-folder-other-frame)
1696 (gnus . org-gnus-no-new-news)
1697 (file . find-file-other-window)
1698 (wl . wl-other-frame))
1699 "Setup the frame configuration for following links.
1700 When following a link with Emacs, it may often be useful to display
1701 this link in another window or frame. This variable can be used to
1702 set this up for the different types of links.
1703 For VM, use any of
1704 `vm-visit-folder'
1705 `vm-visit-folder-other-window'
1706 `vm-visit-folder-other-frame'
1707 For Gnus, use any of
1708 `gnus'
1709 `gnus-other-frame'
1710 `org-gnus-no-new-news'
1711 For FILE, use any of
1712 `find-file'
1713 `find-file-other-window'
1714 `find-file-other-frame'
1715 For Wanderlust use any of
1716 `wl'
1717 `wl-other-frame'
1718 For the calendar, use the variable `calendar-setup'.
1719 For BBDB, it is currently only possible to display the matches in
1720 another window."
1721 :group 'org-link-follow
1722 :type '(list
1723 (cons (const vm)
1724 (choice
1725 (const vm-visit-folder)
1726 (const vm-visit-folder-other-window)
1727 (const vm-visit-folder-other-frame)))
1728 (cons (const gnus)
1729 (choice
1730 (const gnus)
1731 (const gnus-other-frame)
1732 (const org-gnus-no-new-news)))
1733 (cons (const file)
1734 (choice
1735 (const find-file)
1736 (const find-file-other-window)
1737 (const find-file-other-frame)))
1738 (cons (const wl)
1739 (choice
1740 (const wl)
1741 (const wl-other-frame)))))
1743 (defcustom org-display-internal-link-with-indirect-buffer nil
1744 "Non-nil means use indirect buffer to display infile links.
1745 Activating internal links (from one location in a file to another location
1746 in the same file) normally just jumps to the location. When the link is
1747 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1748 is displayed in
1749 another window. When this option is set, the other window actually displays
1750 an indirect buffer clone of the current buffer, to avoid any visibility
1751 changes to the current buffer."
1752 :group 'org-link-follow
1753 :type 'boolean)
1755 (defcustom org-open-non-existing-files nil
1756 "Non-nil means `org-open-file' will open non-existing files.
1757 When nil, an error will be generated.
1758 This variable applies only to external applications because they
1759 might choke on non-existing files. If the link is to a file that
1760 will be opened in Emacs, the variable is ignored."
1761 :group 'org-link-follow
1762 :type 'boolean)
1764 (defcustom org-open-directory-means-index-dot-org nil
1765 "Non-nil means a link to a directory really means to index.org.
1766 When nil, following a directory link will run dired or open a finder/explorer
1767 window on that directory."
1768 :group 'org-link-follow
1769 :type 'boolean)
1771 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1772 "Function and arguments to call for following mailto links.
1773 This is a list with the first element being a Lisp function, and the
1774 remaining elements being arguments to the function. In string arguments,
1775 %a will be replaced by the address, and %s will be replaced by the subject
1776 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1777 :group 'org-link-follow
1778 :type '(choice
1779 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1780 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1781 (const :tag "message-mail" (message-mail "%a" "%s"))
1782 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1784 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1785 "Non-nil means ask for confirmation before executing shell links.
1786 Shell links can be dangerous: just think about a link
1788 [[shell:rm -rf ~/*][Google Search]]
1790 This link would show up in your Org-mode document as \"Google Search\",
1791 but really it would remove your entire home directory.
1792 Therefore we advise against setting this variable to nil.
1793 Just change it to `y-or-n-p' if you want to confirm with a
1794 single keystroke rather than having to type \"yes\"."
1795 :group 'org-link-follow
1796 :type '(choice
1797 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1798 (const :tag "with y-or-n (faster)" y-or-n-p)
1799 (const :tag "no confirmation (dangerous)" nil)))
1800 (put 'org-confirm-shell-link-function
1801 'safe-local-variable
1802 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1804 (defcustom org-confirm-shell-link-not-regexp ""
1805 "A regexp to skip confirmation for shell links."
1806 :group 'org-link-follow
1807 :version "24.1"
1808 :type 'regexp)
1810 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1811 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1812 Elisp links can be dangerous: just think about a link
1814 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1816 This link would show up in your Org-mode document as \"Google Search\",
1817 but really it would remove your entire home directory.
1818 Therefore we advise against setting this variable to nil.
1819 Just change it to `y-or-n-p' if you want to confirm with a
1820 single keystroke rather than having to type \"yes\"."
1821 :group 'org-link-follow
1822 :type '(choice
1823 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1824 (const :tag "with y-or-n (faster)" y-or-n-p)
1825 (const :tag "no confirmation (dangerous)" nil)))
1826 (put 'org-confirm-shell-link-function
1827 'safe-local-variable
1828 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1830 (defcustom org-confirm-elisp-link-not-regexp ""
1831 "A regexp to skip confirmation for Elisp links."
1832 :group 'org-link-follow
1833 :version "24.1"
1834 :type 'regexp)
1836 (defconst org-file-apps-defaults-gnu
1837 '((remote . emacs)
1838 (system . mailcap)
1839 (t . mailcap))
1840 "Default file applications on a UNIX or GNU/Linux system.
1841 See `org-file-apps'.")
1843 (defconst org-file-apps-defaults-macosx
1844 '((remote . emacs)
1845 (t . "open %s")
1846 (system . "open %s")
1847 ("ps.gz" . "gv %s")
1848 ("eps.gz" . "gv %s")
1849 ("dvi" . "xdvi %s")
1850 ("fig" . "xfig %s"))
1851 "Default file applications on a MacOS X system.
1852 The system \"open\" is known as a default, but we use X11 applications
1853 for some files for which the OS does not have a good default.
1854 See `org-file-apps'.")
1856 (defconst org-file-apps-defaults-windowsnt
1857 (list
1858 '(remote . emacs)
1859 (cons t
1860 (list (if (featurep 'xemacs)
1861 'mswindows-shell-execute
1862 'w32-shell-execute)
1863 "open" 'file))
1864 (cons 'system
1865 (list (if (featurep 'xemacs)
1866 'mswindows-shell-execute
1867 'w32-shell-execute)
1868 "open" 'file)))
1869 "Default file applications on a Windows NT system.
1870 The system \"open\" is used for most files.
1871 See `org-file-apps'.")
1873 (defcustom org-file-apps
1875 (auto-mode . emacs)
1876 ("\\.mm\\'" . default)
1877 ("\\.x?html?\\'" . default)
1878 ("\\.pdf\\'" . default)
1880 "External applications for opening `file:path' items in a document.
1881 Org-mode uses system defaults for different file types, but
1882 you can use this variable to set the application for a given file
1883 extension. The entries in this list are cons cells where the car identifies
1884 files and the cdr the corresponding command. Possible values for the
1885 file identifier are
1886 \"string\" A string as a file identifier can be interpreted in different
1887 ways, depending on its contents:
1889 - Alphanumeric characters only:
1890 Match links with this file extension.
1891 Example: (\"pdf\" . \"evince %s\")
1892 to open PDFs with evince.
1894 - Regular expression: Match links where the
1895 filename matches the regexp. If you want to
1896 use groups here, use shy groups.
1898 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1899 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1900 to open *.html and *.xhtml with firefox.
1902 - Regular expression which contains (non-shy) groups:
1903 Match links where the whole link, including \"::\", and
1904 anything after that, matches the regexp.
1905 In a custom command string, %1, %2, etc. are replaced with
1906 the parts of the link that were matched by the groups.
1907 For backwards compatibility, if a command string is given
1908 that does not use any of the group matches, this case is
1909 handled identically to the second one (i.e. match against
1910 file name only).
1911 In a custom lisp form, you can access the group matches with
1912 (match-string n link).
1914 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1915 to open [[file:document.pdf::5]] with evince at page 5.
1917 `directory' Matches a directory
1918 `remote' Matches a remote file, accessible through tramp or efs.
1919 Remote files most likely should be visited through Emacs
1920 because external applications cannot handle such paths.
1921 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1922 so all files Emacs knows how to handle. Using this with
1923 command `emacs' will open most files in Emacs. Beware that this
1924 will also open html files inside Emacs, unless you add
1925 (\"html\" . default) to the list as well.
1926 t Default for files not matched by any of the other options.
1927 `system' The system command to open files, like `open' on Windows
1928 and Mac OS X, and mailcap under GNU/Linux. This is the command
1929 that will be selected if you call `C-c C-o' with a double
1930 \\[universal-argument] \\[universal-argument] prefix.
1932 Possible values for the command are:
1933 `emacs' The file will be visited by the current Emacs process.
1934 `default' Use the default application for this file type, which is the
1935 association for t in the list, most likely in the system-specific
1936 part.
1937 This can be used to overrule an unwanted setting in the
1938 system-specific variable.
1939 `system' Use the system command for opening files, like \"open\".
1940 This command is specified by the entry whose car is `system'.
1941 Most likely, the system-specific version of this variable
1942 does define this command, but you can overrule/replace it
1943 here.
1944 string A command to be executed by a shell; %s will be replaced
1945 by the path to the file.
1946 sexp A Lisp form which will be evaluated. The file path will
1947 be available in the Lisp variable `file'.
1948 For more examples, see the system specific constants
1949 `org-file-apps-defaults-macosx'
1950 `org-file-apps-defaults-windowsnt'
1951 `org-file-apps-defaults-gnu'."
1952 :group 'org-link-follow
1953 :type '(repeat
1954 (cons (choice :value ""
1955 (string :tag "Extension")
1956 (const :tag "System command to open files" system)
1957 (const :tag "Default for unrecognized files" t)
1958 (const :tag "Remote file" remote)
1959 (const :tag "Links to a directory" directory)
1960 (const :tag "Any files that have Emacs modes"
1961 auto-mode))
1962 (choice :value ""
1963 (const :tag "Visit with Emacs" emacs)
1964 (const :tag "Use default" default)
1965 (const :tag "Use the system command" system)
1966 (string :tag "Command")
1967 (sexp :tag "Lisp form")))))
1969 (defcustom org-doi-server-url "http://dx.doi.org/"
1970 "The URL of the DOI server."
1971 :type 'string
1972 :version "24.3"
1973 :group 'org-link-follow)
1975 (defgroup org-refile nil
1976 "Options concerning refiling entries in Org-mode."
1977 :tag "Org Refile"
1978 :group 'org)
1980 (defcustom org-directory "~/org"
1981 "Directory with org files.
1982 This is just a default location to look for Org files. There is no need
1983 at all to put your files into this directory. It is only used in the
1984 following situations:
1986 1. When a capture template specifies a target file that is not an
1987 absolute path. The path will then be interpreted relative to
1988 `org-directory'
1989 2. When a capture note is filed away in an interactive way (when exiting the
1990 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1991 with `org-directory' as the default path."
1992 :group 'org-refile
1993 :group 'org-remember
1994 :group 'org-capture
1995 :type 'directory)
1997 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1998 "Default target for storing notes.
1999 Used as a fall back file for org-remember.el and org-capture.el, for
2000 templates that do not specify a target file."
2001 :group 'org-refile
2002 :group 'org-remember
2003 :group 'org-capture
2004 :type '(choice
2005 (const :tag "Default from remember-data-file" nil)
2006 file))
2008 (defcustom org-goto-interface 'outline
2009 "The default interface to be used for `org-goto'.
2010 Allowed values are:
2011 outline The interface shows an outline of the relevant file
2012 and the correct heading is found by moving through
2013 the outline or by searching with incremental search.
2014 outline-path-completion Headlines in the current buffer are offered via
2015 completion. This is the interface also used by
2016 the refile command."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Outline" outline)
2020 (const :tag "Outline-path-completion" outline-path-completion)))
2022 (defcustom org-goto-max-level 5
2023 "Maximum target level when running `org-goto' with refile interface."
2024 :group 'org-refile
2025 :type 'integer)
2027 (defcustom org-reverse-note-order nil
2028 "Non-nil means store new notes at the beginning of a file or entry.
2029 When nil, new notes will be filed to the end of a file or entry.
2030 This can also be a list with cons cells of regular expressions that
2031 are matched against file names, and values."
2032 :group 'org-remember
2033 :group 'org-capture
2034 :group 'org-refile
2035 :type '(choice
2036 (const :tag "Reverse always" t)
2037 (const :tag "Reverse never" nil)
2038 (repeat :tag "By file name regexp"
2039 (cons regexp boolean))))
2041 (defcustom org-log-refile nil
2042 "Information to record when a task is refiled.
2044 Possible values are:
2046 nil Don't add anything
2047 time Add a time stamp to the task
2048 note Prompt for a note and add it with template `org-log-note-headings'
2050 This option can also be set with on a per-file-basis with
2052 #+STARTUP: nologrefile
2053 #+STARTUP: logrefile
2054 #+STARTUP: lognoterefile
2056 You can have local logging settings for a subtree by setting the LOGGING
2057 property to one or more of these keywords.
2059 When bulk-refiling from the agenda, the value `note' is forbidden and
2060 will temporarily be changed to `time'."
2061 :group 'org-refile
2062 :group 'org-progress
2063 :version "24.1"
2064 :type '(choice
2065 (const :tag "No logging" nil)
2066 (const :tag "Record timestamp" time)
2067 (const :tag "Record timestamp with note." note)))
2069 (defcustom org-refile-targets nil
2070 "Targets for refiling entries with \\[org-refile].
2071 This is a list of cons cells. Each cell contains:
2072 - a specification of the files to be considered, either a list of files,
2073 or a symbol whose function or variable value will be used to retrieve
2074 a file name or a list of file names. If you use `org-agenda-files' for
2075 that, all agenda files will be scanned for targets. Nil means consider
2076 headings in the current buffer.
2077 - A specification of how to find candidate refile targets. This may be
2078 any of:
2079 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2080 This tag has to be present in all target headlines, inheritance will
2081 not be considered.
2082 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2083 todo keyword.
2084 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2085 headlines that are refiling targets.
2086 - a cons cell (:level . N). Any headline of level N is considered a target.
2087 Note that, when `org-odd-levels-only' is set, level corresponds to
2088 order in hierarchy, not to the number of stars.
2089 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2090 Note that, when `org-odd-levels-only' is set, level corresponds to
2091 order in hierarchy, not to the number of stars.
2093 Each element of this list generates a set of possible targets.
2094 The union of these sets is presented (with completion) to
2095 the user by `org-refile'.
2097 You can set the variable `org-refile-target-verify-function' to a function
2098 to verify each headline found by the simple criteria above.
2100 When this variable is nil, all top-level headlines in the current buffer
2101 are used, equivalent to the value `((nil . (:level . 1))'."
2102 :group 'org-refile
2103 :type '(repeat
2104 (cons
2105 (choice :value org-agenda-files
2106 (const :tag "All agenda files" org-agenda-files)
2107 (const :tag "Current buffer" nil)
2108 (function) (variable) (file))
2109 (choice :tag "Identify target headline by"
2110 (cons :tag "Specific tag" (const :value :tag) (string))
2111 (cons :tag "TODO keyword" (const :value :todo) (string))
2112 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2113 (cons :tag "Level number" (const :value :level) (integer))
2114 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2116 (defcustom org-refile-target-verify-function nil
2117 "Function to verify if the headline at point should be a refile target.
2118 The function will be called without arguments, with point at the
2119 beginning of the headline. It should return t and leave point
2120 where it is if the headline is a valid target for refiling.
2122 If the target should not be selected, the function must return nil.
2123 In addition to this, it may move point to a place from where the search
2124 should be continued. For example, the function may decide that the entire
2125 subtree of the current entry should be excluded and move point to the end
2126 of the subtree."
2127 :group 'org-refile
2128 :type 'function)
2130 (defcustom org-refile-use-cache nil
2131 "Non-nil means cache refile targets to speed up the process.
2132 The cache for a particular file will be updated automatically when
2133 the buffer has been killed, or when any of the marker used for flagging
2134 refile targets no longer points at a live buffer.
2135 If you have added new entries to a buffer that might themselves be targets,
2136 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2137 find that easier, `C-u C-u C-u C-c C-w'."
2138 :group 'org-refile
2139 :version "24.1"
2140 :type 'boolean)
2142 (defcustom org-refile-use-outline-path nil
2143 "Non-nil means provide refile targets as paths.
2144 So a level 3 headline will be available as level1/level2/level3.
2146 When the value is `file', also include the file name (without directory)
2147 into the path. In this case, you can also stop the completion after
2148 the file name, to get entries inserted as top level in the file.
2150 When `full-file-path', include the full file path."
2151 :group 'org-refile
2152 :type '(choice
2153 (const :tag "Not" nil)
2154 (const :tag "Yes" t)
2155 (const :tag "Start with file name" file)
2156 (const :tag "Start with full file path" full-file-path)))
2158 (defcustom org-outline-path-complete-in-steps t
2159 "Non-nil means complete the outline path in hierarchical steps.
2160 When Org-mode uses the refile interface to select an outline path
2161 \(see variable `org-refile-use-outline-path'), the completion of
2162 the path can be done is a single go, or if can be done in steps down
2163 the headline hierarchy. Going in steps is probably the best if you
2164 do not use a special completion package like `ido' or `icicles'.
2165 However, when using these packages, going in one step can be very
2166 fast, while still showing the whole path to the entry."
2167 :group 'org-refile
2168 :type 'boolean)
2170 (defcustom org-refile-allow-creating-parent-nodes nil
2171 "Non-nil means allow to create new nodes as refile targets.
2172 New nodes are then created by adding \"/new node name\" to the completion
2173 of an existing node. When the value of this variable is `confirm',
2174 new node creation must be confirmed by the user (recommended)
2175 When nil, the completion must match an existing entry.
2177 Note that, if the new heading is not seen by the criteria
2178 listed in `org-refile-targets', multiple instances of the same
2179 heading would be created by trying again to file under the new
2180 heading."
2181 :group 'org-refile
2182 :type '(choice
2183 (const :tag "Never" nil)
2184 (const :tag "Always" t)
2185 (const :tag "Prompt for confirmation" confirm)))
2187 (defcustom org-refile-active-region-within-subtree nil
2188 "Non-nil means also refile active region within a subtree.
2190 By default `org-refile' doesn't allow refiling regions if they
2191 don't contain a set of subtrees, but it might be convenient to
2192 do so sometimes: in that case, the first line of the region is
2193 converted to a headline before refiling."
2194 :group 'org-refile
2195 :version "24.1"
2196 :type 'boolean)
2198 (defgroup org-todo nil
2199 "Options concerning TODO items in Org-mode."
2200 :tag "Org TODO"
2201 :group 'org)
2203 (defgroup org-progress nil
2204 "Options concerning Progress logging in Org-mode."
2205 :tag "Org Progress"
2206 :group 'org-time)
2208 (defvar org-todo-interpretation-widgets
2209 '((:tag "Sequence (cycling hits every state)" sequence)
2210 (:tag "Type (cycling directly to DONE)" type))
2211 "The available interpretation symbols for customizing `org-todo-keywords'.
2212 Interested libraries should add to this list.")
2214 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2215 "List of TODO entry keyword sequences and their interpretation.
2216 \\<org-mode-map>This is a list of sequences.
2218 Each sequence starts with a symbol, either `sequence' or `type',
2219 indicating if the keywords should be interpreted as a sequence of
2220 action steps, or as different types of TODO items. The first
2221 keywords are states requiring action - these states will select a headline
2222 for inclusion into the global TODO list Org-mode produces. If one of
2223 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2224 signify that no further action is necessary. If \"|\" is not found,
2225 the last keyword is treated as the only DONE state of the sequence.
2227 The command \\[org-todo] cycles an entry through these states, and one
2228 additional state where no keyword is present. For details about this
2229 cycling, see the manual.
2231 TODO keywords and interpretation can also be set on a per-file basis with
2232 the special #+SEQ_TODO and #+TYP_TODO lines.
2234 Each keyword can optionally specify a character for fast state selection
2235 \(in combination with the variable `org-use-fast-todo-selection')
2236 and specifiers for state change logging, using the same syntax that
2237 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2238 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2239 indicates to record a time stamp each time this state is selected.
2241 Each keyword may also specify if a timestamp or a note should be
2242 recorded when entering or leaving the state, by adding additional
2243 characters in the parenthesis after the keyword. This looks like this:
2244 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2245 record only the time of the state change. With X and Y being either
2246 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2247 Y when leaving the state if and only if the *target* state does not
2248 define X. You may omit any of the fast-selection key or X or /Y,
2249 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2251 For backward compatibility, this variable may also be just a list
2252 of keywords. In this case the interpretation (sequence or type) will be
2253 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2254 :group 'org-todo
2255 :group 'org-keywords
2256 :type '(choice
2257 (repeat :tag "Old syntax, just keywords"
2258 (string :tag "Keyword"))
2259 (repeat :tag "New syntax"
2260 (cons
2261 (choice
2262 :tag "Interpretation"
2263 ;;Quick and dirty way to see
2264 ;;`org-todo-interpretations'. This takes the
2265 ;;place of item arguments
2266 :convert-widget
2267 (lambda (widget)
2268 (widget-put widget
2269 :args (mapcar
2270 #'(lambda (x)
2271 (widget-convert
2272 (cons 'const x)))
2273 org-todo-interpretation-widgets))
2274 widget))
2275 (repeat
2276 (string :tag "Keyword"))))))
2278 (defvar org-todo-keywords-1 nil
2279 "All TODO and DONE keywords active in a buffer.")
2280 (make-variable-buffer-local 'org-todo-keywords-1)
2281 (defvar org-todo-keywords-for-agenda nil)
2282 (defvar org-done-keywords-for-agenda nil)
2283 (defvar org-drawers-for-agenda nil)
2284 (defvar org-todo-keyword-alist-for-agenda nil)
2285 (defvar org-tag-alist-for-agenda nil)
2286 (defvar org-agenda-contributing-files nil)
2287 (defvar org-not-done-keywords nil)
2288 (make-variable-buffer-local 'org-not-done-keywords)
2289 (defvar org-done-keywords nil)
2290 (make-variable-buffer-local 'org-done-keywords)
2291 (defvar org-todo-heads nil)
2292 (make-variable-buffer-local 'org-todo-heads)
2293 (defvar org-todo-sets nil)
2294 (make-variable-buffer-local 'org-todo-sets)
2295 (defvar org-todo-log-states nil)
2296 (make-variable-buffer-local 'org-todo-log-states)
2297 (defvar org-todo-kwd-alist nil)
2298 (make-variable-buffer-local 'org-todo-kwd-alist)
2299 (defvar org-todo-key-alist nil)
2300 (make-variable-buffer-local 'org-todo-key-alist)
2301 (defvar org-todo-key-trigger nil)
2302 (make-variable-buffer-local 'org-todo-key-trigger)
2304 (defcustom org-todo-interpretation 'sequence
2305 "Controls how TODO keywords are interpreted.
2306 This variable is in principle obsolete and is only used for
2307 backward compatibility, if the interpretation of todo keywords is
2308 not given already in `org-todo-keywords'. See that variable for
2309 more information."
2310 :group 'org-todo
2311 :group 'org-keywords
2312 :type '(choice (const sequence)
2313 (const type)))
2315 (defcustom org-use-fast-todo-selection t
2316 "Non-nil means use the fast todo selection scheme with C-c C-t.
2317 This variable describes if and under what circumstances the cycling
2318 mechanism for TODO keywords will be replaced by a single-key, direct
2319 selection scheme.
2321 When nil, fast selection is never used.
2323 When the symbol `prefix', it will be used when `org-todo' is called
2324 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2325 `C-u t' in an agenda buffer.
2327 When t, fast selection is used by default. In this case, the prefix
2328 argument forces cycling instead.
2330 In all cases, the special interface is only used if access keys have
2331 actually been assigned by the user, i.e. if keywords in the configuration
2332 are followed by a letter in parenthesis, like TODO(t)."
2333 :group 'org-todo
2334 :type '(choice
2335 (const :tag "Never" nil)
2336 (const :tag "By default" t)
2337 (const :tag "Only with C-u C-c C-t" prefix)))
2339 (defcustom org-provide-todo-statistics t
2340 "Non-nil means update todo statistics after insert and toggle.
2341 ALL-HEADLINES means update todo statistics by including headlines
2342 with no TODO keyword as well, counting them as not done.
2343 A list of TODO keywords means the same, but skip keywords that are
2344 not in this list.
2346 When this is set, todo statistics is updated in the parent of the
2347 current entry each time a todo state is changed."
2348 :group 'org-todo
2349 :type '(choice
2350 (const :tag "Yes, only for TODO entries" t)
2351 (const :tag "Yes, including all entries" 'all-headlines)
2352 (repeat :tag "Yes, for TODOs in this list"
2353 (string :tag "TODO keyword"))
2354 (other :tag "No TODO statistics" nil)))
2356 (defcustom org-hierarchical-todo-statistics t
2357 "Non-nil means TODO statistics covers just direct children.
2358 When nil, all entries in the subtree are considered.
2359 This has only an effect if `org-provide-todo-statistics' is set.
2360 To set this to nil for only a single subtree, use a COOKIE_DATA
2361 property and include the word \"recursive\" into the value."
2362 :group 'org-todo
2363 :type 'boolean)
2365 (defcustom org-after-todo-state-change-hook nil
2366 "Hook which is run after the state of a TODO item was changed.
2367 The new state (a string with a TODO keyword, or nil) is available in the
2368 Lisp variable `org-state'."
2369 :group 'org-todo
2370 :type 'hook)
2372 (defvar org-blocker-hook nil
2373 "Hook for functions that are allowed to block a state change.
2375 Functions in this hook should not modify the buffer.
2376 Each function gets as its single argument a property list,
2377 see `org-trigger-hook' for more information about this list.
2379 If any of the functions in this hook returns nil, the state change
2380 is blocked.")
2382 (defvar org-trigger-hook nil
2383 "Hook for functions that are triggered by a state change.
2385 Each function gets as its single argument a property list with at
2386 least the following elements:
2388 (:type type-of-change :position pos-at-entry-start
2389 :from old-state :to new-state)
2391 Depending on the type, more properties may be present.
2393 This mechanism is currently implemented for:
2395 TODO state changes
2396 ------------------
2397 :type todo-state-change
2398 :from previous state (keyword as a string), or nil, or a symbol
2399 'todo' or 'done', to indicate the general type of state.
2400 :to new state, like in :from")
2402 (defcustom org-enforce-todo-dependencies nil
2403 "Non-nil means undone TODO entries will block switching the parent to DONE.
2404 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2405 be blocked if any prior sibling is not yet done.
2406 Finally, if the parent is blocked because of ordered siblings of its own,
2407 the child will also be blocked."
2408 :set (lambda (var val)
2409 (set var val)
2410 (if val
2411 (add-hook 'org-blocker-hook
2412 'org-block-todo-from-children-or-siblings-or-parent)
2413 (remove-hook 'org-blocker-hook
2414 'org-block-todo-from-children-or-siblings-or-parent)))
2415 :group 'org-todo
2416 :type 'boolean)
2418 (defcustom org-enforce-todo-checkbox-dependencies nil
2419 "Non-nil means unchecked boxes will block switching the parent to DONE.
2420 When this is nil, checkboxes have no influence on switching TODO states.
2421 When non-nil, you first need to check off all check boxes before the TODO
2422 entry can be switched to DONE.
2423 This variable needs to be set before org.el is loaded, and you need to
2424 restart Emacs after a change to make the change effective. The only way
2425 to change is while Emacs is running is through the customize interface."
2426 :set (lambda (var val)
2427 (set var val)
2428 (if val
2429 (add-hook 'org-blocker-hook
2430 'org-block-todo-from-checkboxes)
2431 (remove-hook 'org-blocker-hook
2432 'org-block-todo-from-checkboxes)))
2433 :group 'org-todo
2434 :type 'boolean)
2436 (defcustom org-treat-insert-todo-heading-as-state-change nil
2437 "Non-nil means inserting a TODO heading is treated as state change.
2438 So when the command \\[org-insert-todo-heading] is used, state change
2439 logging will apply if appropriate. When nil, the new TODO item will
2440 be inserted directly, and no logging will take place."
2441 :group 'org-todo
2442 :type 'boolean)
2444 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2445 "Non-nil means switching TODO states with S-cursor counts as state change.
2446 This is the default behavior. However, setting this to nil allows a
2447 convenient way to select a TODO state and bypass any logging associated
2448 with that."
2449 :group 'org-todo
2450 :type 'boolean)
2452 (defcustom org-todo-state-tags-triggers nil
2453 "Tag changes that should be triggered by TODO state changes.
2454 This is a list. Each entry is
2456 (state-change (tag . flag) .......)
2458 State-change can be a string with a state, and empty string to indicate the
2459 state that has no TODO keyword, or it can be one of the symbols `todo'
2460 or `done', meaning any not-done or done state, respectively."
2461 :group 'org-todo
2462 :group 'org-tags
2463 :type '(repeat
2464 (cons (choice :tag "When changing to"
2465 (const :tag "Not-done state" todo)
2466 (const :tag "Done state" done)
2467 (string :tag "State"))
2468 (repeat
2469 (cons :tag "Tag action"
2470 (string :tag "Tag")
2471 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2473 (defcustom org-log-done nil
2474 "Information to record when a task moves to the DONE state.
2476 Possible values are:
2478 nil Don't add anything, just change the keyword
2479 time Add a time stamp to the task
2480 note Prompt for a note and add it with template `org-log-note-headings'
2482 This option can also be set with on a per-file-basis with
2484 #+STARTUP: nologdone
2485 #+STARTUP: logdone
2486 #+STARTUP: lognotedone
2488 You can have local logging settings for a subtree by setting the LOGGING
2489 property to one or more of these keywords."
2490 :group 'org-todo
2491 :group 'org-progress
2492 :type '(choice
2493 (const :tag "No logging" nil)
2494 (const :tag "Record CLOSED timestamp" time)
2495 (const :tag "Record CLOSED timestamp with note." note)))
2497 ;; Normalize old uses of org-log-done.
2498 (cond
2499 ((eq org-log-done t) (setq org-log-done 'time))
2500 ((and (listp org-log-done) (memq 'done org-log-done))
2501 (setq org-log-done 'note)))
2503 (defcustom org-log-reschedule nil
2504 "Information to record when the scheduling date of a tasks is modified.
2506 Possible values are:
2508 nil Don't add anything, just change the date
2509 time Add a time stamp to the task
2510 note Prompt for a note and add it with template `org-log-note-headings'
2512 This option can also be set with on a per-file-basis with
2514 #+STARTUP: nologreschedule
2515 #+STARTUP: logreschedule
2516 #+STARTUP: lognotereschedule"
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type '(choice
2520 (const :tag "No logging" nil)
2521 (const :tag "Record timestamp" time)
2522 (const :tag "Record timestamp with note." note)))
2524 (defcustom org-log-redeadline nil
2525 "Information to record when the deadline date of a tasks is modified.
2527 Possible values are:
2529 nil Don't add anything, just change the date
2530 time Add a time stamp to the task
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologredeadline
2536 #+STARTUP: logredeadline
2537 #+STARTUP: lognoteredeadline
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "No logging" nil)
2545 (const :tag "Record timestamp" time)
2546 (const :tag "Record timestamp with note." note)))
2548 (defcustom org-log-note-clock-out nil
2549 "Non-nil means record a note when clocking out of an item.
2550 This can also be configured on a per-file basis by adding one of
2551 the following lines anywhere in the buffer:
2553 #+STARTUP: lognoteclock-out
2554 #+STARTUP: nolognoteclock-out"
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-log-done-with-time t
2560 "Non-nil means the CLOSED time stamp will contain date and time.
2561 When nil, only the date will be recorded."
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-note-headings
2566 '((done . "CLOSING NOTE %t")
2567 (state . "State %-12s from %-12S %t")
2568 (note . "Note taken on %t")
2569 (reschedule . "Rescheduled from %S on %t")
2570 (delschedule . "Not scheduled, was %S on %t")
2571 (redeadline . "New deadline from %S on %t")
2572 (deldeadline . "Removed deadline, was %S on %t")
2573 (refile . "Refiled on %t")
2574 (clock-out . ""))
2575 "Headings for notes added to entries.
2576 The value is an alist, with the car being a symbol indicating the note
2577 context, and the cdr is the heading to be used. The heading may also be the
2578 empty string.
2579 %t in the heading will be replaced by a time stamp.
2580 %T will be an active time stamp instead the default inactive one
2581 %d will be replaced by a short-format time stamp.
2582 %D will be replaced by an active short-format time stamp.
2583 %s will be replaced by the new TODO state, in double quotes.
2584 %S will be replaced by the old TODO state, in double quotes.
2585 %u will be replaced by the user name.
2586 %U will be replaced by the full user name.
2588 In fact, it is not a good idea to change the `state' entry, because
2589 agenda log mode depends on the format of these entries."
2590 :group 'org-todo
2591 :group 'org-progress
2592 :type '(list :greedy t
2593 (cons (const :tag "Heading when closing an item" done) string)
2594 (cons (const :tag
2595 "Heading when changing todo state (todo sequence only)"
2596 state) string)
2597 (cons (const :tag "Heading when just taking a note" note) string)
2598 (cons (const :tag "Heading when clocking out" clock-out) string)
2599 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2600 (cons (const :tag "Heading when rescheduling" reschedule) string)
2601 (cons (const :tag "Heading when changing deadline" redeadline) string)
2602 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2603 (cons (const :tag "Heading when refiling" refile) string)))
2605 (unless (assq 'note org-log-note-headings)
2606 (push '(note . "%t") org-log-note-headings))
2608 (defcustom org-log-into-drawer nil
2609 "Non-nil means insert state change notes and time stamps into a drawer.
2610 When nil, state changes notes will be inserted after the headline and
2611 any scheduling and clock lines, but not inside a drawer.
2613 The value of this variable should be the name of the drawer to use.
2614 LOGBOOK is proposed as the default drawer for this purpose, you can
2615 also set this to a string to define the drawer of your choice.
2617 A value of t is also allowed, representing \"LOGBOOK\".
2619 A value of t or nil can also be set with on a per-file-basis with
2621 #+STARTUP: logdrawer
2622 #+STARTUP: nologdrawer
2624 If this variable is set, `org-log-state-notes-insert-after-drawers'
2625 will be ignored.
2627 You can set the property LOG_INTO_DRAWER to overrule this setting for
2628 a subtree."
2629 :group 'org-todo
2630 :group 'org-progress
2631 :type '(choice
2632 (const :tag "Not into a drawer" nil)
2633 (const :tag "LOGBOOK" t)
2634 (string :tag "Other")))
2636 (if (fboundp 'defvaralias)
2637 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2639 (defun org-log-into-drawer ()
2640 "Return the value of `org-log-into-drawer', but let properties overrule.
2641 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2642 used instead of the default value."
2643 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2644 (cond
2645 ((not p) org-log-into-drawer)
2646 ((equal p "nil") nil)
2647 ((equal p "t") "LOGBOOK")
2648 (t p))))
2650 (defcustom org-log-state-notes-insert-after-drawers nil
2651 "Non-nil means insert state change notes after any drawers in entry.
2652 Only the drawers that *immediately* follow the headline and the
2653 deadline/scheduled line are skipped.
2654 When nil, insert notes right after the heading and perhaps the line
2655 with deadline/scheduling if present.
2657 This variable will have no effect if `org-log-into-drawer' is
2658 set."
2659 :group 'org-todo
2660 :group 'org-progress
2661 :type 'boolean)
2663 (defcustom org-log-states-order-reversed t
2664 "Non-nil means the latest state note will be directly after heading.
2665 When nil, the state change notes will be ordered according to time.
2667 This option can also be set with on a per-file-basis with
2669 #+STARTUP: logstatesreversed
2670 #+STARTUP: nologstatesreversed"
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type 'boolean)
2675 (defcustom org-todo-repeat-to-state nil
2676 "The TODO state to which a repeater should return the repeating task.
2677 By default this is the first task in a TODO sequence, or the previous state
2678 in a TODO_TYP set. But you can specify another task here.
2679 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2680 :group 'org-todo
2681 :version "24.1"
2682 :type '(choice (const :tag "Head of sequence" nil)
2683 (string :tag "Specific state")))
2685 (defcustom org-log-repeat 'time
2686 "Non-nil means record moving through the DONE state when triggering repeat.
2687 An auto-repeating task is immediately switched back to TODO when
2688 marked DONE. If you are not logging state changes (by adding \"@\"
2689 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2690 record a closing note, there will be no record of the task moving
2691 through DONE. This variable forces taking a note anyway.
2693 nil Don't force a record
2694 time Record a time stamp
2695 note Prompt for a note and add it with template `org-log-note-headings'
2697 This option can also be set with on a per-file-basis with
2699 #+STARTUP: nologrepeat
2700 #+STARTUP: logrepeat
2701 #+STARTUP: lognoterepeat
2703 You can have local logging settings for a subtree by setting the LOGGING
2704 property to one or more of these keywords."
2705 :group 'org-todo
2706 :group 'org-progress
2707 :type '(choice
2708 (const :tag "Don't force a record" nil)
2709 (const :tag "Force recording the DONE state" time)
2710 (const :tag "Force recording a note with the DONE state" note)))
2713 (defgroup org-priorities nil
2714 "Priorities in Org-mode."
2715 :tag "Org Priorities"
2716 :group 'org-todo)
2718 (defcustom org-enable-priority-commands t
2719 "Non-nil means priority commands are active.
2720 When nil, these commands will be disabled, so that you never accidentally
2721 set a priority."
2722 :group 'org-priorities
2723 :type 'boolean)
2725 (defcustom org-highest-priority ?A
2726 "The highest priority of TODO items. A character like ?A, ?B etc.
2727 Must have a smaller ASCII number than `org-lowest-priority'."
2728 :group 'org-priorities
2729 :type 'character)
2731 (defcustom org-lowest-priority ?C
2732 "The lowest priority of TODO items. A character like ?A, ?B etc.
2733 Must have a larger ASCII number than `org-highest-priority'."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-default-priority ?B
2738 "The default priority of TODO items.
2739 This is the priority an item gets if no explicit priority is given.
2740 When starting to cycle on an empty priority the first step in the cycle
2741 depends on `org-priority-start-cycle-with-default'. The resulting first
2742 step priority must not exceed the range from `org-highest-priority' to
2743 `org-lowest-priority' which means that `org-default-priority' has to be
2744 in this range exclusive or inclusive the range boundaries. Else the
2745 first step refuses to set the default and the second will fall back
2746 to (depending on the command used) the highest or lowest priority."
2747 :group 'org-priorities
2748 :type 'character)
2750 (defcustom org-priority-start-cycle-with-default t
2751 "Non-nil means start with default priority when starting to cycle.
2752 When this is nil, the first step in the cycle will be (depending on the
2753 command used) one higher or lower than the default priority.
2754 See also `org-default-priority'."
2755 :group 'org-priorities
2756 :type 'boolean)
2758 (defcustom org-get-priority-function nil
2759 "Function to extract the priority from a string.
2760 The string is normally the headline. If this is nil Org computes the
2761 priority from the priority cookie like [#A] in the headline. It returns
2762 an integer, increasing by 1000 for each priority level.
2763 The user can set a different function here, which should take a string
2764 as an argument and return the numeric priority."
2765 :group 'org-priorities
2766 :version "24.1"
2767 :type 'function)
2769 (defgroup org-time nil
2770 "Options concerning time stamps and deadlines in Org-mode."
2771 :tag "Org Time"
2772 :group 'org)
2774 (defcustom org-insert-labeled-timestamps-at-point nil
2775 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2776 When nil, these labeled time stamps are forces into the second line of an
2777 entry, just after the headline. When scheduling from the global TODO list,
2778 the time stamp will always be forced into the second line."
2779 :group 'org-time
2780 :type 'boolean)
2782 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2783 "Formats for `format-time-string' which are used for time stamps.
2784 It is not recommended to change this constant.")
2786 (defcustom org-time-stamp-rounding-minutes '(0 5)
2787 "Number of minutes to round time stamps to.
2788 These are two values, the first applies when first creating a time stamp.
2789 The second applies when changing it with the commands `S-up' and `S-down'.
2790 When changing the time stamp, this means that it will change in steps
2791 of N minutes, as given by the second value.
2793 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2794 numbers should be factors of 60, so for example 5, 10, 15.
2796 When this is larger than 1, you can still force an exact time stamp by using
2797 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2798 and by using a prefix arg to `S-up/down' to specify the exact number
2799 of minutes to shift."
2800 :group 'org-time
2801 :get #'(lambda (var) ; Make sure both elements are there
2802 (if (integerp (default-value var))
2803 (list (default-value var) 5)
2804 (default-value var)))
2805 :type '(list
2806 (integer :tag "when inserting times")
2807 (integer :tag "when modifying times")))
2809 ;; Normalize old customizations of this variable.
2810 (when (integerp org-time-stamp-rounding-minutes)
2811 (setq org-time-stamp-rounding-minutes
2812 (list org-time-stamp-rounding-minutes
2813 org-time-stamp-rounding-minutes)))
2815 (defcustom org-display-custom-times nil
2816 "Non-nil means overlay custom formats over all time stamps.
2817 The formats are defined through the variable `org-time-stamp-custom-formats'.
2818 To turn this on on a per-file basis, insert anywhere in the file:
2819 #+STARTUP: customtime"
2820 :group 'org-time
2821 :set 'set-default
2822 :type 'sexp)
2823 (make-variable-buffer-local 'org-display-custom-times)
2825 (defcustom org-time-stamp-custom-formats
2826 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2827 "Custom formats for time stamps. See `format-time-string' for the syntax.
2828 These are overlaid over the default ISO format if the variable
2829 `org-display-custom-times' is set. Time like %H:%M should be at the
2830 end of the second format. The custom formats are also honored by export
2831 commands, if custom time display is turned on at the time of export."
2832 :group 'org-time
2833 :type 'sexp)
2835 (defun org-time-stamp-format (&optional long inactive)
2836 "Get the right format for a time string."
2837 (let ((f (if long (cdr org-time-stamp-formats)
2838 (car org-time-stamp-formats))))
2839 (if inactive
2840 (concat "[" (substring f 1 -1) "]")
2841 f)))
2843 (defcustom org-time-clocksum-format
2844 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2845 "The format string used when creating CLOCKSUM lines.
2846 This is also used when Org mode generates a time duration.
2848 The value can be a single format string containing two
2849 %-sequences, which will be filled with the number of hours and
2850 minutes in that order.
2852 Alternatively, the value can be a plist associating any of the
2853 keys :years, :months, :weeks, :days, :hours or :minutes with
2854 format strings. The time duration is formatted using only the
2855 time components that are needed and concatenating the results.
2856 If a time unit in absent, it falls back to the next smallest
2857 unit.
2859 The keys :require-years, :require-months, :require-days,
2860 :require-weeks, :require-hours, :require-minutes are also
2861 meaningful. A non-nil value for these keys indicates that the
2862 corresponding time component should always be included, even if
2863 its value is 0.
2866 For example,
2868 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2869 :require-minutes t)
2871 means durations longer than a day will be expressed in days,
2872 hours and minutes, and durations less than a day will always be
2873 expressed in hours and minutes (even for durations less than an
2874 hour).
2876 The value
2878 \(:days \"%dd\" :minutes \"%dm\")
2880 means durations longer than a day will be expressed in days and
2881 minutes, and durations less than a day will be expressed entirely
2882 in minutes (even for durations longer than an hour)."
2883 :group 'org-time
2884 :group 'org-clock
2885 :version "24.4"
2886 :package-version '(Org . "8.0")
2887 :type '(choice (string :tag "Format string")
2888 (set :tag "Plist"
2889 (group :inline t (const :tag "Years" :years)
2890 (string :tag "Format string"))
2891 (group :inline t
2892 (const :tag "Always show years" :require-years)
2893 (const t))
2894 (group :inline t (const :tag "Months" :months)
2895 (string :tag "Format string"))
2896 (group :inline t
2897 (const :tag "Always show months" :require-months)
2898 (const t))
2899 (group :inline t (const :tag "Weeks" :weeks)
2900 (string :tag "Format string"))
2901 (group :inline t
2902 (const :tag "Always show weeks" :require-weeks)
2903 (const t))
2904 (group :inline t (const :tag "Days" :days)
2905 (string :tag "Format string"))
2906 (group :inline t
2907 (const :tag "Always show days" :require-days)
2908 (const t))
2909 (group :inline t (const :tag "Hours" :hours)
2910 (string :tag "Format string"))
2911 (group :inline t
2912 (const :tag "Always show hours" :require-hours)
2913 (const t))
2914 (group :inline t (const :tag "Minutes" :minutes)
2915 (string :tag "Format string"))
2916 (group :inline t
2917 (const :tag "Always show minutes" :require-minutes)
2918 (const t)))))
2920 (defcustom org-time-clocksum-use-fractional nil
2921 "When non-nil, \\[org-clock-display] uses fractional times.
2922 See `org-time-clocksum-format' for more on time clock formats."
2923 :group 'org-time
2924 :group 'org-clock
2925 :version "24.3"
2926 :type 'boolean)
2928 (defcustom org-time-clocksum-use-effort-durations t
2929 "When non-nil, \\[org-clock-display] uses effort durations.
2930 E.g. by default, one day is considered to be a 8 hours effort,
2931 so a task that has been clocked for 16 hours will be displayed
2932 as during 2 days in the clock display or in the clocktable.
2934 See `org-effort-durations' on how to set effort durations
2935 and `org-time-clocksum-format' for more on time clock formats."
2936 :group 'org-time
2937 :group 'org-clock
2938 :version "24.4"
2939 :package-version '(Org . "8.0")
2940 :type 'boolean)
2942 (defcustom org-time-clocksum-fractional-format "%.2f"
2943 "The format string used when creating CLOCKSUM lines,
2944 or when Org mode generates a time duration, if
2945 `org-time-clocksum-use-fractional' is enabled.
2947 The value can be a single format string containing one
2948 %-sequence, which will be filled with the number of hours as
2949 a float.
2951 Alternatively, the value can be a plist associating any of the
2952 keys :years, :months, :weeks, :days, :hours or :minutes with
2953 a format string. The time duration is formatted using the
2954 largest time unit which gives a non-zero integer part. If all
2955 specified formats have zero integer part, the smallest time unit
2956 is used."
2957 :group 'org-time
2958 :type '(choice (string :tag "Format string")
2959 (set (group :inline t (const :tag "Years" :years)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Months" :months)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Weeks" :weeks)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Days" :days)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Hours" :hours)
2968 (string :tag "Format string"))
2969 (group :inline t (const :tag "Minutes" :minutes)
2970 (string :tag "Format string")))))
2972 (defcustom org-deadline-warning-days 14
2973 "Number of days before expiration during which a deadline becomes active.
2974 This variable governs the display in sparse trees and in the agenda.
2975 When 0 or negative, it means use this number (the absolute value of it)
2976 even if a deadline has a different individual lead time specified.
2978 Custom commands can set this variable in the options section."
2979 :group 'org-time
2980 :group 'org-agenda-daily/weekly
2981 :type 'integer)
2983 (defcustom org-scheduled-delay-days 0
2984 "Number of days before a scheduled item becomes active.
2985 This variable governs the display in sparse trees and in the agenda.
2986 The default value (i.e. 0) means: don't delay scheduled item.
2987 When negative, it means use this number (the absolute value of it)
2988 even if a scheduled item has a different individual delay time
2989 specified.
2991 Custom commands can set this variable in the options section."
2992 :group 'org-time
2993 :group 'org-agenda-daily/weekly
2994 :version "24.4"
2995 :package-version '(Org . "8.0")
2996 :type 'integer)
2998 (defcustom org-read-date-prefer-future t
2999 "Non-nil means assume future for incomplete date input from user.
3000 This affects the following situations:
3001 1. The user gives a month but not a year.
3002 For example, if it is April and you enter \"feb 2\", this will be read
3003 as Feb 2, *next* year. \"May 5\", however, will be this year.
3004 2. The user gives a day, but no month.
3005 For example, if today is the 15th, and you enter \"3\", Org-mode will
3006 read this as the third of *next* month. However, if you enter \"17\",
3007 it will be considered as *this* month.
3009 If you set this variable to the symbol `time', then also the following
3010 will work:
3012 3. If the user gives a time.
3013 If the time is before now, it will be interpreted as tomorrow.
3015 Currently none of this works for ISO week specifications.
3017 When this option is nil, the current day, month and year will always be
3018 used as defaults.
3020 See also `org-agenda-jump-prefer-future'."
3021 :group 'org-time
3022 :type '(choice
3023 (const :tag "Never" nil)
3024 (const :tag "Check month and day" t)
3025 (const :tag "Check month, day, and time" time)))
3027 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3028 "Should the agenda jump command prefer the future for incomplete dates?
3029 The default is to do the same as configured in `org-read-date-prefer-future'.
3030 But you can also set a deviating value here.
3031 This may t or nil, or the symbol `org-read-date-prefer-future'."
3032 :group 'org-agenda
3033 :group 'org-time
3034 :version "24.1"
3035 :type '(choice
3036 (const :tag "Use org-read-date-prefer-future"
3037 org-read-date-prefer-future)
3038 (const :tag "Never" nil)
3039 (const :tag "Always" t)))
3041 (defcustom org-read-date-force-compatible-dates t
3042 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3044 Depending on the system Emacs is running on, certain dates cannot
3045 be represented with the type used internally to represent time.
3046 Dates between 1970-1-1 and 2038-1-1 can always be represented
3047 correctly. Some systems allow for earlier dates, some for later,
3048 some for both. One way to find out it to insert any date into an
3049 Org buffer, putting the cursor on the year and hitting S-up and
3050 S-down to test the range.
3052 When this variable is set to t, the date/time prompt will not let
3053 you specify dates outside the 1970-2037 range, so it is certain that
3054 these dates will work in whatever version of Emacs you are
3055 running, and also that you can move a file from one Emacs implementation
3056 to another. WHenever Org is forcing the year for you, it will display
3057 a message and beep.
3059 When this variable is nil, Org will check if the date is
3060 representable in the specific Emacs implementation you are using.
3061 If not, it will force a year, usually the current year, and beep
3062 to remind you. Currently this setting is not recommended because
3063 the likelihood that you will open your Org files in an Emacs that
3064 has limited date range is not negligible.
3066 A workaround for this problem is to use diary sexp dates for time
3067 stamps outside of this range."
3068 :group 'org-time
3069 :version "24.1"
3070 :type 'boolean)
3072 (defcustom org-read-date-display-live t
3073 "Non-nil means display current interpretation of date prompt live.
3074 This display will be in an overlay, in the minibuffer."
3075 :group 'org-time
3076 :type 'boolean)
3078 (defcustom org-read-date-popup-calendar t
3079 "Non-nil means pop up a calendar when prompting for a date.
3080 In the calendar, the date can be selected with mouse-1. However, the
3081 minibuffer will also be active, and you can simply enter the date as well.
3082 When nil, only the minibuffer will be available."
3083 :group 'org-time
3084 :type 'boolean)
3085 (if (fboundp 'defvaralias)
3086 (defvaralias 'org-popup-calendar-for-date-prompt
3087 'org-read-date-popup-calendar))
3089 (make-obsolete-variable
3090 'org-read-date-minibuffer-setup-hook
3091 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3092 (defcustom org-read-date-minibuffer-setup-hook nil
3093 "Hook to be used to set up keys for the date/time interface.
3094 Add key definitions to `minibuffer-local-map', which will be a
3095 temporary copy.
3097 WARNING: This option is obsolete, you should use
3098 `org-read-date-minibuffer-local-map' to set up keys."
3099 :group 'org-time
3100 :type 'hook)
3102 (defcustom org-extend-today-until 0
3103 "The hour when your day really ends. Must be an integer.
3104 This has influence for the following applications:
3105 - When switching the agenda to \"today\". It it is still earlier than
3106 the time given here, the day recognized as TODAY is actually yesterday.
3107 - When a date is read from the user and it is still before the time given
3108 here, the current date and time will be assumed to be yesterday, 23:59.
3109 Also, timestamps inserted in capture templates follow this rule.
3111 IMPORTANT: This is a feature whose implementation is and likely will
3112 remain incomplete. Really, it is only here because past midnight seems to
3113 be the favorite working time of John Wiegley :-)"
3114 :group 'org-time
3115 :type 'integer)
3117 (defcustom org-use-effective-time nil
3118 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3119 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3120 \"effective time\" of any timestamps between midnight and 8am will be
3121 23:59 of the previous day."
3122 :group 'org-time
3123 :version "24.1"
3124 :type 'boolean)
3126 (defcustom org-use-last-clock-out-time-as-effective-time nil
3127 "When non-nil, use the last clock out time for `org-todo'.
3128 Note that this option has precedence over the combined use of
3129 `org-use-effective-time' and `org-extend-today-until'."
3130 :group 'org-time
3131 :version "24.4"
3132 :package-version '(Org . "8.0")
3133 :type 'boolean)
3135 (defcustom org-edit-timestamp-down-means-later nil
3136 "Non-nil means S-down will increase the time in a time stamp.
3137 When nil, S-up will increase."
3138 :group 'org-time
3139 :type 'boolean)
3141 (defcustom org-calendar-follow-timestamp-change t
3142 "Non-nil means make the calendar window follow timestamp changes.
3143 When a timestamp is modified and the calendar window is visible, it will be
3144 moved to the new date."
3145 :group 'org-time
3146 :type 'boolean)
3148 (defgroup org-tags nil
3149 "Options concerning tags in Org-mode."
3150 :tag "Org Tags"
3151 :group 'org)
3153 (defcustom org-tag-alist nil
3154 "List of tags allowed in Org-mode files.
3155 When this list is nil, Org-mode will base TAG input on what is already in the
3156 buffer.
3157 The value of this variable is an alist, the car of each entry must be a
3158 keyword as a string, the cdr may be a character that is used to select
3159 that tag through the fast-tag-selection interface.
3160 See the manual for details."
3161 :group 'org-tags
3162 :type '(repeat
3163 (choice
3164 (cons (string :tag "Tag name")
3165 (character :tag "Access char"))
3166 (list :tag "Start radio group"
3167 (const :startgroup)
3168 (option (string :tag "Group description")))
3169 (list :tag "End radio group"
3170 (const :endgroup)
3171 (option (string :tag "Group description")))
3172 (const :tag "New line" (:newline)))))
3174 (defcustom org-tag-persistent-alist nil
3175 "List of tags that will always appear in all Org-mode files.
3176 This is in addition to any in buffer settings or customizations
3177 of `org-tag-alist'.
3178 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3179 The value of this variable is an alist, the car of each entry must be a
3180 keyword as a string, the cdr may be a character that is used to select
3181 that tag through the fast-tag-selection interface.
3182 See the manual for details.
3183 To disable these tags on a per-file basis, insert anywhere in the file:
3184 #+STARTUP: noptag"
3185 :group 'org-tags
3186 :type '(repeat
3187 (choice
3188 (cons (string :tag "Tag name")
3189 (character :tag "Access char"))
3190 (const :tag "Start radio group" (:startgroup))
3191 (const :tag "End radio group" (:endgroup))
3192 (const :tag "New line" (:newline)))))
3194 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3195 "If non-nil, always offer completion for all tags of all agenda files.
3196 Instead of customizing this variable directly, you might want to
3197 set it locally for capture buffers, because there no list of
3198 tags in that file can be created dynamically (there are none).
3200 (add-hook 'org-capture-mode-hook
3201 (lambda ()
3202 (set (make-local-variable
3203 'org-complete-tags-always-offer-all-agenda-tags)
3204 t)))"
3205 :group 'org-tags
3206 :version "24.1"
3207 :type 'boolean)
3209 (defvar org-file-tags nil
3210 "List of tags that can be inherited by all entries in the file.
3211 The tags will be inherited if the variable `org-use-tag-inheritance'
3212 says they should be.
3213 This variable is populated from #+FILETAGS lines.")
3215 (defcustom org-use-fast-tag-selection 'auto
3216 "Non-nil means use fast tag selection scheme.
3217 This is a special interface to select and deselect tags with single keys.
3218 When nil, fast selection is never used.
3219 When the symbol `auto', fast selection is used if and only if selection
3220 characters for tags have been configured, either through the variable
3221 `org-tag-alist' or through a #+TAGS line in the buffer.
3222 When t, fast selection is always used and selection keys are assigned
3223 automatically if necessary."
3224 :group 'org-tags
3225 :type '(choice
3226 (const :tag "Always" t)
3227 (const :tag "Never" nil)
3228 (const :tag "When selection characters are configured" 'auto)))
3230 (defcustom org-fast-tag-selection-single-key nil
3231 "Non-nil means fast tag selection exits after first change.
3232 When nil, you have to press RET to exit it.
3233 During fast tag selection, you can toggle this flag with `C-c'.
3234 This variable can also have the value `expert'. In this case, the window
3235 displaying the tags menu is not even shown, until you press C-c again."
3236 :group 'org-tags
3237 :type '(choice
3238 (const :tag "No" nil)
3239 (const :tag "Yes" t)
3240 (const :tag "Expert" expert)))
3242 (defvar org-fast-tag-selection-include-todo nil
3243 "Non-nil means fast tags selection interface will also offer TODO states.
3244 This is an undocumented feature, you should not rely on it.")
3246 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3247 "The column to which tags should be indented in a headline.
3248 If this number is positive, it specifies the column. If it is negative,
3249 it means that the tags should be flushright to that column. For example,
3250 -80 works well for a normal 80 character screen.
3251 When 0, place tags directly after headline text, with only one space in
3252 between."
3253 :group 'org-tags
3254 :type 'integer)
3256 (defcustom org-auto-align-tags t
3257 "Non-nil keeps tags aligned when modifying headlines.
3258 Some operations (i.e. demoting) change the length of a headline and
3259 therefore shift the tags around. With this option turned on, after
3260 each such operation the tags are again aligned to `org-tags-column'."
3261 :group 'org-tags
3262 :type 'boolean)
3264 (defcustom org-use-tag-inheritance t
3265 "Non-nil means tags in levels apply also for sublevels.
3266 When nil, only the tags directly given in a specific line apply there.
3267 This may also be a list of tags that should be inherited, or a regexp that
3268 matches tags that should be inherited. Additional control is possible
3269 with the variable `org-tags-exclude-from-inheritance' which gives an
3270 explicit list of tags to be excluded from inheritance, even if the value of
3271 `org-use-tag-inheritance' would select it for inheritance.
3273 If this option is t, a match early-on in a tree can lead to a large
3274 number of matches in the subtree when constructing the agenda or creating
3275 a sparse tree. If you only want to see the first match in a tree during
3276 a search, check out the variable `org-tags-match-list-sublevels'."
3277 :group 'org-tags
3278 :type '(choice
3279 (const :tag "Not" nil)
3280 (const :tag "Always" t)
3281 (repeat :tag "Specific tags" (string :tag "Tag"))
3282 (regexp :tag "Tags matched by regexp")))
3284 (defcustom org-tags-exclude-from-inheritance nil
3285 "List of tags that should never be inherited.
3286 This is a way to exclude a few tags from inheritance. For way to do
3287 the opposite, to actively allow inheritance for selected tags,
3288 see the variable `org-use-tag-inheritance'."
3289 :group 'org-tags
3290 :type '(repeat (string :tag "Tag")))
3292 (defun org-tag-inherit-p (tag)
3293 "Check if TAG is one that should be inherited."
3294 (cond
3295 ((member tag org-tags-exclude-from-inheritance) nil)
3296 ((eq org-use-tag-inheritance t) t)
3297 ((not org-use-tag-inheritance) nil)
3298 ((stringp org-use-tag-inheritance)
3299 (string-match org-use-tag-inheritance tag))
3300 ((listp org-use-tag-inheritance)
3301 (member tag org-use-tag-inheritance))
3302 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3304 (defcustom org-tags-match-list-sublevels t
3305 "Non-nil means list also sublevels of headlines matching a search.
3306 This variable applies to tags/property searches, and also to stuck
3307 projects because this search is based on a tags match as well.
3309 When set to the symbol `indented', sublevels are indented with
3310 leading dots.
3312 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3313 the sublevels of a headline matching a tag search often also match
3314 the same search. Listing all of them can create very long lists.
3315 Setting this variable to nil causes subtrees of a match to be skipped.
3317 This variable is semi-obsolete and probably should always be true. It
3318 is better to limit inheritance to certain tags using the variables
3319 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3320 :group 'org-tags
3321 :type '(choice
3322 (const :tag "No, don't list them" nil)
3323 (const :tag "Yes, do list them" t)
3324 (const :tag "List them, indented with leading dots" indented)))
3326 (defcustom org-tags-sort-function nil
3327 "When set, tags are sorted using this function as a comparator."
3328 :group 'org-tags
3329 :type '(choice
3330 (const :tag "No sorting" nil)
3331 (const :tag "Alphabetical" string<)
3332 (const :tag "Reverse alphabetical" string>)
3333 (function :tag "Custom function" nil)))
3335 (defvar org-tags-history nil
3336 "History of minibuffer reads for tags.")
3337 (defvar org-last-tags-completion-table nil
3338 "The last used completion table for tags.")
3339 (defvar org-after-tags-change-hook nil
3340 "Hook that is run after the tags in a line have changed.")
3342 (defgroup org-properties nil
3343 "Options concerning properties in Org-mode."
3344 :tag "Org Properties"
3345 :group 'org)
3347 (defcustom org-property-format "%-10s %s"
3348 "How property key/value pairs should be formatted by `indent-line'.
3349 When `indent-line' hits a property definition, it will format the line
3350 according to this format, mainly to make sure that the values are
3351 lined-up with respect to each other."
3352 :group 'org-properties
3353 :type 'string)
3355 (defcustom org-properties-postprocess-alist nil
3356 "Alist of properties and functions to adjust inserted values.
3357 Elements of this alist must be of the form
3359 ([string] [function])
3361 where [string] must be a property name and [function] must be a
3362 lambda expression: this lambda expression must take one argument,
3363 the value to adjust, and return the new value as a string.
3365 For example, this element will allow the property \"Remaining\"
3366 to be updated wrt the relation between the \"Effort\" property
3367 and the clock summary:
3369 ((\"Remaining\" (lambda(value)
3370 (let ((clocksum (org-clock-sum-current-item))
3371 (effort (org-duration-string-to-minutes
3372 (org-entry-get (point) \"Effort\"))))
3373 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3374 :group 'org-properties
3375 :version "24.1"
3376 :type '(alist :key-type (string :tag "Property")
3377 :value-type (function :tag "Function")))
3379 (defcustom org-use-property-inheritance nil
3380 "Non-nil means properties apply also for sublevels.
3382 This setting is chiefly used during property searches. Turning it on can
3383 cause significant overhead when doing a search, which is why it is not
3384 on by default.
3386 When nil, only the properties directly given in the current entry count.
3387 When t, every property is inherited. The value may also be a list of
3388 properties that should have inheritance, or a regular expression matching
3389 properties that should be inherited.
3391 However, note that some special properties use inheritance under special
3392 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3393 and the properties ending in \"_ALL\" when they are used as descriptor
3394 for valid values of a property.
3396 Note for programmers:
3397 When querying an entry with `org-entry-get', you can control if inheritance
3398 should be used. By default, `org-entry-get' looks only at the local
3399 properties. You can request inheritance by setting the inherit argument
3400 to t (to force inheritance) or to `selective' (to respect the setting
3401 in this variable)."
3402 :group 'org-properties
3403 :type '(choice
3404 (const :tag "Not" nil)
3405 (const :tag "Always" t)
3406 (repeat :tag "Specific properties" (string :tag "Property"))
3407 (regexp :tag "Properties matched by regexp")))
3409 (defun org-property-inherit-p (property)
3410 "Check if PROPERTY is one that should be inherited."
3411 (cond
3412 ((eq org-use-property-inheritance t) t)
3413 ((not org-use-property-inheritance) nil)
3414 ((stringp org-use-property-inheritance)
3415 (string-match org-use-property-inheritance property))
3416 ((listp org-use-property-inheritance)
3417 (member property org-use-property-inheritance))
3418 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3420 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3421 "The default column format, if no other format has been defined.
3422 This variable can be set on the per-file basis by inserting a line
3424 #+COLUMNS: %25ITEM ....."
3425 :group 'org-properties
3426 :type 'string)
3428 (defcustom org-columns-ellipses ".."
3429 "The ellipses to be used when a field in column view is truncated.
3430 When this is the empty string, as many characters as possible are shown,
3431 but then there will be no visual indication that the field has been truncated.
3432 When this is a string of length N, the last N characters of a truncated
3433 field are replaced by this string. If the column is narrower than the
3434 ellipses string, only part of the ellipses string will be shown."
3435 :group 'org-properties
3436 :type 'string)
3438 (defcustom org-columns-modify-value-for-display-function nil
3439 "Function that modifies values for display in column view.
3440 For example, it can be used to cut out a certain part from a time stamp.
3441 The function must take 2 arguments:
3443 column-title The title of the column (*not* the property name)
3444 value The value that should be modified.
3446 The function should return the value that should be displayed,
3447 or nil if the normal value should be used."
3448 :group 'org-properties
3449 :type 'function)
3451 (defcustom org-effort-property "Effort"
3452 "The property that is being used to keep track of effort estimates.
3453 Effort estimates given in this property need to have the format H:MM."
3454 :group 'org-properties
3455 :group 'org-progress
3456 :type '(string :tag "Property"))
3458 (defconst org-global-properties-fixed
3459 '(("VISIBILITY_ALL" . "folded children content all")
3460 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3461 "List of property/value pairs that can be inherited by any entry.
3463 These are fixed values, for the preset properties. The user variable
3464 that can be used to add to this list is `org-global-properties'.
3466 The entries in this list are cons cells where the car is a property
3467 name and cdr is a string with the value. If the value represents
3468 multiple items like an \"_ALL\" property, separate the items by
3469 spaces.")
3471 (defcustom org-global-properties nil
3472 "List of property/value pairs that can be inherited by any entry.
3474 This list will be combined with the constant `org-global-properties-fixed'.
3476 The entries in this list are cons cells where the car is a property
3477 name and cdr is a string with the value.
3479 You can set buffer-local values for the same purpose in the variable
3480 `org-file-properties' this by adding lines like
3482 #+PROPERTY: NAME VALUE"
3483 :group 'org-properties
3484 :type '(repeat
3485 (cons (string :tag "Property")
3486 (string :tag "Value"))))
3488 (defvar org-file-properties nil
3489 "List of property/value pairs that can be inherited by any entry.
3490 Valid for the current buffer.
3491 This variable is populated from #+PROPERTY lines.")
3492 (make-variable-buffer-local 'org-file-properties)
3494 (defgroup org-agenda nil
3495 "Options concerning agenda views in Org-mode."
3496 :tag "Org Agenda"
3497 :group 'org)
3499 (defvar org-category nil
3500 "Variable used by org files to set a category for agenda display.
3501 Such files should use a file variable to set it, for example
3503 # -*- mode: org; org-category: \"ELisp\"
3505 or contain a special line
3507 #+CATEGORY: ELisp
3509 If the file does not specify a category, then file's base name
3510 is used instead.")
3511 (make-variable-buffer-local 'org-category)
3512 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3514 (defcustom org-agenda-files nil
3515 "The files to be used for agenda display.
3516 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3517 \\[org-remove-file]. You can also use customize to edit the list.
3519 If an entry is a directory, all files in that directory that are matched by
3520 `org-agenda-file-regexp' will be part of the file list.
3522 If the value of the variable is not a list but a single file name, then
3523 the list of agenda files is actually stored and maintained in that file, one
3524 agenda file per line. In this file paths can be given relative to
3525 `org-directory'. Tilde expansion and environment variable substitution
3526 are also made."
3527 :group 'org-agenda
3528 :type '(choice
3529 (repeat :tag "List of files and directories" file)
3530 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3532 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3533 "Regular expression to match files for `org-agenda-files'.
3534 If any element in the list in that variable contains a directory instead
3535 of a normal file, all files in that directory that are matched by this
3536 regular expression will be included."
3537 :group 'org-agenda
3538 :type 'regexp)
3540 (defcustom org-agenda-text-search-extra-files nil
3541 "List of extra files to be searched by text search commands.
3542 These files will be search in addition to the agenda files by the
3543 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3544 Note that these files will only be searched for text search commands,
3545 not for the other agenda views like todo lists, tag searches or the weekly
3546 agenda. This variable is intended to list notes and possibly archive files
3547 that should also be searched by these two commands.
3548 In fact, if the first element in the list is the symbol `agenda-archives',
3549 than all archive files of all agenda files will be added to the search
3550 scope."
3551 :group 'org-agenda
3552 :type '(set :greedy t
3553 (const :tag "Agenda Archives" agenda-archives)
3554 (repeat :inline t (file))))
3556 (if (fboundp 'defvaralias)
3557 (defvaralias 'org-agenda-multi-occur-extra-files
3558 'org-agenda-text-search-extra-files))
3560 (defcustom org-agenda-skip-unavailable-files nil
3561 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3562 A nil value means to remove them, after a query, from the list."
3563 :group 'org-agenda
3564 :type 'boolean)
3566 (defcustom org-calendar-to-agenda-key [?c]
3567 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3568 The command `org-calendar-goto-agenda' will be bound to this key. The
3569 default is the character `c' because then `c' can be used to switch back and
3570 forth between agenda and calendar."
3571 :group 'org-agenda
3572 :type 'sexp)
3574 (defcustom org-calendar-insert-diary-entry-key [?i]
3575 "The key to be installed in `calendar-mode-map' for adding diary entries.
3576 This option is irrelevant until `org-agenda-diary-file' has been configured
3577 to point to an Org-mode file. When that is the case, the command
3578 `org-agenda-diary-entry' will be bound to the key given here, by default
3579 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3580 if you want to continue doing this, you need to change this to a different
3581 key."
3582 :group 'org-agenda
3583 :type 'sexp)
3585 (defcustom org-agenda-diary-file 'diary-file
3586 "File to which to add new entries with the `i' key in agenda and calendar.
3587 When this is the symbol `diary-file', the functionality in the Emacs
3588 calendar will be used to add entries to the `diary-file'. But when this
3589 points to a file, `org-agenda-diary-entry' will be used instead."
3590 :group 'org-agenda
3591 :type '(choice
3592 (const :tag "The standard Emacs diary file" diary-file)
3593 (file :tag "Special Org file diary entries")))
3595 (eval-after-load "calendar"
3596 '(progn
3597 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3598 'org-calendar-goto-agenda)
3599 (add-hook 'calendar-mode-hook
3600 (lambda ()
3601 (unless (eq org-agenda-diary-file 'diary-file)
3602 (define-key calendar-mode-map
3603 org-calendar-insert-diary-entry-key
3604 'org-agenda-diary-entry))))))
3606 (defgroup org-latex nil
3607 "Options for embedding LaTeX code into Org-mode."
3608 :tag "Org LaTeX"
3609 :group 'org)
3611 (defcustom org-format-latex-options
3612 '(:foreground default :background default :scale 1.0
3613 :html-foreground "Black" :html-background "Transparent"
3614 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3615 "Options for creating images from LaTeX fragments.
3616 This is a property list with the following properties:
3617 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3618 `default' means use the foreground of the default face.
3619 `auto' means use the foreground from the text face.
3620 :background the background color, or \"Transparent\".
3621 `default' means use the background of the default face.
3622 `auto' means use the background from the text face.
3623 :scale a scaling factor for the size of the images, to get more pixels
3624 :html-foreground, :html-background, :html-scale
3625 the same numbers for HTML export.
3626 :matchers a list indicating which matchers should be used to
3627 find LaTeX fragments. Valid members of this list are:
3628 \"begin\" find environments
3629 \"$1\" find single characters surrounded by $.$
3630 \"$\" find math expressions surrounded by $...$
3631 \"$$\" find math expressions surrounded by $$....$$
3632 \"\\(\" find math expressions surrounded by \\(...\\)
3633 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3634 :group 'org-latex
3635 :type 'plist)
3637 (defcustom org-format-latex-signal-error t
3638 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3639 When nil, just push out a message."
3640 :group 'org-latex
3641 :version "24.1"
3642 :type 'boolean)
3644 (defcustom org-latex-to-mathml-jar-file nil
3645 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3646 Use this to specify additional executable file say a jar file.
3648 When using MathToWeb as the converter, specify the full-path to
3649 your mathtoweb.jar file."
3650 :group 'org-latex
3651 :version "24.1"
3652 :type '(choice
3653 (const :tag "None" nil)
3654 (file :tag "JAR file" :must-match t)))
3656 (defcustom org-latex-to-mathml-convert-command nil
3657 "Command to convert LaTeX fragments to MathML.
3658 Replace format-specifiers in the command as noted below and use
3659 `shell-command' to convert LaTeX to MathML.
3660 %j: Executable file in fully expanded form as specified by
3661 `org-latex-to-mathml-jar-file'.
3662 %I: Input LaTeX file in fully expanded form
3663 %o: Output MathML file
3664 This command is used by `org-create-math-formula'.
3666 When using MathToWeb as the converter, set this to
3667 \"java -jar %j -unicode -force -df %o %I\"."
3668 :group 'org-latex
3669 :version "24.1"
3670 :type '(choice
3671 (const :tag "None" nil)
3672 (string :tag "\nShell command")))
3674 (defcustom org-latex-create-formula-image-program 'dvipng
3675 "Program to convert LaTeX fragments with.
3677 dvipng Process the LaTeX fragments to dvi file, then convert
3678 dvi files to png files using dvipng.
3679 This will also include processing of non-math environments.
3680 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3681 to convert pdf files to png files"
3682 :group 'org-latex
3683 :version "24.1"
3684 :type '(choice
3685 (const :tag "dvipng" dvipng)
3686 (const :tag "imagemagick" imagemagick)))
3688 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3689 "Path to store latex preview images.
3690 A relative path here creates many directories relative to the
3691 processed org files paths. An absolute path puts all preview
3692 images at the same place."
3693 :group 'org-latex
3694 :version "24.3"
3695 :type 'string)
3697 (defun org-format-latex-mathml-available-p ()
3698 "Return t if `org-latex-to-mathml-convert-command' is usable."
3699 (save-match-data
3700 (when (and (boundp 'org-latex-to-mathml-convert-command)
3701 org-latex-to-mathml-convert-command)
3702 (let ((executable (car (split-string
3703 org-latex-to-mathml-convert-command))))
3704 (when (executable-find executable)
3705 (if (string-match
3706 "%j" org-latex-to-mathml-convert-command)
3707 (file-readable-p org-latex-to-mathml-jar-file)
3708 t))))))
3710 (defcustom org-format-latex-header "\\documentclass{article}
3711 \\usepackage[usenames]{color}
3712 \\usepackage{amsmath}
3713 \\usepackage[mathscr]{eucal}
3714 \\pagestyle{empty} % do not remove
3715 \[PACKAGES]
3716 \[DEFAULT-PACKAGES]
3717 % The settings below are copied from fullpage.sty
3718 \\setlength{\\textwidth}{\\paperwidth}
3719 \\addtolength{\\textwidth}{-3cm}
3720 \\setlength{\\oddsidemargin}{1.5cm}
3721 \\addtolength{\\oddsidemargin}{-2.54cm}
3722 \\setlength{\\evensidemargin}{\\oddsidemargin}
3723 \\setlength{\\textheight}{\\paperheight}
3724 \\addtolength{\\textheight}{-\\headheight}
3725 \\addtolength{\\textheight}{-\\headsep}
3726 \\addtolength{\\textheight}{-\\footskip}
3727 \\addtolength{\\textheight}{-3cm}
3728 \\setlength{\\topmargin}{1.5cm}
3729 \\addtolength{\\topmargin}{-2.54cm}"
3730 "The document header used for processing LaTeX fragments.
3731 It is imperative that this header make sure that no page number
3732 appears on the page. The package defined in the variables
3733 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3734 will either replace the placeholder \"[PACKAGES]\" in this
3735 header, or they will be appended."
3736 :group 'org-latex
3737 :type 'string)
3739 (defun org-set-packages-alist (var val)
3740 "Set the packages alist and make sure it has 3 elements per entry."
3741 (set var (mapcar (lambda (x)
3742 (if (and (consp x) (= (length x) 2))
3743 (list (car x) (nth 1 x) t)
3745 val)))
3747 (defun org-get-packages-alist (var)
3748 "Get the packages alist and make sure it has 3 elements per entry."
3749 (mapcar (lambda (x)
3750 (if (and (consp x) (= (length x) 2))
3751 (list (car x) (nth 1 x) t)
3753 (default-value var)))
3755 (defcustom org-latex-default-packages-alist
3756 '(("AUTO" "inputenc" t)
3757 ("T1" "fontenc" t)
3758 ("" "fixltx2e" nil)
3759 ("" "graphicx" t)
3760 ("" "longtable" nil)
3761 ("" "float" nil)
3762 ("" "wrapfig" nil)
3763 ("" "soul" t)
3764 ("" "textcomp" t)
3765 ("" "marvosym" t)
3766 ("" "wasysym" t)
3767 ("" "latexsym" t)
3768 ("" "amssymb" t)
3769 ("" "hyperref" nil)
3770 "\\tolerance=1000")
3771 "Alist of default packages to be inserted in the header.
3773 Change this only if one of the packages here causes an
3774 incompatibility with another package you are using.
3776 The packages in this list are needed by one part or another of
3777 Org mode to function properly:
3779 - inputenc, fontenc: for basic font and character selection
3780 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3781 symbols used for interpreting the entities in `org-entities'.
3782 You can skip some of these packages if you don't use any of the
3783 symbols in it.
3784 - graphicx: for including images
3785 - float, wrapfig: for figure placement
3786 - longtable: for long tables
3787 - hyperref: for cross references
3789 Therefore you should not modify this variable unless you know
3790 what you are doing. The one reason to change it anyway is that
3791 you might be loading some other package that conflicts with one
3792 of the default packages. Each cell is of the format
3793 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3794 the package also needs to be included when compiling LaTeX
3795 snippets into images for inclusion into non-LaTeX output."
3796 :group 'org-latex
3797 :group 'org-export-latex
3798 :set 'org-set-packages-alist
3799 :get 'org-get-packages-alist
3800 :version "24.1"
3801 :type '(repeat
3802 (choice
3803 (list :tag "options/package pair"
3804 (string :tag "options")
3805 (string :tag "package")
3806 (boolean :tag "Snippet"))
3807 (string :tag "A line of LaTeX"))))
3809 (defcustom org-latex-packages-alist nil
3810 "Alist of packages to be inserted in every LaTeX header.
3812 These will be inserted after `org-latex-default-packages-alist'.
3813 Each cell is of the format:
3815 \(\"options\" \"package\" snippet-flag)
3817 SNIPPET-FLAG, when t, indicates that this package is also needed
3818 when turning LaTeX snippets into images for inclusion into
3819 non-LaTeX output.
3821 Make sure that you only list packages here which:
3823 - you want in every file
3824 - do not conflict with the setup in `org-format-latex-header'.
3825 - do not conflict with the default packages in
3826 `org-latex-default-packages-alist'."
3827 :group 'org-latex
3828 :group 'org-export-latex
3829 :set 'org-set-packages-alist
3830 :get 'org-get-packages-alist
3831 :type '(repeat
3832 (choice
3833 (list :tag "options/package pair"
3834 (string :tag "options")
3835 (string :tag "package")
3836 (boolean :tag "Snippet"))
3837 (string :tag "A line of LaTeX"))))
3839 (defgroup org-appearance nil
3840 "Settings for Org-mode appearance."
3841 :tag "Org Appearance"
3842 :group 'org)
3844 (defcustom org-level-color-stars-only nil
3845 "Non-nil means fontify only the stars in each headline.
3846 When nil, the entire headline is fontified.
3847 Changing it requires restart of `font-lock-mode' to become effective
3848 also in regions already fontified."
3849 :group 'org-appearance
3850 :type 'boolean)
3852 (defcustom org-hide-leading-stars nil
3853 "Non-nil means hide the first N-1 stars in a headline.
3854 This works by using the face `org-hide' for these stars. This
3855 face is white for a light background, and black for a dark
3856 background. You may have to customize the face `org-hide' to
3857 make this work.
3858 Changing it requires restart of `font-lock-mode' to become effective
3859 also in regions already fontified.
3860 You may also set this on a per-file basis by adding one of the following
3861 lines to the buffer:
3863 #+STARTUP: hidestars
3864 #+STARTUP: showstars"
3865 :group 'org-appearance
3866 :type 'boolean)
3868 (defcustom org-hidden-keywords nil
3869 "List of symbols corresponding to keywords to be hidden the org buffer.
3870 For example, a value '(title) for this list will make the document's title
3871 appear in the buffer without the initial #+TITLE: keyword."
3872 :group 'org-appearance
3873 :version "24.1"
3874 :type '(set (const :tag "#+AUTHOR" author)
3875 (const :tag "#+DATE" date)
3876 (const :tag "#+EMAIL" email)
3877 (const :tag "#+TITLE" title)))
3879 (defcustom org-custom-properties nil
3880 "List of properties (as strings) with a special meaning.
3881 The default use of these custom properties is to let the user
3882 hide them with `org-toggle-custom-properties-visibility'."
3883 :group 'org-properties
3884 :group 'org-appearance
3885 :version "24.3"
3886 :type '(repeat (string :tag "Property Name")))
3888 (defcustom org-fontify-done-headline nil
3889 "Non-nil means change the face of a headline if it is marked DONE.
3890 Normally, only the TODO/DONE keyword indicates the state of a headline.
3891 When this is non-nil, the headline after the keyword is set to the
3892 `org-headline-done' as an additional indication."
3893 :group 'org-appearance
3894 :type 'boolean)
3896 (defcustom org-fontify-emphasized-text t
3897 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3898 Changing this variable requires a restart of Emacs to take effect."
3899 :group 'org-appearance
3900 :type 'boolean)
3902 (defcustom org-fontify-whole-heading-line nil
3903 "Non-nil means fontify the whole line for headings.
3904 This is useful when setting a background color for the
3905 org-level-* faces."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-highlight-latex-and-related nil
3910 "Non-nil means highlight LaTeX related syntax in the buffer.
3911 When non nil, the value should be a list containing any of the
3912 following symbols:
3913 `latex' Highlight LaTeX snippets and environments.
3914 `script' Highlight subscript and superscript.
3915 `entities' Highlight entities."
3916 :group 'org-appearance
3917 :type '(choice
3918 (const :tag "No highlighting" nil)
3919 (set :greedy t :tag "Highlight"
3920 (const :tag "LaTeX snippets and environments" latex)
3921 (const :tag "Subscript and superscript" script)
3922 (const :tag "Entities" entities))))
3924 (defcustom org-hide-emphasis-markers nil
3925 "Non-nil mean font-lock should hide the emphasis marker characters."
3926 :group 'org-appearance
3927 :type 'boolean)
3929 (defcustom org-pretty-entities nil
3930 "Non-nil means show entities as UTF8 characters.
3931 When nil, the \\name form remains in the buffer."
3932 :group 'org-appearance
3933 :version "24.1"
3934 :type 'boolean)
3936 (defcustom org-pretty-entities-include-sub-superscripts t
3937 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3938 :group 'org-appearance
3939 :version "24.1"
3940 :type 'boolean)
3942 (defvar org-emph-re nil
3943 "Regular expression for matching emphasis.
3944 After a match, the match groups contain these elements:
3945 0 The match of the full regular expression, including the characters
3946 before and after the proper match
3947 1 The character before the proper match, or empty at beginning of line
3948 2 The proper match, including the leading and trailing markers
3949 3 The leading marker like * or /, indicating the type of highlighting
3950 4 The text between the emphasis markers, not including the markers
3951 5 The character after the match, empty at the end of a line")
3952 (defvar org-verbatim-re nil
3953 "Regular expression for matching verbatim text.")
3954 (defvar org-emphasis-regexp-components) ; defined just below
3955 (defvar org-emphasis-alist) ; defined just below
3956 (defun org-set-emph-re (var val)
3957 "Set variable and compute the emphasis regular expression."
3958 (set var val)
3959 (when (and (boundp 'org-emphasis-alist)
3960 (boundp 'org-emphasis-regexp-components)
3961 org-emphasis-alist org-emphasis-regexp-components)
3962 (let* ((e org-emphasis-regexp-components)
3963 (pre (car e))
3964 (post (nth 1 e))
3965 (border (nth 2 e))
3966 (body (nth 3 e))
3967 (nl (nth 4 e))
3968 (body1 (concat body "*?"))
3969 (markers (mapconcat 'car org-emphasis-alist ""))
3970 (vmarkers (mapconcat
3971 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3972 org-emphasis-alist "")))
3973 ;; make sure special characters appear at the right position in the class
3974 (if (string-match "\\^" markers)
3975 (setq markers (concat (replace-match "" t t markers) "^")))
3976 (if (string-match "-" markers)
3977 (setq markers (concat (replace-match "" t t markers) "-")))
3978 (if (string-match "\\^" vmarkers)
3979 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3980 (if (string-match "-" vmarkers)
3981 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3982 (if (> nl 0)
3983 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3984 (int-to-string nl) "\\}")))
3985 ;; Make the regexp
3986 (setq org-emph-re
3987 (concat "\\([" pre "]\\|^\\)"
3988 "\\("
3989 "\\([" markers "]\\)"
3990 "\\("
3991 "[^" border "]\\|"
3992 "[^" border "]"
3993 body1
3994 "[^" border "]"
3995 "\\)"
3996 "\\3\\)"
3997 "\\([" post "]\\|$\\)"))
3998 (setq org-verbatim-re
3999 (concat "\\([" pre "]\\|^\\)"
4000 "\\("
4001 "\\([" vmarkers "]\\)"
4002 "\\("
4003 "[^" border "]\\|"
4004 "[^" border "]"
4005 body1
4006 "[^" border "]"
4007 "\\)"
4008 "\\3\\)"
4009 "\\([" post "]\\|$\\)")))))
4011 (defcustom org-emphasis-regexp-components
4012 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4013 "Components used to build the regular expression for emphasis.
4014 This is a list with five entries. Terminology: In an emphasis string
4015 like \" *strong word* \", we call the initial space PREMATCH, the final
4016 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4017 and \"trong wor\" is the body. The different components in this variable
4018 specify what is allowed/forbidden in each part:
4020 pre Chars allowed as prematch. Beginning of line will be allowed too.
4021 post Chars allowed as postmatch. End of line will be allowed too.
4022 border The chars *forbidden* as border characters.
4023 body-regexp A regexp like \".\" to match a body character. Don't use
4024 non-shy groups here, and don't allow newline here.
4025 newline The maximum number of newlines allowed in an emphasis exp.
4027 Use customize to modify this, or restart Emacs after changing it."
4028 :group 'org-appearance
4029 :set 'org-set-emph-re
4030 :type '(list
4031 (sexp :tag "Allowed chars in pre ")
4032 (sexp :tag "Allowed chars in post ")
4033 (sexp :tag "Forbidden chars in border ")
4034 (sexp :tag "Regexp for body ")
4035 (integer :tag "number of newlines allowed")
4036 (option (boolean :tag "Please ignore this button"))))
4038 (defcustom org-emphasis-alist
4039 `(("*" bold "<b>" "</b>")
4040 ("/" italic "<i>" "</i>")
4041 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4042 ("=" org-code "<code>" "</code>" verbatim)
4043 ("~" org-verbatim "<code>" "</code>" verbatim)
4044 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4045 "<del>" "</del>")
4047 "Special syntax for emphasized text.
4048 Text starting and ending with a special character will be emphasized, for
4049 example *bold*, _underlined_ and /italic/. This variable sets the marker
4050 characters, the face to be used by font-lock for highlighting in Org-mode
4051 Emacs buffers, and the HTML tags to be used for this.
4052 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4053 Use customize to modify this, or restart Emacs after changing it."
4054 :group 'org-appearance
4055 :set 'org-set-emph-re
4056 :type '(repeat
4057 (list
4058 (string :tag "Marker character")
4059 (choice
4060 (face :tag "Font-lock-face")
4061 (plist :tag "Face property list"))
4062 (string :tag "HTML start tag")
4063 (string :tag "HTML end tag")
4064 (option (const verbatim)))))
4066 (defvar org-protecting-blocks
4067 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4068 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4069 This is needed for font-lock setup.")
4071 ;;; Miscellaneous options
4073 (defgroup org-completion nil
4074 "Completion in Org-mode."
4075 :tag "Org Completion"
4076 :group 'org)
4078 (defcustom org-completion-use-ido nil
4079 "Non-nil means use ido completion wherever possible.
4080 Note that `ido-mode' must be active for this variable to be relevant.
4081 If you decide to turn this variable on, you might well want to turn off
4082 `org-outline-path-complete-in-steps'.
4083 See also `org-completion-use-iswitchb'."
4084 :group 'org-completion
4085 :type 'boolean)
4087 (defcustom org-completion-use-iswitchb nil
4088 "Non-nil means use iswitchb completion wherever possible.
4089 Note that `iswitchb-mode' must be active for this variable to be relevant.
4090 If you decide to turn this variable on, you might well want to turn off
4091 `org-outline-path-complete-in-steps'.
4092 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4093 :group 'org-completion
4094 :type 'boolean)
4096 (defcustom org-completion-fallback-command 'hippie-expand
4097 "The expansion command called by \\[pcomplete] in normal context.
4098 Normal means, no org-mode-specific context."
4099 :group 'org-completion
4100 :type 'function)
4102 ;;; Functions and variables from their packages
4103 ;; Declared here to avoid compiler warnings
4105 ;; XEmacs only
4106 (defvar outline-mode-menu-heading)
4107 (defvar outline-mode-menu-show)
4108 (defvar outline-mode-menu-hide)
4109 (defvar zmacs-regions) ; XEmacs regions
4111 ;; Emacs only
4112 (defvar mark-active)
4114 ;; Various packages
4115 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4116 (declare-function calendar-forward-day "cal-move" (arg))
4117 (declare-function calendar-goto-date "cal-move" (date))
4118 (declare-function calendar-goto-today "cal-move" ())
4119 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4120 (defvar calc-embedded-close-formula)
4121 (defvar calc-embedded-open-formula)
4122 (declare-function cdlatex-tab "ext:cdlatex" ())
4123 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4124 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4125 (defvar font-lock-unfontify-region-function)
4126 (declare-function iswitchb-read-buffer "iswitchb"
4127 (prompt &optional default require-match start matches-set))
4128 (defvar iswitchb-temp-buflist)
4129 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4130 (defvar org-agenda-tags-todo-honor-ignore-options)
4131 (declare-function org-agenda-skip "org-agenda" ())
4132 (declare-function
4133 org-agenda-format-item "org-agenda"
4134 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4135 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4136 (declare-function org-agenda-change-all-lines "org-agenda"
4137 (newhead hdmarker &optional fixface just-this))
4138 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4139 (declare-function org-agenda-maybe-redo "org-agenda" ())
4140 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4141 (beg end))
4142 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4143 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4144 "org-agenda" (&optional end))
4145 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4146 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4147 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4148 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4149 (declare-function org-indent-mode "org-indent" (&optional arg))
4150 (declare-function parse-time-string "parse-time" (string))
4151 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4152 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4153 (defvar remember-data-file)
4154 (defvar texmathp-why)
4155 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4156 (declare-function table--at-cell-p "table" (position &optional object at-column))
4158 (defvar org-latex-regexps)
4160 ;;; Autoload and prepare some org modules
4162 ;; Some table stuff that needs to be defined here, because it is used
4163 ;; by the functions setting up org-mode or checking for table context.
4165 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4166 "Detect an org-type or table-type table.")
4167 (defconst org-table-line-regexp "^[ \t]*|"
4168 "Detect an org-type table line.")
4169 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4170 "Detect an org-type table line.")
4171 (defconst org-table-hline-regexp "^[ \t]*|-"
4172 "Detect an org-type table hline.")
4173 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4174 "Detect a table-type table hline.")
4175 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4176 "Detect the first line outside a table when searching from within it.
4177 This works for both table types.")
4179 ;; Autoload the functions in org-table.el that are needed by functions here.
4181 (eval-and-compile
4182 (org-autoload "org-table"
4183 '(org-table-begin org-table-blank-field org-table-end)))
4185 ;;;###autoload
4186 (defun turn-on-orgtbl ()
4187 "Unconditionally turn on `orgtbl-mode'."
4188 (require 'org-table)
4189 (orgtbl-mode 1))
4191 (defun org-at-table-p (&optional table-type)
4192 "Return t if the cursor is inside an org-type table.
4193 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4194 (if org-enable-table-editor
4195 (save-excursion
4196 (beginning-of-line 1)
4197 (looking-at (if table-type org-table-any-line-regexp
4198 org-table-line-regexp)))
4199 nil))
4200 (defsubst org-table-p () (org-at-table-p))
4202 (defun org-at-table.el-p ()
4203 "Return t if and only if we are at a table.el table."
4204 (and (org-at-table-p 'any)
4205 (save-excursion
4206 (goto-char (org-table-begin 'any))
4207 (looking-at org-table1-hline-regexp))))
4209 (defun org-table-recognize-table.el ()
4210 "If there is a table.el table nearby, recognize it and move into it."
4211 (if org-table-tab-recognizes-table.el
4212 (if (org-at-table.el-p)
4213 (progn
4214 (beginning-of-line 1)
4215 (if (looking-at org-table-dataline-regexp)
4217 (if (looking-at org-table1-hline-regexp)
4218 (progn
4219 (beginning-of-line 2)
4220 (if (looking-at org-table-any-border-regexp)
4221 (beginning-of-line -1)))))
4222 (if (re-search-forward "|" (org-table-end t) t)
4223 (progn
4224 (require 'table)
4225 (if (table--at-cell-p (point))
4227 (message "recognizing table.el table...")
4228 (table-recognize-table)
4229 (message "recognizing table.el table...done")))
4230 (error "This should not happen"))
4232 nil)
4233 nil))
4235 (defun org-at-table-hline-p ()
4236 "Return t if the cursor is inside a hline in a table."
4237 (if org-enable-table-editor
4238 (save-excursion
4239 (beginning-of-line 1)
4240 (looking-at org-table-hline-regexp))
4241 nil))
4243 (defvar org-table-clean-did-remove-column nil)
4244 (defun org-table-map-tables (function &optional quietly)
4245 "Apply FUNCTION to the start of all tables in the buffer."
4246 (save-excursion
4247 (save-restriction
4248 (widen)
4249 (goto-char (point-min))
4250 (while (re-search-forward org-table-any-line-regexp nil t)
4251 (unless quietly
4252 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4253 (beginning-of-line 1)
4254 (when (and (looking-at org-table-line-regexp)
4255 ;; Exclude tables in src/example/verbatim/clocktable blocks
4256 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4257 (save-excursion (funcall function))
4258 (or (looking-at org-table-line-regexp)
4259 (forward-char 1)))
4260 (re-search-forward org-table-any-border-regexp nil 1))))
4261 (unless quietly (message "Mapping tables: done")))
4263 ;; Declare and autoload functions from ox.el and al.
4265 (declare-function org-export-get-environment "ox"
4266 (&optional backend subtreep ext-plist))
4267 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4269 ;; Declare and autoload functions from org-agenda.el
4271 (eval-and-compile
4272 (org-autoload "org-agenda"
4273 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4275 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4276 (declare-function org-clock-update-mode-line "org-clock" ())
4277 (declare-function org-resolve-clocks "org-clock"
4278 (&optional also-non-dangling-p prompt last-valid))
4279 (defvar org-clock-start-time)
4280 (defvar org-clock-marker (make-marker)
4281 "Marker recording the last clock-in.")
4282 (defvar org-clock-hd-marker (make-marker)
4283 "Marker recording the last clock-in, but the headline position.")
4284 (defvar org-clock-heading ""
4285 "The heading of the current clock entry.")
4286 (defun org-clock-is-active ()
4287 "Return non-nil if clock is currently running.
4288 The return value is actually the clock marker."
4289 (marker-buffer org-clock-marker))
4291 (eval-and-compile
4292 (org-autoload "org-clock" '(org-clock-remove-overlays
4293 org-clock-update-time-maybe
4294 org-clocktable-shift)))
4296 (defun org-check-running-clock ()
4297 "Check if the current buffer contains the running clock.
4298 If yes, offer to stop it and to save the buffer with the changes."
4299 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4300 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4301 (buffer-name))))
4302 (org-clock-out)
4303 (when (y-or-n-p "Save changed buffer?")
4304 (save-buffer))))
4306 (defun org-clocktable-try-shift (dir n)
4307 "Check if this line starts a clock table, if yes, shift the time block."
4308 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4309 (org-clocktable-shift dir n)))
4311 ;;;###autoload
4312 (defun org-clock-persistence-insinuate ()
4313 "Set up hooks for clock persistence."
4314 (require 'org-clock)
4315 (add-hook 'org-mode-hook 'org-clock-load)
4316 (add-hook 'kill-emacs-hook 'org-clock-save))
4318 ;; Define the variable already here, to make sure we have it.
4319 (defvar org-indent-mode nil
4320 "Non-nil if Org-Indent mode is enabled.
4321 Use the command `org-indent-mode' to change this variable.")
4323 ;; Autoload archiving code
4324 ;; The stuff that is needed for cycling and tags has to be defined here.
4326 (defgroup org-archive nil
4327 "Options concerning archiving in Org-mode."
4328 :tag "Org Archive"
4329 :group 'org-structure)
4331 (defcustom org-archive-location "%s_archive::"
4332 "The location where subtrees should be archived.
4334 The value of this variable is a string, consisting of two parts,
4335 separated by a double-colon. The first part is a filename and
4336 the second part is a headline.
4338 When the filename is omitted, archiving happens in the same file.
4339 %s in the filename will be replaced by the current file
4340 name (without the directory part). Archiving to a different file
4341 is useful to keep archived entries from contributing to the
4342 Org-mode Agenda.
4344 The archived entries will be filed as subtrees of the specified
4345 headline. When the headline is omitted, the subtrees are simply
4346 filed away at the end of the file, as top-level entries. Also in
4347 the heading you can use %s to represent the file name, this can be
4348 useful when using the same archive for a number of different files.
4350 Here are a few examples:
4351 \"%s_archive::\"
4352 If the current file is Projects.org, archive in file
4353 Projects.org_archive, as top-level trees. This is the default.
4355 \"::* Archived Tasks\"
4356 Archive in the current file, under the top-level headline
4357 \"* Archived Tasks\".
4359 \"~/org/archive.org::\"
4360 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4362 \"~/org/archive.org::* From %s\"
4363 Archive in file ~/org/archive.org (absolute path), under headlines
4364 \"From FILENAME\" where file name is the current file name.
4366 \"~/org/datetree.org::datetree/* Finished Tasks\"
4367 The \"datetree/\" string is special, signifying to archive
4368 items to the datetree. Items are placed in either the CLOSED
4369 date of the item, or the current date if there is no CLOSED date.
4370 The heading will be a subentry to the current date. There doesn't
4371 need to be a heading, but there always needs to be a slash after
4372 datetree. For example, to store archived items directly in the
4373 datetree, use \"~/org/datetree.org::datetree/\".
4375 \"basement::** Finished Tasks\"
4376 Archive in file ./basement (relative path), as level 3 trees
4377 below the level 2 heading \"** Finished Tasks\".
4379 You may set this option on a per-file basis by adding to the buffer a
4380 line like
4382 #+ARCHIVE: basement::** Finished Tasks
4384 You may also define it locally for a subtree by setting an ARCHIVE property
4385 in the entry. If such a property is found in an entry, or anywhere up
4386 the hierarchy, it will be used."
4387 :group 'org-archive
4388 :type 'string)
4390 (defcustom org-archive-tag "ARCHIVE"
4391 "The tag that marks a subtree as archived.
4392 An archived subtree does not open during visibility cycling, and does
4393 not contribute to the agenda listings.
4394 After changing this, font-lock must be restarted in the relevant buffers to
4395 get the proper fontification."
4396 :group 'org-archive
4397 :group 'org-keywords
4398 :type 'string)
4400 (defcustom org-agenda-skip-archived-trees t
4401 "Non-nil means the agenda will skip any items located in archived trees.
4402 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4403 variable is no longer recommended, you should leave it at the value t.
4404 Instead, use the key `v' to cycle the archives-mode in the agenda."
4405 :group 'org-archive
4406 :group 'org-agenda-skip
4407 :type 'boolean)
4409 (defcustom org-columns-skip-archived-trees t
4410 "Non-nil means ignore archived trees when creating column view."
4411 :group 'org-archive
4412 :group 'org-properties
4413 :type 'boolean)
4415 (defcustom org-cycle-open-archived-trees nil
4416 "Non-nil means `org-cycle' will open archived trees.
4417 An archived tree is a tree marked with the tag ARCHIVE.
4418 When nil, archived trees will stay folded. You can still open them with
4419 normal outline commands like `show-all', but not with the cycling commands."
4420 :group 'org-archive
4421 :group 'org-cycle
4422 :type 'boolean)
4424 (defcustom org-sparse-tree-open-archived-trees nil
4425 "Non-nil means sparse tree construction shows matches in archived trees.
4426 When nil, matches in these trees are highlighted, but the trees are kept in
4427 collapsed state."
4428 :group 'org-archive
4429 :group 'org-sparse-trees
4430 :type 'boolean)
4432 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4433 "The default date type when building a sparse tree.
4434 When this is nil, a date is a scheduled or a deadline timestamp.
4435 Otherwise, these types are allowed:
4437 all: all timestamps
4438 active: only active timestamps (<...>)
4439 inactive: only inactive timestamps (<...)
4440 scheduled: only scheduled timestamps
4441 deadline: only deadline timestamps"
4442 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4443 (const :tag "All timestamps" all)
4444 (const :tag "Only active timestamps" active)
4445 (const :tag "Only inactive timestamps" inactive)
4446 (const :tag "Only scheduled timestamps" scheduled)
4447 (const :tag "Only deadline timestamps" deadline))
4448 :version "24.3"
4449 :group 'org-sparse-trees)
4451 (defun org-cycle-hide-archived-subtrees (state)
4452 "Re-hide all archived subtrees after a visibility state change."
4453 (when (and (not org-cycle-open-archived-trees)
4454 (not (memq state '(overview folded))))
4455 (save-excursion
4456 (let* ((globalp (memq state '(contents all)))
4457 (beg (if globalp (point-min) (point)))
4458 (end (if globalp (point-max) (org-end-of-subtree t))))
4459 (org-hide-archived-subtrees beg end)
4460 (goto-char beg)
4461 (if (looking-at (concat ".*:" org-archive-tag ":"))
4462 (message "%s" (substitute-command-keys
4463 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4465 (defun org-force-cycle-archived ()
4466 "Cycle subtree even if it is archived."
4467 (interactive)
4468 (setq this-command 'org-cycle)
4469 (let ((org-cycle-open-archived-trees t))
4470 (call-interactively 'org-cycle)))
4472 (defun org-hide-archived-subtrees (beg end)
4473 "Re-hide all archived subtrees after a visibility state change."
4474 (save-excursion
4475 (let* ((re (concat ":" org-archive-tag ":")))
4476 (goto-char beg)
4477 (while (re-search-forward re end t)
4478 (when (org-at-heading-p)
4479 (org-flag-subtree t)
4480 (org-end-of-subtree t))))))
4482 (declare-function outline-end-of-heading "outline" ())
4483 (declare-function outline-flag-region "outline" (from to flag))
4484 (defun org-flag-subtree (flag)
4485 (save-excursion
4486 (org-back-to-heading t)
4487 (outline-end-of-heading)
4488 (outline-flag-region (point)
4489 (progn (org-end-of-subtree t) (point))
4490 flag)))
4492 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4494 (eval-and-compile
4495 (org-autoload "org-archive"
4496 '(org-add-archive-files)))
4498 ;; Autoload Column View Code
4500 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4501 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4502 (declare-function org-columns-compute "org-colview" (property))
4504 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4505 '(org-columns-number-to-string
4506 org-columns-get-format-and-top-level
4507 org-columns-compute
4508 org-columns-remove-overlays))
4510 ;; Autoload ID code
4512 (declare-function org-id-store-link "org-id")
4513 (declare-function org-id-locations-load "org-id")
4514 (declare-function org-id-locations-save "org-id")
4515 (defvar org-id-track-globally)
4516 (org-autoload "org-id"
4517 '(org-id-new
4518 org-id-copy
4519 org-id-get-with-outline-path-completion
4520 org-id-get-with-outline-drilling))
4522 ;;; Variables for pre-computed regular expressions, all buffer local
4524 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4525 "Matches first line of a hidden block.")
4526 (make-variable-buffer-local 'org-drawer-regexp)
4527 (defvar org-todo-regexp nil
4528 "Matches any of the TODO state keywords.")
4529 (make-variable-buffer-local 'org-todo-regexp)
4530 (defvar org-not-done-regexp nil
4531 "Matches any of the TODO state keywords except the last one.")
4532 (make-variable-buffer-local 'org-not-done-regexp)
4533 (defvar org-not-done-heading-regexp nil
4534 "Matches a TODO headline that is not done.")
4535 (make-variable-buffer-local 'org-not-done-regexp)
4536 (defvar org-todo-line-regexp nil
4537 "Matches a headline and puts TODO state into group 2 if present.")
4538 (make-variable-buffer-local 'org-todo-line-regexp)
4539 (defvar org-complex-heading-regexp nil
4540 "Matches a headline and puts everything into groups:
4541 group 1: the stars
4542 group 2: The todo keyword, maybe
4543 group 3: Priority cookie
4544 group 4: True headline
4545 group 5: Tags")
4546 (make-variable-buffer-local 'org-complex-heading-regexp)
4547 (defvar org-complex-heading-regexp-format nil
4548 "Printf format to make regexp to match an exact headline.
4549 This regexp will match the headline of any node which has the
4550 exact headline text that is put into the format, but may have any
4551 TODO state, priority and tags.")
4552 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4553 (defvar org-todo-line-tags-regexp nil
4554 "Matches a headline and puts TODO state into group 2 if present.
4555 Also put tags into group 4 if tags are present.")
4556 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4557 (defvar org-ds-keyword-length 12
4558 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4559 (make-variable-buffer-local 'org-ds-keyword-length)
4560 (defvar org-deadline-regexp nil
4561 "Matches the DEADLINE keyword.")
4562 (make-variable-buffer-local 'org-deadline-regexp)
4563 (defvar org-deadline-time-regexp nil
4564 "Matches the DEADLINE keyword together with a time stamp.")
4565 (make-variable-buffer-local 'org-deadline-time-regexp)
4566 (defvar org-deadline-line-regexp nil
4567 "Matches the DEADLINE keyword and the rest of the line.")
4568 (make-variable-buffer-local 'org-deadline-line-regexp)
4569 (defvar org-scheduled-regexp nil
4570 "Matches the SCHEDULED keyword.")
4571 (make-variable-buffer-local 'org-scheduled-regexp)
4572 (defvar org-scheduled-time-regexp nil
4573 "Matches the SCHEDULED keyword together with a time stamp.")
4574 (make-variable-buffer-local 'org-scheduled-time-regexp)
4575 (defvar org-closed-time-regexp nil
4576 "Matches the CLOSED keyword together with a time stamp.")
4577 (make-variable-buffer-local 'org-closed-time-regexp)
4579 (defvar org-keyword-time-regexp nil
4580 "Matches any of the 4 keywords, together with the time stamp.")
4581 (make-variable-buffer-local 'org-keyword-time-regexp)
4582 (defvar org-keyword-time-not-clock-regexp nil
4583 "Matches any of the 3 keywords, together with the time stamp.")
4584 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4585 (defvar org-maybe-keyword-time-regexp nil
4586 "Matches a timestamp, possibly preceded by a keyword.")
4587 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4588 (defvar org-all-time-keywords nil
4589 "List of time keywords.")
4590 (make-variable-buffer-local 'org-all-time-keywords)
4592 (defconst org-plain-time-of-day-regexp
4593 (concat
4594 "\\(\\<[012]?[0-9]"
4595 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4596 "\\(--?"
4597 "\\(\\<[012]?[0-9]"
4598 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4599 "\\)?")
4600 "Regular expression to match a plain time or time range.
4601 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4602 groups carry important information:
4603 0 the full match
4604 1 the first time, range or not
4605 8 the second time, if it is a range.")
4607 (defconst org-plain-time-extension-regexp
4608 (concat
4609 "\\(\\<[012]?[0-9]"
4610 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4611 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4612 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4613 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4614 groups carry important information:
4615 0 the full match
4616 7 hours of duration
4617 9 minutes of duration")
4619 (defconst org-stamp-time-of-day-regexp
4620 (concat
4621 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4622 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4623 "\\(--?"
4624 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4625 "Regular expression to match a timestamp time or time range.
4626 After a match, the following groups carry important information:
4627 0 the full match
4628 1 date plus weekday, for back referencing to make sure both times are on the same day
4629 2 the first time, range or not
4630 4 the second time, if it is a range.")
4632 (defconst org-startup-options
4633 '(("fold" org-startup-folded t)
4634 ("overview" org-startup-folded t)
4635 ("nofold" org-startup-folded nil)
4636 ("showall" org-startup-folded nil)
4637 ("showeverything" org-startup-folded showeverything)
4638 ("content" org-startup-folded content)
4639 ("indent" org-startup-indented t)
4640 ("noindent" org-startup-indented nil)
4641 ("hidestars" org-hide-leading-stars t)
4642 ("showstars" org-hide-leading-stars nil)
4643 ("odd" org-odd-levels-only t)
4644 ("oddeven" org-odd-levels-only nil)
4645 ("align" org-startup-align-all-tables t)
4646 ("noalign" org-startup-align-all-tables nil)
4647 ("inlineimages" org-startup-with-inline-images t)
4648 ("noinlineimages" org-startup-with-inline-images nil)
4649 ("latexpreview" org-startup-with-latex-preview t)
4650 ("nolatexpreview" org-startup-with-latex-preview nil)
4651 ("customtime" org-display-custom-times t)
4652 ("logdone" org-log-done time)
4653 ("lognotedone" org-log-done note)
4654 ("nologdone" org-log-done nil)
4655 ("lognoteclock-out" org-log-note-clock-out t)
4656 ("nolognoteclock-out" org-log-note-clock-out nil)
4657 ("logrepeat" org-log-repeat state)
4658 ("lognoterepeat" org-log-repeat note)
4659 ("logdrawer" org-log-into-drawer t)
4660 ("nologdrawer" org-log-into-drawer nil)
4661 ("logstatesreversed" org-log-states-order-reversed t)
4662 ("nologstatesreversed" org-log-states-order-reversed nil)
4663 ("nologrepeat" org-log-repeat nil)
4664 ("logreschedule" org-log-reschedule time)
4665 ("lognotereschedule" org-log-reschedule note)
4666 ("nologreschedule" org-log-reschedule nil)
4667 ("logredeadline" org-log-redeadline time)
4668 ("lognoteredeadline" org-log-redeadline note)
4669 ("nologredeadline" org-log-redeadline nil)
4670 ("logrefile" org-log-refile time)
4671 ("lognoterefile" org-log-refile note)
4672 ("nologrefile" org-log-refile nil)
4673 ("fninline" org-footnote-define-inline t)
4674 ("nofninline" org-footnote-define-inline nil)
4675 ("fnlocal" org-footnote-section nil)
4676 ("fnauto" org-footnote-auto-label t)
4677 ("fnprompt" org-footnote-auto-label nil)
4678 ("fnconfirm" org-footnote-auto-label confirm)
4679 ("fnplain" org-footnote-auto-label plain)
4680 ("fnadjust" org-footnote-auto-adjust t)
4681 ("nofnadjust" org-footnote-auto-adjust nil)
4682 ("constcgs" constants-unit-system cgs)
4683 ("constSI" constants-unit-system SI)
4684 ("noptag" org-tag-persistent-alist nil)
4685 ("hideblocks" org-hide-block-startup t)
4686 ("nohideblocks" org-hide-block-startup nil)
4687 ("beamer" org-startup-with-beamer-mode t)
4688 ("entitiespretty" org-pretty-entities t)
4689 ("entitiesplain" org-pretty-entities nil))
4690 "Variable associated with STARTUP options for org-mode.
4691 Each element is a list of three items: the startup options (as written
4692 in the #+STARTUP line), the corresponding variable, and the value to set
4693 this variable to if the option is found. An optional forth element PUSH
4694 means to push this value onto the list in the variable.")
4696 (defun org-update-property-plist (key val props)
4697 "Update PROPS with KEY and VAL."
4698 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4699 (key (if appending (substring key 0 (- (length key) 1)) key))
4700 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4701 (previous (cdr (assoc key props))))
4702 (if appending
4703 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4704 (cons (cons key val) remainder))))
4706 (defconst org-block-regexp
4707 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4708 "Regular expression for hiding blocks.")
4709 (defconst org-heading-keyword-regexp-format
4710 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4711 "Printf format for a regexp matching a headline with some keyword.
4712 This regexp will match the headline of any node which has the
4713 exact keyword that is put into the format. The keyword isn't in
4714 any group by default, but the stars and the body are.")
4715 (defconst org-heading-keyword-maybe-regexp-format
4716 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4717 "Printf format for a regexp matching a headline, possibly with some keyword.
4718 This regexp can match any headline with the specified keyword, or
4719 without a keyword. The keyword isn't in any group by default,
4720 but the stars and the body are.")
4722 (defun org-set-regexps-and-options ()
4723 "Precompute regular expressions for current buffer."
4724 (when (derived-mode-p 'org-mode)
4725 (org-set-local 'org-todo-kwd-alist nil)
4726 (org-set-local 'org-todo-key-alist nil)
4727 (org-set-local 'org-todo-key-trigger nil)
4728 (org-set-local 'org-todo-keywords-1 nil)
4729 (org-set-local 'org-done-keywords nil)
4730 (org-set-local 'org-todo-heads nil)
4731 (org-set-local 'org-todo-sets nil)
4732 (org-set-local 'org-todo-log-states nil)
4733 (org-set-local 'org-file-properties nil)
4734 (org-set-local 'org-file-tags nil)
4735 (let ((re (org-make-options-regexp
4736 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4737 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4738 "SETUPFILE" "OPTIONS")
4739 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4740 (splitre "[ \t]+")
4741 (scripts org-use-sub-superscripts)
4742 kwds kws0 kwsa key log value cat arch tags const links hw dws
4743 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4744 (start 0))
4745 (save-excursion
4746 (save-restriction
4747 (widen)
4748 (goto-char (point-min))
4749 (while (or (and ext-setup-or-nil
4750 (string-match re ext-setup-or-nil start)
4751 (setq start (match-end 0)))
4752 (and (setq ext-setup-or-nil nil start 0)
4753 (re-search-forward re nil t)))
4754 (setq key (upcase (match-string 1 ext-setup-or-nil))
4755 value (org-match-string-no-properties 2 ext-setup-or-nil))
4756 (if (stringp value) (setq value (org-trim value)))
4757 (cond
4758 ((equal key "CATEGORY")
4759 (setq cat value))
4760 ((member key '("SEQ_TODO" "TODO"))
4761 (push (cons 'sequence (org-split-string value splitre)) kwds))
4762 ((equal key "TYP_TODO")
4763 (push (cons 'type (org-split-string value splitre)) kwds))
4764 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4765 ;; general TODO-like setup
4766 (push (cons (intern (downcase (match-string 1 key)))
4767 (org-split-string value splitre)) kwds))
4768 ((equal key "TAGS")
4769 (setq tags (append tags (if tags '("\\n") nil)
4770 (org-split-string value splitre))))
4771 ((equal key "COLUMNS")
4772 (org-set-local 'org-columns-default-format value))
4773 ((equal key "LINK")
4774 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4775 (push (cons (match-string 1 value)
4776 (org-trim (match-string 2 value)))
4777 links)))
4778 ((equal key "PRIORITIES")
4779 (setq prio (org-split-string value " +")))
4780 ((equal key "PROPERTY")
4781 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4782 (setq props (org-update-property-plist (match-string 1 value)
4783 (match-string 2 value)
4784 props))))
4785 ((equal key "FILETAGS")
4786 (when (string-match "\\S-" value)
4787 (setq ftags
4788 (append
4789 ftags
4790 (apply 'append
4791 (mapcar (lambda (x) (org-split-string x ":"))
4792 (org-split-string value)))))))
4793 ((equal key "DRAWERS")
4794 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4795 ((equal key "CONSTANTS")
4796 (setq const (append const (org-split-string value splitre))))
4797 ((equal key "STARTUP")
4798 (let ((opts (org-split-string value splitre))
4799 l var val)
4800 (while (setq l (pop opts))
4801 (when (setq l (assoc l org-startup-options))
4802 (setq var (nth 1 l) val (nth 2 l))
4803 (if (not (nth 3 l))
4804 (set (make-local-variable var) val)
4805 (if (not (listp (symbol-value var)))
4806 (set (make-local-variable var) nil))
4807 (set (make-local-variable var) (symbol-value var))
4808 (add-to-list var val))))))
4809 ((equal key "ARCHIVE")
4810 (setq arch value)
4811 (remove-text-properties 0 (length arch)
4812 '(face t fontified t) arch))
4813 ((equal key "OPTIONS")
4814 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4815 (setq scripts (read (match-string 2 value)))))
4816 ((equal key "SETUPFILE")
4817 (setq setup-contents (org-file-contents
4818 (expand-file-name
4819 (org-remove-double-quotes value))
4820 'noerror))
4821 (if (not ext-setup-or-nil)
4822 (setq ext-setup-or-nil setup-contents start 0)
4823 (setq ext-setup-or-nil
4824 (concat (substring ext-setup-or-nil 0 start)
4825 "\n" setup-contents "\n"
4826 (substring ext-setup-or-nil start)))))))
4827 ;; search for property blocks
4828 (goto-char (point-min))
4829 (while (re-search-forward org-block-regexp nil t)
4830 (when (equal "PROPERTY" (upcase (match-string 1)))
4831 (setq value (replace-regexp-in-string
4832 "[\n\r]" " " (match-string 4)))
4833 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4834 (setq props (org-update-property-plist (match-string 1 value)
4835 (match-string 2 value)
4836 props)))))))
4837 (org-set-local 'org-use-sub-superscripts scripts)
4838 (when cat
4839 (org-set-local 'org-category (intern cat))
4840 (push (cons "CATEGORY" cat) props))
4841 (when prio
4842 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4843 (setq prio (mapcar 'string-to-char prio))
4844 (org-set-local 'org-highest-priority (nth 0 prio))
4845 (org-set-local 'org-lowest-priority (nth 1 prio))
4846 (org-set-local 'org-default-priority (nth 2 prio)))
4847 (and props (org-set-local 'org-file-properties (nreverse props)))
4848 (and ftags (org-set-local 'org-file-tags
4849 (mapcar 'org-add-prop-inherited ftags)))
4850 (and drawers (org-set-local 'org-drawers drawers))
4851 (and arch (org-set-local 'org-archive-location arch))
4852 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4853 ;; Process the TODO keywords
4854 (unless kwds
4855 ;; Use the global values as if they had been given locally.
4856 (setq kwds (default-value 'org-todo-keywords))
4857 (if (stringp (car kwds))
4858 (setq kwds (list (cons org-todo-interpretation
4859 (default-value 'org-todo-keywords)))))
4860 (setq kwds (reverse kwds)))
4861 (setq kwds (nreverse kwds))
4862 (let (inter kws kw)
4863 (while (setq kws (pop kwds))
4864 (let ((kws (or
4865 (run-hook-with-args-until-success
4866 'org-todo-setup-filter-hook kws)
4867 kws)))
4868 (setq inter (pop kws) sep (member "|" kws)
4869 kws0 (delete "|" (copy-sequence kws))
4870 kwsa nil
4871 kws1 (mapcar
4872 (lambda (x)
4873 ;; 1 2
4874 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4875 (progn
4876 (setq kw (match-string 1 x)
4877 key (and (match-end 2) (match-string 2 x))
4878 log (org-extract-log-state-settings x))
4879 (push (cons kw (and key (string-to-char key))) kwsa)
4880 (and log (push log org-todo-log-states))
4882 (error "Invalid TODO keyword %s" x)))
4883 kws0)
4884 kwsa (if kwsa (append '((:startgroup))
4885 (nreverse kwsa)
4886 '((:endgroup))))
4887 hw (car kws1)
4888 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4889 tail (list inter hw (car dws) (org-last dws))))
4890 (add-to-list 'org-todo-heads hw 'append)
4891 (push kws1 org-todo-sets)
4892 (setq org-done-keywords (append org-done-keywords dws nil))
4893 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4894 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4895 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4896 (setq org-todo-sets (nreverse org-todo-sets)
4897 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4898 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4899 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4900 ;; Process the constants
4901 (when const
4902 (let (e cst)
4903 (while (setq e (pop const))
4904 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4905 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4906 (setq org-table-formula-constants-local cst)))
4908 ;; Process the tags.
4909 (when tags
4910 (let (e tgs)
4911 (while (setq e (pop tags))
4912 (cond
4913 ((equal e "{") (push '(:startgroup) tgs))
4914 ((equal e "}") (push '(:endgroup) tgs))
4915 ((equal e "\\n") (push '(:newline) tgs))
4916 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4917 (push (cons (match-string 1 e)
4918 (string-to-char (match-string 2 e)))
4919 tgs))
4920 (t (push (list e) tgs))))
4921 (org-set-local 'org-tag-alist nil)
4922 (while (setq e (pop tgs))
4923 (or (and (stringp (car e))
4924 (assoc (car e) org-tag-alist))
4925 (push e org-tag-alist)))))
4927 ;; Compute the regular expressions and other local variables.
4928 ;; Using `org-outline-regexp-bol' would complicate them much,
4929 ;; because of the fixed white space at the end of that string.
4930 (if (not org-done-keywords)
4931 (setq org-done-keywords (and org-todo-keywords-1
4932 (list (org-last org-todo-keywords-1)))))
4933 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4934 (length org-scheduled-string)
4935 (length org-clock-string)
4936 (length org-closed-string)))
4937 org-drawer-regexp
4938 (concat "^[ \t]*:\\("
4939 (mapconcat 'regexp-quote org-drawers "\\|")
4940 "\\):[ \t]*$")
4941 org-not-done-keywords
4942 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4943 org-todo-regexp
4944 (concat "\\("
4945 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4946 "\\)")
4947 org-not-done-regexp
4948 (concat "\\("
4949 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4950 "\\)")
4951 org-not-done-heading-regexp
4952 (format org-heading-keyword-regexp-format org-not-done-regexp)
4953 org-todo-line-regexp
4954 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4955 org-complex-heading-regexp
4956 (concat "^\\(\\*+\\)"
4957 "\\(?: +" org-todo-regexp "\\)?"
4958 "\\(?: +\\(\\[#.\\]\\)\\)?"
4959 "\\(?: +\\(.*?\\)\\)??"
4960 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4961 "[ \t]*$")
4962 org-complex-heading-regexp-format
4963 (concat "^\\(\\*+\\)"
4964 "\\(?: +" org-todo-regexp "\\)?"
4965 "\\(?: +\\(\\[#.\\]\\)\\)?"
4966 "\\(?: +"
4967 ;; Stats cookies can be stuck to body.
4968 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4969 "\\(%s\\)"
4970 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4971 "\\)"
4972 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4973 "[ \t]*$")
4974 org-todo-line-tags-regexp
4975 (concat "^\\(\\*+\\)"
4976 "\\(?: +" org-todo-regexp "\\)?"
4977 "\\(?: +\\(.*?\\)\\)??"
4978 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4979 "[ \t]*$")
4980 org-deadline-regexp (concat "\\<" org-deadline-string)
4981 org-deadline-time-regexp
4982 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4983 org-deadline-line-regexp
4984 (concat "\\<\\(" org-deadline-string "\\).*")
4985 org-scheduled-regexp
4986 (concat "\\<" org-scheduled-string)
4987 org-scheduled-time-regexp
4988 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4989 org-closed-time-regexp
4990 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4991 org-keyword-time-regexp
4992 (concat "\\<\\(" org-scheduled-string
4993 "\\|" org-deadline-string
4994 "\\|" org-closed-string
4995 "\\|" org-clock-string "\\)"
4996 " *[[<]\\([^]>]+\\)[]>]")
4997 org-keyword-time-not-clock-regexp
4998 (concat "\\<\\(" org-scheduled-string
4999 "\\|" org-deadline-string
5000 "\\|" org-closed-string
5001 "\\)"
5002 " *[[<]\\([^]>]+\\)[]>]")
5003 org-maybe-keyword-time-regexp
5004 (concat "\\(\\<\\(" org-scheduled-string
5005 "\\|" org-deadline-string
5006 "\\|" org-closed-string
5007 "\\|" org-clock-string "\\)\\)?"
5008 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5009 org-all-time-keywords
5010 (mapcar (lambda (w) (substring w 0 -1))
5011 (list org-scheduled-string org-deadline-string
5012 org-clock-string org-closed-string)))
5013 (org-compute-latex-and-related-regexp)
5014 (org-set-font-lock-defaults))))
5016 (defun org-file-contents (file &optional noerror)
5017 "Return the contents of FILE, as a string."
5018 (if (or (not file)
5019 (not (file-readable-p file)))
5020 (if noerror
5021 (progn
5022 (message "Cannot read file \"%s\"" file)
5023 (ding) (sit-for 2)
5025 (error "Cannot read file \"%s\"" file))
5026 (with-temp-buffer
5027 (insert-file-contents file)
5028 (buffer-string))))
5030 (defun org-extract-log-state-settings (x)
5031 "Extract the log state setting from a TODO keyword string.
5032 This will extract info from a string like \"WAIT(w@/!)\"."
5033 (let (kw key log1 log2)
5034 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5035 (setq kw (match-string 1 x)
5036 key (and (match-end 2) (match-string 2 x))
5037 log1 (and (match-end 3) (match-string 3 x))
5038 log2 (and (match-end 4) (match-string 4 x)))
5039 (and (or log1 log2)
5040 (list kw
5041 (and log1 (if (equal log1 "!") 'time 'note))
5042 (and log2 (if (equal log2 "!") 'time 'note)))))))
5044 (defun org-remove-keyword-keys (list)
5045 "Remove a pair of parenthesis at the end of each string in LIST."
5046 (mapcar (lambda (x)
5047 (if (string-match "(.*)$" x)
5048 (substring x 0 (match-beginning 0))
5050 list))
5052 (defun org-assign-fast-keys (alist)
5053 "Assign fast keys to a keyword-key alist.
5054 Respect keys that are already there."
5055 (let (new e (alt ?0))
5056 (while (setq e (pop alist))
5057 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5058 (cdr e)) ;; Key already assigned.
5059 (push e new)
5060 (let ((clist (string-to-list (downcase (car e))))
5061 (used (append new alist)))
5062 (when (= (car clist) ?@)
5063 (pop clist))
5064 (while (and clist (rassoc (car clist) used))
5065 (pop clist))
5066 (unless clist
5067 (while (rassoc alt used)
5068 (incf alt)))
5069 (push (cons (car e) (or (car clist) alt)) new))))
5070 (nreverse new)))
5072 ;;; Some variables used in various places
5074 (defvar org-window-configuration nil
5075 "Used in various places to store a window configuration.")
5076 (defvar org-selected-window nil
5077 "Used in various places to store a window configuration.")
5078 (defvar org-finish-function nil
5079 "Function to be called when `C-c C-c' is used.
5080 This is for getting out of special buffers like capture.")
5083 ;; FIXME: Occasionally check by commenting these, to make sure
5084 ;; no other functions uses these, forgetting to let-bind them.
5085 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5086 (defvar org-last-state)
5087 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5089 ;; Defined somewhere in this file, but used before definition.
5090 (defvar org-entities) ;; defined in org-entities.el
5091 (defvar org-struct-menu)
5092 (defvar org-org-menu)
5093 (defvar org-tbl-menu)
5095 ;;;; Define the Org-mode
5097 ;; We use a before-change function to check if a table might need
5098 ;; an update.
5099 (defvar org-table-may-need-update t
5100 "Indicates that a table might need an update.
5101 This variable is set by `org-before-change-function'.
5102 `org-table-align' sets it back to nil.")
5103 (defun org-before-change-function (beg end)
5104 "Every change indicates that a table might need an update."
5105 (setq org-table-may-need-update t))
5106 (defvar org-mode-map)
5107 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5108 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5109 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5110 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5111 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5112 (defvar org-table-buffer-is-an nil)
5114 (defvar bidi-paragraph-direction)
5115 (defvar buffer-face-mode-face)
5117 (require 'outline)
5118 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5119 (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"))
5120 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5122 ;; Other stuff we need.
5123 (require 'time-date)
5124 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5125 (require 'easymenu)
5126 (require 'overlay)
5128 ;; (require 'org-macs) moved higher up in the file before it is first used
5129 (require 'org-entities)
5130 ;; (require 'org-compat) moved higher up in the file before it is first used
5131 (require 'org-faces)
5132 (require 'org-list)
5133 (require 'org-pcomplete)
5134 (require 'org-src)
5135 (require 'org-footnote)
5136 (require 'org-macro)
5138 ;; babel
5139 (require 'ob)
5141 ;;;###autoload
5142 (define-derived-mode org-mode outline-mode "Org"
5143 "Outline-based notes management and organizer, alias
5144 \"Carsten's outline-mode for keeping track of everything.\"
5146 Org-mode develops organizational tasks around a NOTES file which
5147 contains information about projects as plain text. Org-mode is
5148 implemented on top of outline-mode, which is ideal to keep the content
5149 of large files well structured. It supports ToDo items, deadlines and
5150 time stamps, which magically appear in the diary listing of the Emacs
5151 calendar. Tables are easily created with a built-in table editor.
5152 Plain text URL-like links connect to websites, emails (VM), Usenet
5153 messages (Gnus), BBDB entries, and any files related to the project.
5154 For printing and sharing of notes, an Org-mode file (or a part of it)
5155 can be exported as a structured ASCII or HTML file.
5157 The following commands are available:
5159 \\{org-mode-map}"
5161 ;; Get rid of Outline menus, they are not needed
5162 ;; Need to do this here because define-derived-mode sets up
5163 ;; the keymap so late. Still, it is a waste to call this each time
5164 ;; we switch another buffer into org-mode.
5165 (if (featurep 'xemacs)
5166 (when (boundp 'outline-mode-menu-heading)
5167 ;; Assume this is Greg's port, it uses easymenu
5168 (easy-menu-remove outline-mode-menu-heading)
5169 (easy-menu-remove outline-mode-menu-show)
5170 (easy-menu-remove outline-mode-menu-hide))
5171 (define-key org-mode-map [menu-bar headings] 'undefined)
5172 (define-key org-mode-map [menu-bar hide] 'undefined)
5173 (define-key org-mode-map [menu-bar show] 'undefined))
5175 (org-load-modules-maybe)
5176 (easy-menu-add org-org-menu)
5177 (easy-menu-add org-tbl-menu)
5178 (org-install-agenda-files-menu)
5179 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5180 (add-to-invisibility-spec '(org-cwidth))
5181 (add-to-invisibility-spec '(org-hide-block . t))
5182 (when (featurep 'xemacs)
5183 (org-set-local 'line-move-ignore-invisible t))
5184 (org-set-local 'outline-regexp org-outline-regexp)
5185 (org-set-local 'outline-level 'org-outline-level)
5186 (setq bidi-paragraph-direction 'left-to-right)
5187 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5188 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5189 (when (and org-ellipsis
5190 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5191 (fboundp 'make-glyph-code))
5192 (unless org-display-table
5193 (setq org-display-table (make-display-table)))
5194 (set-display-table-slot
5195 org-display-table 4
5196 (vconcat (mapcar
5197 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5198 org-ellipsis)))
5199 (if (stringp org-ellipsis) org-ellipsis "..."))))
5200 (setq buffer-display-table org-display-table))
5201 (org-set-regexps-and-options)
5202 (when (and org-tag-faces (not org-tags-special-faces-re))
5203 ;; tag faces set outside customize.... force initialization.
5204 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5205 ;; Calc embedded
5206 (org-set-local 'calc-embedded-open-mode "# ")
5207 ;; Modify a few syntax entries
5208 (modify-syntax-entry ?@ "w")
5209 (modify-syntax-entry ?\" "\"")
5210 (if org-startup-truncated (setq truncate-lines t))
5211 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5212 (org-set-local 'font-lock-unfontify-region-function
5213 'org-unfontify-region)
5214 ;; Activate before-change-function
5215 (org-set-local 'org-table-may-need-update t)
5216 (org-add-hook 'before-change-functions 'org-before-change-function nil
5217 'local)
5218 ;; Check for running clock before killing a buffer
5219 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5220 ;; Initialize macros templates.
5221 (org-macro-initialize-templates)
5222 ;; Initialize radio targets.
5223 (org-update-radio-target-regexp)
5224 ;; Indentation.
5225 (org-set-local 'indent-line-function 'org-indent-line)
5226 (org-set-local 'indent-region-function 'org-indent-region)
5227 ;; Filling and auto-filling.
5228 (org-setup-filling)
5229 ;; Comments.
5230 (org-setup-comments-handling)
5231 ;; Beginning/end of defun
5232 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5233 (org-set-local 'end-of-defun-function 'org-forward-element)
5234 ;; Next error for sparse trees
5235 (org-set-local 'next-error-function 'org-occur-next-match)
5236 ;; Make sure dependence stuff works reliably, even for users who set it
5237 ;; too late :-(
5238 (if org-enforce-todo-dependencies
5239 (add-hook 'org-blocker-hook
5240 'org-block-todo-from-children-or-siblings-or-parent)
5241 (remove-hook 'org-blocker-hook
5242 'org-block-todo-from-children-or-siblings-or-parent))
5243 (if org-enforce-todo-checkbox-dependencies
5244 (add-hook 'org-blocker-hook
5245 'org-block-todo-from-checkboxes)
5246 (remove-hook 'org-blocker-hook
5247 'org-block-todo-from-checkboxes))
5249 ;; Align options lines
5250 (org-set-local
5251 'align-mode-rules-list
5252 '((org-in-buffer-settings
5253 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5254 (modes . '(org-mode)))))
5256 ;; Imenu
5257 (org-set-local 'imenu-create-index-function
5258 'org-imenu-get-tree)
5260 ;; Make isearch reveal context
5261 (if (or (featurep 'xemacs)
5262 (not (boundp 'outline-isearch-open-invisible-function)))
5263 ;; Emacs 21 and XEmacs make use of the hook
5264 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5265 ;; Emacs 22 deals with this through a special variable
5266 (org-set-local 'outline-isearch-open-invisible-function
5267 (lambda (&rest ignore) (org-show-context 'isearch)))
5268 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5270 ;; Setup the pcomplete hooks
5271 (set (make-local-variable 'pcomplete-command-completion-function)
5272 'org-pcomplete-initial)
5273 (set (make-local-variable 'pcomplete-command-name-function)
5274 'org-command-at-point)
5275 (set (make-local-variable 'pcomplete-default-completion-function)
5276 'ignore)
5277 (set (make-local-variable 'pcomplete-parse-arguments-function)
5278 'org-parse-arguments)
5279 (set (make-local-variable 'pcomplete-termination-string) "")
5280 (when (>= emacs-major-version 23)
5281 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5283 ;; If empty file that did not turn on org-mode automatically, make it to.
5284 (if (and org-insert-mode-line-in-empty-file
5285 (org-called-interactively-p 'any)
5286 (= (point-min) (point-max)))
5287 (insert "# -*- mode: org -*-\n\n"))
5288 (unless org-inhibit-startup
5289 (org-unmodified
5290 (and org-startup-with-beamer-mode (org-beamer-mode))
5291 (when org-startup-align-all-tables
5292 (org-table-map-tables 'org-table-align 'quietly))
5293 (when org-startup-with-inline-images
5294 (org-display-inline-images))
5295 (when org-startup-with-latex-preview
5296 (org-preview-latex-fragment))
5297 (unless org-inhibit-startup-visibility-stuff
5298 (org-set-startup-visibility))))
5299 ;; Try to set org-hide correctly
5300 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5302 (defvar org-mode-transpose-word-syntax-table
5303 (let ((st (make-syntax-table)))
5304 (mapc (lambda(c) (modify-syntax-entry
5305 (string-to-char (car c)) "w p" st))
5306 org-emphasis-alist)
5307 st))
5309 (when (fboundp 'abbrev-table-put)
5310 (abbrev-table-put org-mode-abbrev-table
5311 :parents (list text-mode-abbrev-table)))
5313 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5315 (defsubst org-fix-ellipsis-at-bol ()
5316 (save-excursion (goto-char (window-start)) (recenter 0)))
5318 (defun org-find-invisible-foreground ()
5319 (let ((candidates (remove
5320 "unspecified-bg"
5321 (nconc
5322 (list (face-background 'default)
5323 (face-background 'org-default))
5324 (mapcar
5325 (lambda (alist)
5326 (when (boundp alist)
5327 (cdr (assoc 'background-color (symbol-value alist)))))
5328 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5329 (list (face-foreground 'org-hide))))))
5330 (car (remove nil candidates))))
5332 (defun org-current-time (&optional rounding-minutes past)
5333 "Current time, possibly rounded to ROUNDING-MINUTES.
5334 When ROUNDING-MINUTES is not an integer, fall back on the car of
5335 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5336 the rounding returns a past time."
5337 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5338 (car org-time-stamp-rounding-minutes)))
5339 (time (decode-time)) res)
5340 (if (< r 1)
5341 (current-time)
5342 (setq res
5343 (apply 'encode-time
5344 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5345 (nthcdr 2 time))))
5346 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5347 (seconds-to-time (- (org-float-time res) (* r 60)))
5348 res))))
5350 (defun org-today ()
5351 "Return today date, considering `org-extend-today-until'."
5352 (time-to-days
5353 (time-subtract (current-time)
5354 (list 0 (* 3600 org-extend-today-until) 0))))
5356 ;;;; Font-Lock stuff, including the activators
5358 (defvar org-mouse-map (make-sparse-keymap))
5359 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5360 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5361 (when org-mouse-1-follows-link
5362 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5363 (when org-tab-follows-link
5364 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5365 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5367 (require 'font-lock)
5369 (defconst org-non-link-chars "]\t\n\r<>")
5370 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5371 "shell" "elisp" "doi" "message"))
5372 (defvar org-link-types-re nil
5373 "Matches a link that has a url-like prefix like \"http:\"")
5374 (defvar org-link-re-with-space nil
5375 "Matches a link with spaces, optional angular brackets around it.")
5376 (defvar org-link-re-with-space2 nil
5377 "Matches a link with spaces, optional angular brackets around it.")
5378 (defvar org-link-re-with-space3 nil
5379 "Matches a link with spaces, only for internal part in bracket links.")
5380 (defvar org-angle-link-re nil
5381 "Matches link with angular brackets, spaces are allowed.")
5382 (defvar org-plain-link-re nil
5383 "Matches plain link, without spaces.")
5384 (defvar org-bracket-link-regexp nil
5385 "Matches a link in double brackets.")
5386 (defvar org-bracket-link-analytic-regexp nil
5387 "Regular expression used to analyze links.
5388 Here is what the match groups contain after a match:
5389 1: http:
5390 2: http
5391 3: path
5392 4: [desc]
5393 5: desc")
5394 (defvar org-bracket-link-analytic-regexp++ nil
5395 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5396 (defvar org-any-link-re nil
5397 "Regular expression matching any link.")
5399 (defconst org-match-sexp-depth 3
5400 "Number of stacked braces for sub/superscript matching.")
5402 (defun org-create-multibrace-regexp (left right n)
5403 "Create a regular expression which will match a balanced sexp.
5404 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5405 as single character strings.
5406 The regexp returned will match the entire expression including the
5407 delimiters. It will also define a single group which contains the
5408 match except for the outermost delimiters. The maximum depth of
5409 stacked delimiters is N. Escaping delimiters is not possible."
5410 (let* ((nothing (concat "[^" left right "]*?"))
5411 (or "\\|")
5412 (re nothing)
5413 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5414 (while (> n 1)
5415 (setq n (1- n)
5416 re (concat re or next)
5417 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5418 (concat left "\\(" re "\\)" right)))
5420 (defvar org-match-substring-regexp
5421 (concat
5422 "\\(\\S-\\)\\([_^]\\)\\("
5423 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5424 "\\|"
5425 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5426 "\\|"
5427 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5428 "The regular expression matching a sub- or superscript.")
5430 (defvar org-match-substring-with-braces-regexp
5431 (concat
5432 "\\(\\S-\\)\\([_^]\\)\\("
5433 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5434 "\\)")
5435 "The regular expression matching a sub- or superscript, forcing braces.")
5437 (defun org-make-link-regexps ()
5438 "Update the link regular expressions.
5439 This should be called after the variable `org-link-types' has changed."
5440 (setq org-link-types-re
5441 (concat
5442 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5443 org-link-re-with-space
5444 (concat
5445 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5446 "\\([^" org-non-link-chars " ]"
5447 "[^" org-non-link-chars "]*"
5448 "[^" org-non-link-chars " ]\\)>?")
5449 org-link-re-with-space2
5450 (concat
5451 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5452 "\\([^" org-non-link-chars " ]"
5453 "[^\t\n\r]*"
5454 "[^" org-non-link-chars " ]\\)>?")
5455 org-link-re-with-space3
5456 (concat
5457 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5458 "\\([^" org-non-link-chars " ]"
5459 "[^\t\n\r]*\\)")
5460 org-angle-link-re
5461 (concat
5462 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5463 "\\([^" org-non-link-chars " ]"
5464 "[^" org-non-link-chars "]*"
5465 "\\)>")
5466 org-plain-link-re
5467 (concat
5468 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5469 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5470 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5471 org-bracket-link-regexp
5472 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5473 org-bracket-link-analytic-regexp
5474 (concat
5475 "\\[\\["
5476 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5477 "\\([^]]+\\)"
5478 "\\]"
5479 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5480 "\\]")
5481 org-bracket-link-analytic-regexp++
5482 (concat
5483 "\\[\\["
5484 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5485 "\\([^]]+\\)"
5486 "\\]"
5487 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5488 "\\]")
5489 org-any-link-re
5490 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5491 org-angle-link-re "\\)\\|\\("
5492 org-plain-link-re "\\)")))
5494 (org-make-link-regexps)
5496 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5497 "Regular expression for fast time stamp matching.")
5498 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5499 "Regular expression for fast time stamp matching.")
5500 (defconst org-ts-regexp0
5501 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5502 "Regular expression matching time strings for analysis.
5503 This one does not require the space after the date, so it can be used
5504 on a string that terminates immediately after the date.")
5505 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5506 "Regular expression matching time strings for analysis.")
5507 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5508 "Regular expression matching time stamps, with groups.")
5509 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5510 "Regular expression matching time stamps (also [..]), with groups.")
5511 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5512 "Regular expression matching a time stamp range.")
5513 (defconst org-tr-regexp-both
5514 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5515 "Regular expression matching a time stamp range.")
5516 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5517 org-ts-regexp "\\)?")
5518 "Regular expression matching a time stamp or time stamp range.")
5519 (defconst org-tsr-regexp-both
5520 (concat org-ts-regexp-both "\\(--?-?"
5521 org-ts-regexp-both "\\)?")
5522 "Regular expression matching a time stamp or time stamp range.
5523 The time stamps may be either active or inactive.")
5525 (defvar org-emph-face nil)
5527 (defun org-do-emphasis-faces (limit)
5528 "Run through the buffer and add overlays to emphasized strings."
5529 (let (rtn a)
5530 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5531 (if (not (= (char-after (match-beginning 3))
5532 (char-after (match-beginning 4))))
5533 (progn
5534 (setq rtn t)
5535 (setq a (assoc (match-string 3) org-emphasis-alist))
5536 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5537 'face
5538 (nth 1 a))
5539 (and (nth 4 a)
5540 (org-remove-flyspell-overlays-in
5541 (match-beginning 0) (match-end 0)))
5542 (add-text-properties (match-beginning 2) (match-end 2)
5543 '(font-lock-multiline t org-emphasis t))
5544 (when org-hide-emphasis-markers
5545 (add-text-properties (match-end 4) (match-beginning 5)
5546 '(invisible org-link))
5547 (add-text-properties (match-beginning 3) (match-end 3)
5548 '(invisible org-link)))))
5549 (backward-char 1))
5550 rtn))
5552 (defun org-emphasize (&optional char)
5553 "Insert or change an emphasis, i.e. a font like bold or italic.
5554 If there is an active region, change that region to a new emphasis.
5555 If there is no region, just insert the marker characters and position
5556 the cursor between them.
5557 CHAR should be either the marker character, or the first character of the
5558 HTML tag associated with that emphasis. If CHAR is a space, the means
5559 to remove the emphasis of the selected region.
5560 If char is not given (for example in an interactive call) it
5561 will be prompted for."
5562 (interactive)
5563 (let ((eal org-emphasis-alist) e det
5564 (erc org-emphasis-regexp-components)
5565 (prompt "")
5566 (string "") beg end move tag c s)
5567 (if (org-region-active-p)
5568 (setq beg (region-beginning) end (region-end)
5569 string (buffer-substring beg end))
5570 (setq move t))
5572 (while (setq e (pop eal))
5573 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5574 c (aref tag 0))
5575 (push (cons c (string-to-char (car e))) det)
5576 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5577 (substring tag 1)))))
5578 (setq det (nreverse det))
5579 (unless char
5580 (message "%s" (concat "Emphasis marker or tag:" prompt))
5581 (setq char (read-char-exclusive)))
5582 (setq char (or (cdr (assoc char det)) char))
5583 (if (equal char ?\ )
5584 (setq s "" move nil)
5585 (unless (assoc (char-to-string char) org-emphasis-alist)
5586 (error "No such emphasis marker: \"%c\"" char))
5587 (setq s (char-to-string char)))
5588 (while (and (> (length string) 1)
5589 (equal (substring string 0 1) (substring string -1))
5590 (assoc (substring string 0 1) org-emphasis-alist))
5591 (setq string (substring string 1 -1)))
5592 (setq string (concat s string s))
5593 (if beg (delete-region beg end))
5594 (unless (or (bolp)
5595 (string-match (concat "[" (nth 0 erc) "\n]")
5596 (char-to-string (char-before (point)))))
5597 (insert " "))
5598 (unless (or (eobp)
5599 (string-match (concat "[" (nth 1 erc) "\n]")
5600 (char-to-string (char-after (point)))))
5601 (insert " ") (backward-char 1))
5602 (insert string)
5603 (and move (backward-char 1))))
5605 (defconst org-nonsticky-props
5606 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5608 (defsubst org-rear-nonsticky-at (pos)
5609 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5611 (defun org-activate-plain-links (limit)
5612 "Run through the buffer and add overlays to links."
5613 (let (f hl)
5614 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5615 (not (org-in-src-block-p)))
5616 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5617 (setq f (get-text-property (match-beginning 0) 'face))
5618 (setq hl (org-match-string-no-properties 0))
5619 (if (or (eq f 'org-tag)
5620 (and (listp f) (memq 'org-tag f)))
5622 (add-text-properties (match-beginning 0) (match-end 0)
5623 (list 'mouse-face 'highlight
5624 'face 'org-link
5625 'htmlize-link `(:uri ,hl)
5626 'keymap org-mouse-map))
5627 (org-rear-nonsticky-at (match-end 0)))
5628 t)))
5630 (defun org-activate-code (limit)
5631 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5632 (progn
5633 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5634 (remove-text-properties (match-beginning 0) (match-end 0)
5635 '(display t invisible t intangible t))
5636 t)))
5638 (defcustom org-src-fontify-natively nil
5639 "When non-nil, fontify code in code blocks."
5640 :type 'boolean
5641 :version "24.1"
5642 :group 'org-appearance
5643 :group 'org-babel)
5645 (defcustom org-allow-promoting-top-level-subtree nil
5646 "When non-nil, allow promoting a top level subtree.
5647 The leading star of the top level headline will be replaced
5648 by a #."
5649 :type 'boolean
5650 :version "24.1"
5651 :group 'org-appearance)
5653 (defun org-fontify-meta-lines-and-blocks (limit)
5654 (condition-case nil
5655 (org-fontify-meta-lines-and-blocks-1 limit)
5656 (error (message "org-mode fontification error"))))
5658 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5659 "Fontify #+ lines and blocks, in the correct ways."
5660 (let ((case-fold-search t))
5661 (if (re-search-forward
5662 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5663 limit t)
5664 (let ((beg (match-beginning 0))
5665 (block-start (match-end 0))
5666 (block-end nil)
5667 (lang (match-string 7))
5668 (beg1 (line-beginning-position 2))
5669 (dc1 (downcase (match-string 2)))
5670 (dc3 (downcase (match-string 3)))
5671 end end1 quoting block-type ovl)
5672 (cond
5673 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5674 ;; a single line of backend-specific content
5675 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5676 (remove-text-properties (match-beginning 0) (match-end 0)
5677 '(display t invisible t intangible t))
5678 (add-text-properties (match-beginning 1) (match-end 3)
5679 '(font-lock-fontified t face org-meta-line))
5680 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5681 '(font-lock-fontified t face org-block))
5682 ; for backend-specific code
5684 ((and (match-end 4) (equal dc3 "+begin"))
5685 ;; Truly a block
5686 (setq block-type (downcase (match-string 5))
5687 quoting (member block-type org-protecting-blocks))
5688 (when (re-search-forward
5689 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5690 nil t) ;; on purpose, we look further than LIMIT
5691 (setq end (min (point-max) (match-end 0))
5692 end1 (min (point-max) (1- (match-beginning 0))))
5693 (setq block-end (match-beginning 0))
5694 (when quoting
5695 (remove-text-properties beg end
5696 '(display t invisible t intangible t)))
5697 (add-text-properties
5698 beg end
5699 '(font-lock-fontified t font-lock-multiline t))
5700 (add-text-properties beg beg1 '(face org-meta-line))
5701 (add-text-properties end1 (min (point-max) (1+ end))
5702 '(face org-meta-line)) ; for end_src
5703 (cond
5704 ((and lang (not (string= lang "")) org-src-fontify-natively)
5705 (org-src-font-lock-fontify-block lang block-start block-end)
5706 ;; remove old background overlays
5707 (mapc (lambda (ov)
5708 (if (eq (overlay-get ov 'face) 'org-block-background)
5709 (delete-overlay ov)))
5710 (overlays-at (/ (+ beg1 block-end) 2)))
5711 ;; add a background overlay
5712 (setq ovl (make-overlay beg1 block-end))
5713 (overlay-put ovl 'face 'org-block-background)
5714 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5715 (quoting
5716 (add-text-properties beg1 (min (point-max) (1+ end1))
5717 '(face org-block))) ; end of source block
5718 ((not org-fontify-quote-and-verse-blocks))
5719 ((string= block-type "quote")
5720 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5721 ((string= block-type "verse")
5722 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5723 (add-text-properties beg beg1 '(face org-block-begin-line))
5724 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5725 '(face org-block-end-line))
5727 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5728 (add-text-properties
5729 beg (match-end 3)
5730 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5731 '(font-lock-fontified t invisible t)
5732 '(font-lock-fontified t face org-document-info-keyword)))
5733 (add-text-properties
5734 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5735 (if (string-equal dc1 "+title:")
5736 '(font-lock-fontified t face org-document-title)
5737 '(font-lock-fontified t face org-document-info))))
5738 ((or (equal dc1 "+results")
5739 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5740 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5741 "+call:" "+header:" "+headers:" "+name:"))
5742 (and (match-end 4) (equal dc3 "+attr")))
5743 (add-text-properties
5744 beg (match-end 0)
5745 '(font-lock-fontified t face org-meta-line))
5747 ((member dc3 '(" " ""))
5748 (add-text-properties
5749 beg (match-end 0)
5750 '(font-lock-fontified t face font-lock-comment-face)))
5751 ((not (member (char-after beg) '(?\ ?\t)))
5752 ;; just any other in-buffer setting, but not indented
5753 (add-text-properties
5754 beg (match-end 0)
5755 '(font-lock-fontified t face org-meta-line))
5757 (t nil))))))
5759 (defun org-activate-angle-links (limit)
5760 "Run through the buffer and add overlays to links."
5761 (if (and (re-search-forward org-angle-link-re limit t)
5762 (not (org-in-src-block-p)))
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5765 (add-text-properties (match-beginning 0) (match-end 0)
5766 (list 'mouse-face 'highlight
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 0))
5769 t)))
5771 (defun org-activate-footnote-links (limit)
5772 "Run through the buffer and add overlays to footnotes."
5773 (let ((fn (org-footnote-next-reference-or-definition limit)))
5774 (when fn
5775 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5776 (org-remove-flyspell-overlays-in beg end)
5777 (add-text-properties beg end
5778 (list 'mouse-face 'highlight
5779 'keymap org-mouse-map
5780 'help-echo
5781 (if (= (point-at-bol) beg)
5782 "Footnote definition"
5783 "Footnote reference")
5784 'font-lock-fontified t
5785 'font-lock-multiline t
5786 'face 'org-footnote))))))
5788 (defun org-activate-bracket-links (limit)
5789 "Run through the buffer and add overlays to bracketed links."
5790 (if (and (re-search-forward org-bracket-link-regexp limit t)
5791 (not (org-in-src-block-p)))
5792 (let* ((hl (org-match-string-no-properties 1))
5793 (help (concat "LINK: " hl))
5794 ;; FIXME: Above we should remove the escapes. But that
5795 ;; requires another match, protecting match data, a lot
5796 ;; of overhead for font-lock.
5797 (ip (org-maybe-intangible
5798 (list 'invisible 'org-link
5799 'keymap org-mouse-map 'mouse-face 'highlight
5800 'font-lock-multiline t 'help-echo help
5801 'htmlize-link `(:uri ,hl))))
5802 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5803 'font-lock-multiline t 'help-echo help
5804 'htmlize-link `(:uri ,hl))))
5805 ;; We need to remove the invisible property here. Table narrowing
5806 ;; may have made some of this invisible.
5807 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5808 (remove-text-properties (match-beginning 0) (match-end 0)
5809 '(invisible nil))
5810 (if (match-end 3)
5811 (progn
5812 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5813 (org-rear-nonsticky-at (match-beginning 3))
5814 (add-text-properties (match-beginning 3) (match-end 3) vp)
5815 (org-rear-nonsticky-at (match-end 3))
5816 (add-text-properties (match-end 3) (match-end 0) ip)
5817 (org-rear-nonsticky-at (match-end 0)))
5818 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5819 (org-rear-nonsticky-at (match-beginning 1))
5820 (add-text-properties (match-beginning 1) (match-end 1) vp)
5821 (org-rear-nonsticky-at (match-end 1))
5822 (add-text-properties (match-end 1) (match-end 0) ip)
5823 (org-rear-nonsticky-at (match-end 0)))
5824 t)))
5826 (defun org-activate-dates (limit)
5827 "Run through the buffer and add overlays to dates."
5828 (if (and (re-search-forward org-tsr-regexp-both limit t)
5829 (not (equal (char-before (match-beginning 0)) 91)))
5830 (progn
5831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5832 (add-text-properties (match-beginning 0) (match-end 0)
5833 (list 'mouse-face 'highlight
5834 'keymap org-mouse-map))
5835 (org-rear-nonsticky-at (match-end 0))
5836 (when org-display-custom-times
5837 (if (match-end 3)
5838 (org-display-custom-time (match-beginning 3) (match-end 3)))
5839 (org-display-custom-time (match-beginning 1) (match-end 1)))
5840 t)))
5842 (defvar org-target-link-regexp nil
5843 "Regular expression matching radio targets in plain text.")
5844 (make-variable-buffer-local 'org-target-link-regexp)
5845 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5846 "Regular expression matching a link target.")
5847 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5848 "Regular expression matching a radio target.")
5849 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5850 "Regular expression matching any target.")
5852 (defun org-activate-target-links (limit)
5853 "Run through the buffer and add overlays to target matches."
5854 (when org-target-link-regexp
5855 (let ((case-fold-search t))
5856 (if (re-search-forward org-target-link-regexp limit t)
5857 (progn
5858 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5859 (add-text-properties (match-beginning 0) (match-end 0)
5860 (list 'mouse-face 'highlight
5861 'keymap org-mouse-map
5862 'help-echo "Radio target link"
5863 'org-linked-text t))
5864 (org-rear-nonsticky-at (match-end 0))
5865 t)))))
5867 (defun org-update-radio-target-regexp ()
5868 "Find all radio targets in this file and update the regular expression."
5869 (interactive)
5870 (when (memq 'radio org-activate-links)
5871 (setq org-target-link-regexp
5872 (org-make-target-link-regexp (org-all-targets 'radio)))
5873 (org-restart-font-lock)))
5875 (defun org-hide-wide-columns (limit)
5876 (let (s e)
5877 (setq s (text-property-any (point) (or limit (point-max))
5878 'org-cwidth t))
5879 (when s
5880 (setq e (next-single-property-change s 'org-cwidth))
5881 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5882 (goto-char e)
5883 t)))
5885 (defvar org-latex-and-related-regexp nil
5886 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5887 (defvar org-match-substring-regexp)
5888 (defvar org-match-substring-with-braces-regexp)
5890 (defun org-compute-latex-and-related-regexp ()
5891 "Compute regular expression for LaTeX, entities and sub/superscript.
5892 Result depends on variable `org-highlight-latex-and-related'."
5893 (org-set-local
5894 'org-latex-and-related-regexp
5895 (let* ((re-sub
5896 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5897 ((eq org-use-sub-superscripts '{})
5898 (list org-match-substring-with-braces-regexp))
5899 (org-use-sub-superscripts (list org-match-substring-regexp))))
5900 (re-latex
5901 (when (memq 'latex org-highlight-latex-and-related)
5902 (let ((matchers (plist-get org-format-latex-options :matchers)))
5903 (delq nil
5904 (mapcar (lambda (x)
5905 (and (member (car x) matchers) (nth 1 x)))
5906 org-latex-regexps)))))
5907 (re-entities
5908 (when (memq 'entities org-highlight-latex-and-related)
5909 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5910 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5912 (defun org-do-latex-and-related (limit)
5913 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5914 LIMIT bounds the search for syntax to highlight. Stop at first
5915 highlighted object, if any. Return t if some highlighting was
5916 done, nil otherwise."
5917 (when (org-string-nw-p org-latex-and-related-regexp)
5918 (catch 'found
5919 (while (re-search-forward org-latex-and-related-regexp limit t)
5920 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5921 'face))
5922 '(org-code org-verbatim underline))
5923 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5924 '(?_ ?^))
5926 0)))
5927 (font-lock-prepend-text-property
5928 (+ offset (match-beginning 0)) (match-end 0)
5929 'face 'org-latex-and-related)
5930 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5931 '(font-lock-multiline t)))
5932 (throw 'found t)))
5933 nil)))
5935 (defun org-restart-font-lock ()
5936 "Restart `font-lock-mode', to force refontification."
5937 (when (and (boundp 'font-lock-mode) font-lock-mode)
5938 (font-lock-mode -1)
5939 (font-lock-mode 1)))
5941 (defun org-all-targets (&optional radio)
5942 "Return a list of all targets in this file.
5943 When optional argument RADIO is non-nil, only find radio
5944 targets."
5945 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5946 (save-excursion
5947 (goto-char (point-min))
5948 (while (re-search-forward re nil t)
5949 ;; Make sure point is really within the object.
5950 (backward-char)
5951 (let ((obj (org-element-context)))
5952 (when (memq (org-element-type obj) '(radio-target target))
5953 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5954 rtn)))
5956 (defun org-make-target-link-regexp (targets)
5957 "Make regular expression matching all strings in TARGETS.
5958 The regular expression finds the targets also if there is a line break
5959 between words."
5960 (and targets
5961 (concat
5962 "\\<\\("
5963 (mapconcat
5964 (lambda (x)
5965 (setq x (regexp-quote x))
5966 (while (string-match " +" x)
5967 (setq x (replace-match "\\s-+" t t x)))
5969 targets
5970 "\\|")
5971 "\\)\\>")))
5973 (defun org-activate-tags (limit)
5974 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5975 (progn
5976 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5977 (add-text-properties (match-beginning 1) (match-end 1)
5978 (list 'mouse-face 'highlight
5979 'keymap org-mouse-map))
5980 (org-rear-nonsticky-at (match-end 1))
5981 t)))
5983 (defun org-outline-level ()
5984 "Compute the outline level of the heading at point.
5985 If this is called at a normal headline, the level is the number of stars.
5986 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5987 (save-excursion
5988 (if (not (condition-case nil
5989 (org-back-to-heading t)
5990 (error nil)))
5992 (looking-at org-outline-regexp)
5993 (1- (- (match-end 0) (match-beginning 0))))))
5995 (defvar org-font-lock-keywords nil)
5997 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5998 "Regular expression matching a property line.")
6000 (defvar org-font-lock-hook nil
6001 "Functions to be called for special font lock stuff.")
6003 (defvar org-font-lock-set-keywords-hook nil
6004 "Functions that can manipulate `org-font-lock-extra-keywords'.
6005 This is called after `org-font-lock-extra-keywords' is defined, but before
6006 it is installed to be used by font lock. This can be useful if something
6007 needs to be inserted at a specific position in the font-lock sequence.")
6009 (defun org-font-lock-hook (limit)
6010 "Run `org-font-lock-hook' within LIMIT."
6011 (run-hook-with-args 'org-font-lock-hook limit))
6013 (defun org-set-font-lock-defaults ()
6014 "Set font lock defaults for the current buffer."
6015 (let* ((em org-fontify-emphasized-text)
6016 (lk org-activate-links)
6017 (org-font-lock-extra-keywords
6018 (list
6019 ;; Call the hook
6020 '(org-font-lock-hook)
6021 ;; Headlines
6022 `(,(if org-fontify-whole-heading-line
6023 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6024 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6025 (1 (org-get-level-face 1))
6026 (2 (org-get-level-face 2))
6027 (3 (org-get-level-face 3)))
6028 ;; Table lines
6029 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6030 (1 'org-table t))
6031 ;; Table internals
6032 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6033 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6034 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6035 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6036 ;; Drawers
6037 (list org-drawer-regexp '(0 'org-special-keyword t))
6038 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6039 ;; Properties
6040 (list org-property-re
6041 '(1 'org-special-keyword t)
6042 '(3 'org-property-value t))
6043 ;; Links
6044 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6045 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6046 (if (memq 'plain lk) '(org-activate-plain-links))
6047 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6048 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6049 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6050 (if (memq 'footnote lk) '(org-activate-footnote-links))
6051 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6052 '(org-hide-wide-columns (0 nil append))
6053 ;; TODO keyword
6054 (list (format org-heading-keyword-regexp-format
6055 org-todo-regexp)
6056 '(2 (org-get-todo-face 2) t))
6057 ;; DONE
6058 (if org-fontify-done-headline
6059 (list (format org-heading-keyword-regexp-format
6060 (concat
6061 "\\(?:"
6062 (mapconcat 'regexp-quote org-done-keywords "\\|")
6063 "\\)"))
6064 '(2 'org-headline-done t))
6065 nil)
6066 ;; Priorities
6067 '(org-font-lock-add-priority-faces)
6068 ;; Tags
6069 '(org-font-lock-add-tag-faces)
6070 ;; Special keywords
6071 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6072 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6073 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6074 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6075 ;; Emphasis
6076 (if em
6077 (if (featurep 'xemacs)
6078 '(org-do-emphasis-faces (0 nil append))
6079 '(org-do-emphasis-faces)))
6080 ;; Checkboxes
6081 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6082 1 'org-checkbox prepend)
6083 (if (cdr (assq 'checkbox org-list-automatic-rules))
6084 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6085 (0 (org-get-checkbox-statistics-face) t)))
6086 ;; Description list items
6087 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6088 1 'org-list-dt prepend)
6089 ;; ARCHIVEd headings
6090 (list (concat
6091 org-outline-regexp-bol
6092 "\\(.*:" org-archive-tag ":.*\\)")
6093 '(1 'org-archived prepend))
6094 ;; Specials
6095 '(org-do-latex-and-related)
6096 '(org-fontify-entities)
6097 '(org-raise-scripts)
6098 ;; Code
6099 '(org-activate-code (1 'org-code t))
6100 ;; COMMENT
6101 (list (format org-heading-keyword-regexp-format
6102 (concat "\\("
6103 org-comment-string "\\|" org-quote-string
6104 "\\)"))
6105 '(2 'org-special-keyword t))
6106 ;; Blocks and meta lines
6107 '(org-fontify-meta-lines-and-blocks)
6109 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6110 (run-hooks 'org-font-lock-set-keywords-hook)
6111 ;; Now set the full font-lock-keywords
6112 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6113 (org-set-local 'font-lock-defaults
6114 '(org-font-lock-keywords t nil nil backward-paragraph))
6115 (kill-local-variable 'font-lock-keywords) nil))
6117 (defun org-toggle-pretty-entities ()
6118 "Toggle the composition display of entities as UTF8 characters."
6119 (interactive)
6120 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6121 (org-restart-font-lock)
6122 (if org-pretty-entities
6123 (message "Entities are displayed as UTF8 characters")
6124 (save-restriction
6125 (widen)
6126 (org-decompose-region (point-min) (point-max))
6127 (message "Entities are displayed plain"))))
6129 (defvar org-custom-properties-overlays nil
6130 "List of overlays used for custom properties.")
6131 (make-variable-buffer-local 'org-custom-properties-overlays)
6133 (defun org-toggle-custom-properties-visibility ()
6134 "Display or hide properties in `org-custom-properties'."
6135 (interactive)
6136 (if org-custom-properties-overlays
6137 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6138 (setq org-custom-properties-overlays nil))
6139 (unless (not org-custom-properties)
6140 (save-excursion
6141 (save-restriction
6142 (widen)
6143 (goto-char (point-min))
6144 (while (re-search-forward org-property-re nil t)
6145 (mapc (lambda(p)
6146 (when (equal p (substring (match-string 1) 1 -1))
6147 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6148 (overlay-put o 'invisible t)
6149 (overlay-put o 'org-custom-property t)
6150 (push o org-custom-properties-overlays))))
6151 org-custom-properties)))))))
6153 (defun org-fontify-entities (limit)
6154 "Find an entity to fontify."
6155 (let (ee)
6156 (when org-pretty-entities
6157 (catch 'match
6158 (while (re-search-forward
6159 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6160 limit t)
6161 (if (and (not (org-in-indented-comment-line))
6162 (setq ee (org-entity-get (match-string 1)))
6163 (= (length (nth 6 ee)) 1))
6164 (let*
6165 ((end (if (equal (match-string 2) "{}")
6166 (match-end 2)
6167 (match-end 1))))
6168 (add-text-properties
6169 (match-beginning 0) end
6170 (list 'font-lock-fontified t))
6171 (compose-region (match-beginning 0) end
6172 (nth 6 ee) nil)
6173 (backward-char 1)
6174 (throw 'match t))))
6175 nil))))
6177 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6178 "Fontify string S like in Org-mode."
6179 (with-temp-buffer
6180 (insert s)
6181 (let ((org-odd-levels-only odd-levels))
6182 (org-mode)
6183 (font-lock-fontify-buffer)
6184 (buffer-string))))
6186 (defvar org-m nil)
6187 (defvar org-l nil)
6188 (defvar org-f nil)
6189 (defun org-get-level-face (n)
6190 "Get the right face for match N in font-lock matching of headlines."
6191 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6192 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6193 (if org-cycle-level-faces
6194 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6195 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6196 (cond
6197 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6198 ((eq n 2) org-f)
6199 (t (if org-level-color-stars-only nil org-f))))
6202 (defun org-get-todo-face (kwd)
6203 "Get the right face for a TODO keyword KWD.
6204 If KWD is a number, get the corresponding match group."
6205 (if (numberp kwd) (setq kwd (match-string kwd)))
6206 (or (org-face-from-face-or-color
6207 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6208 (and (member kwd org-done-keywords) 'org-done)
6209 'org-todo))
6211 (defun org-face-from-face-or-color (context inherit face-or-color)
6212 "Create a face list that inherits INHERIT, but sets the foreground color.
6213 When FACE-OR-COLOR is not a string, just return it."
6214 (if (stringp face-or-color)
6215 (list :inherit inherit
6216 (cdr (assoc context org-faces-easy-properties))
6217 face-or-color)
6218 face-or-color))
6220 (defun org-font-lock-add-tag-faces (limit)
6221 "Add the special tag faces."
6222 (when (and org-tag-faces org-tags-special-faces-re)
6223 (while (re-search-forward org-tags-special-faces-re limit t)
6224 (add-text-properties (match-beginning 1) (match-end 1)
6225 (list 'face (org-get-tag-face 1)
6226 'font-lock-fontified t))
6227 (backward-char 1))))
6229 (defun org-font-lock-add-priority-faces (limit)
6230 "Add the special priority faces."
6231 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6232 (when (save-match-data (org-at-heading-p))
6233 (add-text-properties
6234 (match-beginning 0) (match-end 0)
6235 (list 'face (or (org-face-from-face-or-color
6236 'priority 'org-priority
6237 (cdr (assoc (char-after (match-beginning 1))
6238 org-priority-faces)))
6239 'org-priority)
6240 'font-lock-fontified t)))))
6242 (defun org-get-tag-face (kwd)
6243 "Get the right face for a TODO keyword KWD.
6244 If KWD is a number, get the corresponding match group."
6245 (if (numberp kwd) (setq kwd (match-string kwd)))
6246 (or (org-face-from-face-or-color
6247 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6248 'org-tag))
6250 (defun org-unfontify-region (beg end &optional maybe_loudly)
6251 "Remove fontification and activation overlays from links."
6252 (font-lock-default-unfontify-region beg end)
6253 (let* ((buffer-undo-list t)
6254 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6255 (inhibit-modification-hooks t)
6256 deactivate-mark buffer-file-name buffer-file-truename)
6257 (org-decompose-region beg end)
6258 (remove-text-properties beg end
6259 '(mouse-face t keymap t org-linked-text t
6260 invisible t intangible t
6261 org-no-flyspell t org-emphasis t))
6262 (org-remove-font-lock-display-properties beg end)))
6264 (defconst org-script-display '(((raise -0.3) (height 0.7))
6265 ((raise 0.3) (height 0.7))
6266 ((raise -0.5))
6267 ((raise 0.5)))
6268 "Display properties for showing superscripts and subscripts.")
6270 (defun org-remove-font-lock-display-properties (beg end)
6271 "Remove specific display properties that have been added by font lock.
6272 The will remove the raise properties that are used to show superscripts
6273 and subscripts."
6274 (let (next prop)
6275 (while (< beg end)
6276 (setq next (next-single-property-change beg 'display nil end)
6277 prop (get-text-property beg 'display))
6278 (if (member prop org-script-display)
6279 (put-text-property beg next 'display nil))
6280 (setq beg next))))
6282 (defun org-raise-scripts (limit)
6283 "Add raise properties to sub/superscripts."
6284 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6285 (if (re-search-forward
6286 (if (eq org-use-sub-superscripts t)
6287 org-match-substring-regexp
6288 org-match-substring-with-braces-regexp)
6289 limit t)
6290 (let* ((pos (point)) table-p comment-p
6291 (mpos (match-beginning 3))
6292 (emph-p (get-text-property mpos 'org-emphasis))
6293 (link-p (get-text-property mpos 'mouse-face))
6294 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6295 (goto-char (point-at-bol))
6296 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6297 comment-p (org-looking-at-p "[ \t]*#"))
6298 (goto-char pos)
6299 ;; FIXME: Should we go back one character here, for a_b^c
6300 ;; (goto-char (1- pos)) ;????????????????????
6301 (if (or comment-p emph-p link-p keyw-p)
6303 (put-text-property (match-beginning 3) (match-end 0)
6304 'display
6305 (if (equal (char-after (match-beginning 2)) ?^)
6306 (nth (if table-p 3 1) org-script-display)
6307 (nth (if table-p 2 0) org-script-display)))
6308 (add-text-properties (match-beginning 2) (match-end 2)
6309 (list 'invisible t
6310 'org-dwidth t 'org-dwidth-n 1))
6311 (if (and (eq (char-after (match-beginning 3)) ?{)
6312 (eq (char-before (match-end 3)) ?}))
6313 (progn
6314 (add-text-properties
6315 (match-beginning 3) (1+ (match-beginning 3))
6316 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6317 (add-text-properties
6318 (1- (match-end 3)) (match-end 3)
6319 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6320 t)))))
6322 ;;;; Visibility cycling, including org-goto and indirect buffer
6324 ;;; Cycling
6326 (defvar org-cycle-global-status nil)
6327 (make-variable-buffer-local 'org-cycle-global-status)
6328 (put 'org-cycle-global-status 'org-state t)
6329 (defvar org-cycle-subtree-status nil)
6330 (make-variable-buffer-local 'org-cycle-subtree-status)
6331 (put 'org-cycle-subtree-status 'org-state t)
6333 (defvar org-inlinetask-min-level)
6335 ;;;###autoload
6336 (defun org-cycle (&optional arg)
6337 "TAB-action and visibility cycling for Org-mode.
6339 This is the command invoked in Org-mode by the TAB key. Its main purpose
6340 is outline visibility cycling, but it also invokes other actions
6341 in special contexts.
6343 - When this function is called with a prefix argument, rotate the entire
6344 buffer through 3 states (global cycling)
6345 1. OVERVIEW: Show only top-level headlines.
6346 2. CONTENTS: Show all headlines of all levels, but no body text.
6347 3. SHOW ALL: Show everything.
6348 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6349 determined by the variable `org-startup-folded', and by any VISIBILITY
6350 properties in the buffer.
6351 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6352 including any drawers.
6354 - When inside a table, re-align the table and move to the next field.
6356 - When point is at the beginning of a headline, rotate the subtree started
6357 by this line through 3 different states (local cycling)
6358 1. FOLDED: Only the main headline is shown.
6359 2. CHILDREN: The main headline and the direct children are shown.
6360 From this state, you can move to one of the children
6361 and zoom in further.
6362 3. SUBTREE: Show the entire subtree, including body text.
6363 If there is no subtree, switch directly from CHILDREN to FOLDED.
6365 - When point is at the beginning of an empty headline and the variable
6366 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6367 of the headline by demoting and promoting it to likely levels. This
6368 speeds up creation document structure by pressing TAB once or several
6369 times right after creating a new headline.
6371 - When there is a numeric prefix, go up to a heading with level ARG, do
6372 a `show-subtree' and return to the previous cursor position. If ARG
6373 is negative, go up that many levels.
6375 - When point is not at the beginning of a headline, execute the global
6376 binding for TAB, which is re-indenting the line. See the option
6377 `org-cycle-emulate-tab' for details.
6379 - Special case: if point is at the beginning of the buffer and there is
6380 no headline in line 1, this function will act as if called with prefix arg
6381 (C-u TAB, same as S-TAB) also when called without prefix arg.
6382 But only if also the variable `org-cycle-global-at-bob' is t."
6383 (interactive "P")
6384 (org-load-modules-maybe)
6385 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6386 (and org-cycle-level-after-item/entry-creation
6387 (or (org-cycle-level)
6388 (org-cycle-item-indentation))))
6389 (let* (message-log-max ; Don't populate the *Messages* buffer
6390 (limit-level
6391 (or org-cycle-max-level
6392 (and (boundp 'org-inlinetask-min-level)
6393 org-inlinetask-min-level
6394 (1- org-inlinetask-min-level))))
6395 (nstars (and limit-level
6396 (if org-odd-levels-only
6397 (and limit-level (1- (* limit-level 2)))
6398 limit-level)))
6399 (org-outline-regexp
6400 (if (not (derived-mode-p 'org-mode))
6401 outline-regexp
6402 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6403 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6404 (not (looking-at org-outline-regexp))))
6405 (org-cycle-hook
6406 (if bob-special
6407 (delq 'org-optimize-window-after-visibility-change
6408 (copy-sequence org-cycle-hook))
6409 org-cycle-hook))
6410 (pos (point)))
6412 (if (or bob-special (equal arg '(4)))
6413 ;; special case: use global cycling
6414 (setq arg t))
6416 (cond
6418 ((equal arg '(16))
6419 (setq last-command 'dummy)
6420 (org-set-startup-visibility)
6421 (message "Startup visibility, plus VISIBILITY properties"))
6423 ((equal arg '(64))
6424 (show-all)
6425 (message "Entire buffer visible, including drawers"))
6427 ;; Table: enter it or move to the next field.
6428 ((org-at-table-p 'any)
6429 (if (org-at-table.el-p)
6430 (message "Use C-c ' to edit table.el tables")
6431 (if arg (org-table-edit-field t)
6432 (org-table-justify-field-maybe)
6433 (call-interactively 'org-table-next-field))))
6435 ((run-hook-with-args-until-success
6436 'org-tab-after-check-for-table-hook))
6438 ;; Global cycling: delegate to `org-cycle-internal-global'.
6439 ((eq arg t) (org-cycle-internal-global))
6441 ;; Drawers: delegate to `org-flag-drawer'.
6442 ((and org-drawers org-drawer-regexp
6443 (save-excursion
6444 (beginning-of-line 1)
6445 (looking-at org-drawer-regexp)))
6446 (org-flag-drawer ; toggle block visibility
6447 (not (get-char-property (match-end 0) 'invisible))))
6449 ;; Show-subtree, ARG levels up from here.
6450 ((integerp arg)
6451 (save-excursion
6452 (org-back-to-heading)
6453 (outline-up-heading (if (< arg 0) (- arg)
6454 (- (funcall outline-level) arg)))
6455 (org-show-subtree)))
6457 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6458 ((and (featurep 'org-inlinetask)
6459 (org-inlinetask-at-task-p)
6460 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6461 (org-inlinetask-toggle-visibility))
6463 ((org-try-cdlatex-tab))
6465 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6466 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6467 (save-excursion (beginning-of-line 1)
6468 (looking-at org-outline-regexp)))
6469 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6470 (org-cycle-internal-local))
6472 ;; From there: TAB emulation and template completion.
6473 (buffer-read-only (org-back-to-heading))
6475 ((run-hook-with-args-until-success
6476 'org-tab-after-check-for-cycling-hook))
6478 ((org-try-structure-completion))
6480 ((run-hook-with-args-until-success
6481 'org-tab-before-tab-emulation-hook))
6483 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6484 (or (not (bolp))
6485 (not (looking-at org-outline-regexp))))
6486 (call-interactively (global-key-binding "\t")))
6488 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6489 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6490 (or (and (eq org-cycle-emulate-tab 'white)
6491 (= (match-end 0) (point-at-eol)))
6492 (and (eq org-cycle-emulate-tab 'whitestart)
6493 (>= (match-end 0) pos))))
6495 (eq org-cycle-emulate-tab t))
6496 (call-interactively (global-key-binding "\t")))
6498 (t (save-excursion
6499 (org-back-to-heading)
6500 (org-cycle)))))))
6502 (defun org-cycle-internal-global ()
6503 "Do the global cycling action."
6504 ;; Hack to avoid display of messages for .org attachments in Gnus
6505 (let (message-log-max ; Don't populate the *Messages* buffer
6506 (ga (string-match "\\*fontification" (buffer-name))))
6507 (cond
6508 ((and (eq last-command this-command)
6509 (eq org-cycle-global-status 'overview))
6510 ;; We just created the overview - now do table of contents
6511 ;; This can be slow in very large buffers, so indicate action
6512 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6513 (unless ga (message "CONTENTS..."))
6514 (org-content)
6515 (unless ga (message "CONTENTS...done"))
6516 (setq org-cycle-global-status 'contents)
6517 (run-hook-with-args 'org-cycle-hook 'contents))
6519 ((and (eq last-command this-command)
6520 (eq org-cycle-global-status 'contents))
6521 ;; We just showed the table of contents - now show everything
6522 (run-hook-with-args 'org-pre-cycle-hook 'all)
6523 (show-all)
6524 (unless ga (message "SHOW ALL"))
6525 (setq org-cycle-global-status 'all)
6526 (run-hook-with-args 'org-cycle-hook 'all))
6529 ;; Default action: go to overview
6530 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6531 (org-overview)
6532 (unless ga (message "OVERVIEW"))
6533 (setq org-cycle-global-status 'overview)
6534 (run-hook-with-args 'org-cycle-hook 'overview)))))
6536 (defun org-cycle-internal-local ()
6537 "Do the local cycling action."
6538 (let (message-log-max ; Don't populate the *Messages* buffer
6539 (goal-column 0) eoh eol eos has-children children-skipped struct)
6540 ;; First, determine end of headline (EOH), end of subtree or item
6541 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6542 (save-excursion
6543 (if (org-at-item-p)
6544 (progn
6545 (beginning-of-line)
6546 (setq struct (org-list-struct))
6547 (setq eoh (point-at-eol))
6548 (setq eos (org-list-get-item-end-before-blank (point) struct))
6549 (setq has-children (org-list-has-child-p (point) struct)))
6550 (org-back-to-heading)
6551 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6552 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6553 (setq has-children
6554 (or (save-excursion
6555 (let ((level (funcall outline-level)))
6556 (outline-next-heading)
6557 (and (org-at-heading-p t)
6558 (> (funcall outline-level) level))))
6559 (save-excursion
6560 (org-list-search-forward (org-item-beginning-re) eos t)))))
6561 ;; Determine end invisible part of buffer (EOL)
6562 (beginning-of-line 2)
6563 ;; XEmacs doesn't have `next-single-char-property-change'
6564 (if (featurep 'xemacs)
6565 (while (and (not (eobp)) ;; this is like `next-line'
6566 (get-char-property (1- (point)) 'invisible))
6567 (beginning-of-line 2))
6568 (while (and (not (eobp)) ;; this is like `next-line'
6569 (get-char-property (1- (point)) 'invisible))
6570 (goto-char (next-single-char-property-change (point) 'invisible))
6571 (and (eolp) (beginning-of-line 2))))
6572 (setq eol (point)))
6573 ;; Find out what to do next and set `this-command'
6574 (cond
6575 ((= eos eoh)
6576 ;; Nothing is hidden behind this heading
6577 (unless (org-before-first-heading-p)
6578 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6579 (message "EMPTY ENTRY")
6580 (setq org-cycle-subtree-status nil)
6581 (save-excursion
6582 (goto-char eos)
6583 (outline-next-heading)
6584 (if (outline-invisible-p) (org-flag-heading nil))))
6585 ((and (or (>= eol eos)
6586 (not (string-match "\\S-" (buffer-substring eol eos))))
6587 (or has-children
6588 (not (setq children-skipped
6589 org-cycle-skip-children-state-if-no-children))))
6590 ;; Entire subtree is hidden in one line: children view
6591 (unless (org-before-first-heading-p)
6592 (run-hook-with-args 'org-pre-cycle-hook 'children))
6593 (if (org-at-item-p)
6594 (org-list-set-item-visibility (point-at-bol) struct 'children)
6595 (org-show-entry)
6596 (org-with-limited-levels (show-children))
6597 ;; FIXME: This slows down the func way too much.
6598 ;; How keep drawers hidden in subtree anyway?
6599 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6600 ;; (org-cycle-hide-drawers 'subtree))
6602 ;; Fold every list in subtree to top-level items.
6603 (when (eq org-cycle-include-plain-lists 'integrate)
6604 (save-excursion
6605 (org-back-to-heading)
6606 (while (org-list-search-forward (org-item-beginning-re) eos t)
6607 (beginning-of-line 1)
6608 (let* ((struct (org-list-struct))
6609 (prevs (org-list-prevs-alist struct))
6610 (end (org-list-get-bottom-point struct)))
6611 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6612 (org-list-get-all-items (point) struct prevs))
6613 (goto-char end))))))
6614 (message "CHILDREN")
6615 (save-excursion
6616 (goto-char eos)
6617 (outline-next-heading)
6618 (if (outline-invisible-p) (org-flag-heading nil)))
6619 (setq org-cycle-subtree-status 'children)
6620 (unless (org-before-first-heading-p)
6621 (run-hook-with-args 'org-cycle-hook 'children)))
6622 ((or children-skipped
6623 (and (eq last-command this-command)
6624 (eq org-cycle-subtree-status 'children)))
6625 ;; We just showed the children, or no children are there,
6626 ;; now show everything.
6627 (unless (org-before-first-heading-p)
6628 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6629 (outline-flag-region eoh eos nil)
6630 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6631 (setq org-cycle-subtree-status 'subtree)
6632 (unless (org-before-first-heading-p)
6633 (run-hook-with-args 'org-cycle-hook 'subtree)))
6635 ;; Default action: hide the subtree.
6636 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6637 (outline-flag-region eoh eos t)
6638 (message "FOLDED")
6639 (setq org-cycle-subtree-status 'folded)
6640 (unless (org-before-first-heading-p)
6641 (run-hook-with-args 'org-cycle-hook 'folded))))))
6643 ;;;###autoload
6644 (defun org-global-cycle (&optional arg)
6645 "Cycle the global visibility. For details see `org-cycle'.
6646 With \\[universal-argument] prefix arg, switch to startup visibility.
6647 With a numeric prefix, show all headlines up to that level."
6648 (interactive "P")
6649 (let ((org-cycle-include-plain-lists
6650 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6651 (cond
6652 ((integerp arg)
6653 (show-all)
6654 (hide-sublevels arg)
6655 (setq org-cycle-global-status 'contents))
6656 ((equal arg '(4))
6657 (org-set-startup-visibility)
6658 (message "Startup visibility, plus VISIBILITY properties."))
6660 (org-cycle '(4))))))
6662 (defun org-set-startup-visibility ()
6663 "Set the visibility required by startup options and properties."
6664 (cond
6665 ((eq org-startup-folded t)
6666 (org-cycle '(4)))
6667 ((eq org-startup-folded 'content)
6668 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6669 (org-cycle '(4)) (org-cycle '(4)))))
6670 (unless (eq org-startup-folded 'showeverything)
6671 (if org-hide-block-startup (org-hide-block-all))
6672 (org-set-visibility-according-to-property 'no-cleanup)
6673 (org-cycle-hide-archived-subtrees 'all)
6674 (org-cycle-hide-drawers 'all)
6675 (org-cycle-show-empty-lines t)))
6677 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6678 "Switch subtree visibilities according to :VISIBILITY: property."
6679 (interactive)
6680 (let (org-show-entry-below state)
6681 (save-excursion
6682 (goto-char (point-min))
6683 (while (re-search-forward
6684 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6685 nil t)
6686 (setq state (match-string 1))
6687 (save-excursion
6688 (org-back-to-heading t)
6689 (hide-subtree)
6690 (org-reveal)
6691 (cond
6692 ((equal state '("fold" "folded"))
6693 (hide-subtree))
6694 ((equal state "children")
6695 (org-show-hidden-entry)
6696 (show-children))
6697 ((equal state "content")
6698 (save-excursion
6699 (save-restriction
6700 (org-narrow-to-subtree)
6701 (org-content))))
6702 ((member state '("all" "showall"))
6703 (show-subtree)))))
6704 (unless no-cleanup
6705 (org-cycle-hide-archived-subtrees 'all)
6706 (org-cycle-hide-drawers 'all)
6707 (org-cycle-show-empty-lines 'all)))))
6709 ;; This function uses outline-regexp instead of the more fundamental
6710 ;; org-outline-regexp so that org-cycle-global works outside of Org
6711 ;; buffers, where outline-regexp is needed.
6712 (defun org-overview ()
6713 "Switch to overview mode, showing only top-level headlines.
6714 Really, this shows all headlines with level equal or greater than the level
6715 of the first headline in the buffer. This is important, because if the
6716 first headline is not level one, then (hide-sublevels 1) gives confusing
6717 results."
6718 (interactive)
6719 (let ((l (org-current-line))
6720 (level (save-excursion
6721 (goto-char (point-min))
6722 (if (re-search-forward (concat "^" outline-regexp) nil t)
6723 (progn
6724 (goto-char (match-beginning 0))
6725 (funcall outline-level))))))
6726 (and level (hide-sublevels level))
6727 (recenter '(4))
6728 (org-goto-line l)))
6730 (defun org-content (&optional arg)
6731 "Show all headlines in the buffer, like a table of contents.
6732 With numerical argument N, show content up to level N."
6733 (interactive "P")
6734 (save-excursion
6735 ;; Visit all headings and show their offspring
6736 (and (integerp arg) (org-overview))
6737 (goto-char (point-max))
6738 (catch 'exit
6739 (while (and (progn (condition-case nil
6740 (outline-previous-visible-heading 1)
6741 (error (goto-char (point-min))))
6743 (looking-at org-outline-regexp))
6744 (if (integerp arg)
6745 (show-children (1- arg))
6746 (show-branches))
6747 (if (bobp) (throw 'exit nil))))))
6750 (defun org-optimize-window-after-visibility-change (state)
6751 "Adjust the window after a change in outline visibility.
6752 This function is the default value of the hook `org-cycle-hook'."
6753 (when (get-buffer-window (current-buffer))
6754 (cond
6755 ((eq state 'content) nil)
6756 ((eq state 'all) nil)
6757 ((eq state 'folded) nil)
6758 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6759 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6761 (defun org-remove-empty-overlays-at (pos)
6762 "Remove outline overlays that do not contain non-white stuff."
6763 (mapc
6764 (lambda (o)
6765 (and (eq 'outline (overlay-get o 'invisible))
6766 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6767 (overlay-end o))))
6768 (delete-overlay o)))
6769 (overlays-at pos)))
6771 (defun org-clean-visibility-after-subtree-move ()
6772 "Fix visibility issues after moving a subtree."
6773 ;; First, find a reasonable region to look at:
6774 ;; Start two siblings above, end three below
6775 (let* ((beg (save-excursion
6776 (and (org-get-last-sibling)
6777 (org-get-last-sibling))
6778 (point)))
6779 (end (save-excursion
6780 (and (org-get-next-sibling)
6781 (org-get-next-sibling)
6782 (org-get-next-sibling))
6783 (if (org-at-heading-p)
6784 (point-at-eol)
6785 (point))))
6786 (level (looking-at "\\*+"))
6787 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6788 (save-excursion
6789 (save-restriction
6790 (narrow-to-region beg end)
6791 (when re
6792 ;; Properly fold already folded siblings
6793 (goto-char (point-min))
6794 (while (re-search-forward re nil t)
6795 (if (and (not (outline-invisible-p))
6796 (save-excursion
6797 (goto-char (point-at-eol)) (outline-invisible-p)))
6798 (hide-entry))))
6799 (org-cycle-show-empty-lines 'overview)
6800 (org-cycle-hide-drawers 'overview)))))
6802 (defun org-cycle-show-empty-lines (state)
6803 "Show empty lines above all visible headlines.
6804 The region to be covered depends on STATE when called through
6805 `org-cycle-hook'. Lisp program can use t for STATE to get the
6806 entire buffer covered. Note that an empty line is only shown if there
6807 are at least `org-cycle-separator-lines' empty lines before the headline."
6808 (when (not (= org-cycle-separator-lines 0))
6809 (save-excursion
6810 (let* ((n (abs org-cycle-separator-lines))
6811 (re (cond
6812 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6813 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6814 (t (let ((ns (number-to-string (- n 2))))
6815 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6816 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6817 beg end b e)
6818 (cond
6819 ((memq state '(overview contents t))
6820 (setq beg (point-min) end (point-max)))
6821 ((memq state '(children folded))
6822 (setq beg (point) end (progn (org-end-of-subtree t t)
6823 (beginning-of-line 2)
6824 (point)))))
6825 (when beg
6826 (goto-char beg)
6827 (while (re-search-forward re end t)
6828 (unless (get-char-property (match-end 1) 'invisible)
6829 (setq e (match-end 1))
6830 (if (< org-cycle-separator-lines 0)
6831 (setq b (save-excursion
6832 (goto-char (match-beginning 0))
6833 (org-back-over-empty-lines)
6834 (if (save-excursion
6835 (goto-char (max (point-min) (1- (point))))
6836 (org-at-heading-p))
6837 (1- (point))
6838 (point))))
6839 (setq b (match-beginning 1)))
6840 (outline-flag-region b e nil)))))))
6841 ;; Never hide empty lines at the end of the file.
6842 (save-excursion
6843 (goto-char (point-max))
6844 (outline-previous-heading)
6845 (outline-end-of-heading)
6846 (if (and (looking-at "[ \t\n]+")
6847 (= (match-end 0) (point-max)))
6848 (outline-flag-region (point) (match-end 0) nil))))
6850 (defun org-show-empty-lines-in-parent ()
6851 "Move to the parent and re-show empty lines before visible headlines."
6852 (save-excursion
6853 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6854 (org-cycle-show-empty-lines context))))
6856 (defun org-files-list ()
6857 "Return `org-agenda-files' list, plus all open org-mode files.
6858 This is useful for operations that need to scan all of a user's
6859 open and agenda-wise Org files."
6860 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6861 (dolist (buf (buffer-list))
6862 (with-current-buffer buf
6863 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6864 (let ((file (expand-file-name (buffer-file-name))))
6865 (unless (member file files)
6866 (push file files))))))
6867 files))
6869 (defsubst org-entry-beginning-position ()
6870 "Return the beginning position of the current entry."
6871 (save-excursion (outline-back-to-heading t) (point)))
6873 (defsubst org-entry-end-position ()
6874 "Return the end position of the current entry."
6875 (save-excursion (outline-next-heading) (point)))
6877 (defun org-cycle-hide-drawers (state)
6878 "Re-hide all drawers after a visibility state change."
6879 (when (and (derived-mode-p 'org-mode)
6880 (not (memq state '(overview folded contents))))
6881 (save-excursion
6882 (let* ((globalp (memq state '(contents all)))
6883 (beg (if globalp (point-min) (point)))
6884 (end (if globalp (point-max)
6885 (if (eq state 'children)
6886 (save-excursion (outline-next-heading) (point))
6887 (org-end-of-subtree t)))))
6888 (goto-char beg)
6889 (while (re-search-forward org-drawer-regexp end t)
6890 (org-flag-drawer t))))))
6892 (defun org-cycle-hide-inline-tasks (state)
6893 "Re-hide inline task when switching to 'contents visibility state."
6894 (when (and (eq state 'contents)
6895 (boundp 'org-inlinetask-min-level)
6896 org-inlinetask-min-level)
6897 (hide-sublevels (1- org-inlinetask-min-level))))
6899 (defun org-flag-drawer (flag)
6900 "When FLAG is non-nil, hide the drawer we are within.
6901 Otherwise make it visible."
6902 (save-excursion
6903 (beginning-of-line 1)
6904 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6905 (let ((b (match-end 0)))
6906 (if (re-search-forward
6907 "^[ \t]*:END:"
6908 (save-excursion (outline-next-heading) (point)) t)
6909 (outline-flag-region b (point-at-eol) flag)
6910 (error ":END: line missing at position %s" b))))))
6912 (defun org-subtree-end-visible-p ()
6913 "Is the end of the current subtree visible?"
6914 (pos-visible-in-window-p
6915 (save-excursion (org-end-of-subtree t) (point))))
6917 (defun org-first-headline-recenter (&optional N)
6918 "Move cursor to the first headline and recenter the headline.
6919 Optional argument N means put the headline into the Nth line of the window."
6920 (goto-char (point-min))
6921 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6922 (beginning-of-line)
6923 (recenter (prefix-numeric-value N))))
6925 ;;; Saving and restoring visibility
6927 (defun org-outline-overlay-data (&optional use-markers)
6928 "Return a list of the locations of all outline overlays.
6929 These are overlays with the `invisible' property value `outline'.
6930 The return value is a list of cons cells, with start and stop
6931 positions for each overlay.
6932 If USE-MARKERS is set, return the positions as markers."
6933 (let (beg end)
6934 (save-excursion
6935 (save-restriction
6936 (widen)
6937 (delq nil
6938 (mapcar (lambda (o)
6939 (when (eq (overlay-get o 'invisible) 'outline)
6940 (setq beg (overlay-start o)
6941 end (overlay-end o))
6942 (and beg end (> end beg)
6943 (if use-markers
6944 (cons (move-marker (make-marker) beg)
6945 (move-marker (make-marker) end))
6946 (cons beg end)))))
6947 (overlays-in (point-min) (point-max))))))))
6949 (defun org-set-outline-overlay-data (data)
6950 "Create visibility overlays for all positions in DATA.
6951 DATA should have been made by `org-outline-overlay-data'."
6952 (let (o)
6953 (save-excursion
6954 (save-restriction
6955 (widen)
6956 (show-all)
6957 (mapc (lambda (c)
6958 (outline-flag-region (car c) (cdr c) t))
6959 data)))))
6961 ;;; Folding of blocks
6963 (defvar org-hide-block-overlays nil
6964 "Overlays hiding blocks.")
6965 (make-variable-buffer-local 'org-hide-block-overlays)
6967 (defun org-block-map (function &optional start end)
6968 "Call FUNCTION at the head of all source blocks in the current buffer.
6969 Optional arguments START and END can be used to limit the range."
6970 (let ((start (or start (point-min)))
6971 (end (or end (point-max))))
6972 (save-excursion
6973 (goto-char start)
6974 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6975 (save-excursion
6976 (save-match-data
6977 (goto-char (match-beginning 0))
6978 (funcall function)))))))
6980 (defun org-hide-block-toggle-all ()
6981 "Toggle the visibility of all blocks in the current buffer."
6982 (org-block-map #'org-hide-block-toggle))
6984 (defun org-hide-block-all ()
6985 "Fold all blocks in the current buffer."
6986 (interactive)
6987 (org-show-block-all)
6988 (org-block-map #'org-hide-block-toggle-maybe))
6990 (defun org-show-block-all ()
6991 "Unfold all blocks in the current buffer."
6992 (interactive)
6993 (mapc 'delete-overlay org-hide-block-overlays)
6994 (setq org-hide-block-overlays nil))
6996 (defun org-hide-block-toggle-maybe ()
6997 "Toggle visibility of block at point."
6998 (interactive)
6999 (let ((case-fold-search t))
7000 (if (save-excursion
7001 (beginning-of-line 1)
7002 (looking-at org-block-regexp))
7003 (progn (org-hide-block-toggle)
7004 t) ;; to signal that we took action
7005 nil))) ;; to signal that we did not
7007 (defun org-hide-block-toggle (&optional force)
7008 "Toggle the visibility of the current block."
7009 (interactive)
7010 (save-excursion
7011 (beginning-of-line)
7012 (if (re-search-forward org-block-regexp nil t)
7013 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7014 (end (match-end 0)) ;; end of entire body
7016 (if (memq t (mapcar (lambda (overlay)
7017 (eq (overlay-get overlay 'invisible)
7018 'org-hide-block))
7019 (overlays-at start)))
7020 (if (or (not force) (eq force 'off))
7021 (mapc (lambda (ov)
7022 (when (member ov org-hide-block-overlays)
7023 (setq org-hide-block-overlays
7024 (delq ov org-hide-block-overlays)))
7025 (when (eq (overlay-get ov 'invisible)
7026 'org-hide-block)
7027 (delete-overlay ov)))
7028 (overlays-at start)))
7029 (setq ov (make-overlay start end))
7030 (overlay-put ov 'invisible 'org-hide-block)
7031 ;; make the block accessible to isearch
7032 (overlay-put
7033 ov 'isearch-open-invisible
7034 (lambda (ov)
7035 (when (member ov org-hide-block-overlays)
7036 (setq org-hide-block-overlays
7037 (delq ov org-hide-block-overlays)))
7038 (when (eq (overlay-get ov 'invisible)
7039 'org-hide-block)
7040 (delete-overlay ov))))
7041 (push ov org-hide-block-overlays)))
7042 (error "Not looking at a source block"))))
7044 ;; org-tab-after-check-for-cycling-hook
7045 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7046 ;; Remove overlays when changing major mode
7047 (add-hook 'org-mode-hook
7048 (lambda () (org-add-hook 'change-major-mode-hook
7049 'org-show-block-all 'append 'local)))
7051 ;;; Org-goto
7053 (defvar org-goto-window-configuration nil)
7054 (defvar org-goto-marker nil)
7055 (defvar org-goto-map)
7056 (defun org-goto-map ()
7057 "Set the keymap `org-goto'."
7058 (setq org-goto-map
7059 (let ((map (make-sparse-keymap)))
7060 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7061 mouse-drag-region universal-argument org-occur))
7062 cmd)
7063 (while (setq cmd (pop cmds))
7064 (substitute-key-definition cmd cmd map global-map)))
7065 (suppress-keymap map)
7066 (org-defkey map "\C-m" 'org-goto-ret)
7067 (org-defkey map [(return)] 'org-goto-ret)
7068 (org-defkey map [(left)] 'org-goto-left)
7069 (org-defkey map [(right)] 'org-goto-right)
7070 (org-defkey map [(control ?g)] 'org-goto-quit)
7071 (org-defkey map "\C-i" 'org-cycle)
7072 (org-defkey map [(tab)] 'org-cycle)
7073 (org-defkey map [(down)] 'outline-next-visible-heading)
7074 (org-defkey map [(up)] 'outline-previous-visible-heading)
7075 (if org-goto-auto-isearch
7076 (if (fboundp 'define-key-after)
7077 (define-key-after map [t] 'org-goto-local-auto-isearch)
7078 nil)
7079 (org-defkey map "q" 'org-goto-quit)
7080 (org-defkey map "n" 'outline-next-visible-heading)
7081 (org-defkey map "p" 'outline-previous-visible-heading)
7082 (org-defkey map "f" 'outline-forward-same-level)
7083 (org-defkey map "b" 'outline-backward-same-level)
7084 (org-defkey map "u" 'outline-up-heading))
7085 (org-defkey map "/" 'org-occur)
7086 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7087 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7088 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7089 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7090 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7091 map)))
7093 (defconst org-goto-help
7094 "Browse buffer copy, to find location or copy text.%s
7095 RET=jump to location C-g=quit and return to previous location
7096 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7098 (defvar org-goto-start-pos) ; dynamically scoped parameter
7100 ;; FIXME: Docstring does not mention both interfaces
7101 (defun org-goto (&optional alternative-interface)
7102 "Look up a different location in the current file, keeping current visibility.
7104 When you want look-up or go to a different location in a
7105 document, the fastest way is often to fold the entire buffer and
7106 then dive into the tree. This method has the disadvantage, that
7107 the previous location will be folded, which may not be what you
7108 want.
7110 This command works around this by showing a copy of the current
7111 buffer in an indirect buffer, in overview mode. You can dive
7112 into the tree in that copy, use org-occur and incremental search
7113 to find a location. When pressing RET or `Q', the command
7114 returns to the original buffer in which the visibility is still
7115 unchanged. After RET it will also jump to the location selected
7116 in the indirect buffer and expose the headline hierarchy above.
7118 With a prefix argument, use the alternative interface: e.g. if
7119 `org-goto-interface' is 'outline use 'outline-path-completion."
7120 (interactive "P")
7121 (org-goto-map)
7122 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7123 (org-refile-use-outline-path t)
7124 (org-refile-target-verify-function nil)
7125 (interface
7126 (if (not alternative-interface)
7127 org-goto-interface
7128 (if (eq org-goto-interface 'outline)
7129 'outline-path-completion
7130 'outline)))
7131 (org-goto-start-pos (point))
7132 (selected-point
7133 (if (eq interface 'outline)
7134 (car (org-get-location (current-buffer) org-goto-help))
7135 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7136 (org-refile-check-position pa)
7137 (nth 3 pa)))))
7138 (if selected-point
7139 (progn
7140 (org-mark-ring-push org-goto-start-pos)
7141 (goto-char selected-point)
7142 (if (or (outline-invisible-p) (org-invisible-p2))
7143 (org-show-context 'org-goto)))
7144 (message "Quit"))))
7146 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7147 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7148 (defvar org-goto-local-auto-isearch-map) ; defined below
7150 (defun org-get-location (buf help)
7151 "Let the user select a location in the Org-mode buffer BUF.
7152 This function uses a recursive edit. It returns the selected position
7153 or nil."
7154 (org-no-popups
7155 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7156 (isearch-hide-immediately nil)
7157 (isearch-search-fun-function
7158 (lambda () 'org-goto-local-search-headings))
7159 (org-goto-selected-point org-goto-exit-command))
7160 (save-excursion
7161 (save-window-excursion
7162 (delete-other-windows)
7163 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7164 (org-pop-to-buffer-same-window
7165 (condition-case nil
7166 (make-indirect-buffer (current-buffer) "*org-goto*")
7167 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7168 (with-output-to-temp-buffer "*Org Help*"
7169 (princ (format help (if org-goto-auto-isearch
7170 " Just type for auto-isearch."
7171 " n/p/f/b/u to navigate, q to quit."))))
7172 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7173 (setq buffer-read-only nil)
7174 (let ((org-startup-truncated t)
7175 (org-startup-folded nil)
7176 (org-startup-align-all-tables nil))
7177 (org-mode)
7178 (org-overview))
7179 (setq buffer-read-only t)
7180 (if (and (boundp 'org-goto-start-pos)
7181 (integer-or-marker-p org-goto-start-pos))
7182 (let ((org-show-hierarchy-above t)
7183 (org-show-siblings t)
7184 (org-show-following-heading t))
7185 (goto-char org-goto-start-pos)
7186 (and (outline-invisible-p) (org-show-context)))
7187 (goto-char (point-min)))
7188 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7189 (message "Select location and press RET")
7190 (use-local-map org-goto-map)
7191 (recursive-edit)))
7192 (kill-buffer "*org-goto*")
7193 (cons org-goto-selected-point org-goto-exit-command))))
7195 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7196 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7197 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7198 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7200 (defun org-goto-local-search-headings (string bound noerror)
7201 "Search and make sure that any matches are in headlines."
7202 (catch 'return
7203 (while (if isearch-forward
7204 (search-forward string bound noerror)
7205 (search-backward string bound noerror))
7206 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7207 (and (member :headline context)
7208 (not (member :tags context))))
7209 (throw 'return (point))))))
7211 (defun org-goto-local-auto-isearch ()
7212 "Start isearch."
7213 (interactive)
7214 (goto-char (point-min))
7215 (let ((keys (this-command-keys)))
7216 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7217 (isearch-mode t)
7218 (isearch-process-search-char (string-to-char keys)))))
7220 (defun org-goto-ret (&optional arg)
7221 "Finish `org-goto' by going to the new location."
7222 (interactive "P")
7223 (setq org-goto-selected-point (point)
7224 org-goto-exit-command 'return)
7225 (throw 'exit nil))
7227 (defun org-goto-left ()
7228 "Finish `org-goto' by going to the new location."
7229 (interactive)
7230 (if (org-at-heading-p)
7231 (progn
7232 (beginning-of-line 1)
7233 (setq org-goto-selected-point (point)
7234 org-goto-exit-command 'left)
7235 (throw 'exit nil))
7236 (error "Not on a heading")))
7238 (defun org-goto-right ()
7239 "Finish `org-goto' by going to the new location."
7240 (interactive)
7241 (if (org-at-heading-p)
7242 (progn
7243 (setq org-goto-selected-point (point)
7244 org-goto-exit-command 'right)
7245 (throw 'exit nil))
7246 (error "Not on a heading")))
7248 (defun org-goto-quit ()
7249 "Finish `org-goto' without cursor motion."
7250 (interactive)
7251 (setq org-goto-selected-point nil)
7252 (setq org-goto-exit-command 'quit)
7253 (throw 'exit nil))
7255 ;;; Indirect buffer display of subtrees
7257 (defvar org-indirect-dedicated-frame nil
7258 "This is the frame being used for indirect tree display.")
7259 (defvar org-last-indirect-buffer nil)
7261 (defun org-tree-to-indirect-buffer (&optional arg)
7262 "Create indirect buffer and narrow it to current subtree.
7263 With a numerical prefix ARG, go up to this level and then take that tree.
7264 If ARG is negative, go up that many levels.
7266 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7267 indirect buffer previously made with this command, to avoid proliferation of
7268 indirect buffers. However, when you call the command with a \
7269 \\[universal-argument] prefix, or
7270 when `org-indirect-buffer-display' is `new-frame', the last buffer
7271 is kept so that you can work with several indirect buffers at the same time.
7272 If `org-indirect-buffer-display' is `dedicated-frame', the \
7273 \\[universal-argument] prefix also
7274 requests that a new frame be made for the new buffer, so that the dedicated
7275 frame is not changed."
7276 (interactive "P")
7277 (let ((cbuf (current-buffer))
7278 (cwin (selected-window))
7279 (pos (point))
7280 beg end level heading ibuf)
7281 (save-excursion
7282 (org-back-to-heading t)
7283 (when (numberp arg)
7284 (setq level (org-outline-level))
7285 (if (< arg 0) (setq arg (+ level arg)))
7286 (while (> (setq level (org-outline-level)) arg)
7287 (org-up-heading-safe)))
7288 (setq beg (point)
7289 heading (org-get-heading))
7290 (org-end-of-subtree t t)
7291 (if (org-at-heading-p) (backward-char 1))
7292 (setq end (point)))
7293 (if (and (buffer-live-p org-last-indirect-buffer)
7294 (not (eq org-indirect-buffer-display 'new-frame))
7295 (not arg))
7296 (kill-buffer org-last-indirect-buffer))
7297 (setq ibuf (org-get-indirect-buffer cbuf)
7298 org-last-indirect-buffer ibuf)
7299 (cond
7300 ((or (eq org-indirect-buffer-display 'new-frame)
7301 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7302 (select-frame (make-frame))
7303 (delete-other-windows)
7304 (org-pop-to-buffer-same-window ibuf)
7305 (org-set-frame-title heading))
7306 ((eq org-indirect-buffer-display 'dedicated-frame)
7307 (raise-frame
7308 (select-frame (or (and org-indirect-dedicated-frame
7309 (frame-live-p org-indirect-dedicated-frame)
7310 org-indirect-dedicated-frame)
7311 (setq org-indirect-dedicated-frame (make-frame)))))
7312 (delete-other-windows)
7313 (org-pop-to-buffer-same-window ibuf)
7314 (org-set-frame-title (concat "Indirect: " heading)))
7315 ((eq org-indirect-buffer-display 'current-window)
7316 (org-pop-to-buffer-same-window ibuf))
7317 ((eq org-indirect-buffer-display 'other-window)
7318 (pop-to-buffer ibuf))
7319 (t (error "Invalid value")))
7320 (if (featurep 'xemacs)
7321 (save-excursion (org-mode) (turn-on-font-lock)))
7322 (narrow-to-region beg end)
7323 (show-all)
7324 (goto-char pos)
7325 (run-hook-with-args 'org-cycle-hook 'all)
7326 (and (window-live-p cwin) (select-window cwin))))
7328 (defun org-get-indirect-buffer (&optional buffer)
7329 (setq buffer (or buffer (current-buffer)))
7330 (let ((n 1) (base (buffer-name buffer)) bname)
7331 (while (buffer-live-p
7332 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7333 (setq n (1+ n)))
7334 (condition-case nil
7335 (make-indirect-buffer buffer bname 'clone)
7336 (error (make-indirect-buffer buffer bname)))))
7338 (defun org-set-frame-title (title)
7339 "Set the title of the current frame to the string TITLE."
7340 ;; FIXME: how to name a single frame in XEmacs???
7341 (unless (featurep 'xemacs)
7342 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7344 ;;;; Structure editing
7346 ;;; Inserting headlines
7348 (defun org-previous-line-empty-p (&optional next)
7349 "Is the previous line a blank line?
7350 When NEXT is non-nil, check the next line instead."
7351 (save-excursion
7352 (and (not (bobp))
7353 (or (beginning-of-line (if next 2 0)) t)
7354 (save-match-data
7355 (looking-at "[ \t]*$")))))
7357 (defun org-insert-heading (&optional arg invisible-ok)
7358 "Insert a new heading or item with same depth at point.
7359 If point is in a plain list and ARG is nil, create a new list item.
7360 With one universal prefix argument, insert a heading even in lists.
7361 With two universal prefix arguments, insert the heading at the end
7362 of the parent subtree.
7364 If point is at the beginning of a headline, insert a sibling before
7365 the current headline. If point is not at the beginning, split the line
7366 and create a new headline with the text in the current line after point
7367 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7369 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7370 This is important for non-interactive uses of the command."
7371 (interactive "P")
7372 (if (or (= (buffer-size) 0)
7373 (and (not (save-excursion
7374 (and (ignore-errors (org-back-to-heading invisible-ok))
7375 (org-at-heading-p))))
7376 (or arg (not (org-in-item-p)))))
7377 (progn
7378 (insert
7379 (if (org-previous-line-empty-p) "" "\n")
7380 (if (org-in-src-block-p) ",* " "* "))
7381 (run-hooks 'org-insert-heading-hook))
7382 (when (or arg (not (org-insert-item)))
7383 (let* ((empty-line-p nil)
7384 (eops (equal arg '(16))) ; insert at end of parent subtree
7385 (org-insert-heading-respect-content
7386 (or (not (null arg)) org-insert-heading-respect-content))
7387 (level nil)
7388 (on-heading (org-at-heading-p))
7389 (head (save-excursion
7390 (condition-case nil
7391 (progn
7392 (org-back-to-heading invisible-ok)
7393 (when (and (not on-heading)
7394 (featurep 'org-inlinetask)
7395 (integerp org-inlinetask-min-level)
7396 (>= (length (match-string 0))
7397 org-inlinetask-min-level))
7398 ;; Find a heading level before the inline task
7399 (while (and (setq level (org-up-heading-safe))
7400 (>= level org-inlinetask-min-level)))
7401 (if (org-at-heading-p)
7402 (org-back-to-heading invisible-ok)
7403 (error "This should not happen")))
7404 (unless (and (save-excursion
7405 (save-match-data
7406 (org-backward-heading-same-level 1 invisible-ok))
7407 (= (point) (match-beginning 0)))
7408 (not (org-previous-line-empty-p t)))
7409 (setq empty-line-p (org-previous-line-empty-p)))
7410 (match-string 0))
7411 (error "* "))))
7412 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7413 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7414 pos hide-previous previous-pos)
7415 (cond
7416 ;; At the beginning of a heading, open a new line for insertiong
7417 ((and (bolp) (org-at-heading-p)
7418 (not eops)
7419 (or (bobp)
7420 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7421 (open-line (if blank 2 1)))
7423 (save-excursion
7424 (setq previous-pos (point-at-bol))
7425 (end-of-line)
7426 (setq hide-previous (outline-invisible-p)))
7427 (and org-insert-heading-respect-content
7428 (save-excursion
7429 (while (outline-invisible-p)
7430 (org-show-subtree)
7431 (org-up-heading-safe))))
7432 (let ((split
7433 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7434 (save-excursion
7435 (let ((p (point)))
7436 (goto-char (point-at-bol))
7437 (and (looking-at org-complex-heading-regexp)
7438 (match-beginning 4)
7439 (> p (match-beginning 4)))))))
7440 tags pos)
7441 (cond
7442 ;; Insert a new line, possibly at end of parent subtree
7443 (org-insert-heading-respect-content
7444 (if (not eops)
7445 (progn
7446 (org-end-of-subtree nil t)
7447 (and (looking-at "^\\*") (backward-char 1))
7448 (while (and (not (bobp))
7449 (member (char-before) '(?\ ?\t ?\n)))
7450 (backward-delete-char 1)))
7451 (let ((p (point)))
7452 (org-up-heading-safe)
7453 (if (= p (point))
7454 (goto-char (point-max))
7455 (org-end-of-subtree nil t))))
7456 (when (featurep 'org-inlinetask)
7457 (while (and (not (eobp))
7458 (looking-at "\\(\\*+\\)[ \t]+")
7459 (>= (length (match-string 1))
7460 org-inlinetask-min-level))
7461 (org-end-of-subtree nil t)))
7462 (or (bolp) (newline))
7463 (or (org-previous-line-empty-p)
7464 (and blank (newline)))
7465 (if (or empty-line-p eops) (open-line 1)))
7466 ;; Insert a headling containing text after point
7467 ((org-at-heading-p)
7468 (when hide-previous
7469 (show-children)
7470 (org-show-entry))
7471 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7472 (setq tags (and (match-end 2) (match-string 2)))
7473 (and (match-end 1)
7474 (delete-region (match-beginning 1) (match-end 1)))
7475 (setq pos (point-at-bol))
7476 (or split (end-of-line 1))
7477 (delete-horizontal-space)
7478 (if (string-match "\\`\\*+\\'"
7479 (buffer-substring (point-at-bol) (point)))
7480 (insert " "))
7481 (newline (if blank 2 1))
7482 (when tags
7483 (save-excursion
7484 (goto-char pos)
7485 (end-of-line 1)
7486 (insert " " tags)
7487 (org-set-tags nil 'align))))
7489 (or split (end-of-line 1))
7490 (newline (if blank 2 1)))))))
7491 (insert head) (just-one-space)
7492 (setq pos (point))
7493 (end-of-line 1)
7494 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7495 (when (and org-insert-heading-respect-content hide-previous)
7496 (save-excursion
7497 (goto-char previous-pos)
7498 (hide-subtree)))
7499 (run-hooks 'org-insert-heading-hook)))))
7501 (defun org-get-heading (&optional no-tags no-todo)
7502 "Return the heading of the current entry, without the stars.
7503 When NO-TAGS is non-nil, don't include tags.
7504 When NO-TODO is non-nil, don't include TODO keywords."
7505 (save-excursion
7506 (org-back-to-heading t)
7507 (cond
7508 ((and no-tags no-todo)
7509 (looking-at org-complex-heading-regexp)
7510 (match-string 4))
7511 (no-tags
7512 (looking-at (concat org-outline-regexp
7513 "\\(.*?\\)"
7514 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7515 (match-string 1))
7516 (no-todo
7517 (looking-at org-todo-line-regexp)
7518 (match-string 3))
7519 (t (looking-at org-heading-regexp)
7520 (match-string 2)))))
7522 (defvar orgstruct-mode) ; defined below
7524 (defun org-heading-components ()
7525 "Return the components of the current heading.
7526 This is a list with the following elements:
7527 - the level as an integer
7528 - the reduced level, different if `org-odd-levels-only' is set.
7529 - the TODO keyword, or nil
7530 - the priority character, like ?A, or nil if no priority is given
7531 - the headline text itself, or the tags string if no headline text
7532 - the tags string, or nil."
7533 (save-excursion
7534 (org-back-to-heading t)
7535 (if (let (case-fold-search)
7536 (looking-at
7537 (if orgstruct-mode
7538 org-heading-regexp
7539 org-complex-heading-regexp)))
7540 (if orgstruct-mode
7541 (list (length (match-string 1))
7542 (org-reduced-level (length (match-string 1)))
7545 (match-string 2)
7546 nil)
7547 (list (length (match-string 1))
7548 (org-reduced-level (length (match-string 1)))
7549 (org-match-string-no-properties 2)
7550 (and (match-end 3) (aref (match-string 3) 2))
7551 (org-match-string-no-properties 4)
7552 (org-match-string-no-properties 5))))))
7554 (defun org-get-entry ()
7555 "Get the entry text, after heading, entire subtree."
7556 (save-excursion
7557 (org-back-to-heading t)
7558 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7560 (defun org-insert-heading-after-current ()
7561 "Insert a new heading with same level as current, after current subtree."
7562 (interactive)
7563 (org-back-to-heading)
7564 (org-insert-heading)
7565 (org-move-subtree-down)
7566 (end-of-line 1))
7568 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7569 "Insert heading with `org-insert-heading-respect-content' set to t."
7570 (interactive "P")
7571 (let ((org-insert-heading-respect-content t))
7572 (org-insert-heading arg invisible-ok)))
7574 (defun org-insert-todo-heading-respect-content (&optional force-state)
7575 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7576 (interactive "P")
7577 (let ((org-insert-heading-respect-content t))
7578 (org-insert-todo-heading force-state t)))
7580 (defun org-insert-todo-heading (arg &optional force-heading)
7581 "Insert a new heading with the same level and TODO state as current heading.
7582 If the heading has no TODO state, or if the state is DONE, use the first
7583 state (TODO by default). Also one prefix arg, force first state. With two
7584 prefix args, force inserting at the end of the parent subtree."
7585 (interactive "P")
7586 (when (or force-heading (not (org-insert-item 'checkbox)))
7587 (org-insert-heading (or (and (equal arg '(16)) '(16))
7588 force-heading))
7589 (save-excursion
7590 (org-back-to-heading)
7591 (outline-previous-heading)
7592 (looking-at org-todo-line-regexp))
7593 (let*
7594 ((new-mark-x
7595 (if (or arg
7596 (not (match-beginning 2))
7597 (member (match-string 2) org-done-keywords))
7598 (car org-todo-keywords-1)
7599 (match-string 2)))
7600 (new-mark
7602 (run-hook-with-args-until-success
7603 'org-todo-get-default-hook new-mark-x nil)
7604 new-mark-x)))
7605 (beginning-of-line 1)
7606 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7607 (if org-treat-insert-todo-heading-as-state-change
7608 (org-todo new-mark)
7609 (insert new-mark " "))))
7610 (when org-provide-todo-statistics
7611 (org-update-parent-todo-statistics))))
7613 (defun org-insert-subheading (arg)
7614 "Insert a new subheading and demote it.
7615 Works for outline headings and for plain lists alike."
7616 (interactive "P")
7617 (org-insert-heading arg)
7618 (cond
7619 ((org-at-heading-p) (org-do-demote))
7620 ((org-at-item-p) (org-indent-item))))
7622 (defun org-insert-todo-subheading (arg)
7623 "Insert a new subheading with TODO keyword or checkbox and demote it.
7624 Works for outline headings and for plain lists alike."
7625 (interactive "P")
7626 (org-insert-todo-heading arg)
7627 (cond
7628 ((org-at-heading-p) (org-do-demote))
7629 ((org-at-item-p) (org-indent-item))))
7631 ;;; Promotion and Demotion
7633 (defvar org-after-demote-entry-hook nil
7634 "Hook run after an entry has been demoted.
7635 The cursor will be at the beginning of the entry.
7636 When a subtree is being demoted, the hook will be called for each node.")
7638 (defvar org-after-promote-entry-hook nil
7639 "Hook run after an entry has been promoted.
7640 The cursor will be at the beginning of the entry.
7641 When a subtree is being promoted, the hook will be called for each node.")
7643 (defun org-promote-subtree ()
7644 "Promote the entire subtree.
7645 See also `org-promote'."
7646 (interactive)
7647 (save-excursion
7648 (org-with-limited-levels (org-map-tree 'org-promote)))
7649 (org-fix-position-after-promote))
7651 (defun org-demote-subtree ()
7652 "Demote the entire subtree. See `org-demote'.
7653 See also `org-promote'."
7654 (interactive)
7655 (save-excursion
7656 (org-with-limited-levels (org-map-tree 'org-demote)))
7657 (org-fix-position-after-promote))
7660 (defun org-do-promote ()
7661 "Promote the current heading higher up the tree.
7662 If the region is active in `transient-mark-mode', promote all headings
7663 in the region."
7664 (interactive)
7665 (save-excursion
7666 (if (org-region-active-p)
7667 (org-map-region 'org-promote (region-beginning) (region-end))
7668 (org-promote)))
7669 (org-fix-position-after-promote))
7671 (defun org-do-demote ()
7672 "Demote the current heading lower down the tree.
7673 If the region is active in `transient-mark-mode', demote all headings
7674 in the region."
7675 (interactive)
7676 (save-excursion
7677 (if (org-region-active-p)
7678 (org-map-region 'org-demote (region-beginning) (region-end))
7679 (org-demote)))
7680 (org-fix-position-after-promote))
7682 (defun org-fix-position-after-promote ()
7683 "Make sure that after pro/demotion cursor position is right."
7684 (let ((pos (point)))
7685 (when (save-excursion
7686 (beginning-of-line 1)
7687 (looking-at org-todo-line-regexp)
7688 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7689 (cond ((eobp) (insert " "))
7690 ((eolp) (insert " "))
7691 ((equal (char-after) ?\ ) (forward-char 1))))))
7693 (defun org-current-level ()
7694 "Return the level of the current entry, or nil if before the first headline.
7695 The level is the number of stars at the beginning of the headline."
7696 (save-excursion
7697 (org-with-limited-levels
7698 (if (ignore-errors (org-back-to-heading t))
7699 (funcall outline-level)))))
7701 (defun org-get-previous-line-level ()
7702 "Return the outline depth of the last headline before the current line.
7703 Returns 0 for the first headline in the buffer, and nil if before the
7704 first headline."
7705 (let ((current-level (org-current-level))
7706 (prev-level (when (> (line-number-at-pos) 1)
7707 (save-excursion
7708 (beginning-of-line 0)
7709 (org-current-level)))))
7710 (cond ((null current-level) nil) ; Before first headline
7711 ((null prev-level) 0) ; At first headline
7712 (prev-level))))
7714 (defun org-reduced-level (l)
7715 "Compute the effective level of a heading.
7716 This takes into account the setting of `org-odd-levels-only'."
7717 (cond
7718 ((zerop l) 0)
7719 (org-odd-levels-only (1+ (floor (/ l 2))))
7720 (t l)))
7722 (defun org-level-increment ()
7723 "Return the number of stars that will be added or removed at a
7724 time to headlines when structure editing, based on the value of
7725 `org-odd-levels-only'."
7726 (if org-odd-levels-only 2 1))
7728 (defun org-get-valid-level (level &optional change)
7729 "Rectify a level change under the influence of `org-odd-levels-only'
7730 LEVEL is a current level, CHANGE is by how much the level should be
7731 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7732 even level numbers will become the next higher odd number."
7733 (if org-odd-levels-only
7734 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7735 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7736 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7737 (max 1 (+ level (or change 0)))))
7739 (if (boundp 'define-obsolete-function-alias)
7740 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7741 (define-obsolete-function-alias 'org-get-legal-level
7742 'org-get-valid-level)
7743 (define-obsolete-function-alias 'org-get-legal-level
7744 'org-get-valid-level "23.1")))
7746 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7747 ;; ̀org-with-limited-levels'
7748 (defun org-promote ()
7749 "Promote the current heading higher up the tree.
7750 If the region is active in `transient-mark-mode', promote all headings
7751 in the region."
7752 (org-back-to-heading t)
7753 (let* ((level (save-match-data (funcall outline-level)))
7754 (after-change-functions (remove 'flyspell-after-change-function
7755 after-change-functions))
7756 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7757 (diff (abs (- level (length up-head) -1))))
7758 (cond ((and (= level 1) org-called-with-limited-levels
7759 org-allow-promoting-top-level-subtree)
7760 (replace-match "# " nil t))
7761 ((= level 1)
7762 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7763 (t (replace-match up-head nil t)))
7764 ;; Fixup tag positioning
7765 (unless (= level 1)
7766 (and org-auto-align-tags (org-set-tags nil t))
7767 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7768 (run-hooks 'org-after-promote-entry-hook)))
7770 (defun org-demote ()
7771 "Demote the current heading lower down the tree.
7772 If the region is active in `transient-mark-mode', demote all headings
7773 in the region."
7774 (org-back-to-heading t)
7775 (let* ((level (save-match-data (funcall outline-level)))
7776 (after-change-functions (remove 'flyspell-after-change-function
7777 after-change-functions))
7778 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7779 (diff (abs (- level (length down-head) -1))))
7780 (replace-match down-head nil t)
7781 ;; Fixup tag positioning
7782 (and org-auto-align-tags (org-set-tags nil t))
7783 (if org-adapt-indentation (org-fixup-indentation diff))
7784 (run-hooks 'org-after-demote-entry-hook)))
7786 (defun org-cycle-level ()
7787 "Cycle the level of an empty headline through possible states.
7788 This goes first to child, then to parent, level, then up the hierarchy.
7789 After top level, it switches back to sibling level."
7790 (interactive)
7791 (let ((org-adapt-indentation nil))
7792 (when (org-point-at-end-of-empty-headline)
7793 (setq this-command 'org-cycle-level) ; Only needed for caching
7794 (let ((cur-level (org-current-level))
7795 (prev-level (org-get-previous-line-level)))
7796 (cond
7797 ;; If first headline in file, promote to top-level.
7798 ((= prev-level 0)
7799 (loop repeat (/ (- cur-level 1) (org-level-increment))
7800 do (org-do-promote)))
7801 ;; If same level as prev, demote one.
7802 ((= prev-level cur-level)
7803 (org-do-demote))
7804 ;; If parent is top-level, promote to top level if not already.
7805 ((= prev-level 1)
7806 (loop repeat (/ (- cur-level 1) (org-level-increment))
7807 do (org-do-promote)))
7808 ;; If top-level, return to prev-level.
7809 ((= cur-level 1)
7810 (loop repeat (/ (- prev-level 1) (org-level-increment))
7811 do (org-do-demote)))
7812 ;; If less than prev-level, promote one.
7813 ((< cur-level prev-level)
7814 (org-do-promote))
7815 ;; If deeper than prev-level, promote until higher than
7816 ;; prev-level.
7817 ((> cur-level prev-level)
7818 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7819 do (org-do-promote))))
7820 t))))
7822 (defun org-map-tree (fun)
7823 "Call FUN for every heading underneath the current one."
7824 (org-back-to-heading)
7825 (let ((level (funcall outline-level)))
7826 (save-excursion
7827 (funcall fun)
7828 (while (and (progn
7829 (outline-next-heading)
7830 (> (funcall outline-level) level))
7831 (not (eobp)))
7832 (funcall fun)))))
7834 (defun org-map-region (fun beg end)
7835 "Call FUN for every heading between BEG and END."
7836 (let ((org-ignore-region t))
7837 (save-excursion
7838 (setq end (copy-marker end))
7839 (goto-char beg)
7840 (if (and (re-search-forward org-outline-regexp-bol nil t)
7841 (< (point) end))
7842 (funcall fun))
7843 (while (and (progn
7844 (outline-next-heading)
7845 (< (point) end))
7846 (not (eobp)))
7847 (funcall fun)))))
7849 (defvar org-property-end-re) ; silence byte-compiler
7850 (defun org-fixup-indentation (diff)
7851 "Change the indentation in the current entry by DIFF.
7852 However, if any line in the current entry has no indentation, or if it
7853 would end up with no indentation after the change, nothing at all is done."
7854 (save-excursion
7855 (let ((end (save-excursion (outline-next-heading)
7856 (point-marker)))
7857 (prohibit (if (> diff 0)
7858 "^\\S-"
7859 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7860 col)
7861 (unless (save-excursion (end-of-line 1)
7862 (re-search-forward prohibit end t))
7863 (while (and (< (point) end)
7864 (re-search-forward "^[ \t]+" end t))
7865 (goto-char (match-end 0))
7866 (setq col (current-column))
7867 (if (< diff 0) (replace-match ""))
7868 (org-indent-to-column (+ diff col))))
7869 (move-marker end nil))))
7871 (defun org-convert-to-odd-levels ()
7872 "Convert an org-mode file with all levels allowed to one with odd levels.
7873 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7874 level 5 etc."
7875 (interactive)
7876 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7877 (let ((outline-level 'org-outline-level)
7878 (org-odd-levels-only nil) n)
7879 (save-excursion
7880 (goto-char (point-min))
7881 (while (re-search-forward "^\\*\\*+ " nil t)
7882 (setq n (- (length (match-string 0)) 2))
7883 (while (>= (setq n (1- n)) 0)
7884 (org-demote))
7885 (end-of-line 1))))))
7887 (defun org-convert-to-oddeven-levels ()
7888 "Convert an org-mode file with only odd levels to one with odd/even levels.
7889 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7890 file contains a section with an even level, conversion would
7891 destroy the structure of the file. An error is signaled in this
7892 case."
7893 (interactive)
7894 (goto-char (point-min))
7895 ;; First check if there are no even levels
7896 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7897 (org-show-context t)
7898 (error "Not all levels are odd in this file. Conversion not possible"))
7899 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7900 (let ((outline-regexp org-outline-regexp)
7901 (outline-level 'org-outline-level)
7902 (org-odd-levels-only nil) n)
7903 (save-excursion
7904 (goto-char (point-min))
7905 (while (re-search-forward "^\\*\\*+ " nil t)
7906 (setq n (/ (1- (length (match-string 0))) 2))
7907 (while (>= (setq n (1- n)) 0)
7908 (org-promote))
7909 (end-of-line 1))))))
7911 (defun org-tr-level (n)
7912 "Make N odd if required."
7913 (if org-odd-levels-only (1+ (/ n 2)) n))
7915 ;;; Vertical tree motion, cutting and pasting of subtrees
7917 (defun org-move-subtree-up (&optional arg)
7918 "Move the current subtree up past ARG headlines of the same level."
7919 (interactive "p")
7920 (org-move-subtree-down (- (prefix-numeric-value arg))))
7922 (defun org-move-subtree-down (&optional arg)
7923 "Move the current subtree down past ARG headlines of the same level."
7924 (interactive "p")
7925 (setq arg (prefix-numeric-value arg))
7926 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7927 'org-get-last-sibling))
7928 (ins-point (make-marker))
7929 (cnt (abs arg))
7930 (col (current-column))
7931 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7932 ;; Select the tree
7933 (org-back-to-heading)
7934 (setq beg0 (point))
7935 (save-excursion
7936 (setq ne-beg (org-back-over-empty-lines))
7937 (setq beg (point)))
7938 (save-match-data
7939 (save-excursion (outline-end-of-heading)
7940 (setq folded (outline-invisible-p)))
7941 (outline-end-of-subtree))
7942 (outline-next-heading)
7943 (setq ne-end (org-back-over-empty-lines))
7944 (setq end (point))
7945 (goto-char beg0)
7946 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7947 ;; include less whitespace
7948 (save-excursion
7949 (goto-char beg)
7950 (forward-line (- ne-beg ne-end))
7951 (setq beg (point))))
7952 ;; Find insertion point, with error handling
7953 (while (> cnt 0)
7954 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7955 (progn (goto-char beg0)
7956 (user-error "Cannot move past superior level or buffer limit")))
7957 (setq cnt (1- cnt)))
7958 (if (> arg 0)
7959 ;; Moving forward - still need to move over subtree
7960 (progn (org-end-of-subtree t t)
7961 (save-excursion
7962 (org-back-over-empty-lines)
7963 (or (bolp) (newline)))))
7964 (setq ne-ins (org-back-over-empty-lines))
7965 (move-marker ins-point (point))
7966 (setq txt (buffer-substring beg end))
7967 (org-save-markers-in-region beg end)
7968 (delete-region beg end)
7969 (org-remove-empty-overlays-at beg)
7970 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7971 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7972 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7973 (let ((bbb (point)))
7974 (insert-before-markers txt)
7975 (org-reinstall-markers-in-region bbb)
7976 (move-marker ins-point bbb))
7977 (or (bolp) (insert "\n"))
7978 (setq ins-end (point))
7979 (goto-char ins-point)
7980 (org-skip-whitespace)
7981 (when (and (< arg 0)
7982 (org-first-sibling-p)
7983 (> ne-ins ne-beg))
7984 ;; Move whitespace back to beginning
7985 (save-excursion
7986 (goto-char ins-end)
7987 (let ((kill-whole-line t))
7988 (kill-line (- ne-ins ne-beg)) (point)))
7989 (insert (make-string (- ne-ins ne-beg) ?\n)))
7990 (move-marker ins-point nil)
7991 (if folded
7992 (hide-subtree)
7993 (org-show-entry)
7994 (show-children)
7995 (org-cycle-hide-drawers 'children))
7996 (org-clean-visibility-after-subtree-move)
7997 ;; move back to the initial column we were at
7998 (move-to-column col)))
8000 (defvar org-subtree-clip ""
8001 "Clipboard for cut and paste of subtrees.
8002 This is actually only a copy of the kill, because we use the normal kill
8003 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8005 (defvar org-subtree-clip-folded nil
8006 "Was the last copied subtree folded?
8007 This is used to fold the tree back after pasting.")
8009 (defun org-cut-subtree (&optional n)
8010 "Cut the current subtree into the clipboard.
8011 With prefix arg N, cut this many sequential subtrees.
8012 This is a short-hand for marking the subtree and then cutting it."
8013 (interactive "p")
8014 (org-copy-subtree n 'cut))
8016 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8017 "Cut the current subtree into the clipboard.
8018 With prefix arg N, cut this many sequential subtrees.
8019 This is a short-hand for marking the subtree and then copying it.
8020 If CUT is non-nil, actually cut the subtree.
8021 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8022 of some markers in the region, even if CUT is non-nil. This is
8023 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8024 (interactive "p")
8025 (let (beg end folded (beg0 (point)))
8026 (if (org-called-interactively-p 'any)
8027 (org-back-to-heading nil) ; take what looks like a subtree
8028 (org-back-to-heading t)) ; take what is really there
8029 (setq beg (point))
8030 (skip-chars-forward " \t\r\n")
8031 (save-match-data
8032 (if nosubtrees
8033 (outline-next-heading)
8034 (save-excursion (outline-end-of-heading)
8035 (setq folded (outline-invisible-p)))
8036 (condition-case nil
8037 (org-forward-heading-same-level (1- n) t)
8038 (error nil))
8039 (org-end-of-subtree t t)))
8040 (setq end (point))
8041 (goto-char beg0)
8042 (when (> end beg)
8043 (setq org-subtree-clip-folded folded)
8044 (when (or cut force-store-markers)
8045 (org-save-markers-in-region beg end))
8046 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8047 (setq org-subtree-clip (current-kill 0))
8048 (message "%s: Subtree(s) with %d characters"
8049 (if cut "Cut" "Copied")
8050 (length org-subtree-clip)))))
8052 (defun org-paste-subtree (&optional level tree for-yank)
8053 "Paste the clipboard as a subtree, with modification of headline level.
8054 The entire subtree is promoted or demoted in order to match a new headline
8055 level.
8057 If the cursor is at the beginning of a headline, the same level as
8058 that headline is used to paste the tree.
8060 If not, the new level is derived from the *visible* headings
8061 before and after the insertion point, and taken to be the inferior headline
8062 level of the two. So if the previous visible heading is level 3 and the
8063 next is level 4 (or vice versa), level 4 will be used for insertion.
8064 This makes sure that the subtree remains an independent subtree and does
8065 not swallow low level entries.
8067 You can also force a different level, either by using a numeric prefix
8068 argument, or by inserting the heading marker by hand. For example, if the
8069 cursor is after \"*****\", then the tree will be shifted to level 5.
8071 If optional TREE is given, use this text instead of the kill ring.
8073 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8074 move back over whitespace before inserting, and move point to the end of
8075 the inserted text when done."
8076 (interactive "P")
8077 (setq tree (or tree (and kill-ring (current-kill 0))))
8078 (unless (org-kill-is-subtree-p tree)
8079 (error "%s"
8080 (substitute-command-keys
8081 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8082 (org-with-limited-levels
8083 (let* ((visp (not (outline-invisible-p)))
8084 (txt tree)
8085 (^re_ "\\(\\*+\\)[ \t]*")
8086 (old-level (if (string-match org-outline-regexp-bol txt)
8087 (- (match-end 0) (match-beginning 0) 1)
8088 -1))
8089 (force-level (cond (level (prefix-numeric-value level))
8090 ((and (looking-at "[ \t]*$")
8091 (string-match
8092 "^\\*+$" (buffer-substring
8093 (point-at-bol) (point))))
8094 (- (match-end 1) (match-beginning 1)))
8095 ((and (bolp)
8096 (looking-at org-outline-regexp))
8097 (- (match-end 0) (point) 1))))
8098 (previous-level (save-excursion
8099 (condition-case nil
8100 (progn
8101 (outline-previous-visible-heading 1)
8102 (if (looking-at ^re_)
8103 (- (match-end 0) (match-beginning 0) 1)
8105 (error 1))))
8106 (next-level (save-excursion
8107 (condition-case nil
8108 (progn
8109 (or (looking-at org-outline-regexp)
8110 (outline-next-visible-heading 1))
8111 (if (looking-at ^re_)
8112 (- (match-end 0) (match-beginning 0) 1)
8114 (error 1))))
8115 (new-level (or force-level (max previous-level next-level)))
8116 (shift (if (or (= old-level -1)
8117 (= new-level -1)
8118 (= old-level new-level))
8120 (- new-level old-level)))
8121 (delta (if (> shift 0) -1 1))
8122 (func (if (> shift 0) 'org-demote 'org-promote))
8123 (org-odd-levels-only nil)
8124 beg end newend)
8125 ;; Remove the forced level indicator
8126 (if force-level
8127 (delete-region (point-at-bol) (point)))
8128 ;; Paste
8129 (beginning-of-line (if (bolp) 1 2))
8130 (setq beg (point))
8131 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8132 (insert-before-markers txt)
8133 (unless (string-match "\n\\'" txt) (insert "\n"))
8134 (setq newend (point))
8135 (org-reinstall-markers-in-region beg)
8136 (setq end (point))
8137 (goto-char beg)
8138 (skip-chars-forward " \t\n\r")
8139 (setq beg (point))
8140 (if (and (outline-invisible-p) visp)
8141 (save-excursion (outline-show-heading)))
8142 ;; Shift if necessary
8143 (unless (= shift 0)
8144 (save-restriction
8145 (narrow-to-region beg end)
8146 (while (not (= shift 0))
8147 (org-map-region func (point-min) (point-max))
8148 (setq shift (+ delta shift)))
8149 (goto-char (point-min))
8150 (setq newend (point-max))))
8151 (when (or (org-called-interactively-p 'interactive) for-yank)
8152 (message "Clipboard pasted as level %d subtree" new-level))
8153 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8154 kill-ring
8155 (eq org-subtree-clip (current-kill 0))
8156 org-subtree-clip-folded)
8157 ;; The tree was folded before it was killed/copied
8158 (hide-subtree))
8159 (and for-yank (goto-char newend)))))
8161 (defun org-kill-is-subtree-p (&optional txt)
8162 "Check if the current kill is an outline subtree, or a set of trees.
8163 Returns nil if kill does not start with a headline, or if the first
8164 headline level is not the largest headline level in the tree.
8165 So this will actually accept several entries of equal levels as well,
8166 which is OK for `org-paste-subtree'.
8167 If optional TXT is given, check this string instead of the current kill."
8168 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8169 (re (org-get-limited-outline-regexp))
8170 (^re (concat "^" re))
8171 (start-level (and kill
8172 (string-match
8173 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8174 kill)
8175 (- (match-end 2) (match-beginning 2) 1)))
8176 (start (1+ (or (match-beginning 2) -1))))
8177 (if (not start-level)
8178 (progn
8179 nil) ;; does not even start with a heading
8180 (catch 'exit
8181 (while (setq start (string-match ^re kill (1+ start)))
8182 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8183 (throw 'exit nil)))
8184 t))))
8186 (defvar org-markers-to-move nil
8187 "Markers that should be moved with a cut-and-paste operation.
8188 Those markers are stored together with their positions relative to
8189 the start of the region.")
8191 (defun org-save-markers-in-region (beg end)
8192 "Check markers in region.
8193 If these markers are between BEG and END, record their position relative
8194 to BEG, so that after moving the block of text, we can put the markers back
8195 into place.
8196 This function gets called just before an entry or tree gets cut from the
8197 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8198 called immediately, to move the markers with the entries."
8199 (setq org-markers-to-move nil)
8200 (when (featurep 'org-clock)
8201 (org-clock-save-markers-for-cut-and-paste beg end))
8202 (when (featurep 'org-agenda)
8203 (org-agenda-save-markers-for-cut-and-paste beg end)))
8205 (defun org-check-and-save-marker (marker beg end)
8206 "Check if MARKER is between BEG and END.
8207 If yes, remember the marker and the distance to BEG."
8208 (when (and (marker-buffer marker)
8209 (equal (marker-buffer marker) (current-buffer)))
8210 (if (and (>= marker beg) (< marker end))
8211 (push (cons marker (- marker beg)) org-markers-to-move))))
8213 (defun org-reinstall-markers-in-region (beg)
8214 "Move all remembered markers to their position relative to BEG."
8215 (mapc (lambda (x)
8216 (move-marker (car x) (+ beg (cdr x))))
8217 org-markers-to-move)
8218 (setq org-markers-to-move nil))
8220 (defun org-narrow-to-subtree ()
8221 "Narrow buffer to the current subtree."
8222 (interactive)
8223 (save-excursion
8224 (save-match-data
8225 (org-with-limited-levels
8226 (narrow-to-region
8227 (progn (org-back-to-heading t) (point))
8228 (progn (org-end-of-subtree t t)
8229 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8230 (point)))))))
8232 (defun org-narrow-to-block ()
8233 "Narrow buffer to the current block."
8234 (interactive)
8235 (let* ((case-fold-search t)
8236 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8237 "^[ \t]*#\\+end_.*")))
8238 (if blockp
8239 (narrow-to-region (car blockp) (cdr blockp))
8240 (error "Not in a block"))))
8242 (eval-when-compile
8243 (defvar org-property-drawer-re))
8245 (defvar org-property-start-re) ;; defined below
8246 (defun org-clone-subtree-with-time-shift (n &optional shift)
8247 "Clone the task (subtree) at point N times.
8248 The clones will be inserted as siblings.
8250 In interactive use, the user will be prompted for the number of
8251 clones to be produced, and for a time SHIFT, which may be a
8252 repeater as used in time stamps, for example `+3d'.
8254 When a valid repeater is given and the entry contains any time
8255 stamps, the clones will become a sequence in time, with time
8256 stamps in the subtree shifted for each clone produced. If SHIFT
8257 is nil or the empty string, time stamps will be left alone. The
8258 ID property of the original subtree is removed.
8260 If the original subtree did contain time stamps with a repeater,
8261 the following will happen:
8262 - the repeater will be removed in each clone
8263 - an additional clone will be produced, with the current, unshifted
8264 date(s) in the entry.
8265 - the original entry will be placed *after* all the clones, with
8266 repeater intact.
8267 - the start days in the repeater in the original entry will be shifted
8268 to past the last clone.
8269 In this way you can spell out a number of instances of a repeating task,
8270 and still retain the repeater to cover future instances of the task."
8271 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8272 (let (beg end template task idprop
8273 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8274 (drawer-re org-drawer-regexp))
8275 (if (not (and (integerp n) (> n 0)))
8276 (error "Invalid number of replications %s" n))
8277 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8278 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8279 shift)))
8280 (error "Invalid shift specification %s" shift))
8281 (when doshift
8282 (setq shift-n (string-to-number (match-string 1 shift))
8283 shift-what (cdr (assoc (match-string 2 shift)
8284 '(("d" . day) ("w" . week)
8285 ("m" . month) ("y" . year))))))
8286 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8287 (setq nmin 1 nmax n)
8288 (org-back-to-heading t)
8289 (setq beg (point))
8290 (setq idprop (org-entry-get nil "ID"))
8291 (org-end-of-subtree t t)
8292 (or (bolp) (insert "\n"))
8293 (setq end (point))
8294 (setq template (buffer-substring beg end))
8295 (when (and doshift
8296 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8297 (delete-region beg end)
8298 (setq end beg)
8299 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8300 (goto-char end)
8301 (loop for n from nmin to nmax do
8302 ;; prepare clone
8303 (with-temp-buffer
8304 (insert template)
8305 (org-mode)
8306 (goto-char (point-min))
8307 (org-show-subtree)
8308 (and idprop (if org-clone-delete-id
8309 (org-entry-delete nil "ID")
8310 (org-id-get-create t)))
8311 (unless (= n 0)
8312 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8313 (kill-whole-line))
8314 (goto-char (point-min))
8315 (while (re-search-forward drawer-re nil t)
8316 (mapc (lambda (d)
8317 (org-remove-empty-drawer-at d (point))) org-drawers)))
8318 (goto-char (point-min))
8319 (when doshift
8320 (while (re-search-forward org-ts-regexp-both nil t)
8321 (org-timestamp-change (* n shift-n) shift-what))
8322 (unless (= n n-no-remove)
8323 (goto-char (point-min))
8324 (while (re-search-forward org-ts-regexp nil t)
8325 (save-excursion
8326 (goto-char (match-beginning 0))
8327 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8328 (delete-region (match-beginning 1) (match-end 1)))))))
8329 (setq task (buffer-string)))
8330 (insert task))
8331 (goto-char beg)))
8333 ;;; Outline Sorting
8335 (defun org-sort (with-case)
8336 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8337 Optional argument WITH-CASE means sort case-sensitively."
8338 (interactive "P")
8339 (cond
8340 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8341 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8343 (org-call-with-arg 'org-sort-entries with-case))))
8345 (defun org-sort-remove-invisible (s)
8346 "Remove invisible links from string S."
8347 (remove-text-properties 0 (length s) org-rm-props s)
8348 (while (string-match org-bracket-link-regexp s)
8349 (setq s (replace-match (if (match-end 2)
8350 (match-string 3 s)
8351 (match-string 1 s)) t t s)))
8352 (let ((st (format " %s " s)))
8353 (while (string-match org-emph-re st)
8354 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8355 (setq s (substring st 1 -1)))
8358 (defvar org-priority-regexp) ; defined later in the file
8360 (defvar org-after-sorting-entries-or-items-hook nil
8361 "Hook that is run after a bunch of entries or items have been sorted.
8362 When children are sorted, the cursor is in the parent line when this
8363 hook gets called. When a region or a plain list is sorted, the cursor
8364 will be in the first entry of the sorted region/list.")
8366 (defun org-sort-entries
8367 (&optional with-case sorting-type getkey-func compare-func property)
8368 "Sort entries on a certain level of an outline tree.
8369 If there is an active region, the entries in the region are sorted.
8370 Else, if the cursor is before the first entry, sort the top-level items.
8371 Else, the children of the entry at point are sorted.
8373 Sorting can be alphabetically, numerically, by date/time as given by
8374 a time stamp, by a property, by priority order, or by a custom function.
8376 The command prompts for the sorting type unless it has been given to the
8377 function through the SORTING-TYPE argument, which needs to be a character,
8378 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8379 precise meaning of each character:
8381 n Numerically, by converting the beginning of the entry/item to a number.
8382 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8383 o By order of TODO keywords.
8384 t By date/time, either the first active time stamp in the entry, or, if
8385 none exist, by the first inactive one.
8386 s By the scheduled date/time.
8387 d By deadline date/time.
8388 c By creation time, which is assumed to be the first inactive time stamp
8389 at the beginning of a line.
8390 p By priority according to the cookie.
8391 r By the value of a property.
8393 Capital letters will reverse the sort order.
8395 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8396 called with point at the beginning of the record. It must return either
8397 a string or a number that should serve as the sorting key for that record.
8399 Comparing entries ignores case by default. However, with an optional argument
8400 WITH-CASE, the sorting considers case as well.
8402 Sorting is done against the visible part of the headlines, it ignores hidden
8403 links."
8404 (interactive "P")
8405 (let ((case-func (if with-case 'identity 'downcase))
8406 (cmstr
8407 ;; The clock marker is lost when using `sort-subr', let's
8408 ;; store the clocking string.
8409 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8410 (save-excursion
8411 (goto-char org-clock-marker)
8412 (looking-back "^.*") (match-string-no-properties 0))))
8413 start beg end stars re re2
8414 txt what tmp)
8415 ;; Find beginning and end of region to sort
8416 (cond
8417 ((org-region-active-p)
8418 ;; we will sort the region
8419 (setq end (region-end)
8420 what "region")
8421 (goto-char (region-beginning))
8422 (if (not (org-at-heading-p)) (outline-next-heading))
8423 (setq start (point)))
8424 ((or (org-at-heading-p)
8425 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8426 ;; we will sort the children of the current headline
8427 (org-back-to-heading)
8428 (setq start (point)
8429 end (progn (org-end-of-subtree t t)
8430 (or (bolp) (insert "\n"))
8431 (org-back-over-empty-lines)
8432 (point))
8433 what "children")
8434 (goto-char start)
8435 (show-subtree)
8436 (outline-next-heading))
8438 ;; we will sort the top-level entries in this file
8439 (goto-char (point-min))
8440 (or (org-at-heading-p) (outline-next-heading))
8441 (setq start (point))
8442 (goto-char (point-max))
8443 (beginning-of-line 1)
8444 (when (looking-at ".*?\\S-")
8445 ;; File ends in a non-white line
8446 (end-of-line 1)
8447 (insert "\n"))
8448 (setq end (point-max))
8449 (setq what "top-level")
8450 (goto-char start)
8451 (show-all)))
8453 (setq beg (point))
8454 (if (>= beg end) (error "Nothing to sort"))
8456 (looking-at "\\(\\*+\\)")
8457 (setq stars (match-string 1)
8458 re (concat "^" (regexp-quote stars) " +")
8459 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8460 txt (buffer-substring beg end))
8461 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8462 (if (and (not (equal stars "*")) (string-match re2 txt))
8463 (error "Region to sort contains a level above the first entry"))
8465 (unless sorting-type
8466 (message
8467 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8468 [t]ime [s]cheduled [d]eadline [c]reated
8469 A/N/P/R/O/F/T/S/D/C means reversed:"
8470 what)
8471 (setq sorting-type (read-char-exclusive))
8473 (unless getkey-func
8474 (and (= (downcase sorting-type) ?f)
8475 (setq getkey-func
8476 (org-icompleting-read "Sort using function: "
8477 obarray 'fboundp t nil nil))
8478 (setq getkey-func (intern getkey-func))))
8480 (and (= (downcase sorting-type) ?r)
8481 (not property)
8482 (setq property
8483 (org-icompleting-read "Property: "
8484 (mapcar 'list (org-buffer-property-keys t))
8485 nil t))))
8487 (message "Sorting entries...")
8489 (save-restriction
8490 (narrow-to-region start end)
8491 (let ((dcst (downcase sorting-type))
8492 (case-fold-search nil)
8493 (now (current-time)))
8494 (sort-subr
8495 (/= dcst sorting-type)
8496 ;; This function moves to the beginning character of the "record" to
8497 ;; be sorted.
8498 (lambda nil
8499 (if (re-search-forward re nil t)
8500 (goto-char (match-beginning 0))
8501 (goto-char (point-max))))
8502 ;; This function moves to the last character of the "record" being
8503 ;; sorted.
8504 (lambda nil
8505 (save-match-data
8506 (condition-case nil
8507 (outline-forward-same-level 1)
8508 (error
8509 (goto-char (point-max))))))
8510 ;; This function returns the value that gets sorted against.
8511 (lambda nil
8512 (cond
8513 ((= dcst ?n)
8514 (if (looking-at org-complex-heading-regexp)
8515 (string-to-number (org-sort-remove-invisible (match-string 4)))
8516 nil))
8517 ((= dcst ?a)
8518 (if (looking-at org-complex-heading-regexp)
8519 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8520 nil))
8521 ((= dcst ?t)
8522 (let ((end (save-excursion (outline-next-heading) (point))))
8523 (if (or (re-search-forward org-ts-regexp end t)
8524 (re-search-forward org-ts-regexp-both end t))
8525 (org-time-string-to-seconds (match-string 0))
8526 (org-float-time now))))
8527 ((= dcst ?c)
8528 (let ((end (save-excursion (outline-next-heading) (point))))
8529 (if (re-search-forward
8530 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8531 end t)
8532 (org-time-string-to-seconds (match-string 0))
8533 (org-float-time now))))
8534 ((= dcst ?s)
8535 (let ((end (save-excursion (outline-next-heading) (point))))
8536 (if (re-search-forward org-scheduled-time-regexp end t)
8537 (org-time-string-to-seconds (match-string 1))
8538 (org-float-time now))))
8539 ((= dcst ?d)
8540 (let ((end (save-excursion (outline-next-heading) (point))))
8541 (if (re-search-forward org-deadline-time-regexp end t)
8542 (org-time-string-to-seconds (match-string 1))
8543 (org-float-time now))))
8544 ((= dcst ?p)
8545 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8546 (string-to-char (match-string 2))
8547 org-default-priority))
8548 ((= dcst ?r)
8549 (or (org-entry-get nil property) ""))
8550 ((= dcst ?o)
8551 (if (looking-at org-complex-heading-regexp)
8552 (- 9999 (length (member (match-string 2)
8553 org-todo-keywords-1)))))
8554 ((= dcst ?f)
8555 (if getkey-func
8556 (progn
8557 (setq tmp (funcall getkey-func))
8558 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8559 tmp)
8560 (error "Invalid key function `%s'" getkey-func)))
8561 (t (error "Invalid sorting type `%c'" sorting-type))))
8563 (cond
8564 ((= dcst ?a) 'string<)
8565 ((= dcst ?f) compare-func)
8566 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8567 (run-hooks 'org-after-sorting-entries-or-items-hook)
8568 ;; Reset the clock marker if needed
8569 (when cmstr
8570 (save-excursion
8571 (goto-char start)
8572 (search-forward cmstr nil t)
8573 (move-marker org-clock-marker (point))))
8574 (message "Sorting entries...done")))
8576 (defun org-do-sort (table what &optional with-case sorting-type)
8577 "Sort TABLE of WHAT according to SORTING-TYPE.
8578 The user will be prompted for the SORTING-TYPE if the call to this
8579 function does not specify it. WHAT is only for the prompt, to indicate
8580 what is being sorted. The sorting key will be extracted from
8581 the car of the elements of the table.
8582 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8583 (unless sorting-type
8584 (message
8585 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8586 what)
8587 (setq sorting-type (read-char-exclusive)))
8588 (let ((dcst (downcase sorting-type))
8589 extractfun comparefun)
8590 ;; Define the appropriate functions
8591 (cond
8592 ((= dcst ?n)
8593 (setq extractfun 'string-to-number
8594 comparefun (if (= dcst sorting-type) '< '>)))
8595 ((= dcst ?a)
8596 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8597 (lambda(x) (downcase (org-sort-remove-invisible x))))
8598 comparefun (if (= dcst sorting-type)
8599 'string<
8600 (lambda (a b) (and (not (string< a b))
8601 (not (string= a b)))))))
8602 ((= dcst ?t)
8603 (setq extractfun
8604 (lambda (x)
8605 (if (or (string-match org-ts-regexp x)
8606 (string-match org-ts-regexp-both x))
8607 (org-float-time
8608 (org-time-string-to-time (match-string 0 x)))
8610 comparefun (if (= dcst sorting-type) '< '>)))
8611 (t (error "Invalid sorting type `%c'" sorting-type)))
8613 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8614 table)
8615 (lambda (a b) (funcall comparefun (car a) (car b))))))
8618 ;;; The orgstruct minor mode
8620 ;; Define a minor mode which can be used in other modes in order to
8621 ;; integrate the org-mode structure editing commands.
8623 ;; This is really a hack, because the org-mode structure commands use
8624 ;; keys which normally belong to the major mode. Here is how it
8625 ;; works: The minor mode defines all the keys necessary to operate the
8626 ;; structure commands, but wraps the commands into a function which
8627 ;; tests if the cursor is currently at a headline or a plain list
8628 ;; item. If that is the case, the structure command is used,
8629 ;; temporarily setting many Org-mode variables like regular
8630 ;; expressions for filling etc. However, when any of those keys is
8631 ;; used at a different location, function uses `key-binding' to look
8632 ;; up if the key has an associated command in another currently active
8633 ;; keymap (minor modes, major mode, global), and executes that
8634 ;; command. There might be problems if any of the keys is otherwise
8635 ;; used as a prefix key.
8637 (defcustom orgstruct-heading-prefix-regexp ""
8638 "Regexp that matches the custom prefix of Org headlines in
8639 orgstruct(++)-mode."
8640 :group 'org
8641 :version "24.4"
8642 :package-version '(Org . "8.0")
8643 :type 'string)
8644 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8646 (defcustom orgstruct-setup-hook nil
8647 "Hook run after orgstruct-mode-map is filled."
8648 :group 'org
8649 :type 'hook)
8651 (defvar orgstruct-initialized nil)
8653 (defvar org-local-vars nil
8654 "List of local variables, for use by `orgstruct-mode'.")
8656 ;;;###autoload
8657 (define-minor-mode orgstruct-mode
8658 "Toggle the minor mode `orgstruct-mode'.
8659 This mode is for using Org-mode structure commands in other
8660 modes. The following keys behave as if Org-mode were active, if
8661 the cursor is on a headline, or on a plain list item (both as
8662 defined by Org-mode)."
8663 nil " OrgStruct" (make-sparse-keymap)
8664 (when orgstruct-mode
8665 (org-load-modules-maybe)
8666 (unless orgstruct-initialized
8667 (orgstruct-setup)
8668 (setq orgstruct-initialized t))))
8670 ;;;###autoload
8671 (defun turn-on-orgstruct ()
8672 "Unconditionally turn on `orgstruct-mode'."
8673 (orgstruct-mode 1))
8675 (defvar org-fb-vars nil)
8676 (make-variable-buffer-local 'org-fb-vars)
8677 (defun orgstruct++-mode (&optional arg)
8678 "Toggle `orgstruct-mode', the enhanced version of it.
8679 In addition to setting orgstruct-mode, this also exports all
8680 indentation and autofilling variables from org-mode into the
8681 buffer. It will also recognize item context in multiline items."
8682 (interactive "P")
8683 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8684 (if (< arg 1)
8685 (progn (orgstruct-mode -1)
8686 (mapc (lambda(v)
8687 (org-set-local (car v)
8688 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8689 org-fb-vars))
8690 (orgstruct-mode 1)
8691 (setq org-fb-vars nil)
8692 (let (var val)
8693 (mapc
8694 (lambda (x)
8695 (when (string-match
8696 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8697 (symbol-name (car x)))
8698 (setq var (car x) val (nth 1 x))
8699 (push (list var `(quote ,(eval var))) org-fb-vars)
8700 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8701 org-local-vars)
8702 (org-set-local 'orgstruct-is-++ t))))
8704 (defvar orgstruct-is-++ nil
8705 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8706 (make-variable-buffer-local 'orgstruct-is-++)
8708 ;;;###autoload
8709 (defun turn-on-orgstruct++ ()
8710 "Unconditionally turn on `orgstruct++-mode'."
8711 (orgstruct++-mode 1))
8713 (defun orgstruct-error ()
8714 "Error when there is no default binding for a structure key."
8715 (interactive)
8716 (error "This key has no function outside structure elements"))
8718 (defun orgstruct-setup ()
8719 "Setup orgstruct keymap."
8720 (dolist (f
8721 '("org-meta"
8722 "org-shift"
8723 "org-shiftmeta"
8724 org-shifttab
8725 org-backward-element
8726 org-backward-heading-same-level
8727 org-ctrl-c-ret
8728 org-cycle
8729 org-forward-heading-same-level
8730 org-insert-heading
8731 org-insert-heading-respect-content
8732 org-kill-note-or-show-branches
8733 org-mark-subtree
8734 org-narrow-to-subtree
8735 org-promote-subtree
8736 org-reveal
8737 org-show-subtree
8738 org-sort
8739 org-up-element
8740 outline-demote
8741 outline-next-visible-heading
8742 outline-previous-visible-heading
8743 outline-promote
8744 outline-up-heading
8745 show-children))
8746 (dolist (f (if (stringp f)
8747 (let ((flist))
8748 (dolist (postfix
8749 '("-return" "tab" "left" "right" "up" "down")
8750 flist)
8751 (let ((f (intern (concat f postfix))))
8752 (when (fboundp f)
8753 (push f flist)))))
8754 (list f)))
8755 (dolist (binding (nconc (where-is-internal f org-mode-map)
8756 (where-is-internal f outline-mode-map)))
8757 ;; TODO use local-function-key-map
8758 (dolist (rep '(("<tab>" . "TAB")
8759 ("<return>" . "RET")
8760 ("<escape>" . "ESC")
8761 ("<delete>" . "DEL")))
8762 (setq binding (read-kbd-macro (replace-regexp-in-string
8763 (regexp-quote (car rep))
8764 (cdr rep)
8765 (key-description binding)))))
8766 (let ((key (lookup-key orgstruct-mode-map binding)))
8767 (when (or (not key) (numberp key))
8768 (condition-case nil
8769 (org-defkey orgstruct-mode-map
8770 binding
8771 (orgstruct-make-binding f binding))
8772 (error nil)))))))
8773 (run-hooks 'orgstruct-setup-hook))
8775 (defun orgstruct-make-binding (fun key)
8776 "Create a function for binding in the structure minor mode.
8777 FUN is the command to call inside a table. KEY is the key that
8778 should be checked in for a command to execute outside of tables."
8779 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8780 (let ((nname name)
8781 (i 0))
8782 (while (fboundp (intern nname))
8783 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8784 (setq name (intern nname)))
8785 (eval
8786 (let ((bindings '((org-heading-regexp
8787 (concat "^"
8788 orgstruct-heading-prefix-regexp
8789 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8790 (org-outline-regexp
8791 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8792 (org-outline-regexp-bol
8793 (concat "^" org-outline-regexp))
8794 (outline-regexp org-outline-regexp)
8795 (outline-heading-end-regexp "\n")
8796 (outline-level 'outline-level)
8797 (outline-heading-alist))))
8798 `(defun ,name (arg)
8799 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8800 "Outside of structure, run the binding of `"
8801 (key-description key) "'.")
8802 (interactive "p")
8803 (unless
8804 (let* ,bindings
8805 (when (org-context-p 'headline 'item
8806 ,(when (memq fun '(org-insert-heading))
8807 '(when orgstruct-is-++
8808 'item-body)))
8809 (org-run-like-in-org-mode
8810 (lambda ()
8811 (interactive)
8812 (let* ,bindings
8813 (call-interactively ',fun))))
8815 (let* ((orgstruct-mode)
8816 (binding (key-binding ,key)))
8817 (if (keymapp binding)
8818 (set-temporary-overlay-map binding)
8819 (call-interactively
8820 (or binding 'orgstruct-error))))))))
8821 name))
8823 (defun org-contextualize-keys (alist contexts)
8824 "Return valid elements in ALIST depending on CONTEXTS.
8826 `org-agenda-custom-commands' or `org-capture-templates' are the
8827 values used for ALIST, and `org-agenda-custom-commands-contexts'
8828 or `org-capture-templates-contexts' are the associated contexts
8829 definitions."
8830 (let ((contexts
8831 ;; normalize contexts
8832 (mapcar
8833 (lambda(c) (cond ((listp (cadr c))
8834 (list (car c) (car c) (cadr c)))
8835 ((string= "" (cadr c))
8836 (list (car c) (car c) (caddr c)))
8837 (t c))) contexts))
8838 (a alist) c r s)
8839 ;; loop over all commands or templates
8840 (while (setq c (pop a))
8841 (let (vrules repl)
8842 (cond
8843 ((not (assoc (car c) contexts))
8844 (push c r))
8845 ((and (assoc (car c) contexts)
8846 (setq vrules (org-contextualize-validate-key
8847 (car c) contexts)))
8848 (mapc (lambda (vr)
8849 (when (not (equal (car vr) (cadr vr)))
8850 (setq repl vr))) vrules)
8851 (if (not repl) (push c r)
8852 (push (cadr repl) s)
8853 (push
8854 (cons (car c)
8855 (cdr (or (assoc (cadr repl) alist)
8856 (error "Undefined key `%s' as contextual replacement for `%s'"
8857 (cadr repl) (car c)))))
8858 r))))))
8859 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8860 (delq
8862 (delete-dups
8863 (mapcar (lambda (x)
8864 (let ((tpl (car x)))
8865 (when (not (delq
8867 (mapcar (lambda(y)
8868 (equal y tpl)) s))) x)))
8869 (reverse r))))))
8871 (defun org-contextualize-validate-key (key contexts)
8872 "Check CONTEXTS for agenda or capture KEY."
8873 (let (r rr res)
8874 (while (setq r (pop contexts))
8875 (mapc
8876 (lambda (rr)
8877 (when
8878 (and (equal key (car r))
8879 (if (functionp rr) (funcall rr)
8880 (or (and (eq (car rr) 'in-file)
8881 (buffer-file-name)
8882 (string-match (cdr rr) (buffer-file-name)))
8883 (and (eq (car rr) 'in-mode)
8884 (string-match (cdr rr) (symbol-name major-mode)))
8885 (and (eq (car rr) 'in-buffer)
8886 (string-match (cdr rr) (buffer-name)))
8887 (when (and (eq (car rr) 'not-in-file)
8888 (buffer-file-name))
8889 (not (string-match (cdr rr) (buffer-file-name))))
8890 (when (eq (car rr) 'not-in-mode)
8891 (not (string-match (cdr rr) (symbol-name major-mode))))
8892 (when (eq (car rr) 'not-in-buffer)
8893 (not (string-match (cdr rr) (buffer-name)))))))
8894 (push r res)))
8895 (car (last r))))
8896 (delete-dups (delq nil res))))
8898 (defun org-context-p (&rest contexts)
8899 "Check if local context is any of CONTEXTS.
8900 Possible values in the list of contexts are `table', `headline', and `item'."
8901 (let ((pos (point)))
8902 (goto-char (point-at-bol))
8903 (prog1 (or (and (memq 'table contexts)
8904 (looking-at "[ \t]*|"))
8905 (and (memq 'headline contexts)
8906 (looking-at org-outline-regexp))
8907 (and (memq 'item contexts)
8908 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8909 (and (memq 'item-body contexts)
8910 (org-in-item-p)))
8911 (goto-char pos))))
8913 (defun org-get-local-variables ()
8914 "Return a list of all local variables in an Org mode buffer."
8915 (let (varlist)
8916 (with-current-buffer (get-buffer-create "*Org tmp*")
8917 (erase-buffer)
8918 (org-mode)
8919 (setq varlist (buffer-local-variables)))
8920 (kill-buffer "*Org tmp*")
8921 (delq nil
8922 (mapcar
8923 (lambda (x)
8924 (setq x
8925 (if (symbolp x)
8926 (list x)
8927 (list (car x) (cdr x))))
8928 (if (and (not (get (car x) 'org-state))
8929 (string-match
8930 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8931 (symbol-name (car x))))
8932 x nil))
8933 varlist))))
8935 (defun org-clone-local-variables (from-buffer &optional regexp)
8936 "Clone local variables from FROM-BUFFER.
8937 Optional argument REGEXP selects variables to clone."
8938 (mapc
8939 (lambda (pair)
8940 (and (symbolp (car pair))
8941 (or (null regexp)
8942 (string-match regexp (symbol-name (car pair))))
8943 (set (make-local-variable (car pair))
8944 (cdr pair))))
8945 (buffer-local-variables from-buffer)))
8947 ;;;###autoload
8948 (defun org-run-like-in-org-mode (cmd)
8949 "Run a command, pretending that the current buffer is in Org-mode.
8950 This will temporarily bind local variables that are typically bound in
8951 Org-mode to the values they have in Org-mode, and then interactively
8952 call CMD."
8953 (org-load-modules-maybe)
8954 (unless org-local-vars
8955 (setq org-local-vars (org-get-local-variables)))
8956 (let (binds)
8957 (dolist (var org-local-vars)
8958 (when (or (not (boundp (car var)))
8959 (eq (symbol-value (car var))
8960 (default-value (car var))))
8961 (push (list (car var) `(quote ,(cadr var))) binds)))
8962 (eval `(let ,binds
8963 (call-interactively (quote ,cmd))))))
8965 ;;;; Archiving
8967 (defun org-get-category (&optional pos force-refresh)
8968 "Get the category applying to position POS."
8969 (save-match-data
8970 (if force-refresh (org-refresh-category-properties))
8971 (let ((pos (or pos (point))))
8972 (or (get-text-property pos 'org-category)
8973 (progn (org-refresh-category-properties)
8974 (get-text-property pos 'org-category))))))
8976 (defun org-refresh-category-properties ()
8977 "Refresh category text properties in the buffer."
8978 (let ((case-fold-search t)
8979 (inhibit-read-only t)
8980 (def-cat (cond
8981 ((null org-category)
8982 (if buffer-file-name
8983 (file-name-sans-extension
8984 (file-name-nondirectory buffer-file-name))
8985 "???"))
8986 ((symbolp org-category) (symbol-name org-category))
8987 (t org-category)))
8988 beg end cat pos optionp)
8989 (org-with-silent-modifications
8990 (save-excursion
8991 (save-restriction
8992 (widen)
8993 (goto-char (point-min))
8994 (put-text-property (point) (point-max) 'org-category def-cat)
8995 (while (re-search-forward
8996 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8997 (setq pos (match-end 0)
8998 optionp (equal (char-after (match-beginning 0)) ?#)
8999 cat (org-trim (match-string 2)))
9000 (if optionp
9001 (setq beg (point-at-bol) end (point-max))
9002 (org-back-to-heading t)
9003 (setq beg (point) end (org-end-of-subtree t t)))
9004 (put-text-property beg end 'org-category cat)
9005 (put-text-property beg end 'org-category-position beg)
9006 (goto-char pos)))))))
9008 (defun org-refresh-properties (dprop tprop)
9009 "Refresh buffer text properties.
9010 DPROP is the drawer property and TPROP is the corresponding text
9011 property to set."
9012 (let ((case-fold-search t)
9013 (inhibit-read-only t) p)
9014 (org-with-silent-modifications
9015 (save-excursion
9016 (save-restriction
9017 (widen)
9018 (goto-char (point-min))
9019 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9020 (setq p (org-match-string-no-properties 1))
9021 (save-excursion
9022 (org-back-to-heading t)
9023 (put-text-property
9024 (point-at-bol) (point-at-eol) tprop p))))))))
9027 ;;;; Link Stuff
9029 ;;; Link abbreviations
9031 (defun org-link-expand-abbrev (link)
9032 "Apply replacements as defined in `org-link-abbrev-alist'."
9033 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9034 (let* ((key (match-string 1 link))
9035 (as (or (assoc key org-link-abbrev-alist-local)
9036 (assoc key org-link-abbrev-alist)))
9037 (tag (and (match-end 2) (match-string 3 link)))
9038 rpl)
9039 (if (not as)
9040 link
9041 (setq rpl (cdr as))
9042 (cond
9043 ((symbolp rpl) (funcall rpl tag))
9044 ((string-match "%(\\([^)]+\\))" rpl)
9045 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9046 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9047 ((string-match "%h" rpl)
9048 (replace-match (url-hexify-string (or tag "")) t t rpl))
9049 (t (concat rpl tag)))))
9050 link))
9052 ;;; Storing and inserting links
9054 (defvar org-insert-link-history nil
9055 "Minibuffer history for links inserted with `org-insert-link'.")
9057 (defvar org-stored-links nil
9058 "Contains the links stored with `org-store-link'.")
9060 (defvar org-store-link-plist nil
9061 "Plist with info about the most recently link created with `org-store-link'.")
9063 (defvar org-link-protocols nil
9064 "Link protocols added to Org-mode using `org-add-link-type'.")
9066 (defvar org-store-link-functions nil
9067 "List of functions that are called to create and store a link.
9068 Each function will be called in turn until one returns a non-nil
9069 value. Each function should check if it is responsible for creating
9070 this link (for example by looking at the major mode).
9071 If not, it must exit and return nil.
9072 If yes, it should return a non-nil value after a calling
9073 `org-store-link-props' with a list of properties and values.
9074 Special properties are:
9076 :type The link prefix, like \"http\". This must be given.
9077 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9078 This is obligatory as well.
9079 :description Optional default description for the second pair
9080 of brackets in an Org-mode link. The user can still change
9081 this when inserting this link into an Org-mode buffer.
9083 In addition to these, any additional properties can be specified
9084 and then used in capture templates.")
9086 (defun org-add-link-type (type &optional follow export)
9087 "Add TYPE to the list of `org-link-types'.
9088 Re-compute all regular expressions depending on `org-link-types'
9090 FOLLOW and EXPORT are two functions.
9092 FOLLOW should take the link path as the single argument and do whatever
9093 is necessary to follow the link, for example find a file or display
9094 a mail message.
9096 EXPORT should format the link path for export to one of the export formats.
9097 It should be a function accepting three arguments:
9099 path the path of the link, the text after the prefix (like \"http:\")
9100 desc the description of the link, if any, or a description added by
9101 org-export-normalize-links if there is none
9102 format the export format, a symbol like `html' or `latex' or `ascii'..
9104 The function may use the FORMAT information to return different values
9105 depending on the format. The return value will be put literally into
9106 the exported file. If the return value is nil, this means Org should
9107 do what it normally does with links which do not have EXPORT defined.
9109 Org-mode has a built-in default for exporting links. If you are happy with
9110 this default, there is no need to define an export function for the link
9111 type. For a simple example of an export function, see `org-bbdb.el'."
9112 (add-to-list 'org-link-types type t)
9113 (org-make-link-regexps)
9114 (if (assoc type org-link-protocols)
9115 (setcdr (assoc type org-link-protocols) (list follow export))
9116 (push (list type follow export) org-link-protocols)))
9118 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9119 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9121 ;;;###autoload
9122 (defun org-store-link (arg)
9123 "\\<org-mode-map>Store an org-link to the current location.
9124 This link is added to `org-stored-links' and can later be inserted
9125 into an org-buffer with \\[org-insert-link].
9127 For some link types, a prefix arg is interpreted.
9128 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9129 For file links, arg negates `org-context-in-file-links'.
9131 A double prefix arg force skipping storing functions that are not
9132 part of Org's core."
9133 (interactive "P")
9134 (org-load-modules-maybe)
9135 (setq org-store-link-plist nil) ; reset
9136 (org-with-limited-levels
9137 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9138 (cond
9139 ((and (not (equal arg '(16)))
9140 (setq sfuns
9141 (delq
9142 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9143 org-store-link-functions))
9144 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9145 (or (and (cdr sfuns)
9146 (funcall (intern
9147 (completing-read "Which function for creating the link? "
9148 sfunsn t (car sfunsn)))))
9149 (funcall (caar sfuns)))
9150 (setq link (plist-get org-store-link-plist :link)
9151 desc (or (plist-get org-store-link-plist :description) link))))
9152 ((org-src-edit-buffer-p)
9153 (let (label gc)
9154 (while (or (not label)
9155 (save-excursion
9156 (save-restriction
9157 (widen)
9158 (goto-char (point-min))
9159 (re-search-forward
9160 (regexp-quote (format org-coderef-label-format label))
9161 nil t))))
9162 (when label (message "Label exists already") (sit-for 2))
9163 (setq label (read-string "Code line label: " label)))
9164 (end-of-line 1)
9165 (setq link (format org-coderef-label-format label))
9166 (setq gc (- 79 (length link)))
9167 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9168 (insert link)
9169 (setq link (concat "(" label ")") desc nil)))
9171 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9172 ;; We are in the agenda, link to referenced location
9173 (let ((m (or (get-text-property (point) 'org-hd-marker)
9174 (get-text-property (point) 'org-marker))))
9175 (when m
9176 (org-with-point-at m
9177 (setq agenda-link
9178 (if (org-called-interactively-p 'any)
9179 (call-interactively 'org-store-link)
9180 (org-store-link nil)))))))
9182 ((eq major-mode 'calendar-mode)
9183 (let ((cd (calendar-cursor-to-date)))
9184 (setq link
9185 (format-time-string
9186 (car org-time-stamp-formats)
9187 (apply 'encode-time
9188 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9189 nil nil nil))))
9190 (org-store-link-props :type "calendar" :date cd)))
9192 ((eq major-mode 'help-mode)
9193 (setq link (concat "help:" (save-excursion
9194 (goto-char (point-min))
9195 (looking-at "^[^ ]+")
9196 (match-string 0))))
9197 (org-store-link-props :type "help"))
9199 ((eq major-mode 'w3-mode)
9200 (setq cpltxt (if (and (buffer-name)
9201 (not (string-match "Untitled" (buffer-name))))
9202 (buffer-name)
9203 (url-view-url t))
9204 link (url-view-url t))
9205 (org-store-link-props :type "w3" :url (url-view-url t)))
9207 ((setq search (run-hook-with-args-until-success
9208 'org-create-file-search-functions))
9209 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9210 "::" search))
9211 (setq cpltxt (or description link)))
9213 ((eq major-mode 'image-mode)
9214 (setq cpltxt (concat "file:"
9215 (abbreviate-file-name buffer-file-name))
9216 link cpltxt)
9217 (org-store-link-props :type "image" :file buffer-file-name))
9219 ((eq major-mode 'dired-mode)
9220 ;; link to the file in the current line
9221 (let ((file (dired-get-filename nil t)))
9222 (setq file (if file
9223 (abbreviate-file-name
9224 (expand-file-name (dired-get-filename nil t)))
9225 ;; otherwise, no file so use current directory.
9226 default-directory))
9227 (setq cpltxt (concat "file:" file)
9228 link cpltxt)))
9230 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9231 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9232 (cond
9233 ((org-in-regexp "<<\\(.*?\\)>>")
9234 (setq cpltxt
9235 (concat "file:"
9236 (abbreviate-file-name
9237 (buffer-file-name (buffer-base-buffer)))
9238 "::" (match-string 1))
9239 link cpltxt))
9240 ((and (featurep 'org-id)
9241 (or (eq org-id-link-to-org-use-id t)
9242 (and (org-called-interactively-p 'any)
9243 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9244 (and (eq org-id-link-to-org-use-id
9245 'create-if-interactive-and-no-custom-id)
9246 (not custom-id))))
9247 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9248 ;; We can make a link using the ID.
9249 (setq link (condition-case nil
9250 (prog1 (org-id-store-link)
9251 (setq desc (plist-get org-store-link-plist :description)))
9252 (error
9253 ;; probably before first headline, link to file only
9254 (concat "file:"
9255 (abbreviate-file-name
9256 (buffer-file-name (buffer-base-buffer))))))))
9258 ;; Just link to current headline
9259 (setq cpltxt (concat "file:"
9260 (abbreviate-file-name
9261 (buffer-file-name (buffer-base-buffer)))))
9262 ;; Add a context search string
9263 (when (org-xor org-context-in-file-links arg)
9264 (let* ((ee (org-element-at-point))
9265 (et (org-element-type ee))
9266 (ev (plist-get (cadr ee) :value)))
9267 (setq txt (cond
9268 ((org-at-heading-p) nil)
9269 ((eq et 'keyword) ev)
9270 ((org-region-active-p)
9271 (buffer-substring (region-beginning) (region-end)))))
9272 (when (or (null txt) (string-match "\\S-" txt))
9273 (setq cpltxt
9274 (concat cpltxt "::"
9275 (condition-case nil
9276 (org-make-org-heading-search-string txt)
9277 (error "")))
9278 desc (or (and (eq et 'keyword) ev)
9279 (nth 4 (ignore-errors (org-heading-components)))
9280 "NONE")))))
9281 (if (string-match "::\\'" cpltxt)
9282 (setq cpltxt (substring cpltxt 0 -2)))
9283 (setq link cpltxt))))
9285 ((buffer-file-name (buffer-base-buffer))
9286 ;; Just link to this file here.
9287 (setq cpltxt (concat "file:"
9288 (abbreviate-file-name
9289 (buffer-file-name (buffer-base-buffer)))))
9290 ;; Add a context string
9291 (when (org-xor org-context-in-file-links arg)
9292 (setq txt (if (org-region-active-p)
9293 (buffer-substring (region-beginning) (region-end))
9294 (buffer-substring (point-at-bol) (point-at-eol))))
9295 ;; Only use search option if there is some text.
9296 (when (string-match "\\S-" txt)
9297 (setq cpltxt
9298 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9299 desc "NONE")))
9300 (setq link cpltxt))
9302 ((org-called-interactively-p 'interactive)
9303 (user-error "No method for storing a link from this buffer"))
9305 (t (setq link nil)))
9307 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9308 (setq link (or link cpltxt)
9309 desc (or desc cpltxt))
9310 (cond ((equal desc "NONE") (setq desc nil))
9311 ((string-match org-bracket-link-regexp desc)
9312 (setq desc (replace-regexp-in-string
9313 org-bracket-link-regexp
9314 (concat "\\3" (if (equal (length (match-string 0 desc))
9315 (length desc)) "*" "")) desc))))
9317 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9318 (progn
9319 (setq org-stored-links
9320 (cons (list link desc) org-stored-links))
9321 (message "Stored: %s" (or desc link))
9322 (when custom-id
9323 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9324 "::#" custom-id))
9325 (setq org-stored-links
9326 (cons (list link desc) org-stored-links))))
9327 (or agenda-link (and link (org-make-link-string link desc)))))))
9329 (defun org-store-link-props (&rest plist)
9330 "Store link properties, extract names and addresses."
9331 (let (x adr)
9332 (when (setq x (plist-get plist :from))
9333 (setq adr (mail-extract-address-components x))
9334 (setq plist (plist-put plist :fromname (car adr)))
9335 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9336 (when (setq x (plist-get plist :to))
9337 (setq adr (mail-extract-address-components x))
9338 (setq plist (plist-put plist :toname (car adr)))
9339 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9340 (let ((from (plist-get plist :from))
9341 (to (plist-get plist :to)))
9342 (when (and from to org-from-is-user-regexp)
9343 (setq plist
9344 (plist-put plist :fromto
9345 (if (string-match org-from-is-user-regexp from)
9346 (concat "to %t")
9347 (concat "from %f"))))))
9348 (setq org-store-link-plist plist))
9350 (defun org-add-link-props (&rest plist)
9351 "Add these properties to the link property list."
9352 (let (key value)
9353 (while plist
9354 (setq key (pop plist) value (pop plist))
9355 (setq org-store-link-plist
9356 (plist-put org-store-link-plist key value)))))
9358 (defun org-email-link-description (&optional fmt)
9359 "Return the description part of an email link.
9360 This takes information from `org-store-link-plist' and formats it
9361 according to FMT (default from `org-email-link-description-format')."
9362 (setq fmt (or fmt org-email-link-description-format))
9363 (let* ((p org-store-link-plist)
9364 (to (plist-get p :toaddress))
9365 (from (plist-get p :fromaddress))
9366 (table
9367 (list
9368 (cons "%c" (plist-get p :fromto))
9369 (cons "%F" (plist-get p :from))
9370 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9371 (cons "%T" (plist-get p :to))
9372 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9373 (cons "%s" (plist-get p :subject))
9374 (cons "%d" (plist-get p :date))
9375 (cons "%m" (plist-get p :message-id)))))
9376 (when (string-match "%c" fmt)
9377 ;; Check if the user wrote this message
9378 (if (and org-from-is-user-regexp from to
9379 (save-match-data (string-match org-from-is-user-regexp from)))
9380 (setq fmt (replace-match "to %t" t t fmt))
9381 (setq fmt (replace-match "from %f" t t fmt))))
9382 (org-replace-escapes fmt table)))
9384 (defun org-make-org-heading-search-string (&optional string)
9385 "Make search string for the current headline or STRING."
9386 (let ((s (or string
9387 (and (derived-mode-p 'org-mode)
9388 (save-excursion
9389 (org-back-to-heading t)
9390 (org-element-property :raw-value (org-element-at-point))))))
9391 (lines org-context-in-file-links))
9392 (or string (setq s (concat "*" s))) ; Add * for headlines
9393 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9394 (when (and string (integerp lines) (> lines 0))
9395 (let ((slines (org-split-string s "\n")))
9396 (when (< lines (length slines))
9397 (setq s (mapconcat
9398 'identity
9399 (reverse (nthcdr (- (length slines) lines)
9400 (reverse slines))) "\n")))))
9401 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9403 (defun org-make-link-string (link &optional description)
9404 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9405 (unless (string-match "\\S-" link)
9406 (error "Empty link"))
9407 (when (and description
9408 (stringp description)
9409 (not (string-match "\\S-" description)))
9410 (setq description nil))
9411 (when (stringp description)
9412 ;; Remove brackets from the description, they are fatal.
9413 (while (string-match "\\[" description)
9414 (setq description (replace-match "{" t t description)))
9415 (while (string-match "\\]" description)
9416 (setq description (replace-match "}" t t description))))
9417 (when (equal link description)
9418 ;; No description needed, it is identical
9419 (setq description nil))
9420 (when (and (not description)
9421 (not (string-match (org-image-file-name-regexp) link))
9422 (not (equal link (org-link-escape link))))
9423 (setq description (org-extract-attributes link)))
9424 (setq link
9425 (cond ((string-match (org-image-file-name-regexp) link) link)
9426 ((string-match org-link-types-re link)
9427 (concat (match-string 1 link)
9428 (org-link-escape (substring link (match-end 1)))))
9429 (t (org-link-escape link))))
9430 (concat "[[" link "]"
9431 (if description (concat "[" description "]") "")
9432 "]"))
9434 (defconst org-link-escape-chars
9435 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9436 "List of characters that should be escaped in link.
9437 This is the list that is used for internal purposes.")
9439 (defconst org-link-escape-chars-browser
9440 '(?\ )
9441 "List of escapes for characters that are problematic in links.
9442 This is the list that is used before handing over to the browser.")
9444 (defun org-link-escape (text &optional table merge)
9445 "Return percent escaped representation of TEXT.
9446 TEXT is a string with the text to escape.
9447 Optional argument TABLE is a list with characters that should be
9448 escaped. When nil, `org-link-escape-chars' is used.
9449 If optional argument MERGE is set, merge TABLE into
9450 `org-link-escape-chars'."
9451 (cond
9452 ((and table merge)
9453 (mapc (lambda (defchr)
9454 (unless (member defchr table)
9455 (setq table (cons defchr table)))) org-link-escape-chars))
9456 ((null table)
9457 (setq table org-link-escape-chars)))
9458 (mapconcat
9459 (lambda (char)
9460 (if (or (member char table)
9461 (and (or (< char 32) (= char 37) (> char 126))
9462 org-url-hexify-p))
9463 (mapconcat (lambda (sequence-element)
9464 (format "%%%.2X" sequence-element))
9465 (or (encode-coding-char char 'utf-8)
9466 (error "Unable to percent escape character: %s"
9467 (char-to-string char))) "")
9468 (char-to-string char))) text ""))
9470 (defun org-link-unescape (str)
9471 "Unhex hexified Unicode strings as returned from the JavaScript function
9472 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9473 (unless (and (null str) (string= "" str))
9474 (let ((pos 0) (case-fold-search t) unhexed)
9475 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9476 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9477 (setq str (replace-match unhexed t t str))
9478 (setq pos (+ pos (length unhexed))))))
9479 str)
9481 (defun org-link-unescape-compound (hex)
9482 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9483 Note: this function also decodes single byte encodings like
9484 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9485 (save-match-data
9486 (let* ((bytes (cdr (split-string hex "%")))
9487 (ret "")
9488 (eat 0)
9489 (sum 0))
9490 (while bytes
9491 (let* ((val (string-to-number (pop bytes) 16))
9492 (shift-xor
9493 (if (= 0 eat)
9494 (cond
9495 ((>= val 252) (cons 6 252))
9496 ((>= val 248) (cons 5 248))
9497 ((>= val 240) (cons 4 240))
9498 ((>= val 224) (cons 3 224))
9499 ((>= val 192) (cons 2 192))
9500 (t (cons 0 0)))
9501 (cons 6 128))))
9502 (if (>= val 192) (setq eat (car shift-xor)))
9503 (setq val (logxor val (cdr shift-xor)))
9504 (setq sum (+ (lsh sum (car shift-xor)) val))
9505 (if (> eat 0) (setq eat (- eat 1)))
9506 (cond
9507 ((= 0 eat) ;multi byte
9508 (setq ret (concat ret (org-char-to-string sum)))
9509 (setq sum 0))
9510 ((not bytes) ; single byte(s)
9511 (setq ret (org-link-unescape-single-byte-sequence hex))))
9512 )) ;; end (while bytes
9513 ret )))
9515 (defun org-link-unescape-single-byte-sequence (hex)
9516 "Unhexify hex-encoded single byte character sequences."
9517 (mapconcat (lambda (byte)
9518 (char-to-string (string-to-number byte 16)))
9519 (cdr (split-string hex "%")) ""))
9521 (defun org-xor (a b)
9522 "Exclusive or."
9523 (if a (not b) b))
9525 (defun org-fixup-message-id-for-http (s)
9526 "Replace special characters in a message id, so it can be used in an http query."
9527 (when (string-match "%" s)
9528 (setq s (mapconcat (lambda (c)
9529 (if (eq c ?%)
9530 "%25"
9531 (char-to-string c)))
9532 s "")))
9533 (while (string-match "<" s)
9534 (setq s (replace-match "%3C" t t s)))
9535 (while (string-match ">" s)
9536 (setq s (replace-match "%3E" t t s)))
9537 (while (string-match "@" s)
9538 (setq s (replace-match "%40" t t s)))
9541 (defun org-link-prettify (link)
9542 "Return a human-readable representation of LINK.
9543 The car of LINK must be a raw link the cdr of LINK must be either
9544 a link description or nil."
9545 (let ((desc (or (cadr link) "<no description>")))
9546 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9547 "<" (car link) ">")))
9549 ;;;###autoload
9550 (defun org-insert-link-global ()
9551 "Insert a link like Org-mode does.
9552 This command can be called in any mode to insert a link in Org-mode syntax."
9553 (interactive)
9554 (org-load-modules-maybe)
9555 (org-run-like-in-org-mode 'org-insert-link))
9557 (defun org-insert-all-links (&optional keep)
9558 "Insert all links in `org-stored-links'."
9559 (interactive "P")
9560 (let ((links (copy-sequence org-stored-links)) l)
9561 (while (setq l (if keep (pop links) (pop org-stored-links)))
9562 (insert "- ")
9563 (org-insert-link nil (car l) (cadr l))
9564 (insert "\n"))))
9566 (defun org-link-fontify-links-to-this-file ()
9567 "Fontify links to the current file in `org-stored-links'."
9568 (let ((f (buffer-file-name)) a b)
9569 (setq a (mapcar (lambda(l)
9570 (let ((ll (car l)))
9571 (when (and (string-match "^file:\\(.+\\)::" ll)
9572 (equal f (expand-file-name (match-string 1 ll))))
9573 ll)))
9574 org-stored-links))
9575 (when (featurep 'org-id)
9576 (setq b (mapcar (lambda(l)
9577 (let ((ll (car l)))
9578 (when (and (string-match "^id:\\(.+\\)$" ll)
9579 (equal f (expand-file-name
9580 (or (org-id-find-id-file
9581 (match-string 1 ll)) ""))))
9582 ll)))
9583 org-stored-links)))
9584 (mapcar (lambda(l)
9585 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9586 (delq nil (append a b)))))
9588 (defvar org-link-links-in-this-file nil)
9589 (defun org-insert-link (&optional complete-file link-location default-description)
9590 "Insert a link. At the prompt, enter the link.
9592 Completion can be used to insert any of the link protocol prefixes like
9593 http or ftp in use.
9595 The history can be used to select a link previously stored with
9596 `org-store-link'. When the empty string is entered (i.e. if you just
9597 press RET at the prompt), the link defaults to the most recently
9598 stored link. As SPC triggers completion in the minibuffer, you need to
9599 use M-SPC or C-q SPC to force the insertion of a space character.
9601 You will also be prompted for a description, and if one is given, it will
9602 be displayed in the buffer instead of the link.
9604 If there is already a link at point, this command will allow you to edit link
9605 and description parts.
9607 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9608 be selected using completion. The path to the file will be relative to the
9609 current directory if the file is in the current directory or a subdirectory.
9610 Otherwise, the link will be the absolute path as completed in the minibuffer
9611 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9612 option `org-link-file-path-type'.
9614 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9615 the current directory or below.
9617 With three \\[universal-argument] prefixes, negate the meaning of
9618 `org-keep-stored-link-after-insertion'.
9620 If `org-make-link-description-function' is non-nil, this function will be
9621 called with the link target, and the result will be the default
9622 link description.
9624 If the LINK-LOCATION parameter is non-nil, this value will be
9625 used as the link location instead of reading one interactively.
9627 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9628 be used as the default description."
9629 (interactive "P")
9630 (let* ((wcf (current-window-configuration))
9631 (origbuf (current-buffer))
9632 (region (if (org-region-active-p)
9633 (buffer-substring (region-beginning) (region-end))))
9634 (remove (and region (list (region-beginning) (region-end))))
9635 (desc region)
9636 tmphist ; byte-compile incorrectly complains about this
9637 (link link-location)
9638 (abbrevs org-link-abbrev-alist-local)
9639 entry file all-prefixes auto-desc)
9640 (cond
9641 (link-location) ; specified by arg, just use it.
9642 ((org-in-regexp org-bracket-link-regexp 1)
9643 ;; We do have a link at point, and we are going to edit it.
9644 (setq remove (list (match-beginning 0) (match-end 0)))
9645 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9646 (setq link (read-string "Link: "
9647 (org-link-unescape
9648 (org-match-string-no-properties 1)))))
9649 ((or (org-in-regexp org-angle-link-re)
9650 (org-in-regexp org-plain-link-re))
9651 ;; Convert to bracket link
9652 (setq remove (list (match-beginning 0) (match-end 0))
9653 link (read-string "Link: "
9654 (org-remove-angle-brackets (match-string 0)))))
9655 ((member complete-file '((4) (16)))
9656 ;; Completing read for file names.
9657 (setq link (org-file-complete-link complete-file)))
9659 ;; Read link, with completion for stored links.
9660 (org-link-fontify-links-to-this-file)
9661 (org-switch-to-buffer-other-window "*Org Links*")
9662 (with-current-buffer "*Org Links*"
9663 (erase-buffer)
9664 (insert "Insert a link.
9665 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9666 (when org-stored-links
9667 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9668 (insert (mapconcat 'org-link-prettify
9669 (reverse org-stored-links) "\n")))
9670 (goto-char (point-min)))
9671 (let ((cw (selected-window)))
9672 (select-window (get-buffer-window "*Org Links*" 'visible))
9673 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9674 (unless (pos-visible-in-window-p (point-max))
9675 (org-fit-window-to-buffer))
9676 (and (window-live-p cw) (select-window cw)))
9677 ;; Fake a link history, containing the stored links.
9678 (setq tmphist (append (mapcar 'car org-stored-links)
9679 org-insert-link-history))
9680 (setq all-prefixes (append (mapcar 'car abbrevs)
9681 (mapcar 'car org-link-abbrev-alist)
9682 org-link-types))
9683 (unwind-protect
9684 (progn
9685 (setq link
9686 (org-completing-read
9687 "Link: "
9688 (append
9689 (mapcar (lambda (x) (concat x ":"))
9690 all-prefixes)
9691 (mapcar 'car org-stored-links))
9692 nil nil nil
9693 'tmphist
9694 (caar org-stored-links)))
9695 (if (not (string-match "\\S-" link))
9696 (error "No link selected"))
9697 (mapc (lambda(l)
9698 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9699 org-stored-links)
9700 (if (or (member link all-prefixes)
9701 (and (equal ":" (substring link -1))
9702 (member (substring link 0 -1) all-prefixes)
9703 (setq link (substring link 0 -1))))
9704 (setq link (with-current-buffer origbuf
9705 (org-link-try-special-completion link)))))
9706 (set-window-configuration wcf)
9707 (kill-buffer "*Org Links*"))
9708 (setq entry (assoc link org-stored-links))
9709 (or entry (push link org-insert-link-history))
9710 (setq desc (or desc (nth 1 entry)))))
9712 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9713 (not org-keep-stored-link-after-insertion))
9714 (setq org-stored-links (delq (assoc link org-stored-links)
9715 org-stored-links)))
9717 (if (string-match org-plain-link-re link)
9718 ;; URL-like link, normalize the use of angular brackets.
9719 (setq link (org-remove-angle-brackets link)))
9721 ;; Check if we are linking to the current file with a search
9722 ;; option If yes, simplify the link by using only the search
9723 ;; option.
9724 (when (and buffer-file-name
9725 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9726 (let* ((path (match-string 1 link))
9727 (case-fold-search nil)
9728 (search (match-string 2 link)))
9729 (save-match-data
9730 (if (equal (file-truename buffer-file-name) (file-truename path))
9731 ;; We are linking to this same file, with a search option
9732 (setq link search)))))
9734 ;; Check if we can/should use a relative path. If yes, simplify the link
9735 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9736 (let* ((type (match-string 1 link))
9737 (path (match-string 2 link))
9738 (origpath path)
9739 (case-fold-search nil))
9740 (cond
9741 ((or (eq org-link-file-path-type 'absolute)
9742 (equal complete-file '(16)))
9743 (setq path (abbreviate-file-name (expand-file-name path))))
9744 ((eq org-link-file-path-type 'noabbrev)
9745 (setq path (expand-file-name path)))
9746 ((eq org-link-file-path-type 'relative)
9747 (setq path (file-relative-name path)))
9749 (save-match-data
9750 (if (string-match (concat "^" (regexp-quote
9751 (expand-file-name
9752 (file-name-as-directory
9753 default-directory))))
9754 (expand-file-name path))
9755 ;; We are linking a file with relative path name.
9756 (setq path (substring (expand-file-name path)
9757 (match-end 0)))
9758 (setq path (abbreviate-file-name (expand-file-name path)))))))
9759 (setq link (concat type path))
9760 (if (equal desc origpath)
9761 (setq desc path))))
9763 (if org-make-link-description-function
9764 (setq desc
9765 (or (condition-case nil
9766 (funcall org-make-link-description-function link desc)
9767 (error (progn (message "Can't get link description from `%s'"
9768 (symbol-name org-make-link-description-function))
9769 (sit-for 2) nil)))
9770 (read-string "Description: " default-description)))
9771 (if default-description (setq desc default-description)
9772 (setq desc (or (and auto-desc desc)
9773 (read-string "Description: " desc)))))
9775 (unless (string-match "\\S-" desc) (setq desc nil))
9776 (if remove (apply 'delete-region remove))
9777 (insert (org-make-link-string link desc))))
9779 (defun org-link-try-special-completion (type)
9780 "If there is completion support for link type TYPE, offer it."
9781 (let ((fun (intern (concat "org-" type "-complete-link"))))
9782 (if (functionp fun)
9783 (funcall fun)
9784 (read-string "Link (no completion support): " (concat type ":")))))
9786 (defun org-file-complete-link (&optional arg)
9787 "Create a file link using completion."
9788 (let (file link)
9789 (setq file (org-iread-file-name "File: "))
9790 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9791 (pwd1 (file-name-as-directory (abbreviate-file-name
9792 (expand-file-name ".")))))
9793 (cond
9794 ((equal arg '(16))
9795 (setq link (concat
9796 "file:"
9797 (abbreviate-file-name (expand-file-name file)))))
9798 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9799 (setq link (concat "file:" (match-string 1 file))))
9800 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9801 (expand-file-name file))
9802 (setq link (concat
9803 "file:" (match-string 1 (expand-file-name file)))))
9804 (t (setq link (concat "file:" file)))))
9805 link))
9807 (defun org-iread-file-name (&rest args)
9808 "Read-file-name using `ido-mode' speedup if available.
9809 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9810 See `read-file-name' for a description of parameters."
9811 (org-without-partial-completion
9812 (if (and org-completion-use-ido
9813 (fboundp 'ido-read-file-name)
9814 (boundp 'ido-mode) ido-mode
9815 (listp (second args)))
9816 (let ((ido-enter-matching-directory nil))
9817 (apply 'ido-read-file-name args))
9818 (apply 'read-file-name args))))
9820 (defun org-completing-read (&rest args)
9821 "Completing-read with SPACE being a normal character."
9822 (let ((enable-recursive-minibuffers t)
9823 (minibuffer-local-completion-map
9824 (copy-keymap minibuffer-local-completion-map)))
9825 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9826 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9827 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9828 (apply 'org-icompleting-read args)))
9830 (defun org-completing-read-no-i (&rest args)
9831 (let (org-completion-use-ido org-completion-use-iswitchb)
9832 (apply 'org-completing-read args)))
9834 (defun org-iswitchb-completing-read (prompt choices &rest args)
9835 "Use iswitch as a completing-read replacement to choose from choices.
9836 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9837 from."
9838 (let* ((iswitchb-use-virtual-buffers nil)
9839 (iswitchb-make-buflist-hook
9840 (lambda ()
9841 (setq iswitchb-temp-buflist choices))))
9842 (iswitchb-read-buffer prompt)))
9844 (defun org-icompleting-read (&rest args)
9845 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9846 (org-without-partial-completion
9847 (if (and org-completion-use-ido
9848 (fboundp 'ido-completing-read)
9849 (boundp 'ido-mode) ido-mode
9850 (listp (second args)))
9851 (let ((ido-enter-matching-directory nil))
9852 (apply 'ido-completing-read (concat (car args))
9853 (if (consp (car (nth 1 args)))
9854 (mapcar 'car (nth 1 args))
9855 (nth 1 args))
9856 (cddr args)))
9857 (if (and org-completion-use-iswitchb
9858 (boundp 'iswitchb-mode) iswitchb-mode
9859 (listp (second args)))
9860 (apply 'org-iswitchb-completing-read (concat (car args))
9861 (if (consp (car (nth 1 args)))
9862 (mapcar 'car (nth 1 args))
9863 (nth 1 args))
9864 (cddr args))
9865 (apply 'completing-read args)))))
9867 (defun org-extract-attributes (s)
9868 "Extract the attributes cookie from a string and set as text property."
9869 (let (a attr (start 0) key value)
9870 (save-match-data
9871 (when (string-match "{{\\([^}]+\\)}}$" s)
9872 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9873 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9874 (setq key (match-string 1 a) value (match-string 2 a)
9875 start (match-end 0)
9876 attr (plist-put attr (intern key) value))))
9877 (org-add-props s nil 'org-attr attr))
9880 (defun org-extract-attributes-from-string (tag)
9881 (let (key value attr)
9882 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9883 (setq key (match-string 1 tag) value (match-string 2 tag)
9884 tag (replace-match "" t t tag)
9885 attr (plist-put attr (intern key) value)))
9886 (cons tag attr)))
9888 (defun org-attributes-to-string (plist)
9889 "Format a property list into an HTML attribute list."
9890 (let ((s "") key value)
9891 (while plist
9892 (setq key (pop plist) value (pop plist))
9893 (and value
9894 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9897 ;;; Opening/following a link
9899 (defvar org-link-search-failed nil)
9901 (defvar org-open-link-functions nil
9902 "Hook for functions finding a plain text link.
9903 These functions must take a single argument, the link content.
9904 They will be called for links that look like [[link text][description]]
9905 when LINK TEXT does not have a protocol like \"http:\" and does not look
9906 like a filename (e.g. \"./blue.png\").
9908 These functions will be called *before* Org attempts to resolve the
9909 link by doing text searches in the current buffer - so if you want a
9910 link \"[[target]]\" to still find \"<<target>>\", your function should
9911 handle this as a special case.
9913 When the function does handle the link, it must return a non-nil value.
9914 If it decides that it is not responsible for this link, it must return
9915 nil to indicate that that Org-mode can continue with other options
9916 like exact and fuzzy text search.")
9918 (defun org-next-link (&optional search-backward)
9919 "Move forward to the next link.
9920 If the link is in hidden text, expose it."
9921 (interactive "P")
9922 (when (and org-link-search-failed (eq this-command last-command))
9923 (goto-char (point-min))
9924 (message "Link search wrapped back to beginning of buffer"))
9925 (setq org-link-search-failed nil)
9926 (let* ((pos (point))
9927 (ct (org-context))
9928 (a (assoc :link ct))
9929 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9930 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9931 ((looking-at org-any-link-re)
9932 ;; Don't stay stuck at link without an org-link face
9933 (forward-char (if search-backward -1 1))))
9934 (if (funcall srch-fun org-any-link-re nil t)
9935 (progn
9936 (goto-char (match-beginning 0))
9937 (if (outline-invisible-p) (org-show-context)))
9938 (goto-char pos)
9939 (setq org-link-search-failed t)
9940 (message "No further link found"))))
9942 (defun org-previous-link ()
9943 "Move backward to the previous link.
9944 If the link is in hidden text, expose it."
9945 (interactive)
9946 (funcall 'org-next-link t))
9948 (defun org-translate-link (s)
9949 "Translate a link string if a translation function has been defined."
9950 (if (and org-link-translation-function
9951 (fboundp org-link-translation-function)
9952 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9953 (progn
9954 (setq s (funcall org-link-translation-function
9955 (match-string 1 s) (match-string 2 s)))
9956 (concat (car s) ":" (cdr s)))
9959 (defun org-translate-link-from-planner (type path)
9960 "Translate a link from Emacs Planner syntax so that Org can follow it.
9961 This is still an experimental function, your mileage may vary."
9962 (cond
9963 ((member type '("http" "https" "news" "ftp"))
9964 ;; standard Internet links are the same.
9965 nil)
9966 ((and (equal type "irc") (string-match "^//" path))
9967 ;; Planner has two / at the beginning of an irc link, we have 1.
9968 ;; We should have zero, actually....
9969 (setq path (substring path 1)))
9970 ((and (equal type "lisp") (string-match "^/" path))
9971 ;; Planner has a slash, we do not.
9972 (setq type "elisp" path (substring path 1)))
9973 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9974 ;; A typical message link. Planner has the id after the final slash,
9975 ;; we separate it with a hash mark
9976 (setq path (concat (match-string 1 path) "#"
9977 (org-remove-angle-brackets (match-string 2 path)))))
9979 (cons type path))
9981 (defun org-find-file-at-mouse (ev)
9982 "Open file link or URL at mouse."
9983 (interactive "e")
9984 (mouse-set-point ev)
9985 (org-open-at-point 'in-emacs))
9987 (defun org-open-at-mouse (ev)
9988 "Open file link or URL at mouse.
9989 See the docstring of `org-open-file' for details."
9990 (interactive "e")
9991 (mouse-set-point ev)
9992 (if (eq major-mode 'org-agenda-mode)
9993 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9994 (org-open-at-point))
9996 (defvar org-window-config-before-follow-link nil
9997 "The window configuration before following a link.
9998 This is saved in case the need arises to restore it.")
10000 (defvar org-open-link-marker (make-marker)
10001 "Marker pointing to the location where `org-open-at-point; was called.")
10003 ;;;###autoload
10004 (defun org-open-at-point-global ()
10005 "Follow a link like Org-mode does.
10006 This command can be called in any mode to follow a link that has
10007 Org-mode syntax."
10008 (interactive)
10009 (org-run-like-in-org-mode 'org-open-at-point))
10011 ;;;###autoload
10012 (defun org-open-link-from-string (s &optional arg reference-buffer)
10013 "Open a link in the string S, as if it was in Org-mode."
10014 (interactive "sLink: \nP")
10015 (let ((reference-buffer (or reference-buffer (current-buffer))))
10016 (with-temp-buffer
10017 (let ((org-inhibit-startup (not reference-buffer)))
10018 (org-mode)
10019 (insert s)
10020 (goto-char (point-min))
10021 (when reference-buffer
10022 (setq org-link-abbrev-alist-local
10023 (with-current-buffer reference-buffer
10024 org-link-abbrev-alist-local)))
10025 (org-open-at-point arg reference-buffer)))))
10027 (defvar org-open-at-point-functions nil
10028 "Hook that is run when following a link at point.
10030 Functions in this hook must return t if they identify and follow
10031 a link at point. If they don't find anything interesting at point,
10032 they must return nil.")
10034 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10035 (defun org-open-at-point (&optional arg reference-buffer)
10036 "Open link at or after point.
10037 If there is no link at point, this function will search forward up to
10038 the end of the current line.
10039 Normally, files will be opened by an appropriate application. If the
10040 optional prefix argument ARG is non-nil, Emacs will visit the file.
10041 With a double prefix argument, try to open outside of Emacs, in the
10042 application the system uses for this file type."
10043 (interactive "P")
10044 ;; if in a code block, then open the block's results
10045 (unless (call-interactively #'org-babel-open-src-block-result)
10046 (org-load-modules-maybe)
10047 (move-marker org-open-link-marker (point))
10048 (setq org-window-config-before-follow-link (current-window-configuration))
10049 (org-remove-occur-highlights nil nil t)
10050 (cond
10051 ((and (org-at-heading-p)
10052 (not (org-at-timestamp-p t))
10053 (not (org-in-regexp
10054 (concat org-plain-link-re "\\|"
10055 org-bracket-link-regexp "\\|"
10056 org-angle-link-re "\\|"
10057 "[ \t]:[^ \t\n]+:[ \t]*$")))
10058 (not (get-text-property (point) 'org-linked-text)))
10059 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10060 (lk0 (car lkall))
10061 (lk (if (stringp lk0) (list lk0) lk0))
10062 (lkend (cdr lkall)))
10063 (mapcar (lambda(l)
10064 (search-forward l nil lkend)
10065 (goto-char (match-beginning 0))
10066 (org-open-at-point))
10067 lk))
10068 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10069 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10070 ((and (org-at-timestamp-p t)
10071 (not (org-in-regexp org-bracket-link-regexp)))
10072 (org-follow-timestamp-link))
10073 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10074 (not (org-in-regexp org-any-link-re)))
10075 (org-footnote-action))
10077 (let (type path link line search (pos (point)))
10078 (catch 'match
10079 (save-excursion
10080 (skip-chars-forward "^]\n\r")
10081 (when (org-in-regexp org-bracket-link-regexp 1)
10082 (setq link (org-extract-attributes
10083 (org-link-unescape (org-match-string-no-properties 1))))
10084 (while (string-match " *\n *" link)
10085 (setq link (replace-match " " t t link)))
10086 (setq link (org-link-expand-abbrev link))
10087 (cond
10088 ((or (file-name-absolute-p link)
10089 (string-match "^\\.\\.?/" link))
10090 (setq type "file" path link))
10091 ((string-match org-link-re-with-space3 link)
10092 (setq type (match-string 1 link) path (match-string 2 link)))
10093 ((string-match "^help:+\\(.+\\)" link)
10094 (setq type "help" path (match-string 1 link)))
10095 (t (setq type "thisfile" path link)))
10096 (throw 'match t)))
10098 (when (get-text-property (point) 'org-linked-text)
10099 (setq type "thisfile"
10100 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10101 (1+ (point)) (point))
10102 path (buffer-substring
10103 (or (previous-single-property-change pos 'org-linked-text)
10104 (point-min))
10105 (or (next-single-property-change pos 'org-linked-text)
10106 (point-max))))
10107 (throw 'match t))
10109 (save-excursion
10110 (when (or (org-in-regexp org-angle-link-re)
10111 (let ((match (org-in-regexp org-plain-link-re)))
10112 ;; Check a plain link is not within a bracket link
10113 (and match
10114 (save-excursion
10115 (progn
10116 (goto-char (car match))
10117 (not (org-in-regexp org-bracket-link-regexp))))))
10118 (let ((line_ending (save-excursion (end-of-line) (point))))
10119 ;; We are in a line before a plain or bracket link
10120 (or (re-search-forward org-plain-link-re line_ending t)
10121 (re-search-forward org-bracket-link-regexp line_ending t))))
10122 (setq type (match-string 1)
10123 path (org-link-unescape (match-string 2)))
10124 (throw 'match t)))
10125 (save-excursion
10126 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10127 (setq type "tags"
10128 path (match-string 1))
10129 (while (string-match ":" path)
10130 (setq path (replace-match "+" t t path)))
10131 (throw 'match t)))
10132 (when (org-in-regexp "<\\([^><\n]+\\)>")
10133 (setq type "tree-match"
10134 path (match-string 1))
10135 (throw 'match t)))
10136 (unless path
10137 (user-error "No link found"))
10139 ;; switch back to reference buffer
10140 ;; needed when if called in a temporary buffer through
10141 ;; org-open-link-from-string
10142 (with-current-buffer (or reference-buffer (current-buffer))
10144 ;; Remove any trailing spaces in path
10145 (if (string-match " +\\'" path)
10146 (setq path (replace-match "" t t path)))
10147 (if (and org-link-translation-function
10148 (fboundp org-link-translation-function))
10149 ;; Check if we need to translate the link
10150 (let ((tmp (funcall org-link-translation-function type path)))
10151 (setq type (car tmp) path (cdr tmp))))
10153 (cond
10155 ((assoc type org-link-protocols)
10156 (funcall (nth 1 (assoc type org-link-protocols)) path))
10158 ((equal type "help")
10159 (let ((f-or-v (intern path)))
10160 (cond ((fboundp f-or-v)
10161 (describe-function f-or-v))
10162 ((boundp f-or-v)
10163 (describe-variable f-or-v))
10164 (t (error "Not a known function or variable")))))
10166 ((equal type "mailto")
10167 (let ((cmd (car org-link-mailto-program))
10168 (args (cdr org-link-mailto-program)) args1
10169 (address path) (subject "") a)
10170 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10171 (setq address (match-string 1 path)
10172 subject (org-link-escape (match-string 2 path))))
10173 (while args
10174 (cond
10175 ((not (stringp (car args))) (push (pop args) args1))
10176 (t (setq a (pop args))
10177 (if (string-match "%a" a)
10178 (setq a (replace-match address t t a)))
10179 (if (string-match "%s" a)
10180 (setq a (replace-match subject t t a)))
10181 (push a args1))))
10182 (apply cmd (nreverse args1))))
10184 ((member type '("http" "https" "ftp" "news"))
10185 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10186 (org-link-escape
10187 path org-link-escape-chars-browser)
10188 path))))
10190 ((string= type "doi")
10191 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10192 (org-link-escape
10193 path org-link-escape-chars-browser)
10194 path))))
10196 ((member type '("message"))
10197 (browse-url (concat type ":" path)))
10199 ((string= type "tags")
10200 (org-tags-view arg path))
10202 ((string= type "tree-match")
10203 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10205 ((string= type "file")
10206 (if (string-match "::\\([0-9]+\\)\\'" path)
10207 (setq line (string-to-number (match-string 1 path))
10208 path (substring path 0 (match-beginning 0)))
10209 (if (string-match "::\\(.+\\)\\'" path)
10210 (setq search (match-string 1 path)
10211 path (substring path 0 (match-beginning 0)))))
10212 (if (string-match "[*?{]" (file-name-nondirectory path))
10213 (dired path)
10214 (org-open-file path arg line search)))
10216 ((string= type "shell")
10217 (let ((buf (generate-new-buffer "*Org Shell Output"))
10218 (cmd path))
10219 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10220 (string-match org-confirm-shell-link-not-regexp cmd))
10221 (not org-confirm-shell-link-function)
10222 (funcall org-confirm-shell-link-function
10223 (format "Execute \"%s\" in shell? "
10224 (org-add-props cmd nil
10225 'face 'org-warning))))
10226 (progn
10227 (message "Executing %s" cmd)
10228 (shell-command cmd buf)
10229 (if (featurep 'midnight)
10230 (setq clean-buffer-list-kill-buffer-names
10231 (cons buf clean-buffer-list-kill-buffer-names))))
10232 (error "Abort"))))
10234 ((string= type "elisp")
10235 (let ((cmd path))
10236 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10237 (string-match org-confirm-elisp-link-not-regexp cmd))
10238 (not org-confirm-elisp-link-function)
10239 (funcall org-confirm-elisp-link-function
10240 (format "Execute \"%s\" as elisp? "
10241 (org-add-props cmd nil
10242 'face 'org-warning))))
10243 (message "%s => %s" cmd
10244 (if (equal (string-to-char cmd) ?\()
10245 (eval (read cmd))
10246 (call-interactively (read cmd))))
10247 (error "Abort"))))
10249 ((and (string= type "thisfile")
10250 (run-hook-with-args-until-success
10251 'org-open-link-functions path)))
10253 ((string= type "thisfile")
10254 (if arg
10255 (switch-to-buffer-other-window
10256 (org-get-buffer-for-internal-link (current-buffer)))
10257 (org-mark-ring-push))
10258 (let ((cmd `(org-link-search
10259 ,path
10260 ,(cond ((equal arg '(4)) ''occur)
10261 ((equal arg '(16)) ''org-occur))
10262 ,pos)))
10263 (condition-case nil (let ((org-link-search-inhibit-query t))
10264 (eval cmd))
10265 (error (progn (widen) (eval cmd))))))
10267 (t (browse-url-at-point)))))))
10268 (move-marker org-open-link-marker nil)
10269 (run-hook-with-args 'org-follow-link-hook)))
10271 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10272 "Offer links in the current entry and return the selected link.
10273 If there is only one link, return it.
10274 If NTH is an integer, return the NTH link found.
10275 If ZERO is a string, check also this string for a link, and if
10276 there is one, return it."
10277 (with-current-buffer buffer
10278 (save-excursion
10279 (save-restriction
10280 (widen)
10281 (goto-char marker)
10282 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10283 "\\(" org-angle-link-re "\\)\\|"
10284 "\\(" org-plain-link-re "\\)"))
10285 (cnt ?0)
10286 (in-emacs (if (integerp nth) nil nth))
10287 have-zero end links link c)
10288 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10289 (push (match-string 0 zero) links)
10290 (setq cnt (1- cnt) have-zero t))
10291 (save-excursion
10292 (org-back-to-heading t)
10293 (setq end (save-excursion (outline-next-heading) (point)))
10294 (while (re-search-forward re end t)
10295 (push (match-string 0) links))
10296 (setq links (org-uniquify (reverse links))))
10297 (cond
10298 ((null links)
10299 (message "No links"))
10300 ((equal (length links) 1)
10301 (setq link (car links)))
10302 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10303 (setq link (nth (if have-zero nth (1- nth)) links)))
10304 (t ; we have to select a link
10305 (save-excursion
10306 (save-window-excursion
10307 (delete-other-windows)
10308 (with-output-to-temp-buffer "*Select Link*"
10309 (mapc (lambda (l)
10310 (if (not (string-match org-bracket-link-regexp l))
10311 (princ (format "[%c] %s\n" (incf cnt)
10312 (org-remove-angle-brackets l)))
10313 (if (match-end 3)
10314 (princ (format "[%c] %s (%s)\n" (incf cnt)
10315 (match-string 3 l) (match-string 1 l)))
10316 (princ (format "[%c] %s\n" (incf cnt)
10317 (match-string 1 l))))))
10318 links))
10319 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10320 (message "Select link to open, RET to open all:")
10321 (setq c (read-char-exclusive))
10322 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10323 (when (equal c ?q) (error "Abort"))
10324 (if (equal c ?\C-m)
10325 (setq link links)
10326 (setq nth (- c ?0))
10327 (if have-zero (setq nth (1+ nth)))
10328 (unless (and (integerp nth) (>= (length links) nth))
10329 (error "Invalid link selection"))
10330 (setq link (nth (1- nth) links)))))
10331 (cons link end))))))
10333 ;; Add special file links that specify the way of opening
10335 (org-add-link-type "file+sys" 'org-open-file-with-system)
10336 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10337 (defun org-open-file-with-system (path)
10338 "Open file at PATH using the system way of opening it."
10339 (org-open-file path 'system))
10340 (defun org-open-file-with-emacs (path)
10341 "Open file at PATH in Emacs."
10342 (org-open-file path 'emacs))
10345 ;;; File search
10347 (defvar org-create-file-search-functions nil
10348 "List of functions to construct the right search string for a file link.
10349 These functions are called in turn with point at the location to
10350 which the link should point.
10352 A function in the hook should first test if it would like to
10353 handle this file type, for example by checking the `major-mode'
10354 or the file extension. If it decides not to handle this file, it
10355 should just return nil to give other functions a chance. If it
10356 does handle the file, it must return the search string to be used
10357 when following the link. The search string will be part of the
10358 file link, given after a double colon, and `org-open-at-point'
10359 will automatically search for it. If special measures must be
10360 taken to make the search successful, another function should be
10361 added to the companion hook `org-execute-file-search-functions',
10362 which see.
10364 A function in this hook may also use `setq' to set the variable
10365 `description' to provide a suggestion for the descriptive text to
10366 be used for this link when it gets inserted into an Org-mode
10367 buffer with \\[org-insert-link].")
10369 (defvar org-execute-file-search-functions nil
10370 "List of functions to execute a file search triggered by a link.
10372 Functions added to this hook must accept a single argument, the
10373 search string that was part of the file link, the part after the
10374 double colon. The function must first check if it would like to
10375 handle this search, for example by checking the `major-mode' or
10376 the file extension. If it decides not to handle this search, it
10377 should just return nil to give other functions a chance. If it
10378 does handle the search, it must return a non-nil value to keep
10379 other functions from trying.
10381 Each function can access the current prefix argument through the
10382 variable `current-prefix-argument'. Note that a single prefix is
10383 used to force opening a link in Emacs, so it may be good to only
10384 use a numeric or double prefix to guide the search function.
10386 In case this is needed, a function in this hook can also restore
10387 the window configuration before `org-open-at-point' was called using:
10389 (set-window-configuration org-window-config-before-follow-link)")
10391 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10392 (defun org-link-search (s &optional type avoid-pos stealth)
10393 "Search for a link search option.
10394 If S is surrounded by forward slashes, it is interpreted as a
10395 regular expression. In org-mode files, this will create an `org-occur'
10396 sparse tree. In ordinary files, `occur' will be used to list matches.
10397 If the current buffer is in `dired-mode', grep will be used to search
10398 in all files. If AVOID-POS is given, ignore matches near that position.
10400 When optional argument STEALTH is non-nil, do not modify
10401 visibility around point, thus ignoring
10402 `org-show-hierarchy-above', `org-show-following-heading' and
10403 `org-show-siblings' variables."
10404 (let ((case-fold-search t)
10405 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10406 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10407 (append '(("") (" ") ("\t") ("\n"))
10408 org-emphasis-alist)
10409 "\\|") "\\)"))
10410 (pos (point))
10411 (pre nil) (post nil)
10412 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10413 (cond
10414 ;; First check if there are any special search functions
10415 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10416 ;; Now try the builtin stuff
10417 ((and (equal (string-to-char s0) ?#)
10418 (> (length s0) 1)
10419 (save-excursion
10420 (goto-char (point-min))
10421 (and
10422 (re-search-forward
10423 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10424 (setq type 'dedicated
10425 pos (match-beginning 0))))
10426 ;; There is an exact target for this
10427 (goto-char pos)
10428 (org-back-to-heading t)))
10429 ((save-excursion
10430 (goto-char (point-min))
10431 (and
10432 (re-search-forward
10433 (concat "<<" (regexp-quote s0) ">>") nil t)
10434 (setq type 'dedicated
10435 pos (match-beginning 0))))
10436 ;; There is an exact target for this
10437 (goto-char pos))
10438 ((save-excursion
10439 (goto-char (point-min))
10440 (and
10441 (re-search-forward
10442 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10443 (setq type 'dedicated pos (match-beginning 0))))
10444 ;; Found an invisible target.
10445 (goto-char pos))
10446 ((save-excursion
10447 (goto-char (point-min))
10448 (and
10449 (re-search-forward
10450 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10451 (setq type 'dedicated pos (match-beginning 0))))
10452 ;; Found an element with a matching #+name affiliated keyword.
10453 (goto-char pos))
10454 ((and (string-match "^(\\(.*\\))$" s0)
10455 (save-excursion
10456 (goto-char (point-min))
10457 (and
10458 (re-search-forward
10459 (concat "[^[]" (regexp-quote
10460 (format org-coderef-label-format
10461 (match-string 1 s0))))
10462 nil t)
10463 (setq type 'dedicated
10464 pos (1+ (match-beginning 0))))))
10465 ;; There is a coderef target for this
10466 (goto-char pos))
10467 ((string-match "^/\\(.*\\)/$" s)
10468 ;; A regular expression
10469 (cond
10470 ((derived-mode-p 'org-mode)
10471 (org-occur (match-string 1 s)))
10472 (t (org-do-occur (match-string 1 s)))))
10473 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10474 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10475 (goto-char (point-min))
10476 (cond
10477 ((let (case-fold-search)
10478 (re-search-forward (format org-complex-heading-regexp-format
10479 (regexp-quote s))
10480 nil t))
10481 ;; OK, found a match
10482 (setq type 'dedicated)
10483 (goto-char (match-beginning 0)))
10484 ((and (not org-link-search-inhibit-query)
10485 (eq org-link-search-must-match-exact-headline 'query-to-create)
10486 (y-or-n-p "No match - create this as a new heading? "))
10487 (goto-char (point-max))
10488 (or (bolp) (newline))
10489 (insert "* " s "\n")
10490 (beginning-of-line 0))
10492 (goto-char pos)
10493 (error "No match"))))
10495 ;; A normal search string
10496 (when (equal (string-to-char s) ?*)
10497 ;; Anchor on headlines, post may include tags.
10498 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10499 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10500 s (substring s 1)))
10501 (remove-text-properties
10502 0 (length s)
10503 '(face nil mouse-face nil keymap nil fontified nil) s)
10504 ;; Make a series of regular expressions to find a match
10505 (setq words (org-split-string s "[ \n\r\t]+")
10507 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10508 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10509 "\\)" markers)
10510 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10511 re2a (concat "[ \t\r\n]" re2a_)
10512 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10513 re4 (concat "[^a-zA-Z_]" re4_)
10515 re1 (concat pre re2 post)
10516 re3 (concat pre (if pre re4_ re4) post)
10517 re5 (concat pre ".*" re4)
10518 re2 (concat pre re2)
10519 re2a (concat pre (if pre re2a_ re2a))
10520 re4 (concat pre (if pre re4_ re4))
10521 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10522 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10523 re5 "\\)"
10525 (cond
10526 ((eq type 'org-occur) (org-occur reall))
10527 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10528 (t (goto-char (point-min))
10529 (setq type 'fuzzy)
10530 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10531 (org-search-not-self 1 re1 nil t)
10532 (org-search-not-self 1 re2 nil t)
10533 (org-search-not-self 1 re2a nil t)
10534 (org-search-not-self 1 re3 nil t)
10535 (org-search-not-self 1 re4 nil t)
10536 (org-search-not-self 1 re5 nil t)
10538 (goto-char (match-beginning 1))
10539 (goto-char pos)
10540 (error "No match"))))))
10541 (and (derived-mode-p 'org-mode)
10542 (not stealth)
10543 (org-show-context 'link-search))
10544 type))
10546 (defun org-search-not-self (group &rest args)
10547 "Execute `re-search-forward', but only accept matches that do not
10548 enclose the position of `org-open-link-marker'."
10549 (let ((m org-open-link-marker))
10550 (catch 'exit
10551 (while (apply 're-search-forward args)
10552 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10553 (goto-char (match-end group))
10554 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10555 (> (match-beginning 0) (marker-position m))
10556 (< (match-end 0) (marker-position m)))
10557 (save-match-data
10558 (or (not (org-in-regexp
10559 org-bracket-link-analytic-regexp 1))
10560 (not (match-end 4)) ; no description
10561 (and (<= (match-beginning 4) (point))
10562 (>= (match-end 4) (point))))))
10563 (throw 'exit (point))))))))
10565 (defun org-get-buffer-for-internal-link (buffer)
10566 "Return a buffer to be used for displaying the link target of internal links."
10567 (cond
10568 ((not org-display-internal-link-with-indirect-buffer)
10569 buffer)
10570 ((string-match "(Clone)$" (buffer-name buffer))
10571 (message "Buffer is already a clone, not making another one")
10572 ;; we also do not modify visibility in this case
10573 buffer)
10574 (t ; make a new indirect buffer for displaying the link
10575 (let* ((bn (buffer-name buffer))
10576 (ibn (concat bn "(Clone)"))
10577 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10578 (with-current-buffer ib (org-overview))
10579 ib))))
10581 (defun org-do-occur (regexp &optional cleanup)
10582 "Call the Emacs command `occur'.
10583 If CLEANUP is non-nil, remove the printout of the regular expression
10584 in the *Occur* buffer. This is useful if the regex is long and not useful
10585 to read."
10586 (occur regexp)
10587 (when cleanup
10588 (let ((cwin (selected-window)) win beg end)
10589 (when (setq win (get-buffer-window "*Occur*"))
10590 (select-window win))
10591 (goto-char (point-min))
10592 (when (re-search-forward "match[a-z]+" nil t)
10593 (setq beg (match-end 0))
10594 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10595 (setq end (1- (match-beginning 0)))))
10596 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10597 (goto-char (point-min))
10598 (select-window cwin))))
10600 ;;; The mark ring for links jumps
10602 (defvar org-mark-ring nil
10603 "Mark ring for positions before jumps in Org-mode.")
10604 (defvar org-mark-ring-last-goto nil
10605 "Last position in the mark ring used to go back.")
10606 ;; Fill and close the ring
10607 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10608 (loop for i from 1 to org-mark-ring-length do
10609 (push (make-marker) org-mark-ring))
10610 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10611 org-mark-ring)
10613 (defun org-mark-ring-push (&optional pos buffer)
10614 "Put the current position or POS into the mark ring and rotate it."
10615 (interactive)
10616 (setq pos (or pos (point)))
10617 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10618 (move-marker (car org-mark-ring)
10619 (or pos (point))
10620 (or buffer (current-buffer)))
10621 (message "%s"
10622 (substitute-command-keys
10623 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10625 (defun org-mark-ring-goto (&optional n)
10626 "Jump to the previous position in the mark ring.
10627 With prefix arg N, jump back that many stored positions. When
10628 called several times in succession, walk through the entire ring.
10629 Org-mode commands jumping to a different position in the current file,
10630 or to another Org-mode file, automatically push the old position
10631 onto the ring."
10632 (interactive "p")
10633 (let (p m)
10634 (if (eq last-command this-command)
10635 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10636 (setq p org-mark-ring))
10637 (setq org-mark-ring-last-goto p)
10638 (setq m (car p))
10639 (org-pop-to-buffer-same-window (marker-buffer m))
10640 (goto-char m)
10641 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10643 (defun org-remove-angle-brackets (s)
10644 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10645 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10647 (defun org-add-angle-brackets (s)
10648 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10649 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10651 (defun org-remove-double-quotes (s)
10652 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10653 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10656 ;;; Following specific links
10658 (defun org-follow-timestamp-link ()
10659 "Open an agenda view for the time-stamp date/range at point."
10660 (cond
10661 ((org-at-date-range-p t)
10662 (let ((org-agenda-start-on-weekday)
10663 (t1 (match-string 1))
10664 (t2 (match-string 2)) tt1 tt2)
10665 (setq tt1 (time-to-days (org-time-string-to-time t1))
10666 tt2 (time-to-days (org-time-string-to-time t2)))
10667 (let ((org-agenda-buffer-tmp-name
10668 (format "*Org Agenda(a:%s)"
10669 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10670 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10671 ((org-at-timestamp-p t)
10672 (let ((org-agenda-buffer-tmp-name
10673 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10674 (org-agenda-list nil (time-to-days (org-time-string-to-time
10675 (substring (match-string 1) 0 10)))
10676 1)))
10677 (t (error "This should not happen"))))
10680 ;;; Following file links
10681 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10682 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10683 (declare-function mailcap-mime-info
10684 "mailcap" (string &optional request no-decode))
10685 (defvar org-wait nil)
10686 (defun org-open-file (path &optional in-emacs line search)
10687 "Open the file at PATH.
10688 First, this expands any special file name abbreviations. Then the
10689 configuration variable `org-file-apps' is checked if it contains an
10690 entry for this file type, and if yes, the corresponding command is launched.
10692 If no application is found, Emacs simply visits the file.
10694 With optional prefix argument IN-EMACS, Emacs will visit the file.
10695 With a double \\[universal-argument] \\[universal-argument] \
10696 prefix arg, Org tries to avoid opening in Emacs
10697 and to use an external application to visit the file.
10699 Optional LINE specifies a line to go to, optional SEARCH a string
10700 to search for. If LINE or SEARCH is given, the file will be
10701 opened in Emacs, unless an entry from org-file-apps that makes
10702 use of groups in a regexp matches.
10704 If you want to change the way frames are used when following a
10705 link, please customize `org-link-frame-setup'.
10707 If the file does not exist, an error is thrown."
10708 (let* ((file (if (equal path "")
10709 buffer-file-name
10710 (substitute-in-file-name (expand-file-name path))))
10711 (file-apps (append org-file-apps (org-default-apps)))
10712 (apps (org-remove-if
10713 'org-file-apps-entry-match-against-dlink-p file-apps))
10714 (apps-dlink (org-remove-if-not
10715 'org-file-apps-entry-match-against-dlink-p file-apps))
10716 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10717 (dirp (if remp nil (file-directory-p file)))
10718 (file (if (and dirp org-open-directory-means-index-dot-org)
10719 (concat (file-name-as-directory file) "index.org")
10720 file))
10721 (a-m-a-p (assq 'auto-mode apps))
10722 (dfile (downcase file))
10723 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10724 (link (cond ((and (eq line nil)
10725 (eq search nil))
10726 file)
10727 (line
10728 (concat file "::" (number-to-string line)))
10729 (search
10730 (concat file "::" search))))
10731 (dlink (downcase link))
10732 (old-buffer (current-buffer))
10733 (old-pos (point))
10734 (old-mode major-mode)
10735 ext cmd link-match-data)
10736 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10737 (setq ext (match-string 1 dfile))
10738 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10739 (setq ext (match-string 1 dfile))))
10740 (cond
10741 ((member in-emacs '((16) system))
10742 (setq cmd (cdr (assoc 'system apps))))
10743 (in-emacs (setq cmd 'emacs))
10745 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10746 (and dirp (cdr (assoc 'directory apps)))
10747 ; first, try matching against apps-dlink
10748 ; if we get a match here, store the match data for later
10749 (let ((match (assoc-default dlink apps-dlink
10750 'string-match)))
10751 (if match
10752 (progn (setq link-match-data (match-data))
10753 match)
10754 (progn (setq in-emacs (or in-emacs line search))
10755 nil))) ; if we have no match in apps-dlink,
10756 ; always open the file in emacs if line or search
10757 ; is given (for backwards compatibility)
10758 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10759 'string-match)
10760 (cdr (assoc ext apps))
10761 (cdr (assoc t apps))))))
10762 (when (eq cmd 'system)
10763 (setq cmd (cdr (assoc 'system apps))))
10764 (when (eq cmd 'default)
10765 (setq cmd (cdr (assoc t apps))))
10766 (when (eq cmd 'mailcap)
10767 (require 'mailcap)
10768 (mailcap-parse-mailcaps)
10769 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10770 (command (mailcap-mime-info mime-type)))
10771 (if (stringp command)
10772 (setq cmd command)
10773 (setq cmd 'emacs))))
10774 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10775 (not (file-exists-p file))
10776 (not org-open-non-existing-files))
10777 (error "No such file: %s" file))
10778 (cond
10779 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10780 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10781 (while (string-match "['\"]%s['\"]" cmd)
10782 (setq cmd (replace-match "%s" t t cmd)))
10783 (while (string-match "%s" cmd)
10784 (setq cmd (replace-match
10785 (save-match-data
10786 (shell-quote-argument
10787 (convert-standard-filename file)))
10788 t t cmd)))
10790 ;; Replace "%1", "%2" etc. in command with group matches from regex
10791 (save-match-data
10792 (let ((match-index 1)
10793 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10794 (set-match-data link-match-data)
10795 (while (<= match-index number-of-groups)
10796 (let ((regex (concat "%" (number-to-string match-index)))
10797 (replace-with (match-string match-index dlink)))
10798 (while (string-match regex cmd)
10799 (setq cmd (replace-match replace-with t t cmd))))
10800 (setq match-index (+ match-index 1)))))
10802 (save-window-excursion
10803 (message "Running %s...done" cmd)
10804 (start-process-shell-command cmd nil cmd)
10805 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10806 ((or (stringp cmd)
10807 (eq cmd 'emacs))
10808 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10809 (widen)
10810 (if line (org-goto-line line)
10811 (if search (org-link-search search))))
10812 ((consp cmd)
10813 (let ((file (convert-standard-filename file)))
10814 (save-match-data
10815 (set-match-data link-match-data)
10816 (eval cmd))))
10817 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10818 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10819 (or (not (equal old-buffer (current-buffer)))
10820 (not (equal old-pos (point))))
10821 (org-mark-ring-push old-pos old-buffer))))
10823 (defun org-file-apps-entry-match-against-dlink-p (entry)
10824 "This function returns non-nil if `entry' uses a regular
10825 expression which should be matched against the whole link by
10826 org-open-file.
10828 It assumes that is the case when the entry uses a regular
10829 expression which has at least one grouping construct and the
10830 action is either a lisp form or a command string containing
10831 '%1', i.e. using at least one subexpression match as a
10832 parameter."
10833 (let ((selector (car entry))
10834 (action (cdr entry)))
10835 (if (stringp selector)
10836 (and (> (regexp-opt-depth selector) 0)
10837 (or (and (stringp action)
10838 (string-match "%[0-9]" action))
10839 (consp action)))
10840 nil)))
10842 (defun org-default-apps ()
10843 "Return the default applications for this operating system."
10844 (cond
10845 ((eq system-type 'darwin)
10846 org-file-apps-defaults-macosx)
10847 ((eq system-type 'windows-nt)
10848 org-file-apps-defaults-windowsnt)
10849 (t org-file-apps-defaults-gnu)))
10851 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10852 "Convert extensions to regular expressions in the cars of LIST.
10853 Also, weed out any non-string entries, because the return value is used
10854 only for regexp matching.
10855 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10856 point to the symbol `emacs', indicating that the file should
10857 be opened in Emacs."
10858 (append
10859 (delq nil
10860 (mapcar (lambda (x)
10861 (if (not (stringp (car x)))
10863 (if (string-match "\\W" (car x))
10865 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10866 list))
10867 (if add-auto-mode
10868 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10870 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10871 (defun org-file-remote-p (file)
10872 "Test whether FILE specifies a location on a remote system.
10873 Return non-nil if the location is indeed remote.
10875 For example, the filename \"/user@host:/foo\" specifies a location
10876 on the system \"/user@host:\"."
10877 (cond ((fboundp 'file-remote-p)
10878 (file-remote-p file))
10879 ((fboundp 'tramp-handle-file-remote-p)
10880 (tramp-handle-file-remote-p file))
10881 ((and (boundp 'ange-ftp-name-format)
10882 (string-match (car ange-ftp-name-format) file))
10883 t)))
10886 ;;;; Refiling
10888 (defun org-get-org-file ()
10889 "Read a filename, with default directory `org-directory'."
10890 (let ((default (or org-default-notes-file remember-data-file)))
10891 (read-file-name (format "File name [%s]: " default)
10892 (file-name-as-directory org-directory)
10893 default)))
10895 (defun org-notes-order-reversed-p ()
10896 "Check if the current file should receive notes in reversed order."
10897 (cond
10898 ((not org-reverse-note-order) nil)
10899 ((eq t org-reverse-note-order) t)
10900 ((not (listp org-reverse-note-order)) nil)
10901 (t (catch 'exit
10902 (let ((all org-reverse-note-order)
10903 entry)
10904 (while (setq entry (pop all))
10905 (if (string-match (car entry) buffer-file-name)
10906 (throw 'exit (cdr entry))))
10907 nil)))))
10909 (defvar org-refile-target-table nil
10910 "The list of refile targets, created by `org-refile'.")
10912 (defvar org-agenda-new-buffers nil
10913 "Buffers created to visit agenda files.")
10915 (defvar org-refile-cache nil
10916 "Cache for refile targets.")
10918 (defvar org-refile-markers nil
10919 "All the markers used for caching refile locations.")
10921 (defun org-refile-marker (pos)
10922 "Get a new refile marker, but only if caching is in use."
10923 (if (not org-refile-use-cache)
10925 (let ((m (make-marker)))
10926 (move-marker m pos)
10927 (push m org-refile-markers)
10928 m)))
10930 (defun org-refile-cache-clear ()
10931 "Clear the refile cache and disable all the markers."
10932 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10933 (setq org-refile-markers nil)
10934 (setq org-refile-cache nil)
10935 (message "Refile cache has been cleared"))
10937 (defun org-refile-cache-check-set (set)
10938 "Check if all the markers in the cache still have live buffers."
10939 (let (marker)
10940 (catch 'exit
10941 (while (and set (setq marker (nth 3 (pop set))))
10942 ;; if org-refile-use-outline-path is 'file, marker may be nil
10943 (when (and marker (null (marker-buffer marker)))
10944 (message "not found") (sit-for 3)
10945 (throw 'exit nil)))
10946 t)))
10948 (defun org-refile-cache-put (set &rest identifiers)
10949 "Push the refile targets SET into the cache, under IDENTIFIERS."
10950 (let* ((key (sha1 (prin1-to-string identifiers)))
10951 (entry (assoc key org-refile-cache)))
10952 (if entry
10953 (setcdr entry set)
10954 (push (cons key set) org-refile-cache))))
10956 (defun org-refile-cache-get (&rest identifiers)
10957 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10958 (cond
10959 ((not org-refile-cache) nil)
10960 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10962 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10963 org-refile-cache))))
10964 (and set (org-refile-cache-check-set set) set)))))
10966 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10967 "Produce a table with refile targets."
10968 (let ((case-fold-search nil)
10969 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10970 (entries (or org-refile-targets '((nil . (:level . 1)))))
10971 targets tgs txt re files f desc descre fast-path-p level pos0)
10972 (message "Getting targets...")
10973 (with-current-buffer (or default-buffer (current-buffer))
10974 (while (setq entry (pop entries))
10975 (setq files (car entry) desc (cdr entry))
10976 (setq fast-path-p nil)
10977 (cond
10978 ((null files) (setq files (list (current-buffer))))
10979 ((eq files 'org-agenda-files)
10980 (setq files (org-agenda-files 'unrestricted)))
10981 ((and (symbolp files) (fboundp files))
10982 (setq files (funcall files)))
10983 ((and (symbolp files) (boundp files))
10984 (setq files (symbol-value files))))
10985 (if (stringp files) (setq files (list files)))
10986 (cond
10987 ((eq (car desc) :tag)
10988 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10989 ((eq (car desc) :todo)
10990 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10991 ((eq (car desc) :regexp)
10992 (setq descre (cdr desc)))
10993 ((eq (car desc) :level)
10994 (setq descre (concat "^\\*\\{" (number-to-string
10995 (if org-odd-levels-only
10996 (1- (* 2 (cdr desc)))
10997 (cdr desc)))
10998 "\\}[ \t]")))
10999 ((eq (car desc) :maxlevel)
11000 (setq fast-path-p t)
11001 (setq descre (concat "^\\*\\{1," (number-to-string
11002 (if org-odd-levels-only
11003 (1- (* 2 (cdr desc)))
11004 (cdr desc)))
11005 "\\}[ \t]")))
11006 (t (error "Bad refiling target description %s" desc)))
11007 (while (setq f (pop files))
11008 (with-current-buffer
11009 (if (bufferp f) f (org-get-agenda-file-buffer f))
11011 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11012 (progn
11013 (if (bufferp f) (setq f (buffer-file-name
11014 (buffer-base-buffer f))))
11015 (setq f (and f (expand-file-name f)))
11016 (if (eq org-refile-use-outline-path 'file)
11017 (push (list (file-name-nondirectory f) f nil nil) tgs))
11018 (save-excursion
11019 (save-restriction
11020 (widen)
11021 (goto-char (point-min))
11022 (while (re-search-forward descre nil t)
11023 (goto-char (setq pos0 (point-at-bol)))
11024 (catch 'next
11025 (when org-refile-target-verify-function
11026 (save-match-data
11027 (or (funcall org-refile-target-verify-function)
11028 (throw 'next t))))
11029 (when (and (looking-at org-complex-heading-regexp)
11030 (not (member (match-string 4) excluded-entries))
11031 (match-string 4))
11032 (setq level (org-reduced-level
11033 (- (match-end 1) (match-beginning 1)))
11034 txt (org-link-display-format (match-string 4))
11035 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11036 re (format org-complex-heading-regexp-format
11037 (regexp-quote (match-string 4))))
11038 (when org-refile-use-outline-path
11039 (setq txt (mapconcat
11040 'org-protect-slash
11041 (append
11042 (if (eq org-refile-use-outline-path
11043 'file)
11044 (list (file-name-nondirectory
11045 (buffer-file-name
11046 (buffer-base-buffer))))
11047 (if (eq org-refile-use-outline-path
11048 'full-file-path)
11049 (list (buffer-file-name
11050 (buffer-base-buffer)))))
11051 (org-get-outline-path fast-path-p
11052 level txt)
11053 (list txt))
11054 "/")))
11055 (push (list txt f re (org-refile-marker (point)))
11056 tgs)))
11057 (when (= (point) pos0)
11058 ;; verification function has not moved point
11059 (goto-char (point-at-eol))))))))
11060 (when org-refile-use-cache
11061 (org-refile-cache-put tgs (buffer-file-name) descre))
11062 (setq targets (append tgs targets))
11063 ))))
11064 (message "Getting targets...done")
11065 (nreverse targets)))
11067 (defun org-protect-slash (s)
11068 (while (string-match "/" s)
11069 (setq s (replace-match "\\" t t s)))
11072 (defvar org-olpa (make-vector 20 nil))
11074 (defun org-get-outline-path (&optional fastp level heading)
11075 "Return the outline path to the current entry, as a list.
11077 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11078 routine which makes outline path derivations for an entire file,
11079 avoiding backtracing. Refile target collection makes use of that."
11080 (if fastp
11081 (progn
11082 (if (> level 19)
11083 (error "Outline path failure, more than 19 levels"))
11084 (loop for i from level upto 19 do
11085 (aset org-olpa i nil))
11086 (prog1
11087 (delq nil (append org-olpa nil))
11088 (aset org-olpa level heading)))
11089 (let (rtn case-fold-search)
11090 (save-excursion
11091 (save-restriction
11092 (widen)
11093 (while (org-up-heading-safe)
11094 (when (looking-at org-complex-heading-regexp)
11095 (push (org-match-string-no-properties 4) rtn)))
11096 rtn)))))
11098 (defun org-format-outline-path (path &optional width prefix separator)
11099 "Format the outline path PATH for display.
11100 WIDTH is the maximum number of characters that is available.
11101 PREFIX is a prefix to be included in the returned string,
11102 such as the file name.
11103 SEPARATOR is inserted between the different parts of the path,
11104 the default is \"/\"."
11105 (setq width (or width 79))
11106 (if prefix (setq width (- width (length prefix))))
11107 (if (not path)
11108 (or prefix "")
11109 (let* ((nsteps (length path))
11110 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11111 (maxwidth (if (<= total-width width)
11112 10000 ;; everything fits
11113 ;; we need to shorten the level headings
11114 (/ (- width nsteps) nsteps)))
11115 (org-odd-levels-only nil)
11116 (n 0)
11117 (total (1+ (length prefix))))
11118 (setq maxwidth (max maxwidth 10))
11119 (concat prefix
11120 (if prefix (or separator "/"))
11121 (mapconcat
11122 (lambda (h)
11123 (setq n (1+ n))
11124 (if (and (= n nsteps) (< maxwidth 10000))
11125 (setq maxwidth (- total-width total)))
11126 (if (< (length h) maxwidth)
11127 (progn (setq total (+ total (length h) 1)) h)
11128 (setq h (substring h 0 (- maxwidth 2))
11129 total (+ total maxwidth 1))
11130 (if (string-match "[ \t]+\\'" h)
11131 (setq h (substring h 0 (match-beginning 0))))
11132 (setq h (concat h "..")))
11133 (org-add-props h nil 'face
11134 (nth (% (1- n) org-n-level-faces)
11135 org-level-faces))
11137 path (or separator "/"))))))
11139 (defun org-display-outline-path (&optional file current separator just-return-string)
11140 "Display the current outline path in the echo area.
11142 If FILE is non-nil, prepend the output with the file name.
11143 If CURRENT is non-nil, append the current heading to the output.
11144 SEPARATOR is passed through to `org-format-outline-path'. It separates
11145 the different parts of the path and defaults to \"/\".
11146 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11147 (interactive "P")
11148 (let* (case-fold-search
11149 message-log-max ; Don't populate the *Messages* buffer
11150 (bfn (buffer-file-name (buffer-base-buffer)))
11151 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11152 res)
11153 (if current (setq path (append path
11154 (save-excursion
11155 (org-back-to-heading t)
11156 (if (looking-at org-complex-heading-regexp)
11157 (list (match-string 4)))))))
11158 (setq res
11159 (org-format-outline-path
11160 path
11161 (1- (frame-width))
11162 (and file bfn (concat (file-name-nondirectory bfn) separator))
11163 separator))
11164 (if just-return-string
11165 (org-no-properties res)
11166 (message "%s" res))))
11168 (defvar org-refile-history nil
11169 "History for refiling operations.")
11171 (defvar org-after-refile-insert-hook nil
11172 "Hook run after `org-refile' has inserted its stuff at the new location.
11173 Note that this is still *before* the stuff will be removed from
11174 the *old* location.")
11176 (defvar org-capture-last-stored-marker)
11177 (defvar org-refile-keep nil
11178 "Non-nil means `org-refile' will copy instead of refile.")
11180 (defun org-copy ()
11181 "Like `org-refile', but copy."
11182 (interactive)
11183 (let ((org-refile-keep t))
11184 (funcall 'org-refile nil nil nil "Copy")))
11186 (defun org-refile (&optional goto default-buffer rfloc msg)
11187 "Move the entry or entries at point to another heading.
11188 The list of target headings is compiled using the information in
11189 `org-refile-targets', which see.
11191 At the target location, the entry is filed as a subitem of the target
11192 heading. Depending on `org-reverse-note-order', the new subitem will
11193 either be the first or the last subitem.
11195 If there is an active region, all entries in that region will be moved.
11196 However, the region must fulfill the requirement that the first heading
11197 is the first one sets the top-level of the moved text - at most siblings
11198 below it are allowed.
11200 With prefix arg GOTO, the command will only visit the target location
11201 and not actually move anything.
11203 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11204 go to the location where the last refiling operation has put the subtree.
11205 With a prefix argument of `2', refile to the running clock.
11207 RFLOC can be a refile location obtained in a different way.
11209 MSG is a string to replace \"Refile\" in the default prompt with
11210 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11212 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11214 If you are using target caching (see `org-refile-use-cache'),
11215 you have to clear the target cache in order to find new targets.
11216 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11217 prefix argument (`C-u C-u C-u C-c C-w')."
11219 (interactive "P")
11220 (if (member goto '(0 (64)))
11221 (org-refile-cache-clear)
11222 (let* ((actionmsg (or msg "Refile"))
11223 (cbuf (current-buffer))
11224 (regionp (org-region-active-p))
11225 (region-start (and regionp (region-beginning)))
11226 (region-end (and regionp (region-end)))
11227 (region-length (and regionp (- region-end region-start)))
11228 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11229 pos it nbuf file re level reversed)
11230 (setq last-command nil)
11231 (when regionp
11232 (goto-char region-start)
11233 (or (bolp) (goto-char (point-at-bol)))
11234 (setq region-start (point))
11235 (unless (or (org-kill-is-subtree-p
11236 (buffer-substring region-start region-end))
11237 (prog1 org-refile-active-region-within-subtree
11238 (org-toggle-heading)))
11239 (error "The region is not a (sequence of) subtree(s)")))
11240 (if (equal goto '(16))
11241 (org-refile-goto-last-stored)
11242 (when (or
11243 (and (equal goto 2)
11244 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11245 (prog1
11246 (setq it (list (or org-clock-heading "running clock")
11247 (buffer-file-name
11248 (marker-buffer org-clock-hd-marker))
11250 (marker-position org-clock-hd-marker)))
11251 (setq goto nil)))
11252 (setq it (or rfloc
11253 (let (heading-text)
11254 (save-excursion
11255 (unless goto
11256 (org-back-to-heading t)
11257 (setq heading-text
11258 (nth 4 (org-heading-components))))
11260 (org-refile-get-location
11261 (cond (goto "Goto")
11262 (regionp (concat actionmsg " region to"))
11263 (t (concat actionmsg " subtree \""
11264 heading-text "\" to")))
11265 default-buffer
11266 (and (not (equal '(4) goto))
11267 org-refile-allow-creating-parent-nodes)
11268 goto))))))
11269 (setq file (nth 1 it)
11270 re (nth 2 it)
11271 pos (nth 3 it))
11272 (if (and (not goto)
11274 (equal (buffer-file-name) file)
11275 (if regionp
11276 (and (>= pos region-start)
11277 (<= pos region-end))
11278 (and (>= pos (point))
11279 (< pos (save-excursion
11280 (org-end-of-subtree t t))))))
11281 (error "Cannot refile to position inside the tree or region"))
11283 (setq nbuf (or (find-buffer-visiting file)
11284 (find-file-noselect file)))
11285 (if goto
11286 (progn
11287 (org-pop-to-buffer-same-window nbuf)
11288 (goto-char pos)
11289 (org-show-context 'org-goto))
11290 (if regionp
11291 (progn
11292 (org-kill-new (buffer-substring region-start region-end))
11293 (org-save-markers-in-region region-start region-end))
11294 (org-copy-subtree 1 nil t))
11295 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11296 (find-file-noselect file)))
11297 (setq reversed (org-notes-order-reversed-p))
11298 (save-excursion
11299 (save-restriction
11300 (widen)
11301 (if pos
11302 (progn
11303 (goto-char pos)
11304 (looking-at org-outline-regexp)
11305 (setq level (org-get-valid-level (funcall outline-level) 1))
11306 (goto-char
11307 (if reversed
11308 (or (outline-next-heading) (point-max))
11309 (or (save-excursion (org-get-next-sibling))
11310 (org-end-of-subtree t t)
11311 (point-max)))))
11312 (setq level 1)
11313 (if (not reversed)
11314 (goto-char (point-max))
11315 (goto-char (point-min))
11316 (or (outline-next-heading) (goto-char (point-max)))))
11317 (if (not (bolp)) (newline))
11318 (org-paste-subtree level)
11319 (when org-log-refile
11320 (org-add-log-setup 'refile nil nil 'findpos
11321 org-log-refile)
11322 (unless (eq org-log-refile 'note)
11323 (save-excursion (org-add-log-note))))
11324 (and org-auto-align-tags
11325 (let ((org-loop-over-headlines-in-active-region nil))
11326 (org-set-tags nil t)))
11327 (with-demoted-errors
11328 (bookmark-set "org-refile-last-stored"))
11329 ;; If we are refiling for capture, make sure that the
11330 ;; last-capture pointers point here
11331 (when (org-bound-and-true-p org-refile-for-capture)
11332 (with-demoted-errors
11333 (bookmark-set "org-capture-last-stored-marker"))
11334 (move-marker org-capture-last-stored-marker (point)))
11335 (if (fboundp 'deactivate-mark) (deactivate-mark))
11336 (run-hooks 'org-after-refile-insert-hook))))
11337 (unless org-refile-keep
11338 (if regionp
11339 (delete-region (point) (+ (point) region-length))
11340 (org-cut-subtree)))
11341 (when (featurep 'org-inlinetask)
11342 (org-inlinetask-remove-END-maybe))
11343 (setq org-markers-to-move nil)
11344 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11346 (defun org-refile-goto-last-stored ()
11347 "Go to the location where the last refile was stored."
11348 (interactive)
11349 (bookmark-jump "org-refile-last-stored")
11350 (message "This is the location of the last refile"))
11352 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11353 no-exclude)
11354 "Prompt the user for a refile location, using PROMPT.
11355 PROMPT should not be suffixed with a colon and a space, because
11356 this function appends the default value from
11357 `org-refile-history' automatically, if that is not empty.
11358 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11359 this is used for the GOTO interface."
11360 (let ((org-refile-targets org-refile-targets)
11361 (org-refile-use-outline-path org-refile-use-outline-path)
11362 excluded-entries)
11363 (when (and (derived-mode-p 'org-mode)
11364 (not org-refile-use-cache)
11365 (not no-exclude))
11366 (org-map-tree
11367 (lambda()
11368 (setq excluded-entries
11369 (append excluded-entries (list (org-get-heading t t)))))))
11370 (setq org-refile-target-table
11371 (org-refile-get-targets default-buffer excluded-entries)))
11372 (unless org-refile-target-table
11373 (error "No refile targets"))
11374 (let* ((cbuf (current-buffer))
11375 (partial-completion-mode nil)
11376 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11377 (cfunc (if (and org-refile-use-outline-path
11378 org-outline-path-complete-in-steps)
11379 'org-olpath-completing-read
11380 'org-icompleting-read))
11381 (extra (if org-refile-use-outline-path "/" ""))
11382 (cbnex (concat (buffer-name) extra))
11383 (filename (and cfn (expand-file-name cfn)))
11384 (tbl (mapcar
11385 (lambda (x)
11386 (if (and (not (member org-refile-use-outline-path
11387 '(file full-file-path)))
11388 (not (equal filename (nth 1 x))))
11389 (cons (concat (car x) extra " ("
11390 (file-name-nondirectory (nth 1 x)) ")")
11391 (cdr x))
11392 (cons (concat (car x) extra) (cdr x))))
11393 org-refile-target-table))
11394 (completion-ignore-case t)
11395 cdef
11396 (prompt (concat prompt
11397 (or (and (car org-refile-history)
11398 (concat " (default " (car org-refile-history) ")"))
11399 (and (assoc cbnex tbl) (setq cdef cbnex)
11400 (concat " (default " cbnex ")"))) ": "))
11401 pa answ parent-target child parent old-hist)
11402 (setq old-hist org-refile-history)
11403 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11404 nil 'org-refile-history (or cdef (car org-refile-history))))
11405 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11406 (org-refile-check-position pa)
11407 (if pa
11408 (progn
11409 (when (or (not org-refile-history)
11410 (not (eq old-hist org-refile-history))
11411 (not (equal (car pa) (car org-refile-history))))
11412 (setq org-refile-history
11413 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11414 org-refile-history
11415 (cdr org-refile-history))))
11416 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11417 (pop org-refile-history)))
11419 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11420 (progn
11421 (setq parent (match-string 1 answ)
11422 child (match-string 2 answ))
11423 (setq parent-target (or (assoc parent tbl)
11424 (assoc (concat parent "/") tbl)))
11425 (when (and parent-target
11426 (or (eq new-nodes t)
11427 (and (eq new-nodes 'confirm)
11428 (y-or-n-p (format "Create new node \"%s\"? "
11429 child)))))
11430 (org-refile-new-child parent-target child)))
11431 (error "Invalid target location")))))
11433 (declare-function org-string-nw-p "org-macs" (s))
11434 (defun org-refile-check-position (refile-pointer)
11435 "Check if the refile pointer matches the headline to which it points."
11436 (let* ((file (nth 1 refile-pointer))
11437 (re (nth 2 refile-pointer))
11438 (pos (nth 3 refile-pointer))
11439 buffer)
11440 (if (and (not (markerp pos)) (not file))
11441 (error "Please save the buffer to a file before refiling")
11442 (when (org-string-nw-p re)
11443 (setq buffer (if (markerp pos)
11444 (marker-buffer pos)
11445 (or (find-buffer-visiting file)
11446 (find-file-noselect file))))
11447 (with-current-buffer buffer
11448 (save-excursion
11449 (save-restriction
11450 (widen)
11451 (goto-char pos)
11452 (beginning-of-line 1)
11453 (unless (org-looking-at-p re)
11454 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11456 (defun org-refile-new-child (parent-target child)
11457 "Use refile target PARENT-TARGET to add new CHILD below it."
11458 (unless parent-target
11459 (error "Cannot find parent for new node"))
11460 (let ((file (nth 1 parent-target))
11461 (pos (nth 3 parent-target))
11462 level)
11463 (with-current-buffer (or (find-buffer-visiting file)
11464 (find-file-noselect file))
11465 (save-excursion
11466 (save-restriction
11467 (widen)
11468 (if pos
11469 (goto-char pos)
11470 (goto-char (point-max))
11471 (if (not (bolp)) (newline)))
11472 (when (looking-at org-outline-regexp)
11473 (setq level (funcall outline-level))
11474 (org-end-of-subtree t t))
11475 (org-back-over-empty-lines)
11476 (insert "\n" (make-string
11477 (if pos (org-get-valid-level level 1) 1) ?*)
11478 " " child "\n")
11479 (beginning-of-line 0)
11480 (list (concat (car parent-target) "/" child) file "" (point)))))))
11482 (defun org-olpath-completing-read (prompt collection &rest args)
11483 "Read an outline path like a file name."
11484 (let ((thetable collection)
11485 (org-completion-use-ido nil) ; does not work with ido.
11486 (org-completion-use-iswitchb nil)) ; or iswitchb
11487 (apply
11488 'org-icompleting-read prompt
11489 (lambda (string predicate &optional flag)
11490 (let (rtn r f (l (length string)))
11491 (cond
11492 ((eq flag nil)
11493 ;; try completion
11494 (try-completion string thetable))
11495 ((eq flag t)
11496 ;; all-completions
11497 (setq rtn (all-completions string thetable predicate))
11498 (mapcar
11499 (lambda (x)
11500 (setq r (substring x l))
11501 (if (string-match " ([^)]*)$" x)
11502 (setq f (match-string 0 x))
11503 (setq f ""))
11504 (if (string-match "/" r)
11505 (concat string (substring r 0 (match-end 0)) f)
11507 rtn))
11508 ((eq flag 'lambda)
11509 ;; exact match?
11510 (assoc string thetable)))))
11511 args)))
11513 ;;;; Dynamic blocks
11515 (defun org-find-dblock (name)
11516 "Find the first dynamic block with name NAME in the buffer.
11517 If not found, stay at current position and return nil."
11518 (let ((case-fold-search t) pos)
11519 (save-excursion
11520 (goto-char (point-min))
11521 (setq pos (and (re-search-forward
11522 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11523 (match-beginning 0))))
11524 (if pos (goto-char pos))
11525 pos))
11527 (defconst org-dblock-start-re
11528 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11529 "Matches the start line of a dynamic block, with parameters.")
11531 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11532 "Matches the end of a dynamic block.")
11534 (defun org-create-dblock (plist)
11535 "Create a dynamic block section, with parameters taken from PLIST.
11536 PLIST must contain a :name entry which is used as name of the block."
11537 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11538 (end-of-line 1)
11539 (newline))
11540 (let ((col (current-column))
11541 (name (plist-get plist :name)))
11542 (insert "#+BEGIN: " name)
11543 (while plist
11544 (if (eq (car plist) :name)
11545 (setq plist (cddr plist))
11546 (insert " " (prin1-to-string (pop plist)))))
11547 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11548 (beginning-of-line -2)))
11550 (defun org-prepare-dblock ()
11551 "Prepare dynamic block for refresh.
11552 This empties the block, puts the cursor at the insert position and returns
11553 the property list including an extra property :name with the block name."
11554 (unless (looking-at org-dblock-start-re)
11555 (error "Not at a dynamic block"))
11556 (let* ((begdel (1+ (match-end 0)))
11557 (name (org-no-properties (match-string 1)))
11558 (params (append (list :name name)
11559 (read (concat "(" (match-string 3) ")")))))
11560 (save-excursion
11561 (beginning-of-line 1)
11562 (skip-chars-forward " \t")
11563 (setq params (plist-put params :indentation-column (current-column))))
11564 (unless (re-search-forward org-dblock-end-re nil t)
11565 (error "Dynamic block not terminated"))
11566 (setq params
11567 (append params
11568 (list :content (buffer-substring
11569 begdel (match-beginning 0)))))
11570 (delete-region begdel (match-beginning 0))
11571 (goto-char begdel)
11572 (open-line 1)
11573 params))
11575 (defun org-map-dblocks (&optional command)
11576 "Apply COMMAND to all dynamic blocks in the current buffer.
11577 If COMMAND is not given, use `org-update-dblock'."
11578 (let ((cmd (or command 'org-update-dblock)))
11579 (save-excursion
11580 (goto-char (point-min))
11581 (while (re-search-forward org-dblock-start-re nil t)
11582 (goto-char (match-beginning 0))
11583 (save-excursion
11584 (condition-case nil
11585 (funcall cmd)
11586 (error (message "Error during update of dynamic block"))))
11587 (unless (re-search-forward org-dblock-end-re nil t)
11588 (error "Dynamic block not terminated"))))))
11590 (defun org-dblock-update (&optional arg)
11591 "User command for updating dynamic blocks.
11592 Update the dynamic block at point. With prefix ARG, update all dynamic
11593 blocks in the buffer."
11594 (interactive "P")
11595 (if arg
11596 (org-update-all-dblocks)
11597 (or (looking-at org-dblock-start-re)
11598 (org-beginning-of-dblock))
11599 (org-update-dblock)))
11601 (defun org-update-dblock ()
11602 "Update the dynamic block at point.
11603 This means to empty the block, parse for parameters and then call
11604 the correct writing function."
11605 (interactive)
11606 (save-window-excursion
11607 (let* ((pos (point))
11608 (line (org-current-line))
11609 (params (org-prepare-dblock))
11610 (name (plist-get params :name))
11611 (indent (plist-get params :indentation-column))
11612 (cmd (intern (concat "org-dblock-write:" name))))
11613 (message "Updating dynamic block `%s' at line %d..." name line)
11614 (funcall cmd params)
11615 (message "Updating dynamic block `%s' at line %d...done" name line)
11616 (goto-char pos)
11617 (when (and indent (> indent 0))
11618 (setq indent (make-string indent ?\ ))
11619 (save-excursion
11620 (org-beginning-of-dblock)
11621 (forward-line 1)
11622 (while (not (looking-at org-dblock-end-re))
11623 (insert indent)
11624 (beginning-of-line 2))
11625 (when (looking-at org-dblock-end-re)
11626 (and (looking-at "[ \t]+")
11627 (replace-match ""))
11628 (insert indent)))))))
11630 (defun org-beginning-of-dblock ()
11631 "Find the beginning of the dynamic block at point.
11632 Error if there is no such block at point."
11633 (let ((pos (point))
11634 beg)
11635 (end-of-line 1)
11636 (if (and (re-search-backward org-dblock-start-re nil t)
11637 (setq beg (match-beginning 0))
11638 (re-search-forward org-dblock-end-re nil t)
11639 (> (match-end 0) pos))
11640 (goto-char beg)
11641 (goto-char pos)
11642 (error "Not in a dynamic block"))))
11644 (defun org-update-all-dblocks ()
11645 "Update all dynamic blocks in the buffer.
11646 This function can be used in a hook."
11647 (interactive)
11648 (when (derived-mode-p 'org-mode)
11649 (org-map-dblocks 'org-update-dblock)))
11652 ;;;; Completion
11654 (defun org-get-export-keywords ()
11655 "Return a list of all currently understood export keywords.
11656 Export keywords include options, block names, attributes and
11657 keywords relative to each registered export back-end."
11658 (delq nil
11659 (let (keywords)
11660 (mapc
11661 (lambda (back-end)
11662 (let ((props (cdr back-end)))
11663 ;; Back-end name (for keywords, like #+LATEX:)
11664 (push (upcase (symbol-name (car back-end))) keywords)
11665 ;; Back-end options.
11666 (mapc (lambda (option) (push (cadr option) keywords))
11667 (plist-get (cdr back-end) :options-alist))))
11668 (org-bound-and-true-p org-export-registered-backends))
11669 keywords)))
11671 (defconst org-options-keywords
11672 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11673 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11674 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11675 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11676 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11678 (defcustom org-structure-template-alist
11679 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11680 "<src lang=\"?\">\n\n</src>")
11681 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11682 "<example>\n?\n</example>")
11683 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11684 "<quote>\n?\n</quote>")
11685 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11686 "<verse>\n?\n</verse>")
11687 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11688 "<verbatim>\n?\n</verbatim>")
11689 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11690 "<center>\n?\n</center>")
11691 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11692 "<literal style=\"latex\">\n?\n</literal>")
11693 ("L" "#+LaTeX: "
11694 "<literal style=\"latex\">?</literal>")
11695 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11696 "<literal style=\"html\">\n?\n</literal>")
11697 ("H" "#+HTML: "
11698 "<literal style=\"html\">?</literal>")
11699 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11700 ("A" "#+ASCII: ")
11701 ("i" "#+INDEX: ?"
11702 "#+INDEX: ?")
11703 ("I" "#+INCLUDE: %file ?"
11704 "<include file=%file markup=\"?\">"))
11705 "Structure completion elements.
11706 This is a list of abbreviation keys and values. The value gets inserted
11707 if you type `<' followed by the key and then press the completion key,
11708 usually `M-TAB'. %file will be replaced by a file name after prompting
11709 for the file using completion. The cursor will be placed at the position
11710 of the `?` in the template.
11711 There are two templates for each key, the first uses the original Org syntax,
11712 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11713 the default when the /org-mtags.el/ module has been loaded. See also the
11714 variable `org-mtags-prefer-muse-templates'."
11715 :group 'org-completion
11716 :type '(repeat
11717 (string :tag "Key")
11718 (string :tag "Template")
11719 (string :tag "Muse Template")))
11721 (defun org-try-structure-completion ()
11722 "Try to complete a structure template before point.
11723 This looks for strings like \"<e\" on an otherwise empty line and
11724 expands them."
11725 (let ((l (buffer-substring (point-at-bol) (point)))
11727 (when (and (looking-at "[ \t]*$")
11728 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11729 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11730 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11731 (match-beginning 1)) a)
11732 t)))
11734 (defun org-complete-expand-structure-template (start cell)
11735 "Expand a structure template."
11736 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11737 (rpl (nth (if musep 2 1) cell))
11738 (ind ""))
11739 (delete-region start (point))
11740 (when (string-match "\\`#\\+" rpl)
11741 (cond
11742 ((bolp))
11743 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11744 (setq ind (buffer-substring (point-at-bol) (point))))
11745 (t (newline))))
11746 (setq start (point))
11747 (if (string-match "%file" rpl)
11748 (setq rpl (replace-match
11749 (concat
11750 "\""
11751 (save-match-data
11752 (abbreviate-file-name (read-file-name "Include file: ")))
11753 "\"")
11754 t t rpl)))
11755 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11756 (concat "\n" ind)))
11757 (insert rpl)
11758 (if (re-search-backward "\\?" start t) (delete-char 1))))
11760 ;;;; TODO, DEADLINE, Comments
11762 (defun org-toggle-comment ()
11763 "Change the COMMENT state of an entry."
11764 (interactive)
11765 (save-excursion
11766 (org-back-to-heading)
11767 (let (case-fold-search)
11768 (cond
11769 ((looking-at (format org-heading-keyword-regexp-format
11770 org-comment-string))
11771 (goto-char (match-end 1))
11772 (looking-at (concat " +" org-comment-string))
11773 (replace-match "" t t)
11774 (when (eolp) (insert " ")))
11775 ((looking-at org-outline-regexp)
11776 (goto-char (match-end 0))
11777 (insert org-comment-string " "))))))
11779 (defvar org-last-todo-state-is-todo nil
11780 "This is non-nil when the last TODO state change led to a TODO state.
11781 If the last change removed the TODO tag or switched to DONE, then
11782 this is nil.")
11784 (defvar org-setting-tags nil) ; dynamically skipped
11786 (defvar org-todo-setup-filter-hook nil
11787 "Hook for functions that pre-filter todo specs.
11788 Each function takes a todo spec and returns either nil or the spec
11789 transformed into canonical form." )
11791 (defvar org-todo-get-default-hook nil
11792 "Hook for functions that get a default item for todo.
11793 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11794 nil or a string to be used for the todo mark." )
11796 (defvar org-agenda-headline-snapshot-before-repeat)
11798 (defun org-current-effective-time ()
11799 "Return current time adjusted for `org-extend-today-until' variable."
11800 (let* ((ct (org-current-time))
11801 (dct (decode-time ct))
11802 (ct1
11803 (cond
11804 (org-use-last-clock-out-time-as-effective-time
11805 (or (org-clock-get-last-clock-out-time) ct))
11806 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11807 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11808 (t ct))))
11809 ct1))
11811 (defun org-todo-yesterday (&optional arg)
11812 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11813 (interactive "P")
11814 (if (eq major-mode 'org-agenda-mode)
11815 (apply 'org-agenda-todo-yesterday arg)
11816 (let* ((hour (third (decode-time
11817 (org-current-time))))
11818 (org-extend-today-until (1+ hour)))
11819 (org-todo arg))))
11821 (defvar org-block-entry-blocking ""
11822 "First entry preventing the TODO state change.")
11824 (defun org-todo (&optional arg)
11825 "Change the TODO state of an item.
11826 The state of an item is given by a keyword at the start of the heading,
11827 like
11828 *** TODO Write paper
11829 *** DONE Call mom
11831 The different keywords are specified in the variable `org-todo-keywords'.
11832 By default the available states are \"TODO\" and \"DONE\".
11833 So for this example: when the item starts with TODO, it is changed to DONE.
11834 When it starts with DONE, the DONE is removed. And when neither TODO nor
11835 DONE are present, add TODO at the beginning of the heading.
11837 With \\[universal-argument] prefix arg, use completion to determine the new \
11838 state.
11839 With numeric prefix arg, switch to that state.
11840 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11841 keywords (nextset).
11842 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11843 With a numeric prefix arg of 0, inhibit note taking for the change.
11845 For calling through lisp, arg is also interpreted in the following way:
11846 'none -> empty state
11847 \"\"(empty string) -> switch to empty state
11848 'done -> switch to DONE
11849 'nextset -> switch to the next set of keywords
11850 'previousset -> switch to the previous set of keywords
11851 \"WAITING\" -> switch to the specified keyword, but only if it
11852 really is a member of `org-todo-keywords'."
11853 (interactive "P")
11854 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11855 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11856 'region-start-level 'region))
11857 org-loop-over-headlines-in-active-region)
11858 (org-map-entries
11859 `(org-todo ,arg)
11860 org-loop-over-headlines-in-active-region
11861 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11862 (if (equal arg '(16)) (setq arg 'nextset))
11863 (let ((org-blocker-hook org-blocker-hook)
11864 commentp
11865 case-fold-search)
11866 (when (equal arg '(64))
11867 (setq arg nil org-blocker-hook nil))
11868 (when (and org-blocker-hook
11869 (or org-inhibit-blocking
11870 (org-entry-get nil "NOBLOCKING")))
11871 (setq org-blocker-hook nil))
11872 (save-excursion
11873 (catch 'exit
11874 (org-back-to-heading t)
11875 (when (looking-at (concat "^\\*+ " org-comment-string))
11876 (org-toggle-comment)
11877 (setq commentp t))
11878 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11879 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11880 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11881 (let* ((match-data (match-data))
11882 (startpos (point-at-bol))
11883 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11884 (org-log-done org-log-done)
11885 (org-log-repeat org-log-repeat)
11886 (org-todo-log-states org-todo-log-states)
11887 (org-inhibit-logging
11888 (if (equal arg 0)
11889 (progn (setq arg nil) 'note) org-inhibit-logging))
11890 (this (match-string 1))
11891 (hl-pos (match-beginning 0))
11892 (head (org-get-todo-sequence-head this))
11893 (ass (assoc head org-todo-kwd-alist))
11894 (interpret (nth 1 ass))
11895 (done-word (nth 3 ass))
11896 (final-done-word (nth 4 ass))
11897 (org-last-state (or this ""))
11898 (completion-ignore-case t)
11899 (member (member this org-todo-keywords-1))
11900 (tail (cdr member))
11901 (org-state (cond
11902 ((and org-todo-key-trigger
11903 (or (and (equal arg '(4))
11904 (eq org-use-fast-todo-selection 'prefix))
11905 (and (not arg) org-use-fast-todo-selection
11906 (not (eq org-use-fast-todo-selection
11907 'prefix)))))
11908 ;; Use fast selection
11909 (org-fast-todo-selection))
11910 ((and (equal arg '(4))
11911 (or (not org-use-fast-todo-selection)
11912 (not org-todo-key-trigger)))
11913 ;; Read a state with completion
11914 (org-icompleting-read
11915 "State: " (mapcar (lambda(x) (list x))
11916 org-todo-keywords-1)
11917 nil t))
11918 ((eq arg 'right)
11919 (if this
11920 (if tail (car tail) nil)
11921 (car org-todo-keywords-1)))
11922 ((eq arg 'left)
11923 (if (equal member org-todo-keywords-1)
11925 (if this
11926 (nth (- (length org-todo-keywords-1)
11927 (length tail) 2)
11928 org-todo-keywords-1)
11929 (org-last org-todo-keywords-1))))
11930 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11931 (setq arg nil))) ; hack to fall back to cycling
11932 (arg
11933 ;; user or caller requests a specific state
11934 (cond
11935 ((equal arg "") nil)
11936 ((eq arg 'none) nil)
11937 ((eq arg 'done) (or done-word (car org-done-keywords)))
11938 ((eq arg 'nextset)
11939 (or (car (cdr (member head org-todo-heads)))
11940 (car org-todo-heads)))
11941 ((eq arg 'previousset)
11942 (let ((org-todo-heads (reverse org-todo-heads)))
11943 (or (car (cdr (member head org-todo-heads)))
11944 (car org-todo-heads))))
11945 ((car (member arg org-todo-keywords-1)))
11946 ((stringp arg)
11947 (error "State `%s' not valid in this file" arg))
11948 ((nth (1- (prefix-numeric-value arg))
11949 org-todo-keywords-1))))
11950 ((null member) (or head (car org-todo-keywords-1)))
11951 ((equal this final-done-word) nil) ;; -> make empty
11952 ((null tail) nil) ;; -> first entry
11953 ((memq interpret '(type priority))
11954 (if (eq this-command last-command)
11955 (car tail)
11956 (if (> (length tail) 0)
11957 (or done-word (car org-done-keywords))
11958 nil)))
11960 (car tail))))
11961 (org-state (or
11962 (run-hook-with-args-until-success
11963 'org-todo-get-default-hook org-state org-last-state)
11964 org-state))
11965 (next (if org-state (concat " " org-state " ") " "))
11966 (change-plist (list :type 'todo-state-change :from this :to org-state
11967 :position startpos))
11968 dolog now-done-p)
11969 (when org-blocker-hook
11970 (setq org-last-todo-state-is-todo
11971 (not (member this org-done-keywords)))
11972 (unless (save-excursion
11973 (save-match-data
11974 (org-with-wide-buffer
11975 (run-hook-with-args-until-failure
11976 'org-blocker-hook change-plist))))
11977 (if (org-called-interactively-p 'interactive)
11978 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11979 this org-state org-block-entry-blocking)
11980 ;; fail silently
11981 (message "TODO state change from %s to %s blocked (by \"%s\")"
11982 this org-state org-block-entry-blocking)
11983 (throw 'exit nil))))
11984 (store-match-data match-data)
11985 (replace-match next t t)
11986 (unless (pos-visible-in-window-p hl-pos)
11987 (message "TODO state changed to %s" (org-trim next)))
11988 (unless head
11989 (setq head (org-get-todo-sequence-head org-state)
11990 ass (assoc head org-todo-kwd-alist)
11991 interpret (nth 1 ass)
11992 done-word (nth 3 ass)
11993 final-done-word (nth 4 ass)))
11994 (when (memq arg '(nextset previousset))
11995 (message "Keyword-Set %d/%d: %s"
11996 (- (length org-todo-sets) -1
11997 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11998 (length org-todo-sets)
11999 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12000 (setq org-last-todo-state-is-todo
12001 (not (member org-state org-done-keywords)))
12002 (setq now-done-p (and (member org-state org-done-keywords)
12003 (not (member this org-done-keywords))))
12004 (and logging (org-local-logging logging))
12005 (when (and (or org-todo-log-states org-log-done)
12006 (not (eq org-inhibit-logging t))
12007 (not (memq arg '(nextset previousset))))
12008 ;; we need to look at recording a time and note
12009 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12010 (nth 2 (assoc this org-todo-log-states))))
12011 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12012 (setq dolog 'time))
12013 (when (and org-state
12014 (member org-state org-not-done-keywords)
12015 (not (member this org-not-done-keywords)))
12016 ;; This is now a todo state and was not one before
12017 ;; If there was a CLOSED time stamp, get rid of it.
12018 (org-add-planning-info nil nil 'closed))
12019 (when (and now-done-p org-log-done)
12020 ;; It is now done, and it was not done before
12021 (org-add-planning-info 'closed (org-current-effective-time))
12022 (if (and (not dolog) (eq 'note org-log-done))
12023 (org-add-log-setup 'done org-state this 'findpos 'note)))
12024 (when (and org-state dolog)
12025 ;; This is a non-nil state, and we need to log it
12026 (org-add-log-setup 'state org-state this 'findpos dolog)))
12027 ;; Fixup tag positioning
12028 (org-todo-trigger-tag-changes org-state)
12029 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12030 (when org-provide-todo-statistics
12031 (org-update-parent-todo-statistics))
12032 (run-hooks 'org-after-todo-state-change-hook)
12033 (if (and arg (not (member org-state org-done-keywords)))
12034 (setq head (org-get-todo-sequence-head org-state)))
12035 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12036 ;; Do we need to trigger a repeat?
12037 (when now-done-p
12038 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12039 ;; This is for the agenda, take a snapshot of the headline.
12040 (save-match-data
12041 (setq org-agenda-headline-snapshot-before-repeat
12042 (org-get-heading))))
12043 (org-auto-repeat-maybe org-state))
12044 ;; Fixup cursor location if close to the keyword
12045 (if (and (outline-on-heading-p)
12046 (not (bolp))
12047 (save-excursion (beginning-of-line 1)
12048 (looking-at org-todo-line-regexp))
12049 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12050 (progn
12051 (goto-char (or (match-end 2) (match-end 1)))
12052 (and (looking-at " ") (just-one-space))))
12053 (when org-trigger-hook
12054 (save-excursion
12055 (run-hook-with-args 'org-trigger-hook change-plist)))
12056 (when commentp (org-toggle-comment))))))))
12058 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12059 "Block turning an entry into a TODO, using the hierarchy.
12060 This checks whether the current task should be blocked from state
12061 changes. Such blocking occurs when:
12063 1. The task has children which are not all in a completed state.
12065 2. A task has a parent with the property :ORDERED:, and there
12066 are siblings prior to the current task with incomplete
12067 status.
12069 3. The parent of the task is blocked because it has siblings that should
12070 be done first, or is child of a block grandparent TODO entry."
12072 (if (not org-enforce-todo-dependencies)
12073 t ; if locally turned off don't block
12074 (catch 'dont-block
12075 ;; If this is not a todo state change, or if this entry is already DONE,
12076 ;; do not block
12077 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12078 (member (plist-get change-plist :from)
12079 (cons 'done org-done-keywords))
12080 (member (plist-get change-plist :to)
12081 (cons 'todo org-not-done-keywords))
12082 (not (plist-get change-plist :to)))
12083 (throw 'dont-block t))
12084 ;; If this task has children, and any are undone, it's blocked
12085 (save-excursion
12086 (org-back-to-heading t)
12087 (let ((this-level (funcall outline-level)))
12088 (outline-next-heading)
12089 (let ((child-level (funcall outline-level)))
12090 (while (and (not (eobp))
12091 (> child-level this-level))
12092 ;; this todo has children, check whether they are all
12093 ;; completed
12094 (if (and (not (org-entry-is-done-p))
12095 (org-entry-is-todo-p))
12096 (progn (setq org-block-entry-blocking (org-get-heading))
12097 (throw 'dont-block nil)))
12098 (outline-next-heading)
12099 (setq child-level (funcall outline-level))))))
12100 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12101 ;; any previous siblings are undone, it's blocked
12102 (save-excursion
12103 (org-back-to-heading t)
12104 (let* ((pos (point))
12105 (parent-pos (and (org-up-heading-safe) (point))))
12106 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12107 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12108 (forward-line 1)
12109 (re-search-forward org-not-done-heading-regexp pos t))
12110 (setq org-block-entry-blocking (match-string 0))
12111 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12112 ;; Search further up the hierarchy, to see if an ancestor is blocked
12113 (while t
12114 (goto-char parent-pos)
12115 (if (not (looking-at org-not-done-heading-regexp))
12116 (throw 'dont-block t)) ; do not block, parent is not a TODO
12117 (setq pos (point))
12118 (setq parent-pos (and (org-up-heading-safe) (point)))
12119 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12120 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12121 (forward-line 1)
12122 (re-search-forward org-not-done-heading-regexp pos t)
12123 (setq org-block-entry-blocking (org-get-heading)))
12124 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12126 (defcustom org-track-ordered-property-with-tag nil
12127 "Should the ORDERED property also be shown as a tag?
12128 The ORDERED property decides if an entry should require subtasks to be
12129 completed in sequence. Since a property is not very visible, setting
12130 this option means that toggling the ORDERED property with the command
12131 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12132 not relevant for the behavior, but it makes things more visible.
12134 Note that toggling the tag with tags commands will not change the property
12135 and therefore not influence behavior!
12137 This can be t, meaning the tag ORDERED should be used, It can also be a
12138 string to select a different tag for this task."
12139 :group 'org-todo
12140 :type '(choice
12141 (const :tag "No tracking" nil)
12142 (const :tag "Track with ORDERED tag" t)
12143 (string :tag "Use other tag")))
12145 (defun org-toggle-ordered-property ()
12146 "Toggle the ORDERED property of the current entry.
12147 For better visibility, you can track the value of this property with a tag.
12148 See variable `org-track-ordered-property-with-tag'."
12149 (interactive)
12150 (let* ((t1 org-track-ordered-property-with-tag)
12151 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12152 (save-excursion
12153 (org-back-to-heading)
12154 (if (org-entry-get nil "ORDERED")
12155 (progn
12156 (org-delete-property "ORDERED" "PROPERTIES")
12157 (and tag (org-toggle-tag tag 'off))
12158 (message "Subtasks can be completed in arbitrary order"))
12159 (org-entry-put nil "ORDERED" "t")
12160 (and tag (org-toggle-tag tag 'on))
12161 (message "Subtasks must be completed in sequence")))))
12163 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12164 (defun org-block-todo-from-checkboxes (change-plist)
12165 "Block turning an entry into a TODO, using checkboxes.
12166 This checks whether the current task should be blocked from state
12167 changes because there are unchecked boxes in this entry."
12168 (if (not org-enforce-todo-checkbox-dependencies)
12169 t ; if locally turned off don't block
12170 (catch 'dont-block
12171 ;; If this is not a todo state change, or if this entry is already DONE,
12172 ;; do not block
12173 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12174 (member (plist-get change-plist :from)
12175 (cons 'done org-done-keywords))
12176 (member (plist-get change-plist :to)
12177 (cons 'todo org-not-done-keywords))
12178 (not (plist-get change-plist :to)))
12179 (throw 'dont-block t))
12180 ;; If this task has checkboxes that are not checked, it's blocked
12181 (save-excursion
12182 (org-back-to-heading t)
12183 (let ((beg (point)) end)
12184 (outline-next-heading)
12185 (setq end (point))
12186 (goto-char beg)
12187 (if (org-list-search-forward
12188 (concat (org-item-beginning-re)
12189 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12190 "\\[[- ]\\]")
12191 end t)
12192 (progn
12193 (if (boundp 'org-blocked-by-checkboxes)
12194 (setq org-blocked-by-checkboxes t))
12195 (throw 'dont-block nil)))))
12196 t))) ; do not block
12198 (defun org-entry-blocked-p ()
12199 "Is the current entry blocked?"
12200 (org-with-silent-modifications
12201 (if (org-entry-get nil "NOBLOCKING")
12202 nil ;; Never block this entry
12203 (not (run-hook-with-args-until-failure
12204 'org-blocker-hook
12205 (list :type 'todo-state-change
12206 :position (point)
12207 :from 'todo
12208 :to 'done))))))
12210 (defun org-update-statistics-cookies (all)
12211 "Update the statistics cookie, either from TODO or from checkboxes.
12212 This should be called with the cursor in a line with a statistics cookie."
12213 (interactive "P")
12214 (if all
12215 (progn
12216 (org-update-checkbox-count 'all)
12217 (org-map-entries 'org-update-parent-todo-statistics))
12218 (if (not (org-at-heading-p))
12219 (org-update-checkbox-count)
12220 (let ((pos (point-marker))
12221 end l1 l2)
12222 (ignore-errors (org-back-to-heading t))
12223 (if (not (org-at-heading-p))
12224 (org-update-checkbox-count)
12225 (setq l1 (org-outline-level))
12226 (setq end (save-excursion
12227 (outline-next-heading)
12228 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12229 (point)))
12230 (if (and (save-excursion
12231 (re-search-forward
12232 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12233 (not (save-excursion (re-search-forward
12234 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12235 (org-update-checkbox-count)
12236 (if (and l2 (> l2 l1))
12237 (progn
12238 (goto-char end)
12239 (org-update-parent-todo-statistics))
12240 (goto-char pos)
12241 (beginning-of-line 1)
12242 (while (re-search-forward
12243 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12244 (point-at-eol) t)
12245 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12246 (goto-char pos)
12247 (move-marker pos nil)))))
12249 (defvar org-entry-property-inherited-from) ;; defined below
12250 (defun org-update-parent-todo-statistics ()
12251 "Update any statistics cookie in the parent of the current headline.
12252 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12253 the entire subtree and this will travel up the hierarchy and update
12254 statistics everywhere."
12255 (let* ((prop (save-excursion (org-up-heading-safe)
12256 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12257 (recursive (or (not org-hierarchical-todo-statistics)
12258 (and prop (string-match "\\<recursive\\>" prop))))
12259 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12261 (first t)
12262 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12263 level ltoggle l1 new ndel
12264 (cnt-all 0) (cnt-done 0) is-percent kwd
12265 checkbox-beg ov ovs ove cookie-present)
12266 (catch 'exit
12267 (save-excursion
12268 (beginning-of-line 1)
12269 (setq ltoggle (funcall outline-level))
12270 ;; Three situations are to consider:
12272 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12273 ;; to the top-level ancestor on the headline;
12275 ;; 2. If parent has "recursive" property, repeat up to the
12276 ;; headline setting that property, taking inheritance into
12277 ;; account;
12279 ;; 3. Else, move up to direct parent and proceed only once.
12280 (while (and (setq level (org-up-heading-safe))
12281 (or recursive first)
12282 (>= (point) lim))
12283 (setq first nil cookie-present nil)
12284 (unless (and level
12285 (not (string-match
12286 "\\<checkbox\\>"
12287 (downcase (or (org-entry-get nil "COOKIE_DATA")
12288 "")))))
12289 (throw 'exit nil))
12290 (while (re-search-forward box-re (point-at-eol) t)
12291 (setq cnt-all 0 cnt-done 0 cookie-present t)
12292 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12293 (save-match-data
12294 (unless (outline-next-heading) (throw 'exit nil))
12295 (while (and (looking-at org-complex-heading-regexp)
12296 (> (setq l1 (length (match-string 1))) level))
12297 (setq kwd (and (or recursive (= l1 ltoggle))
12298 (match-string 2)))
12299 (if (or (eq org-provide-todo-statistics 'all-headlines)
12300 (and (listp org-provide-todo-statistics)
12301 (or (member kwd org-provide-todo-statistics)
12302 (member kwd org-done-keywords))))
12303 (setq cnt-all (1+ cnt-all))
12304 (if (eq org-provide-todo-statistics t)
12305 (and kwd (setq cnt-all (1+ cnt-all)))))
12306 (and (member kwd org-done-keywords)
12307 (setq cnt-done (1+ cnt-done)))
12308 (outline-next-heading)))
12309 (setq new
12310 (if is-percent
12311 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12312 (format "[%d/%d]" cnt-done cnt-all))
12313 ndel (- (match-end 0) checkbox-beg))
12314 ;; handle overlays when updating cookie from column view
12315 (when (setq ov (car (overlays-at checkbox-beg)))
12316 (setq ovs (overlay-start ov) ove (overlay-end ov))
12317 (delete-overlay ov))
12318 (goto-char checkbox-beg)
12319 (insert new)
12320 (delete-region (point) (+ (point) ndel))
12321 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12322 (when ov (move-overlay ov ovs ove)))
12323 (when cookie-present
12324 (run-hook-with-args 'org-after-todo-statistics-hook
12325 cnt-done (- cnt-all cnt-done))))))
12326 (run-hooks 'org-todo-statistics-hook)))
12328 (defvar org-after-todo-statistics-hook nil
12329 "Hook that is called after a TODO statistics cookie has been updated.
12330 Each function is called with two arguments: the number of not-done entries
12331 and the number of done entries.
12333 For example, the following function, when added to this hook, will switch
12334 an entry to DONE when all children are done, and back to TODO when new
12335 entries are set to a TODO status. Note that this hook is only called
12336 when there is a statistics cookie in the headline!
12338 (defun org-summary-todo (n-done n-not-done)
12339 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12340 (let (org-log-done org-log-states) ; turn off logging
12341 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12344 (defvar org-todo-statistics-hook nil
12345 "Hook that is run whenever Org thinks TODO statistics should be updated.
12346 This hook runs even if there is no statistics cookie present, in which case
12347 `org-after-todo-statistics-hook' would not run.")
12349 (defun org-todo-trigger-tag-changes (state)
12350 "Apply the changes defined in `org-todo-state-tags-triggers'."
12351 (let ((l org-todo-state-tags-triggers)
12352 changes)
12353 (when (or (not state) (equal state ""))
12354 (setq changes (append changes (cdr (assoc "" l)))))
12355 (when (and (stringp state) (> (length state) 0))
12356 (setq changes (append changes (cdr (assoc state l)))))
12357 (when (member state org-not-done-keywords)
12358 (setq changes (append changes (cdr (assoc 'todo l)))))
12359 (when (member state org-done-keywords)
12360 (setq changes (append changes (cdr (assoc 'done l)))))
12361 (dolist (c changes)
12362 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12364 (defun org-local-logging (value)
12365 "Get logging settings from a property VALUE."
12366 (let* (words w a)
12367 ;; directly set the variables, they are already local.
12368 (setq org-log-done nil
12369 org-log-repeat nil
12370 org-todo-log-states nil)
12371 (setq words (org-split-string value))
12372 (while (setq w (pop words))
12373 (cond
12374 ((setq a (assoc w org-startup-options))
12375 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12376 (set (nth 1 a) (nth 2 a))))
12377 ((setq a (org-extract-log-state-settings w))
12378 (and (member (car a) org-todo-keywords-1)
12379 (push a org-todo-log-states)))))))
12381 (defun org-get-todo-sequence-head (kwd)
12382 "Return the head of the TODO sequence to which KWD belongs.
12383 If KWD is not set, check if there is a text property remembering the
12384 right sequence."
12385 (let (p)
12386 (cond
12387 ((not kwd)
12388 (or (get-text-property (point-at-bol) 'org-todo-head)
12389 (progn
12390 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12391 nil (point-at-eol)))
12392 (get-text-property p 'org-todo-head))))
12393 ((not (member kwd org-todo-keywords-1))
12394 (car org-todo-keywords-1))
12395 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12397 (defun org-fast-todo-selection ()
12398 "Fast TODO keyword selection with single keys.
12399 Returns the new TODO keyword, or nil if no state change should occur."
12400 (let* ((fulltable org-todo-key-alist)
12401 (done-keywords org-done-keywords) ;; needed for the faces.
12402 (maxlen (apply 'max (mapcar
12403 (lambda (x)
12404 (if (stringp (car x)) (string-width (car x)) 0))
12405 fulltable)))
12406 (expert nil)
12407 (fwidth (+ maxlen 3 1 3))
12408 (ncol (/ (- (window-width) 4) fwidth))
12409 tg cnt e c tbl
12410 groups ingroup)
12411 (save-excursion
12412 (save-window-excursion
12413 (if expert
12414 (set-buffer (get-buffer-create " *Org todo*"))
12415 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12416 (erase-buffer)
12417 (org-set-local 'org-done-keywords done-keywords)
12418 (setq tbl fulltable cnt 0)
12419 (while (setq e (pop tbl))
12420 (cond
12421 ((equal e '(:startgroup))
12422 (push '() groups) (setq ingroup t)
12423 (when (not (= cnt 0))
12424 (setq cnt 0)
12425 (insert "\n"))
12426 (insert "{ "))
12427 ((equal e '(:endgroup))
12428 (setq ingroup nil cnt 0)
12429 (insert "}\n"))
12430 ((equal e '(:newline))
12431 (when (not (= cnt 0))
12432 (setq cnt 0)
12433 (insert "\n")
12434 (setq e (car tbl))
12435 (while (equal (car tbl) '(:newline))
12436 (insert "\n")
12437 (setq tbl (cdr tbl)))))
12439 (setq tg (car e) c (cdr e))
12440 (if ingroup (push tg (car groups)))
12441 (setq tg (org-add-props tg nil 'face
12442 (org-get-todo-face tg)))
12443 (if (and (= cnt 0) (not ingroup)) (insert " "))
12444 (insert "[" c "] " tg (make-string
12445 (- fwidth 4 (length tg)) ?\ ))
12446 (when (= (setq cnt (1+ cnt)) ncol)
12447 (insert "\n")
12448 (if ingroup (insert " "))
12449 (setq cnt 0)))))
12450 (insert "\n")
12451 (goto-char (point-min))
12452 (if (not expert) (org-fit-window-to-buffer))
12453 (message "[a-z..]:Set [SPC]:clear")
12454 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12455 (cond
12456 ((or (= c ?\C-g)
12457 (and (= c ?q) (not (rassoc c fulltable))))
12458 (setq quit-flag t))
12459 ((= c ?\ ) nil)
12460 ((setq e (rassoc c fulltable) tg (car e))
12462 (t (setq quit-flag t)))))))
12464 (defun org-entry-is-todo-p ()
12465 (member (org-get-todo-state) org-not-done-keywords))
12467 (defun org-entry-is-done-p ()
12468 (member (org-get-todo-state) org-done-keywords))
12470 (defun org-get-todo-state ()
12471 (save-excursion
12472 (org-back-to-heading t)
12473 (and (looking-at org-todo-line-regexp)
12474 (match-end 2)
12475 (match-string 2))))
12477 (defun org-at-date-range-p (&optional inactive-ok)
12478 "Is the cursor inside a date range?"
12479 (interactive)
12480 (save-excursion
12481 (catch 'exit
12482 (let ((pos (point)))
12483 (skip-chars-backward "^[<\r\n")
12484 (skip-chars-backward "<[")
12485 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12486 (>= (match-end 0) pos)
12487 (throw 'exit t))
12488 (skip-chars-backward "^<[\r\n")
12489 (skip-chars-backward "<[")
12490 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12491 (>= (match-end 0) pos)
12492 (throw 'exit t)))
12493 nil)))
12495 (defun org-get-repeat (&optional tagline)
12496 "Check if there is a deadline/schedule with repeater in this entry."
12497 (save-match-data
12498 (save-excursion
12499 (org-back-to-heading t)
12500 (and (re-search-forward (if tagline
12501 (concat tagline "\\s-*" org-repeat-re)
12502 org-repeat-re)
12503 (org-entry-end-position) t)
12504 (match-string-no-properties 1)))))
12506 (defvar org-last-changed-timestamp)
12507 (defvar org-last-inserted-timestamp)
12508 (defvar org-log-post-message)
12509 (defvar org-log-note-purpose)
12510 (defvar org-log-note-how)
12511 (defvar org-log-note-extra)
12512 (defun org-auto-repeat-maybe (done-word)
12513 "Check if the current headline contains a repeated deadline/schedule.
12514 If yes, set TODO state back to what it was and change the base date
12515 of repeating deadline/scheduled time stamps to new date.
12516 This function is run automatically after each state change to a DONE state."
12517 ;; last-state is dynamically scoped into this function
12518 (let* ((repeat (org-get-repeat))
12519 (aa (assoc org-last-state org-todo-kwd-alist))
12520 (interpret (nth 1 aa))
12521 (head (nth 2 aa))
12522 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12523 (msg "Entry repeats: ")
12524 (org-log-done nil)
12525 (org-todo-log-states nil)
12526 re type n what ts time to-state)
12527 (when repeat
12528 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12529 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12530 org-todo-repeat-to-state))
12531 (unless (and to-state (member to-state org-todo-keywords-1))
12532 (setq to-state (if (eq interpret 'type) org-last-state head)))
12533 (org-todo to-state)
12534 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12535 (org-entry-put nil "LAST_REPEAT" (format-time-string
12536 (org-time-stamp-format t t))))
12537 (when org-log-repeat
12538 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12539 (memq 'org-add-log-note post-command-hook))
12540 ;; OK, we are already setup for some record
12541 (if (eq org-log-repeat 'note)
12542 ;; make sure we take a note, not only a time stamp
12543 (setq org-log-note-how 'note))
12544 ;; Set up for taking a record
12545 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12546 org-last-state
12547 'findpos org-log-repeat)))
12548 (org-back-to-heading t)
12549 (org-add-planning-info nil nil 'closed)
12550 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12551 org-deadline-time-regexp "\\)\\|\\("
12552 org-ts-regexp "\\)"))
12553 (while (re-search-forward
12554 re (save-excursion (outline-next-heading) (point)) t)
12555 (setq type (if (match-end 1) org-scheduled-string
12556 (if (match-end 3) org-deadline-string "Plain:"))
12557 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12558 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12559 (setq n (string-to-number (match-string 2 ts))
12560 what (match-string 3 ts))
12561 (if (equal what "w") (setq n (* n 7) what "d"))
12562 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12563 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12564 ;; Preparation, see if we need to modify the start date for the change
12565 (when (match-end 1)
12566 (setq time (save-match-data (org-time-string-to-time ts)))
12567 (cond
12568 ((equal (match-string 1 ts) ".")
12569 ;; Shift starting date to today
12570 (org-timestamp-change
12571 (- (org-today) (time-to-days time))
12572 'day))
12573 ((equal (match-string 1 ts) "+")
12574 (let ((nshiftmax 10) (nshift 0))
12575 (while (or (= nshift 0)
12576 (<= (time-to-days time)
12577 (time-to-days (current-time))))
12578 (when (= (incf nshift) nshiftmax)
12579 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12580 (error "Abort")))
12581 (org-timestamp-change n (cdr (assoc what whata)))
12582 (org-at-timestamp-p t)
12583 (setq ts (match-string 1))
12584 (setq time (save-match-data (org-time-string-to-time ts)))))
12585 (org-timestamp-change (- n) (cdr (assoc what whata)))
12586 ;; rematch, so that we have everything in place for the real shift
12587 (org-at-timestamp-p t)
12588 (setq ts (match-string 1))
12589 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12590 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12591 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12592 (setq org-log-post-message msg)
12593 (message "%s" msg))))
12595 (defun org-show-todo-tree (arg)
12596 "Make a compact tree which shows all headlines marked with TODO.
12597 The tree will show the lines where the regexp matches, and all higher
12598 headlines above the match.
12599 With a \\[universal-argument] prefix, prompt for a regexp to match.
12600 With a numeric prefix N, construct a sparse tree for the Nth element
12601 of `org-todo-keywords-1'."
12602 (interactive "P")
12603 (let ((case-fold-search nil)
12604 (kwd-re
12605 (cond ((null arg) org-not-done-regexp)
12606 ((equal arg '(4))
12607 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12608 (mapcar 'list org-todo-keywords-1))))
12609 (concat "\\("
12610 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12611 "\\)\\>")))
12612 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12613 (regexp-quote (nth (1- (prefix-numeric-value arg))
12614 org-todo-keywords-1)))
12615 (t (error "Invalid prefix argument: %s" arg)))))
12616 (message "%d TODO entries found"
12617 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12619 (defun org-deadline (arg &optional time)
12620 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12621 With one universal prefix argument, remove any deadline from the item.
12622 With two universal prefix arguments, prompt for a warning delay.
12623 With argument TIME, set the deadline at the corresponding date. TIME
12624 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12625 (interactive "P")
12626 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12627 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12628 'region-start-level 'region))
12629 org-loop-over-headlines-in-active-region)
12630 (org-map-entries
12631 `(org-deadline ',arg ,time)
12632 org-loop-over-headlines-in-active-region
12633 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12634 (let* ((old-date (org-entry-get nil "DEADLINE"))
12635 (old-date-time (org-time-string-to-time old-date))
12636 (repeater (and old-date
12637 (string-match
12638 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12639 old-date)
12640 (match-string 1 old-date))))
12641 (cond
12642 ((equal arg '(4))
12643 (when (and old-date org-log-redeadline)
12644 (org-add-log-setup 'deldeadline nil old-date 'findpos
12645 org-log-redeadline))
12646 (org-remove-timestamp-with-keyword org-deadline-string)
12647 (message "Item no longer has a deadline."))
12648 ((equal arg '(16))
12649 (save-excursion
12650 (if (re-search-forward
12651 org-deadline-time-regexp
12652 (save-excursion (outline-next-heading) (point)) t)
12653 (let* ((rpl0 (match-string 1))
12654 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12655 (replace-match
12656 (concat org-deadline-string
12657 " <" rpl
12658 (format " -%dd"
12659 (abs
12660 (- (time-to-days
12661 (save-match-data
12662 (org-read-date nil t nil "Warn starting from" old-date-time)))
12663 (time-to-days old-date-time))))
12664 ">") t t))
12665 (user-error "No deadline information to update"))))
12667 (org-add-planning-info 'deadline time 'closed)
12668 (when (and old-date org-log-redeadline
12669 (not (equal old-date
12670 (substring org-last-inserted-timestamp 1 -1))))
12671 (org-add-log-setup 'redeadline nil old-date 'findpos
12672 org-log-redeadline))
12673 (when repeater
12674 (save-excursion
12675 (org-back-to-heading t)
12676 (when (re-search-forward (concat org-deadline-string " "
12677 org-last-inserted-timestamp)
12678 (save-excursion
12679 (outline-next-heading) (point)) t)
12680 (goto-char (1- (match-end 0)))
12681 (insert " " repeater)
12682 (setq org-last-inserted-timestamp
12683 (concat (substring org-last-inserted-timestamp 0 -1)
12684 " " repeater
12685 (substring org-last-inserted-timestamp -1))))))
12686 (message "Deadline on %s" org-last-inserted-timestamp))))))
12688 (defun org-schedule (arg &optional time)
12689 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12690 With one universal prefix argument, remove any scheduling date from the item.
12691 With two universal prefix arguments, prompt for a delay cookie.
12692 With argument TIME, scheduled at the corresponding date. TIME can
12693 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12694 (interactive "P")
12695 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12696 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12697 'region-start-level 'region))
12698 org-loop-over-headlines-in-active-region)
12699 (org-map-entries
12700 `(org-schedule ',arg ,time)
12701 org-loop-over-headlines-in-active-region
12702 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12703 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12704 (old-date-time (org-time-string-to-time old-date))
12705 (repeater (and old-date
12706 (string-match
12707 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12708 old-date)
12709 (match-string 1 old-date))))
12710 (cond
12711 ((equal arg '(4))
12712 (progn
12713 (when (and old-date org-log-reschedule)
12714 (org-add-log-setup 'delschedule nil old-date 'findpos
12715 org-log-reschedule))
12716 (org-remove-timestamp-with-keyword org-scheduled-string)
12717 (message "Item is no longer scheduled.")))
12718 ((equal arg '(16))
12719 (save-excursion
12720 (if (re-search-forward
12721 org-scheduled-time-regexp
12722 (save-excursion (outline-next-heading) (point)) t)
12723 (let* ((rpl0 (match-string 1))
12724 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12725 (replace-match
12726 (concat org-scheduled-string
12727 " <" rpl
12728 (format " -%dd"
12729 (abs
12730 (- (time-to-days
12731 (save-match-data
12732 (org-read-date nil t nil "Delay until" old-date-time)))
12733 (time-to-days old-date-time))))
12734 ">") t t))
12735 (user-error "No scheduled information to update"))))
12737 (org-add-planning-info 'scheduled time 'closed)
12738 (when (and old-date org-log-reschedule
12739 (not (equal old-date
12740 (substring org-last-inserted-timestamp 1 -1))))
12741 (org-add-log-setup 'reschedule nil old-date 'findpos
12742 org-log-reschedule))
12743 (when repeater
12744 (save-excursion
12745 (org-back-to-heading t)
12746 (when (re-search-forward (concat org-scheduled-string " "
12747 org-last-inserted-timestamp)
12748 (save-excursion
12749 (outline-next-heading) (point)) t)
12750 (goto-char (1- (match-end 0)))
12751 (insert " " repeater)
12752 (setq org-last-inserted-timestamp
12753 (concat (substring org-last-inserted-timestamp 0 -1)
12754 " " repeater
12755 (substring org-last-inserted-timestamp -1))))))
12756 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12758 (defun org-get-scheduled-time (pom &optional inherit)
12759 "Get the scheduled time as a time tuple, of a format suitable
12760 for calling org-schedule with, or if there is no scheduling,
12761 returns nil."
12762 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12763 (when time
12764 (apply 'encode-time (org-parse-time-string time)))))
12766 (defun org-get-deadline-time (pom &optional inherit)
12767 "Get the deadline as a time tuple, of a format suitable for
12768 calling org-deadline with, or if there is no scheduling, returns
12769 nil."
12770 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12771 (when time
12772 (apply 'encode-time (org-parse-time-string time)))))
12774 (defun org-remove-timestamp-with-keyword (keyword)
12775 "Remove all time stamps with KEYWORD in the current entry."
12776 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12777 beg)
12778 (save-excursion
12779 (org-back-to-heading t)
12780 (setq beg (point))
12781 (outline-next-heading)
12782 (while (re-search-backward re beg t)
12783 (replace-match "")
12784 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12785 (equal (char-before) ?\ ))
12786 (backward-delete-char 1)
12787 (if (string-match "^[ \t]*$" (buffer-substring
12788 (point-at-bol) (point-at-eol)))
12789 (delete-region (point-at-bol)
12790 (min (point-max) (1+ (point-at-eol))))))))))
12792 (defun org-add-planning-info (what &optional time &rest remove)
12793 "Insert new timestamp with keyword in the line directly after the headline.
12794 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12795 If non is given, the user is prompted for a date.
12796 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12797 be removed."
12798 (interactive)
12799 (let (org-time-was-given org-end-time-was-given ts
12800 end default-time default-input)
12802 (catch 'exit
12803 (when (and (memq what '(scheduled deadline))
12804 (or (not time)
12805 (and (stringp time)
12806 (string-match "^[-+]+[0-9]" time))))
12807 ;; Try to get a default date/time from existing timestamp
12808 (save-excursion
12809 (org-back-to-heading t)
12810 (setq end (save-excursion (outline-next-heading) (point)))
12811 (when (re-search-forward (if (eq what 'scheduled)
12812 org-scheduled-time-regexp
12813 org-deadline-time-regexp)
12814 end t)
12815 (setq ts (match-string 1)
12816 default-time
12817 (apply 'encode-time (org-parse-time-string ts))
12818 default-input (and ts (org-get-compact-tod ts))))))
12819 (when what
12820 (setq time
12821 (if (stringp time)
12822 ;; This is a string (relative or absolute), set proper date
12823 (apply 'encode-time
12824 (org-read-date-analyze
12825 time default-time (decode-time default-time)))
12826 ;; If necessary, get the time from the user
12827 (or time (org-read-date nil 'to-time nil nil
12828 default-time default-input)))))
12830 (when (and org-insert-labeled-timestamps-at-point
12831 (member what '(scheduled deadline)))
12832 (insert
12833 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12834 (org-insert-time-stamp time org-time-was-given
12835 nil nil nil (list org-end-time-was-given))
12836 (setq what nil))
12837 (save-excursion
12838 (save-restriction
12839 (let (col list elt ts buffer-invisibility-spec)
12840 (org-back-to-heading t)
12841 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12842 (goto-char (match-end 1))
12843 (setq col (current-column))
12844 (goto-char (match-end 0))
12845 (if (eobp) (insert "\n") (forward-char 1))
12846 (when (and (not what)
12847 (not (looking-at
12848 (concat "[ \t]*"
12849 org-keyword-time-not-clock-regexp))))
12850 ;; Nothing to add, nothing to remove...... :-)
12851 (throw 'exit nil))
12852 (if (and (not (looking-at org-outline-regexp))
12853 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12854 "[^\r\n]*"))
12855 (not (equal (match-string 1) org-clock-string)))
12856 (narrow-to-region (match-beginning 0) (match-end 0))
12857 (insert-before-markers "\n")
12858 (backward-char 1)
12859 (narrow-to-region (point) (point))
12860 (and org-adapt-indentation (org-indent-to-column col)))
12861 ;; Check if we have to remove something.
12862 (setq list (cons what remove))
12863 (while list
12864 (setq elt (pop list))
12865 (when (or (and (eq elt 'scheduled)
12866 (re-search-forward org-scheduled-time-regexp nil t))
12867 (and (eq elt 'deadline)
12868 (re-search-forward org-deadline-time-regexp nil t))
12869 (and (eq elt 'closed)
12870 (re-search-forward org-closed-time-regexp nil t)))
12871 (replace-match "")
12872 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12873 (and (looking-at "[ \t]+") (replace-match ""))
12874 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12875 (when what
12876 (insert
12877 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12878 (cond ((eq what 'scheduled) org-scheduled-string)
12879 ((eq what 'deadline) org-deadline-string)
12880 ((eq what 'closed) org-closed-string))
12881 " ")
12882 (setq ts (org-insert-time-stamp
12883 time
12884 (or org-time-was-given
12885 (and (eq what 'closed) org-log-done-with-time))
12886 (eq what 'closed)
12887 nil nil (list org-end-time-was-given)))
12888 (insert
12889 (if (not (or (bolp) (eq (char-before) ?\ )
12890 (memq (char-after) '(32 10))
12891 (eobp))) " " ""))
12892 (end-of-line 1))
12893 (goto-char (point-min))
12894 (widen)
12895 (if (and (looking-at "[ \t]*\n")
12896 (equal (char-before) ?\n))
12897 (delete-region (1- (point)) (point-at-eol)))
12898 ts))))))
12900 (defvar org-log-note-marker (make-marker))
12901 (defvar org-log-note-purpose nil)
12902 (defvar org-log-note-state nil)
12903 (defvar org-log-note-previous-state nil)
12904 (defvar org-log-note-how nil)
12905 (defvar org-log-note-extra nil)
12906 (defvar org-log-note-window-configuration nil)
12907 (defvar org-log-note-return-to (make-marker))
12908 (defvar org-log-note-effective-time nil
12909 "Remembered current time so that dynamically scoped
12910 `org-extend-today-until' affects tha timestamps in state change
12911 log")
12913 (defvar org-log-post-message nil
12914 "Message to be displayed after a log note has been stored.
12915 The auto-repeater uses this.")
12917 (defun org-add-note ()
12918 "Add a note to the current entry.
12919 This is done in the same way as adding a state change note."
12920 (interactive)
12921 (org-add-log-setup 'note nil nil 'findpos nil))
12923 (defvar org-property-end-re)
12924 (defun org-add-log-setup (&optional purpose state prev-state
12925 findpos how extra)
12926 "Set up the post command hook to take a note.
12927 If this is about to TODO state change, the new state is expected in STATE.
12928 When FINDPOS is non-nil, find the correct position for the note in
12929 the current entry. If not, assume that it can be inserted at point.
12930 HOW is an indicator what kind of note should be created.
12931 EXTRA is additional text that will be inserted into the notes buffer."
12932 (let* ((org-log-into-drawer (org-log-into-drawer))
12933 (drawer (cond ((stringp org-log-into-drawer)
12934 org-log-into-drawer)
12935 (org-log-into-drawer "LOGBOOK"))))
12936 (save-restriction
12937 (save-excursion
12938 (when findpos
12939 (org-back-to-heading t)
12940 (narrow-to-region (point) (save-excursion
12941 (outline-next-heading) (point)))
12942 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12943 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12944 "[^\r\n]*\\)?"))
12945 (goto-char (match-end 0))
12946 (cond
12947 (drawer
12948 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12949 nil t)
12950 (progn
12951 (goto-char (match-end 0))
12952 (or org-log-states-order-reversed
12953 (and (re-search-forward org-property-end-re nil t)
12954 (goto-char (1- (match-beginning 0))))))
12955 (insert "\n:" drawer ":\n:END:")
12956 (beginning-of-line 0)
12957 (org-indent-line)
12958 (beginning-of-line 2)
12959 (org-indent-line)
12960 (end-of-line 0)))
12961 ((and org-log-state-notes-insert-after-drawers
12962 (save-excursion
12963 (forward-line) (looking-at org-drawer-regexp)))
12964 (forward-line)
12965 (while (looking-at org-drawer-regexp)
12966 (goto-char (match-end 0))
12967 (re-search-forward org-property-end-re (point-max) t)
12968 (forward-line))
12969 (forward-line -1)))
12970 (unless org-log-states-order-reversed
12971 (and (= (char-after) ?\n) (forward-char 1))
12972 (org-skip-over-state-notes)
12973 (skip-chars-backward " \t\n\r")))
12974 (move-marker org-log-note-marker (point))
12975 (setq org-log-note-purpose purpose
12976 org-log-note-state state
12977 org-log-note-previous-state prev-state
12978 org-log-note-how how
12979 org-log-note-extra extra
12980 org-log-note-effective-time (org-current-effective-time))
12981 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12983 (defun org-skip-over-state-notes ()
12984 "Skip past the list of State notes in an entry."
12985 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12986 (when (ignore-errors (goto-char (org-in-item-p)))
12987 (let* ((struct (org-list-struct))
12988 (prevs (org-list-prevs-alist struct)))
12989 (while (looking-at "[ \t]*- State")
12990 (goto-char (or (org-list-get-next-item (point) struct prevs)
12991 (org-list-get-item-end (point) struct)))))))
12993 (defun org-add-log-note (&optional purpose)
12994 "Pop up a window for taking a note, and add this note later at point."
12995 (remove-hook 'post-command-hook 'org-add-log-note)
12996 (setq org-log-note-window-configuration (current-window-configuration))
12997 (delete-other-windows)
12998 (move-marker org-log-note-return-to (point))
12999 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13000 (goto-char org-log-note-marker)
13001 (org-switch-to-buffer-other-window "*Org Note*")
13002 (erase-buffer)
13003 (if (memq org-log-note-how '(time state))
13004 (let (current-prefix-arg) (org-store-log-note))
13005 (let ((org-inhibit-startup t)) (org-mode))
13006 (insert (format "# Insert note for %s.
13007 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13008 (cond
13009 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13010 ((eq org-log-note-purpose 'done) "closed todo item")
13011 ((eq org-log-note-purpose 'state)
13012 (format "state change from \"%s\" to \"%s\""
13013 (or org-log-note-previous-state "")
13014 (or org-log-note-state "")))
13015 ((eq org-log-note-purpose 'reschedule)
13016 "rescheduling")
13017 ((eq org-log-note-purpose 'delschedule)
13018 "no longer scheduled")
13019 ((eq org-log-note-purpose 'redeadline)
13020 "changing deadline")
13021 ((eq org-log-note-purpose 'deldeadline)
13022 "removing deadline")
13023 ((eq org-log-note-purpose 'refile)
13024 "refiling")
13025 ((eq org-log-note-purpose 'note)
13026 "this entry")
13027 (t (error "This should not happen")))))
13028 (if org-log-note-extra (insert org-log-note-extra))
13029 (org-set-local 'org-finish-function 'org-store-log-note)
13030 (run-hooks 'org-log-buffer-setup-hook)))
13032 (defvar org-note-abort nil) ; dynamically scoped
13033 (defun org-store-log-note ()
13034 "Finish taking a log note, and insert it to where it belongs."
13035 (let ((txt (buffer-string)))
13036 (kill-buffer (current-buffer))
13037 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13038 lines ind bul)
13039 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13040 (setq txt (replace-match "" t t txt)))
13041 (if (string-match "\\s-+\\'" txt)
13042 (setq txt (replace-match "" t t txt)))
13043 (setq lines (org-split-string txt "\n"))
13044 (when (and note (string-match "\\S-" note))
13045 (setq note
13046 (org-replace-escapes
13047 note
13048 (list (cons "%u" (user-login-name))
13049 (cons "%U" user-full-name)
13050 (cons "%t" (format-time-string
13051 (org-time-stamp-format 'long 'inactive)
13052 org-log-note-effective-time))
13053 (cons "%T" (format-time-string
13054 (org-time-stamp-format 'long nil)
13055 org-log-note-effective-time))
13056 (cons "%d" (format-time-string
13057 (org-time-stamp-format nil 'inactive)
13058 org-log-note-effective-time))
13059 (cons "%D" (format-time-string
13060 (org-time-stamp-format nil nil)
13061 org-log-note-effective-time))
13062 (cons "%s" (if org-log-note-state
13063 (concat "\"" org-log-note-state "\"")
13064 ""))
13065 (cons "%S" (if org-log-note-previous-state
13066 (concat "\"" org-log-note-previous-state "\"")
13067 "\"\"")))))
13068 (if lines (setq note (concat note " \\\\")))
13069 (push note lines))
13070 (when (or current-prefix-arg org-note-abort)
13071 (when org-log-into-drawer
13072 (org-remove-empty-drawer-at
13073 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13074 org-log-note-marker))
13075 (setq lines nil))
13076 (when lines
13077 (with-current-buffer (marker-buffer org-log-note-marker)
13078 (save-excursion
13079 (goto-char org-log-note-marker)
13080 (move-marker org-log-note-marker nil)
13081 (end-of-line 1)
13082 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13083 (setq ind (save-excursion
13084 (if (ignore-errors (goto-char (org-in-item-p)))
13085 (let ((struct (org-list-struct)))
13086 (org-list-get-ind
13087 (org-list-get-top-point struct) struct))
13088 (skip-chars-backward " \r\t\n")
13089 (cond
13090 ((and (org-at-heading-p)
13091 org-adapt-indentation)
13092 (1+ (org-current-level)))
13093 ((org-at-heading-p) 0)
13094 (t (org-get-indentation))))))
13095 (setq bul (org-list-bullet-string "-"))
13096 (org-indent-line-to ind)
13097 (insert bul (pop lines))
13098 (let ((ind-body (+ (length bul) ind)))
13099 (while lines
13100 (insert "\n")
13101 (org-indent-line-to ind-body)
13102 (insert (pop lines))))
13103 (message "Note stored")
13104 (org-back-to-heading t)
13105 (org-cycle-hide-drawers 'children))))))
13106 (set-window-configuration org-log-note-window-configuration)
13107 (with-current-buffer (marker-buffer org-log-note-return-to)
13108 (goto-char org-log-note-return-to))
13109 (move-marker org-log-note-return-to nil)
13110 (and org-log-post-message (message "%s" org-log-post-message)))
13112 (defun org-remove-empty-drawer-at (drawer pos)
13113 "Remove an empty drawer DRAWER at position POS.
13114 POS may also be a marker."
13115 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13116 (save-excursion
13117 (save-restriction
13118 (widen)
13119 (goto-char pos)
13120 (if (org-in-regexp
13121 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13122 (replace-match ""))))))
13124 (defvar org-ts-type nil)
13125 (defun org-sparse-tree (&optional arg type)
13126 "Create a sparse tree, prompt for the details.
13127 This command can create sparse trees. You first need to select the type
13128 of match used to create the tree:
13130 t Show all TODO entries.
13131 T Show entries with a specific TODO keyword.
13132 m Show entries selected by a tags/property match.
13133 p Enter a property name and its value (both with completion on existing
13134 names/values) and show entries with that property.
13135 r Show entries matching a regular expression (`/' can be used as well).
13136 b Show deadlines and scheduled items before a date.
13137 a Show deadlines and scheduled items after a date.
13138 d Show deadlines due within `org-deadline-warning-days'.
13139 D Show deadlines and scheduled items between a date range."
13140 (interactive "P")
13141 (let (ans kwd value ts-type)
13142 (setq type (or type org-sparse-tree-default-date-type))
13143 (setq org-ts-type type)
13144 (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"
13145 (cond ((eq type 'all) "all timestamps")
13146 ((eq type 'scheduled) "only scheduled")
13147 ((eq type 'deadline) "only deadline")
13148 ((eq type 'active) "only active timestamps")
13149 ((eq type 'inactive) "only inactive timestamps")
13150 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13151 (t "scheduled/deadline")))
13152 (setq ans (read-char-exclusive))
13153 (cond
13154 ((equal ans ?c)
13155 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13156 ((equal ans ?d)
13157 (call-interactively 'org-check-deadlines))
13158 ((equal ans ?b)
13159 (call-interactively 'org-check-before-date))
13160 ((equal ans ?a)
13161 (call-interactively 'org-check-after-date))
13162 ((equal ans ?D)
13163 (call-interactively 'org-check-dates-range))
13164 ((equal ans ?t)
13165 (call-interactively 'org-show-todo-tree))
13166 ((equal ans ?T)
13167 (org-show-todo-tree '(4)))
13168 ((member ans '(?T ?m))
13169 (call-interactively 'org-match-sparse-tree))
13170 ((member ans '(?p ?P))
13171 (setq kwd (org-icompleting-read "Property: "
13172 (mapcar 'list (org-buffer-property-keys))))
13173 (setq value (org-icompleting-read "Value: "
13174 (mapcar 'list (org-property-values kwd))))
13175 (unless (string-match "\\`{.*}\\'" value)
13176 (setq value (concat "\"" value "\"")))
13177 (org-match-sparse-tree arg (concat kwd "=" value)))
13178 ((member ans '(?r ?R ?/))
13179 (call-interactively 'org-occur))
13180 (t (error "No such sparse tree command \"%c\"" ans)))))
13182 (defvar org-occur-highlights nil
13183 "List of overlays used for occur matches.")
13184 (make-variable-buffer-local 'org-occur-highlights)
13185 (defvar org-occur-parameters nil
13186 "Parameters of the active org-occur calls.
13187 This is a list, each call to org-occur pushes as cons cell,
13188 containing the regular expression and the callback, onto the list.
13189 The list can contain several entries if `org-occur' has been called
13190 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13191 will only contain one set of parameters. When the highlights are
13192 removed (for example with `C-c C-c', or with the next edit (depending
13193 on `org-remove-highlights-with-change'), this variable is emptied
13194 as well.")
13195 (make-variable-buffer-local 'org-occur-parameters)
13197 (defun org-occur (regexp &optional keep-previous callback)
13198 "Make a compact tree which shows all matches of REGEXP.
13199 The tree will show the lines where the regexp matches, and all higher
13200 headlines above the match. It will also show the heading after the match,
13201 to make sure editing the matching entry is easy.
13202 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13203 call to `org-occur' will be kept, to allow stacking of calls to this
13204 command.
13205 If CALLBACK is non-nil, it is a function which is called to confirm
13206 that the match should indeed be shown."
13207 (interactive "sRegexp: \nP")
13208 (when (equal regexp "")
13209 (error "Regexp cannot be empty"))
13210 (unless keep-previous
13211 (org-remove-occur-highlights nil nil t))
13212 (push (cons regexp callback) org-occur-parameters)
13213 (let ((cnt 0))
13214 (save-excursion
13215 (goto-char (point-min))
13216 (if (or (not keep-previous) ; do not want to keep
13217 (not org-occur-highlights)) ; no previous matches
13218 ;; hide everything
13219 (org-overview))
13220 (while (re-search-forward regexp nil t)
13221 (when (or (not callback)
13222 (save-match-data (funcall callback)))
13223 (setq cnt (1+ cnt))
13224 (when org-highlight-sparse-tree-matches
13225 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13226 (org-show-context 'occur-tree))))
13227 (when org-remove-highlights-with-change
13228 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13229 nil 'local))
13230 (unless org-sparse-tree-open-archived-trees
13231 (org-hide-archived-subtrees (point-min) (point-max)))
13232 (run-hooks 'org-occur-hook)
13233 (if (org-called-interactively-p 'interactive)
13234 (message "%d match(es) for regexp %s" cnt regexp))
13235 cnt))
13237 (defun org-occur-next-match (&optional n reset)
13238 "Function for `next-error-function' to find sparse tree matches.
13239 N is the number of matches to move, when negative move backwards.
13240 RESET is entirely ignored - this function always goes back to the
13241 starting point when no match is found."
13242 (let* ((limit (if (< n 0) (point-min) (point-max)))
13243 (search-func (if (< n 0)
13244 'previous-single-char-property-change
13245 'next-single-char-property-change))
13246 (n (abs n))
13247 (pos (point))
13249 (catch 'exit
13250 (while (setq p1 (funcall search-func (point) 'org-type))
13251 (when (equal p1 limit)
13252 (goto-char pos)
13253 (error "No more matches"))
13254 (when (equal (get-char-property p1 'org-type) 'org-occur)
13255 (setq n (1- n))
13256 (when (= n 0)
13257 (goto-char p1)
13258 (throw 'exit (point))))
13259 (goto-char p1))
13260 (goto-char p1)
13261 (error "No more matches"))))
13263 (defun org-show-context (&optional key)
13264 "Make sure point and context are visible.
13265 How much context is shown depends upon the variables
13266 `org-show-hierarchy-above', `org-show-following-heading',
13267 `org-show-entry-below' and `org-show-siblings'."
13268 (let ((heading-p (org-at-heading-p t))
13269 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13270 (following-p (org-get-alist-option org-show-following-heading key))
13271 (entry-p (org-get-alist-option org-show-entry-below key))
13272 (siblings-p (org-get-alist-option org-show-siblings key)))
13273 ;; Show heading or entry text
13274 (if (and heading-p (not entry-p))
13275 (org-flag-heading nil) ; only show the heading
13276 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13277 (org-show-hidden-entry))) ; show entire entry
13278 (when following-p
13279 ;; Show next sibling, or heading below text
13280 (save-excursion
13281 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13282 (org-flag-heading nil))))
13283 (when siblings-p (org-show-siblings))
13284 (when hierarchy-p
13285 ;; show all higher headings, possibly with siblings
13286 (save-excursion
13287 (while (and (condition-case nil
13288 (progn (org-up-heading-all 1) t)
13289 (error nil))
13290 (not (bobp)))
13291 (org-flag-heading nil)
13292 (when siblings-p (org-show-siblings)))))
13293 (org-fix-ellipsis-at-bol)))
13295 (defvar org-reveal-start-hook nil
13296 "Hook run before revealing a location.")
13298 (defun org-reveal (&optional siblings)
13299 "Show current entry, hierarchy above it, and the following headline.
13300 This can be used to show a consistent set of context around locations
13301 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13302 not t for the search context.
13304 With optional argument SIBLINGS, on each level of the hierarchy all
13305 siblings are shown. This repairs the tree structure to what it would
13306 look like when opened with hierarchical calls to `org-cycle'.
13307 With double optional argument \\[universal-argument] \\[universal-argument], \
13308 go to the parent and show the
13309 entire tree."
13310 (interactive "P")
13311 (run-hooks 'org-reveal-start-hook)
13312 (let ((org-show-hierarchy-above t)
13313 (org-show-following-heading t)
13314 (org-show-siblings (if siblings t org-show-siblings)))
13315 (org-show-context nil))
13316 (when (equal siblings '(16))
13317 (save-excursion
13318 (when (org-up-heading-safe)
13319 (org-show-subtree)
13320 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13322 (defun org-highlight-new-match (beg end)
13323 "Highlight from BEG to END and mark the highlight is an occur headline."
13324 (let ((ov (make-overlay beg end)))
13325 (overlay-put ov 'face 'secondary-selection)
13326 (overlay-put ov 'org-type 'org-occur)
13327 (push ov org-occur-highlights)))
13329 (defun org-remove-occur-highlights (&optional beg end noremove)
13330 "Remove the occur highlights from the buffer.
13331 BEG and END are ignored. If NOREMOVE is nil, remove this function
13332 from the `before-change-functions' in the current buffer."
13333 (interactive)
13334 (unless org-inhibit-highlight-removal
13335 (mapc 'delete-overlay org-occur-highlights)
13336 (setq org-occur-highlights nil)
13337 (setq org-occur-parameters nil)
13338 (unless noremove
13339 (remove-hook 'before-change-functions
13340 'org-remove-occur-highlights 'local))))
13342 ;;;; Priorities
13344 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13345 "Regular expression matching the priority indicator.")
13347 (defvar org-remove-priority-next-time nil)
13349 (defun org-priority-up ()
13350 "Increase the priority of the current item."
13351 (interactive)
13352 (org-priority 'up))
13354 (defun org-priority-down ()
13355 "Decrease the priority of the current item."
13356 (interactive)
13357 (org-priority 'down))
13359 (defun org-priority (&optional action show)
13360 "Change the priority of an item.
13361 ACTION can be `set', `up', `down', or a character."
13362 (interactive "P")
13363 (if (equal action '(4))
13364 (org-show-priority)
13365 (unless org-enable-priority-commands
13366 (error "Priority commands are disabled"))
13367 (setq action (or action 'set))
13368 (let (current new news have remove)
13369 (save-excursion
13370 (org-back-to-heading t)
13371 (if (looking-at org-priority-regexp)
13372 (setq current (string-to-char (match-string 2))
13373 have t))
13374 (cond
13375 ((eq action 'remove)
13376 (setq remove t new ?\ ))
13377 ((or (eq action 'set)
13378 (if (featurep 'xemacs) (characterp action) (integerp action)))
13379 (if (not (eq action 'set))
13380 (setq new action)
13381 (message "Priority %c-%c, SPC to remove: "
13382 org-highest-priority org-lowest-priority)
13383 (save-match-data
13384 (setq new (read-char-exclusive))))
13385 (if (and (= (upcase org-highest-priority) org-highest-priority)
13386 (= (upcase org-lowest-priority) org-lowest-priority))
13387 (setq new (upcase new)))
13388 (cond ((equal new ?\ ) (setq remove t))
13389 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13390 (error "Priority must be between `%c' and `%c'"
13391 org-highest-priority org-lowest-priority))))
13392 ((eq action 'up)
13393 (setq new (if have
13394 (1- current) ; normal cycling
13395 ;; last priority was empty
13396 (if (eq last-command this-command)
13397 org-lowest-priority ; wrap around empty to lowest
13398 ;; default
13399 (if org-priority-start-cycle-with-default
13400 org-default-priority
13401 (1- org-default-priority))))))
13402 ((eq action 'down)
13403 (setq new (if have
13404 (1+ current) ; normal cycling
13405 ;; last priority was empty
13406 (if (eq last-command this-command)
13407 org-highest-priority ; wrap around empty to highest
13408 ;; default
13409 (if org-priority-start-cycle-with-default
13410 org-default-priority
13411 (1+ org-default-priority))))))
13412 (t (error "Invalid action")))
13413 (if (or (< (upcase new) org-highest-priority)
13414 (> (upcase new) org-lowest-priority))
13415 (if (and (memq action '(up down))
13416 (not have) (not (eq last-command this-command)))
13417 ;; `new' is from default priority
13418 (error
13419 "The default can not be set, see `org-default-priority' why")
13420 ;; normal cycling: `new' is beyond highest/lowest priority
13421 ;; and is wrapped around to the empty priority
13422 (setq remove t)))
13423 (setq news (format "%c" new))
13424 (if have
13425 (if remove
13426 (replace-match "" t t nil 1)
13427 (replace-match news t t nil 2))
13428 (if remove
13429 (error "No priority cookie found in line")
13430 (let ((case-fold-search nil))
13431 (looking-at org-todo-line-regexp))
13432 (if (match-end 2)
13433 (progn
13434 (goto-char (match-end 2))
13435 (insert " [#" news "]"))
13436 (goto-char (match-beginning 3))
13437 (insert "[#" news "] "))))
13438 (org-preserve-lc (org-set-tags nil 'align)))
13439 (if remove
13440 (message "Priority removed")
13441 (message "Priority of current item set to %s" news)))))
13443 (defun org-show-priority ()
13444 "Show the priority of the current item.
13445 This priority is composed of the main priority given with the [#A] cookies,
13446 and by additional input from the age of a schedules or deadline entry."
13447 (interactive)
13448 (let ((pri (if (eq major-mode 'org-agenda-mode)
13449 (org-get-at-bol 'priority)
13450 (save-excursion
13451 (save-match-data
13452 (beginning-of-line)
13453 (and (looking-at org-heading-regexp)
13454 (org-get-priority (match-string 0))))))))
13455 (message "Priority is %d" (if pri pri -1000))))
13457 (defun org-get-priority (s)
13458 "Find priority cookie and return priority."
13459 (save-match-data
13460 (if (functionp org-get-priority-function)
13461 (funcall org-get-priority-function)
13462 (if (not (string-match org-priority-regexp s))
13463 (* 1000 (- org-lowest-priority org-default-priority))
13464 (* 1000 (- org-lowest-priority
13465 (string-to-char (match-string 2 s))))))))
13467 ;;;; Tags
13469 (defvar org-agenda-archives-mode)
13470 (defvar org-map-continue-from nil
13471 "Position from where mapping should continue.
13472 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13474 (defvar org-scanner-tags nil
13475 "The current tag list while the tags scanner is running.")
13476 (defvar org-trust-scanner-tags nil
13477 "Should `org-get-tags-at' use the tags for the scanner.
13478 This is for internal dynamical scoping only.
13479 When this is non-nil, the function `org-get-tags-at' will return the value
13480 of `org-scanner-tags' instead of building the list by itself. This
13481 can lead to large speed-ups when the tags scanner is used in a file with
13482 many entries, and when the list of tags is retrieved, for example to
13483 obtain a list of properties. Building the tags list for each entry in such
13484 a file becomes an N^2 operation - but with this variable set, it scales
13485 as N.")
13487 (defun org-scan-tags (action matcher todo-only &optional start-level)
13488 "Sca headline tags with inheritance and produce output ACTION.
13490 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13491 or `agenda' to produce an entry list for an agenda view. It can also be
13492 a Lisp form or a function that should be called at each matched headline, in
13493 this case the return value is a list of all return values from these calls.
13495 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13496 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13497 only lines with a not-done TODO keyword are included in the output.
13498 This should be the same variable that was scoped into
13499 and set by `org-make-tags-matcher' when it constructed MATCHER.
13501 START-LEVEL can be a string with asterisks, reducing the scope to
13502 headlines matching this string."
13503 (require 'org-agenda)
13504 (let* ((re (concat "^"
13505 (if start-level
13506 ;; Get the correct level to match
13507 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13508 org-outline-regexp)
13509 " *\\(\\<\\("
13510 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13511 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13512 (props (list 'face 'default
13513 'done-face 'org-agenda-done
13514 'undone-face 'default
13515 'mouse-face 'highlight
13516 'org-not-done-regexp org-not-done-regexp
13517 'org-todo-regexp org-todo-regexp
13518 'org-complex-heading-regexp org-complex-heading-regexp
13519 'help-echo
13520 (format "mouse-2 or RET jump to org file %s"
13521 (abbreviate-file-name
13522 (or (buffer-file-name (buffer-base-buffer))
13523 (buffer-name (buffer-base-buffer)))))))
13524 (case-fold-search nil)
13525 (org-map-continue-from nil)
13526 lspos tags tags-list
13527 (tags-alist (list (cons 0 org-file-tags)))
13528 (llast 0) rtn rtn1 level category i txt
13529 todo marker entry priority)
13530 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13531 (setq action (list 'lambda nil action)))
13532 (save-excursion
13533 (goto-char (point-min))
13534 (when (eq action 'sparse-tree)
13535 (org-overview)
13536 (org-remove-occur-highlights))
13537 (while (re-search-forward re nil t)
13538 (setq org-map-continue-from nil)
13539 (catch :skip
13540 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13541 tags (if (match-end 4) (org-match-string-no-properties 4)))
13542 (goto-char (setq lspos (match-beginning 0)))
13543 (setq level (org-reduced-level (org-outline-level))
13544 category (org-get-category))
13545 (setq i llast llast level)
13546 ;; remove tag lists from same and sublevels
13547 (while (>= i level)
13548 (when (setq entry (assoc i tags-alist))
13549 (setq tags-alist (delete entry tags-alist)))
13550 (setq i (1- i)))
13551 ;; add the next tags
13552 (when tags
13553 (setq tags (org-split-string tags ":")
13554 tags-alist
13555 (cons (cons level tags) tags-alist)))
13556 ;; compile tags for current headline
13557 (setq tags-list
13558 (if org-use-tag-inheritance
13559 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13560 tags)
13561 org-scanner-tags tags-list)
13562 (when org-use-tag-inheritance
13563 (setcdr (car tags-alist)
13564 (mapcar (lambda (x)
13565 (setq x (copy-sequence x))
13566 (org-add-prop-inherited x))
13567 (cdar tags-alist))))
13568 (when (and tags org-use-tag-inheritance
13569 (or (not (eq t org-use-tag-inheritance))
13570 org-tags-exclude-from-inheritance))
13571 ;; selective inheritance, remove uninherited ones
13572 (setcdr (car tags-alist)
13573 (org-remove-uninherited-tags (cdar tags-alist))))
13574 (when (and
13576 ;; eval matcher only when the todo condition is OK
13577 (and (or (not todo-only) (member todo org-not-done-keywords))
13578 (let ((case-fold-search t) (org-trust-scanner-tags t))
13579 (eval matcher)))
13581 ;; Call the skipper, but return t if it does not skip,
13582 ;; so that the `and' form continues evaluating
13583 (progn
13584 (unless (eq action 'sparse-tree) (org-agenda-skip))
13587 ;; Check if timestamps are deselecting this entry
13588 (or (not todo-only)
13589 (and (member todo org-not-done-keywords)
13590 (or (not org-agenda-tags-todo-honor-ignore-options)
13591 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13593 ;; select this headline
13594 (cond
13595 ((eq action 'sparse-tree)
13596 (and org-highlight-sparse-tree-matches
13597 (org-get-heading) (match-end 0)
13598 (org-highlight-new-match
13599 (match-beginning 1) (match-end 1)))
13600 (org-show-context 'tags-tree))
13601 ((eq action 'agenda)
13602 (setq txt (org-agenda-format-item
13604 (concat
13605 (if (eq org-tags-match-list-sublevels 'indented)
13606 (make-string (1- level) ?.) "")
13607 (org-get-heading))
13608 level category
13609 tags-list)
13610 priority (org-get-priority txt))
13611 (goto-char lspos)
13612 (setq marker (org-agenda-new-marker))
13613 (org-add-props txt props
13614 'org-marker marker 'org-hd-marker marker 'org-category category
13615 'todo-state todo
13616 'priority priority 'type "tagsmatch")
13617 (push txt rtn))
13618 ((functionp action)
13619 (setq org-map-continue-from nil)
13620 (save-excursion
13621 (setq rtn1 (funcall action))
13622 (push rtn1 rtn)))
13623 (t (error "Invalid action")))
13625 ;; if we are to skip sublevels, jump to end of subtree
13626 (unless org-tags-match-list-sublevels
13627 (org-end-of-subtree t)
13628 (backward-char 1))))
13629 ;; Get the correct position from where to continue
13630 (if org-map-continue-from
13631 (goto-char org-map-continue-from)
13632 (and (= (point) lspos) (end-of-line 1)))))
13633 (when (and (eq action 'sparse-tree)
13634 (not org-sparse-tree-open-archived-trees))
13635 (org-hide-archived-subtrees (point-min) (point-max)))
13636 (nreverse rtn)))
13638 (defun org-remove-uninherited-tags (tags)
13639 "Remove all tags that are not inherited from the list TAGS."
13640 (cond
13641 ((eq org-use-tag-inheritance t)
13642 (if org-tags-exclude-from-inheritance
13643 (org-delete-all org-tags-exclude-from-inheritance tags)
13644 tags))
13645 ((not org-use-tag-inheritance) nil)
13646 ((stringp org-use-tag-inheritance)
13647 (delq nil (mapcar
13648 (lambda (x)
13649 (if (and (string-match org-use-tag-inheritance x)
13650 (not (member x org-tags-exclude-from-inheritance)))
13651 x nil))
13652 tags)))
13653 ((listp org-use-tag-inheritance)
13654 (delq nil (mapcar
13655 (lambda (x)
13656 (if (member x org-use-tag-inheritance) x nil))
13657 tags)))))
13659 (defun org-match-sparse-tree (&optional todo-only match)
13660 "Create a sparse tree according to tags string MATCH.
13661 MATCH can contain positive and negative selection of tags, like
13662 \"+WORK+URGENT-WITHBOSS\".
13663 If optional argument TODO-ONLY is non-nil, only select lines that are
13664 also TODO lines."
13665 (interactive "P")
13666 (org-agenda-prepare-buffers (list (current-buffer)))
13667 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13669 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13671 (defvar org-cached-props nil)
13672 (defun org-cached-entry-get (pom property)
13673 (if (or (eq t org-use-property-inheritance)
13674 (and (stringp org-use-property-inheritance)
13675 (string-match org-use-property-inheritance property))
13676 (and (listp org-use-property-inheritance)
13677 (member property org-use-property-inheritance)))
13678 ;; Caching is not possible, check it directly
13679 (org-entry-get pom property 'inherit)
13680 ;; Get all properties, so that we can do complicated checks easily
13681 (cdr (assoc property (or org-cached-props
13682 (setq org-cached-props
13683 (org-entry-properties pom)))))))
13685 (defun org-global-tags-completion-table (&optional files)
13686 "Return the list of all tags in all agenda buffer/files.
13687 Optional FILES argument is a list of files which can be used
13688 instead of the agenda files."
13689 (save-excursion
13690 (org-uniquify
13691 (delq nil
13692 (apply 'append
13693 (mapcar
13694 (lambda (file)
13695 (set-buffer (find-file-noselect file))
13696 (append (org-get-buffer-tags)
13697 (mapcar (lambda (x) (if (stringp (car-safe x))
13698 (list (car-safe x)) nil))
13699 org-tag-alist)))
13700 (if (and files (car files))
13701 files
13702 (org-agenda-files))))))))
13704 (defun org-make-tags-matcher (match)
13705 "Create the TAGS/TODO matcher form for the selection string MATCH.
13707 The variable `todo-only' is scoped dynamically into this function.
13708 It will be set to t if the matcher restricts matching to TODO entries,
13709 otherwise will not be touched.
13711 Returns a cons of the selection string MATCH and the constructed
13712 lisp form implementing the matcher. The matcher is to be evaluated
13713 at an Org entry, with point on the headline, and returns t if the
13714 entry matches the selection string MATCH. The returned lisp form
13715 references two variables with information about the entry, which
13716 must be bound around the form's evaluation: todo, the TODO keyword
13717 at the entry (or nil of none); and tags-list, the list of all tags
13718 at the entry including inherited ones. Additionally, the category
13719 of the entry (if any) must be specified as the text property
13720 'org-category on the headline.
13722 See also `org-scan-tags'.
13724 (declare (special todo-only))
13725 (unless (boundp 'todo-only)
13726 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13727 (unless match
13728 ;; Get a new match request, with completion
13729 (let ((org-last-tags-completion-table
13730 (org-global-tags-completion-table)))
13731 (setq match (org-completing-read-no-i
13732 "Match: " 'org-tags-completion-function nil nil nil
13733 'org-tags-history))))
13735 ;; Parse the string and create a lisp form
13736 (let ((match0 match)
13737 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13738 minus tag mm
13739 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13740 orterms term orlist re-p str-p level-p level-op time-p
13741 prop-p pn pv po gv rest)
13742 (if (string-match "/+" match)
13743 ;; match contains also a todo-matching request
13744 (progn
13745 (setq tagsmatch (substring match 0 (match-beginning 0))
13746 todomatch (substring match (match-end 0)))
13747 (if (string-match "^!" todomatch)
13748 (setq todo-only t todomatch (substring todomatch 1)))
13749 (if (string-match "^\\s-*$" todomatch)
13750 (setq todomatch nil)))
13751 ;; only matching tags
13752 (setq tagsmatch match todomatch nil))
13754 ;; Make the tags matcher
13755 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13756 (setq tagsmatcher t)
13757 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13758 (while (setq term (pop orterms))
13759 (while (and (equal (substring term -1) "\\") orterms)
13760 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13761 (while (string-match re term)
13762 (setq rest (substring term (match-end 0))
13763 minus (and (match-end 1)
13764 (equal (match-string 1 term) "-"))
13765 tag (save-match-data (replace-regexp-in-string
13766 "\\\\-" "-"
13767 (match-string 2 term)))
13768 re-p (equal (string-to-char tag) ?{)
13769 level-p (match-end 4)
13770 prop-p (match-end 5)
13771 mm (cond
13772 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13773 (level-p
13774 (setq level-op (org-op-to-function (match-string 3 term)))
13775 `(,level-op level ,(string-to-number
13776 (match-string 4 term))))
13777 (prop-p
13778 (setq pn (match-string 5 term)
13779 po (match-string 6 term)
13780 pv (match-string 7 term)
13781 re-p (equal (string-to-char pv) ?{)
13782 str-p (equal (string-to-char pv) ?\")
13783 time-p (save-match-data
13784 (string-match "^\"[[<].*[]>]\"$" pv))
13785 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13786 (if time-p (setq pv (org-matcher-time pv)))
13787 (setq po (org-op-to-function po (if time-p 'time str-p)))
13788 (cond
13789 ((equal pn "CATEGORY")
13790 (setq gv '(get-text-property (point) 'org-category)))
13791 ((equal pn "TODO")
13792 (setq gv 'todo))
13794 (setq gv `(org-cached-entry-get nil ,pn))))
13795 (if re-p
13796 (if (eq po 'org<>)
13797 `(not (string-match ,pv (or ,gv "")))
13798 `(string-match ,pv (or ,gv "")))
13799 (if str-p
13800 `(,po (or ,gv "") ,pv)
13801 `(,po (string-to-number (or ,gv ""))
13802 ,(string-to-number pv) ))))
13803 (t `(member ,tag tags-list)))
13804 mm (if minus (list 'not mm) mm)
13805 term rest)
13806 (push mm tagsmatcher))
13807 (push (if (> (length tagsmatcher) 1)
13808 (cons 'and tagsmatcher)
13809 (car tagsmatcher))
13810 orlist)
13811 (setq tagsmatcher nil))
13812 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13813 (setq tagsmatcher
13814 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13815 ;; Make the todo matcher
13816 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13817 (setq todomatcher t)
13818 (setq orterms (org-split-string todomatch "|") orlist nil)
13819 (while (setq term (pop orterms))
13820 (while (string-match re term)
13821 (setq minus (and (match-end 1)
13822 (equal (match-string 1 term) "-"))
13823 kwd (match-string 2 term)
13824 re-p (equal (string-to-char kwd) ?{)
13825 term (substring term (match-end 0))
13826 mm (if re-p
13827 `(string-match ,(substring kwd 1 -1) todo)
13828 (list 'equal 'todo kwd))
13829 mm (if minus (list 'not mm) mm))
13830 (push mm todomatcher))
13831 (push (if (> (length todomatcher) 1)
13832 (cons 'and todomatcher)
13833 (car todomatcher))
13834 orlist)
13835 (setq todomatcher nil))
13836 (setq todomatcher (if (> (length orlist) 1)
13837 (cons 'or orlist) (car orlist))))
13839 ;; Return the string and lisp forms of the matcher
13840 (setq matcher (if todomatcher
13841 (list 'and tagsmatcher todomatcher)
13842 tagsmatcher))
13843 (when todo-only
13844 (setq matcher (list 'and '(member todo org-not-done-keywords)
13845 matcher)))
13846 (cons match0 matcher)))
13848 (defun org-op-to-function (op &optional stringp)
13849 "Turn an operator into the appropriate function."
13850 (setq op
13851 (cond
13852 ((equal op "<" ) '(< string< org-time<))
13853 ((equal op ">" ) '(> org-string> org-time>))
13854 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13855 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13856 ((member op '("=" "==")) '(= string= org-time=))
13857 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13858 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13860 (defun org<> (a b) (not (= a b)))
13861 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13862 (defun org-string>= (a b) (not (string< a b)))
13863 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13864 (defun org-string<> (a b) (not (string= a b)))
13865 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13866 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13867 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13868 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13869 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13870 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13871 (defun org-2ft (s)
13872 "Convert S to a floating point time.
13873 If S is already a number, just return it. If it is a string, parse
13874 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13875 (cond
13876 ((numberp s) s)
13877 ((stringp s)
13878 (condition-case nil
13879 (float-time (apply 'encode-time (org-parse-time-string s)))
13880 (error 0.)))
13881 (t 0.)))
13883 (defun org-time-today ()
13884 "Time in seconds today at 0:00.
13885 Returns the float number of seconds since the beginning of the
13886 epoch to the beginning of today (00:00)."
13887 (float-time (apply 'encode-time
13888 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13890 (defun org-matcher-time (s)
13891 "Interpret a time comparison value."
13892 (save-match-data
13893 (cond
13894 ((string= s "<now>") (float-time))
13895 ((string= s "<today>") (org-time-today))
13896 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13897 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13898 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13899 (+ (org-time-today)
13900 (* (string-to-number (match-string 1 s))
13901 (cdr (assoc (match-string 2 s)
13902 '(("d" . 86400.0) ("w" . 604800.0)
13903 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13904 (t (org-2ft s)))))
13906 (defun org-match-any-p (re list)
13907 "Does re match any element of list?"
13908 (setq list (mapcar (lambda (x) (string-match re x)) list))
13909 (delq nil list))
13911 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13912 (defvar org-tags-overlay (make-overlay 1 1))
13913 (org-detach-overlay org-tags-overlay)
13915 (defun org-get-local-tags-at (&optional pos)
13916 "Get a list of tags defined in the current headline."
13917 (org-get-tags-at pos 'local))
13919 (defun org-get-local-tags ()
13920 "Get a list of tags defined in the current headline."
13921 (org-get-tags-at nil 'local))
13923 (defun org-get-tags-at (&optional pos local)
13924 "Get a list of all headline tags applicable at POS.
13925 POS defaults to point. If tags are inherited, the list contains
13926 the targets in the same sequence as the headlines appear, i.e.
13927 the tags of the current headline come last.
13928 When LOCAL is non-nil, only return tags from the current headline,
13929 ignore inherited ones."
13930 (interactive)
13931 (if (and org-trust-scanner-tags
13932 (or (not pos) (equal pos (point)))
13933 (not local))
13934 org-scanner-tags
13935 (let (tags ltags lastpos parent)
13936 (save-excursion
13937 (save-restriction
13938 (widen)
13939 (goto-char (or pos (point)))
13940 (save-match-data
13941 (catch 'done
13942 (condition-case nil
13943 (progn
13944 (org-back-to-heading t)
13945 (while (not (equal lastpos (point)))
13946 (setq lastpos (point))
13947 (when (looking-at
13948 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13949 (setq ltags (org-split-string
13950 (org-match-string-no-properties 1) ":"))
13951 (when parent
13952 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13953 (setq tags (append
13954 (if parent
13955 (org-remove-uninherited-tags ltags)
13956 ltags)
13957 tags)))
13958 (or org-use-tag-inheritance (throw 'done t))
13959 (if local (throw 'done t))
13960 (or (org-up-heading-safe) (error nil))
13961 (setq parent t)))
13962 (error nil)))))
13963 (if local
13964 tags
13965 (reverse (delete-dups
13966 (reverse (append
13967 (org-remove-uninherited-tags
13968 org-file-tags) tags)))))))))
13970 (defun org-add-prop-inherited (s)
13971 (add-text-properties 0 (length s) '(inherited t) s)
13974 (defun org-toggle-tag (tag &optional onoff)
13975 "Toggle the tag TAG for the current line.
13976 If ONOFF is `on' or `off', don't toggle but set to this state."
13977 (let (res current)
13978 (save-excursion
13979 (org-back-to-heading t)
13980 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13981 (point-at-eol) t)
13982 (progn
13983 (setq current (match-string 1))
13984 (replace-match ""))
13985 (setq current ""))
13986 (setq current (nreverse (org-split-string current ":")))
13987 (cond
13988 ((eq onoff 'on)
13989 (setq res t)
13990 (or (member tag current) (push tag current)))
13991 ((eq onoff 'off)
13992 (or (not (member tag current)) (setq current (delete tag current))))
13993 (t (if (member tag current)
13994 (setq current (delete tag current))
13995 (setq res t)
13996 (push tag current))))
13997 (end-of-line 1)
13998 (if current
13999 (progn
14000 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14001 (org-set-tags nil t))
14002 (delete-horizontal-space))
14003 (run-hooks 'org-after-tags-change-hook))
14004 res))
14006 (defun org-align-tags-here (to-col)
14007 ;; Assumes that this is a headline
14008 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14009 (beginning-of-line 1)
14010 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14011 (< pos (match-beginning 2)))
14012 (progn
14013 (setq tags-l (- (match-end 2) (match-beginning 2)))
14014 (goto-char (match-beginning 1))
14015 (insert " ")
14016 (delete-region (point) (1+ (match-beginning 2)))
14017 (setq ncol (max (current-column)
14018 (1+ col)
14019 (if (> to-col 0)
14020 to-col
14021 (- (abs to-col) tags-l))))
14022 (setq p (point))
14023 (insert (make-string (- ncol (current-column)) ?\ ))
14024 (setq ncol (current-column))
14025 (when indent-tabs-mode (tabify p (point-at-eol)))
14026 (org-move-to-column (min ncol col) t))
14027 (goto-char pos))))
14029 (defun org-set-tags-command (&optional arg just-align)
14030 "Call the set-tags command for the current entry."
14031 (interactive "P")
14032 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14033 (org-set-tags arg just-align)
14034 (save-excursion
14035 (unless (and (org-region-active-p)
14036 org-loop-over-headlines-in-active-region)
14037 (org-back-to-heading t))
14038 (org-set-tags arg just-align))))
14040 (defun org-set-tags-to (data)
14041 "Set the tags of the current entry to DATA, replacing the current tags.
14042 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14043 If DATA is nil or the empty string, any tags will be removed."
14044 (interactive "sTags: ")
14045 (setq data
14046 (cond
14047 ((eq data nil) "")
14048 ((equal data "") "")
14049 ((stringp data)
14050 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14051 ":"))
14052 ((listp data)
14053 (concat ":" (mapconcat 'identity data ":") ":"))))
14054 (when data
14055 (save-excursion
14056 (org-back-to-heading t)
14057 (when (looking-at org-complex-heading-regexp)
14058 (if (match-end 5)
14059 (progn
14060 (goto-char (match-beginning 5))
14061 (insert data)
14062 (delete-region (point) (point-at-eol))
14063 (org-set-tags nil 'align))
14064 (goto-char (point-at-eol))
14065 (insert " " data)
14066 (org-set-tags nil 'align)))
14067 (beginning-of-line 1)
14068 (if (looking-at ".*?\\([ \t]+\\)$")
14069 (delete-region (match-beginning 1) (match-end 1))))))
14071 (defun org-align-all-tags ()
14072 "Align the tags i all headings."
14073 (interactive)
14074 (save-excursion
14075 (or (ignore-errors (org-back-to-heading t))
14076 (outline-next-heading))
14077 (if (org-at-heading-p)
14078 (org-set-tags t)
14079 (message "No headings"))))
14081 (defvar org-indent-indentation-per-level)
14082 (defun org-set-tags (&optional arg just-align)
14083 "Set the tags for the current headline.
14084 With prefix ARG, realign all tags in headings in the current buffer."
14085 (interactive "P")
14086 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14087 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14088 'region-start-level 'region))
14089 org-loop-over-headlines-in-active-region)
14090 (org-map-entries
14091 ;; We don't use ARG and JUST-ALIGN here these args are not
14092 ;; useful when looping over headlines
14093 `(org-set-tags)
14094 org-loop-over-headlines-in-active-region
14095 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14096 (let* ((re org-outline-regexp-bol)
14097 (current (unless arg (org-get-tags-string)))
14098 (col (current-column))
14099 (org-setting-tags t)
14100 table current-tags inherited-tags ; computed below when needed
14101 tags p0 c0 c1 rpl di tc level)
14102 (if arg
14103 (save-excursion
14104 (goto-char (point-min))
14105 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14106 (while (re-search-forward re nil t)
14107 (org-set-tags nil t)
14108 (end-of-line 1)))
14109 (message "All tags realigned to column %d" org-tags-column))
14110 (if just-align
14111 (setq tags current)
14112 ;; Get a new set of tags from the user
14113 (save-excursion
14114 (setq table (append org-tag-persistent-alist
14115 (or org-tag-alist (org-get-buffer-tags))
14116 (and
14117 org-complete-tags-always-offer-all-agenda-tags
14118 (org-global-tags-completion-table
14119 (org-agenda-files))))
14120 org-last-tags-completion-table table
14121 current-tags (org-split-string current ":")
14122 inherited-tags (nreverse
14123 (nthcdr (length current-tags)
14124 (nreverse (org-get-tags-at))))
14125 tags
14126 (if (or (eq t org-use-fast-tag-selection)
14127 (and org-use-fast-tag-selection
14128 (delq nil (mapcar 'cdr table))))
14129 (org-fast-tag-selection
14130 current-tags inherited-tags table
14131 (if org-fast-tag-selection-include-todo
14132 org-todo-key-alist))
14133 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14134 (org-trim
14135 (org-icompleting-read "Tags: "
14136 'org-tags-completion-function
14137 nil nil current 'org-tags-history))))))
14138 (while (string-match "[-+&]+" tags)
14139 ;; No boolean logic, just a list
14140 (setq tags (replace-match ":" t t tags))))
14142 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14144 (if org-tags-sort-function
14145 (setq tags (mapconcat 'identity
14146 (sort (org-split-string
14147 tags (org-re "[^[:alnum:]_@#%]+"))
14148 org-tags-sort-function) ":")))
14150 (if (string-match "\\`[\t ]*\\'" tags)
14151 (setq tags "")
14152 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14153 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14155 ;; Insert new tags at the correct column
14156 (beginning-of-line 1)
14157 (setq level (or (and (looking-at org-outline-regexp)
14158 (- (match-end 0) (point) 1))
14160 (cond
14161 ((and (equal current "") (equal tags "")))
14162 ((re-search-forward
14163 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14164 (point-at-eol) t)
14165 (if (equal tags "")
14166 (setq rpl "")
14167 (goto-char (match-beginning 0))
14168 (setq c0 (current-column)
14169 ;; compute offset for the case of org-indent-mode active
14170 di (if org-indent-mode
14171 (* (1- org-indent-indentation-per-level) (1- level))
14173 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14174 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14175 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14176 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14177 (replace-match rpl t t)
14178 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14179 tags)
14180 (t (error "Tags alignment failed")))
14181 (org-move-to-column col)
14182 (unless just-align
14183 (run-hooks 'org-after-tags-change-hook))))))
14185 (defun org-change-tag-in-region (beg end tag off)
14186 "Add or remove TAG for each entry in the region.
14187 This works in the agenda, and also in an org-mode buffer."
14188 (interactive
14189 (list (region-beginning) (region-end)
14190 (let ((org-last-tags-completion-table
14191 (if (derived-mode-p 'org-mode)
14192 (org-get-buffer-tags)
14193 (org-global-tags-completion-table))))
14194 (org-icompleting-read
14195 "Tag: " 'org-tags-completion-function nil nil nil
14196 'org-tags-history))
14197 (progn
14198 (message "[s]et or [r]emove? ")
14199 (equal (read-char-exclusive) ?r))))
14200 (if (fboundp 'deactivate-mark) (deactivate-mark))
14201 (let ((agendap (equal major-mode 'org-agenda-mode))
14202 l1 l2 m buf pos newhead (cnt 0))
14203 (goto-char end)
14204 (setq l2 (1- (org-current-line)))
14205 (goto-char beg)
14206 (setq l1 (org-current-line))
14207 (loop for l from l1 to l2 do
14208 (org-goto-line l)
14209 (setq m (get-text-property (point) 'org-hd-marker))
14210 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14211 (and agendap m))
14212 (setq buf (if agendap (marker-buffer m) (current-buffer))
14213 pos (if agendap m (point)))
14214 (with-current-buffer buf
14215 (save-excursion
14216 (save-restriction
14217 (goto-char pos)
14218 (setq cnt (1+ cnt))
14219 (org-toggle-tag tag (if off 'off 'on))
14220 (setq newhead (org-get-heading)))))
14221 (and agendap (org-agenda-change-all-lines newhead m))))
14222 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14224 (defun org-tags-completion-function (string predicate &optional flag)
14225 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14226 (confirm (lambda (x) (stringp (car x)))))
14227 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14228 (setq s1 (match-string 1 string)
14229 s2 (match-string 2 string))
14230 (setq s1 "" s2 string))
14231 (cond
14232 ((eq flag nil)
14233 ;; try completion
14234 (setq rtn (try-completion s2 ctable confirm))
14235 (if (stringp rtn)
14236 (setq rtn
14237 (concat s1 s2 (substring rtn (length s2))
14238 (if (and org-add-colon-after-tag-completion
14239 (assoc rtn ctable))
14240 ":" ""))))
14241 rtn)
14242 ((eq flag t)
14243 ;; all-completions
14244 (all-completions s2 ctable confirm)
14246 ((eq flag 'lambda)
14247 ;; exact match?
14248 (assoc s2 ctable)))
14251 (defun org-fast-tag-insert (kwd tags face &optional end)
14252 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14253 (insert (format "%-12s" (concat kwd ":"))
14254 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14255 (or end "")))
14257 (defun org-fast-tag-show-exit (flag)
14258 (save-excursion
14259 (org-goto-line 3)
14260 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14261 (replace-match ""))
14262 (when flag
14263 (end-of-line 1)
14264 (org-move-to-column (- (window-width) 19) t)
14265 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14267 (defun org-set-current-tags-overlay (current prefix)
14268 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14269 (if (featurep 'xemacs)
14270 (org-overlay-display org-tags-overlay (concat prefix s)
14271 'secondary-selection)
14272 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14273 (org-overlay-display org-tags-overlay (concat prefix s)))))
14275 (defvar org-last-tag-selection-key nil)
14276 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14277 "Fast tag selection with single keys.
14278 CURRENT is the current list of tags in the headline, INHERITED is the
14279 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14280 possibly with grouping information. TODO-TABLE is a similar table with
14281 TODO keywords, should these have keys assigned to them.
14282 If the keys are nil, a-z are automatically assigned.
14283 Returns the new tags string, or nil to not change the current settings."
14284 (let* ((fulltable (append table todo-table))
14285 (maxlen (apply 'max (mapcar
14286 (lambda (x)
14287 (if (stringp (car x)) (string-width (car x)) 0))
14288 fulltable)))
14289 (buf (current-buffer))
14290 (expert (eq org-fast-tag-selection-single-key 'expert))
14291 (buffer-tags nil)
14292 (fwidth (+ maxlen 3 1 3))
14293 (ncol (/ (- (window-width) 4) fwidth))
14294 (i-face 'org-done)
14295 (c-face 'org-todo)
14296 tg cnt e c char c1 c2 ntable tbl rtn
14297 ov-start ov-end ov-prefix
14298 (exit-after-next org-fast-tag-selection-single-key)
14299 (done-keywords org-done-keywords)
14300 groups ingroup)
14301 (save-excursion
14302 (beginning-of-line 1)
14303 (if (looking-at
14304 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14305 (setq ov-start (match-beginning 1)
14306 ov-end (match-end 1)
14307 ov-prefix "")
14308 (setq ov-start (1- (point-at-eol))
14309 ov-end (1+ ov-start))
14310 (skip-chars-forward "^\n\r")
14311 (setq ov-prefix
14312 (concat
14313 (buffer-substring (1- (point)) (point))
14314 (if (> (current-column) org-tags-column)
14316 (make-string (- org-tags-column (current-column)) ?\ ))))))
14317 (move-overlay org-tags-overlay ov-start ov-end)
14318 (save-window-excursion
14319 (if expert
14320 (set-buffer (get-buffer-create " *Org tags*"))
14321 (delete-other-windows)
14322 (split-window-vertically)
14323 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14324 (erase-buffer)
14325 (org-set-local 'org-done-keywords done-keywords)
14326 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14327 (org-fast-tag-insert "Current" current c-face "\n\n")
14328 (org-fast-tag-show-exit exit-after-next)
14329 (org-set-current-tags-overlay current ov-prefix)
14330 (setq tbl fulltable char ?a cnt 0)
14331 (while (setq e (pop tbl))
14332 (cond
14333 ((equal (car e) :startgroup)
14334 (push '() groups) (setq ingroup t)
14335 (when (not (= cnt 0))
14336 (setq cnt 0)
14337 (insert "\n"))
14338 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14339 ((equal (car e) :endgroup)
14340 (setq ingroup nil cnt 0)
14341 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14342 ((equal e '(:newline))
14343 (when (not (= cnt 0))
14344 (setq cnt 0)
14345 (insert "\n")
14346 (setq e (car tbl))
14347 (while (equal (car tbl) '(:newline))
14348 (insert "\n")
14349 (setq tbl (cdr tbl)))))
14351 (setq tg (copy-sequence (car e)) c2 nil)
14352 (if (cdr e)
14353 (setq c (cdr e))
14354 ;; automatically assign a character.
14355 (setq c1 (string-to-char
14356 (downcase (substring
14357 tg (if (= (string-to-char tg) ?@) 1 0)))))
14358 (if (or (rassoc c1 ntable) (rassoc c1 table))
14359 (while (or (rassoc char ntable) (rassoc char table))
14360 (setq char (1+ char)))
14361 (setq c2 c1))
14362 (setq c (or c2 char)))
14363 (if ingroup (push tg (car groups)))
14364 (setq tg (org-add-props tg nil 'face
14365 (cond
14366 ((not (assoc tg table))
14367 (org-get-todo-face tg))
14368 ((member tg current) c-face)
14369 ((member tg inherited) i-face))))
14370 (if (and (= cnt 0) (not ingroup)) (insert " "))
14371 (insert "[" c "] " tg (make-string
14372 (- fwidth 4 (length tg)) ?\ ))
14373 (push (cons tg c) ntable)
14374 (when (= (setq cnt (1+ cnt)) ncol)
14375 (insert "\n")
14376 (if ingroup (insert " "))
14377 (setq cnt 0)))))
14378 (setq ntable (nreverse ntable))
14379 (insert "\n")
14380 (goto-char (point-min))
14381 (if (not expert) (org-fit-window-to-buffer))
14382 (setq rtn
14383 (catch 'exit
14384 (while t
14385 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14386 (if (not groups) "no " "")
14387 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14388 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14389 (setq org-last-tag-selection-key c)
14390 (cond
14391 ((= c ?\r) (throw 'exit t))
14392 ((= c ?!)
14393 (setq groups (not groups))
14394 (goto-char (point-min))
14395 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14396 ((= c ?\C-c)
14397 (if (not expert)
14398 (org-fast-tag-show-exit
14399 (setq exit-after-next (not exit-after-next)))
14400 (setq expert nil)
14401 (delete-other-windows)
14402 (set-window-buffer (split-window-vertically) " *Org tags*")
14403 (org-switch-to-buffer-other-window " *Org tags*")
14404 (org-fit-window-to-buffer)))
14405 ((or (= c ?\C-g)
14406 (and (= c ?q) (not (rassoc c ntable))))
14407 (org-detach-overlay org-tags-overlay)
14408 (setq quit-flag t))
14409 ((= c ?\ )
14410 (setq current nil)
14411 (if exit-after-next (setq exit-after-next 'now)))
14412 ((= c ?\t)
14413 (condition-case nil
14414 (setq tg (org-icompleting-read
14415 "Tag: "
14416 (or buffer-tags
14417 (with-current-buffer buf
14418 (org-get-buffer-tags)))))
14419 (quit (setq tg "")))
14420 (when (string-match "\\S-" tg)
14421 (add-to-list 'buffer-tags (list tg))
14422 (if (member tg current)
14423 (setq current (delete tg current))
14424 (push tg current)))
14425 (if exit-after-next (setq exit-after-next 'now)))
14426 ((setq e (rassoc c todo-table) tg (car e))
14427 (with-current-buffer buf
14428 (save-excursion (org-todo tg)))
14429 (if exit-after-next (setq exit-after-next 'now)))
14430 ((setq e (rassoc c ntable) tg (car e))
14431 (if (member tg current)
14432 (setq current (delete tg current))
14433 (loop for g in groups do
14434 (if (member tg g)
14435 (mapc (lambda (x)
14436 (setq current (delete x current)))
14437 g)))
14438 (push tg current))
14439 (if exit-after-next (setq exit-after-next 'now))))
14441 ;; Create a sorted list
14442 (setq current
14443 (sort current
14444 (lambda (a b)
14445 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14446 (if (eq exit-after-next 'now) (throw 'exit t))
14447 (goto-char (point-min))
14448 (beginning-of-line 2)
14449 (delete-region (point) (point-at-eol))
14450 (org-fast-tag-insert "Current" current c-face)
14451 (org-set-current-tags-overlay current ov-prefix)
14452 (while (re-search-forward
14453 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14454 (setq tg (match-string 1))
14455 (add-text-properties
14456 (match-beginning 1) (match-end 1)
14457 (list 'face
14458 (cond
14459 ((member tg current) c-face)
14460 ((member tg inherited) i-face)
14461 (t (get-text-property (match-beginning 1) 'face))))))
14462 (goto-char (point-min)))))
14463 (org-detach-overlay org-tags-overlay)
14464 (if rtn
14465 (mapconcat 'identity current ":")
14466 nil))))
14468 (defun org-get-tags-string ()
14469 "Get the TAGS string in the current headline."
14470 (unless (org-at-heading-p t)
14471 (error "Not on a heading"))
14472 (save-excursion
14473 (beginning-of-line 1)
14474 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14475 (org-match-string-no-properties 1)
14476 "")))
14478 (defun org-get-tags ()
14479 "Get the list of tags specified in the current headline."
14480 (org-split-string (org-get-tags-string) ":"))
14482 (defun org-get-buffer-tags ()
14483 "Get a table of all tags used in the buffer, for completion."
14484 (let (tags)
14485 (save-excursion
14486 (goto-char (point-min))
14487 (while (re-search-forward
14488 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14489 (when (equal (char-after (point-at-bol 0)) ?*)
14490 (mapc (lambda (x) (add-to-list 'tags x))
14491 (org-split-string (org-match-string-no-properties 1) ":")))))
14492 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14493 (mapcar 'list tags)))
14495 ;;;; The mapping API
14497 (defun org-map-entries (func &optional match scope &rest skip)
14498 "Call FUNC at each headline selected by MATCH in SCOPE.
14500 FUNC is a function or a lisp form. The function will be called without
14501 arguments, with the cursor positioned at the beginning of the headline.
14502 The return values of all calls to the function will be collected and
14503 returned as a list.
14505 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14506 does not need to preserve point. After evaluation, the cursor will be
14507 moved to the end of the line (presumably of the headline of the
14508 processed entry) and search continues from there. Under some
14509 circumstances, this may not produce the wanted results. For example,
14510 if you have removed (e.g. archived) the current (sub)tree it could
14511 mean that the next entry will be skipped entirely. In such cases, you
14512 can specify the position from where search should continue by making
14513 FUNC set the variable `org-map-continue-from' to the desired buffer
14514 position.
14516 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14517 Only headlines that are matched by this query will be considered during
14518 the iteration. When MATCH is nil or t, all headlines will be
14519 visited by the iteration.
14521 SCOPE determines the scope of this command. It can be any of:
14523 nil The current buffer, respecting the restriction if any
14524 tree The subtree started with the entry at point
14525 region The entries within the active region, if any
14526 region-start-level
14527 The entries within the active region, but only those at
14528 the same level than the first one.
14529 file The current buffer, without restriction
14530 file-with-archives
14531 The current buffer, and any archives associated with it
14532 agenda All agenda files
14533 agenda-with-archives
14534 All agenda files with any archive files associated with them
14535 \(file1 file2 ...)
14536 If this is a list, all files in the list will be scanned
14538 The remaining args are treated as settings for the skipping facilities of
14539 the scanner. The following items can be given here:
14541 archive skip trees with the archive tag
14542 comment skip trees with the COMMENT keyword
14543 function or Emacs Lisp form:
14544 will be used as value for `org-agenda-skip-function', so
14545 whenever the function returns a position, FUNC will not be
14546 called for that entry and search will continue from the
14547 position returned
14549 If your function needs to retrieve the tags including inherited tags
14550 at the *current* entry, you can use the value of the variable
14551 `org-scanner-tags' which will be much faster than getting the value
14552 with `org-get-tags-at'. If your function gets properties with
14553 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14554 to t around the call to `org-entry-properties' to get the same speedup.
14555 Note that if your function moves around to retrieve tags and properties at
14556 a *different* entry, you cannot use these techniques."
14557 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14558 (not (org-region-active-p)))
14559 (let* ((org-agenda-archives-mode nil) ; just to make sure
14560 (org-agenda-skip-archived-trees (memq 'archive skip))
14561 (org-agenda-skip-comment-trees (memq 'comment skip))
14562 (org-agenda-skip-function
14563 (car (org-delete-all '(comment archive) skip)))
14564 (org-tags-match-list-sublevels t)
14565 (start-level (eq scope 'region-start-level))
14566 matcher file res
14567 org-todo-keywords-for-agenda
14568 org-done-keywords-for-agenda
14569 org-todo-keyword-alist-for-agenda
14570 org-drawers-for-agenda
14571 org-tag-alist-for-agenda
14572 todo-only)
14574 (cond
14575 ((eq match t) (setq matcher t))
14576 ((eq match nil) (setq matcher t))
14577 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14579 (save-excursion
14580 (save-restriction
14581 (cond ((eq scope 'tree)
14582 (org-back-to-heading t)
14583 (org-narrow-to-subtree)
14584 (setq scope nil))
14585 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14586 (org-region-active-p))
14587 ;; If needed, set start-level to a string like "2"
14588 (when start-level
14589 (save-excursion
14590 (goto-char (region-beginning))
14591 (unless (org-at-heading-p) (outline-next-heading))
14592 (setq start-level (org-current-level))))
14593 (narrow-to-region (region-beginning)
14594 (save-excursion
14595 (goto-char (region-end))
14596 (unless (and (bolp) (org-at-heading-p))
14597 (outline-next-heading))
14598 (point)))
14599 (setq scope nil)))
14601 (if (not scope)
14602 (progn
14603 (org-agenda-prepare-buffers
14604 (list (buffer-file-name (current-buffer))))
14605 (setq res (org-scan-tags func matcher todo-only start-level)))
14606 ;; Get the right scope
14607 (cond
14608 ((and scope (listp scope) (symbolp (car scope)))
14609 (setq scope (eval scope)))
14610 ((eq scope 'agenda)
14611 (setq scope (org-agenda-files t)))
14612 ((eq scope 'agenda-with-archives)
14613 (setq scope (org-agenda-files t))
14614 (setq scope (org-add-archive-files scope)))
14615 ((eq scope 'file)
14616 (setq scope (list (buffer-file-name))))
14617 ((eq scope 'file-with-archives)
14618 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14619 (org-agenda-prepare-buffers scope)
14620 (while (setq file (pop scope))
14621 (with-current-buffer (org-find-base-buffer-visiting file)
14622 (save-excursion
14623 (save-restriction
14624 (widen)
14625 (goto-char (point-min))
14626 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14627 res)))
14629 ;;;; Properties
14631 ;;; Setting and retrieving properties
14633 (defconst org-special-properties
14634 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14635 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14636 "The special properties valid in Org-mode.
14638 These are properties that are not defined in the property drawer,
14639 but in some other way.")
14641 (defconst org-default-properties
14642 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14643 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14644 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14645 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14646 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14647 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14648 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14649 "Some properties that are used by Org-mode for various purposes.
14650 Being in this list makes sure that they are offered for completion.")
14652 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14653 "Regular expression matching the first line of a property drawer.")
14655 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14656 "Regular expression matching the last line of a property drawer.")
14658 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14659 "Regular expression matching the first line of a property drawer.")
14661 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14662 "Regular expression matching the first line of a property drawer.")
14664 (defconst org-property-drawer-re
14665 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14666 org-property-end-re "\\)\n?")
14667 "Matches an entire property drawer.")
14669 (defconst org-clock-drawer-re
14670 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14671 org-property-end-re "\\)\n?")
14672 "Matches an entire clock drawer.")
14674 (defsubst org-re-property (property)
14675 "Return a regexp matching a PROPERTY line.
14676 Match group 1 will be set to the value."
14677 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14679 (defsubst org-re-property-keyword (property)
14680 "Return a regexp matching a PROPERTY line, possibly with no
14681 value for the property."
14682 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14684 (defun org-property-action ()
14685 "Do an action on properties."
14686 (interactive)
14687 (let (c)
14688 (org-at-property-p)
14689 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14690 (setq c (read-char-exclusive))
14691 (cond
14692 ((equal c ?s)
14693 (call-interactively 'org-set-property))
14694 ((equal c ?d)
14695 (call-interactively 'org-delete-property))
14696 ((equal c ?D)
14697 (call-interactively 'org-delete-property-globally))
14698 ((equal c ?c)
14699 (call-interactively 'org-compute-property-at-point))
14700 (t (error "No such property action %c" c)))))
14702 (defun org-inc-effort ()
14703 "Increment the value of the effort property in the current entry."
14704 (interactive)
14705 (org-set-effort nil t))
14707 (defvar org-clock-effort) ;; Defined in org-clock.el
14708 (defvar org-clock-current-task) ;; Defined in org-clock.el
14709 (defun org-set-effort (&optional value increment)
14710 "Set the effort property of the current entry.
14711 With numerical prefix arg, use the nth allowed value, 0 stands for the
14712 10th allowed value.
14714 When INCREMENT is non-nil, set the property to the next allowed value."
14715 (interactive "P")
14716 (if (equal value 0) (setq value 10))
14717 (let* ((completion-ignore-case t)
14718 (prop org-effort-property)
14719 (cur (org-entry-get nil prop))
14720 (allowed (org-property-get-allowed-values nil prop 'table))
14721 (existing (mapcar 'list (org-property-values prop)))
14722 (heading (nth 4 (org-heading-components)))
14724 (val (cond
14725 ((stringp value) value)
14726 ((and allowed (integerp value))
14727 (or (car (nth (1- value) allowed))
14728 (car (org-last allowed))))
14729 ((and allowed increment)
14730 (or (caadr (member (list cur) allowed))
14731 (error "Allowed effort values are not set")))
14732 (allowed
14733 (message "Select 1-9,0, [RET%s]: %s"
14734 (if cur (concat "=" cur) "")
14735 (mapconcat 'car allowed " "))
14736 (setq rpl (read-char-exclusive))
14737 (if (equal rpl ?\r)
14739 (setq rpl (- rpl ?0))
14740 (if (equal rpl 0) (setq rpl 10))
14741 (if (and (> rpl 0) (<= rpl (length allowed)))
14742 (car (nth (1- rpl) allowed))
14743 (org-completing-read "Effort: " allowed nil))))
14745 (let (org-completion-use-ido org-completion-use-iswitchb)
14746 (org-completing-read
14747 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14748 (concat "[" cur "]") "")
14749 ": ")
14750 existing nil nil "" nil cur))))))
14751 (unless (equal (org-entry-get nil prop) val)
14752 (org-entry-put nil prop val))
14753 (save-excursion
14754 (org-back-to-heading t)
14755 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14756 (when (string= heading org-clock-current-task)
14757 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14758 (org-clock-update-mode-line))
14759 (message "%s is now %s" prop val)))
14761 (defun org-at-property-p ()
14762 "Is cursor inside a property drawer?"
14763 (save-excursion
14764 (beginning-of-line 1)
14765 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14766 (save-match-data ;; Used by calling procedures
14767 (let ((p (point))
14768 (range (unless (org-before-first-heading-p)
14769 (org-get-property-block))))
14770 (and range (<= (car range) p) (< p (cdr range))))))))
14772 (defun org-get-property-block (&optional beg end force)
14773 "Return the (beg . end) range of the body of the property drawer.
14774 BEG and END are the beginning and end of the current subtree, or of
14775 the part before the first headline. If they are not given, they will
14776 be found. If the drawer does not exist and FORCE is non-nil, create
14777 the drawer."
14778 (catch 'exit
14779 (save-excursion
14780 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14781 (progn (org-back-to-heading t) (point))))
14782 (end (or end (and (not (outline-next-heading)) (point-max))
14783 (point))))
14784 (goto-char beg)
14785 (if (re-search-forward org-property-start-re end t)
14786 (setq beg (1+ (match-end 0)))
14787 (if force
14788 (save-excursion
14789 (org-insert-property-drawer)
14790 (setq end (progn (outline-next-heading) (point))))
14791 (throw 'exit nil))
14792 (goto-char beg)
14793 (if (re-search-forward org-property-start-re end t)
14794 (setq beg (1+ (match-end 0)))))
14795 (if (re-search-forward org-property-end-re end t)
14796 (setq end (match-beginning 0))
14797 (or force (throw 'exit nil))
14798 (goto-char beg)
14799 (setq end beg)
14800 (org-indent-line)
14801 (insert ":END:\n"))
14802 (cons beg end)))))
14804 (defun org-entry-properties (&optional pom which specific)
14805 "Get all properties of the entry at point-or-marker POM.
14806 This includes the TODO keyword, the tags, time strings for deadline,
14807 scheduled, and clocking, and any additional properties defined in the
14808 entry. The return value is an alist, keys may occur multiple times
14809 if the property key was used several times.
14810 POM may also be nil, in which case the current entry is used.
14811 If WHICH is nil or `all', get all properties. If WHICH is
14812 `special' or `standard', only get that subclass. If WHICH
14813 is a string only get exactly this property. SPECIFIC can be a string, the
14814 specific property we are interested in. Specifying it can speed
14815 things up because then unnecessary parsing is avoided."
14816 (setq which (or which 'all))
14817 (org-with-point-at pom
14818 (let ((clockstr (substring org-clock-string 0 -1))
14819 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14820 (case-fold-search nil)
14821 beg end range props sum-props key key1 value string clocksum clocksumt)
14822 (save-excursion
14823 (when (condition-case nil
14824 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14825 (error nil))
14826 (setq beg (point))
14827 (setq sum-props (get-text-property (point) 'org-summaries))
14828 (setq clocksum (get-text-property (point) :org-clock-minutes)
14829 clocksumt (get-text-property (point) :org-clock-minutes-today))
14830 (outline-next-heading)
14831 (setq end (point))
14832 (when (memq which '(all special))
14833 ;; Get the special properties, like TODO and tags
14834 (goto-char beg)
14835 (when (and (or (not specific) (string= specific "TODO"))
14836 (looking-at org-todo-line-regexp) (match-end 2))
14837 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14838 (when (and (or (not specific) (string= specific "PRIORITY"))
14839 (looking-at org-priority-regexp))
14840 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14841 (when (or (not specific) (string= specific "FILE"))
14842 (push (cons "FILE" buffer-file-name) props))
14843 (when (and (or (not specific) (string= specific "TAGS"))
14844 (setq value (org-get-tags-string))
14845 (string-match "\\S-" value))
14846 (push (cons "TAGS" value) props))
14847 (when (and (or (not specific) (string= specific "ALLTAGS"))
14848 (setq value (org-get-tags-at)))
14849 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14850 ":"))
14851 props))
14852 (when (or (not specific) (string= specific "BLOCKED"))
14853 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14854 (when (or (not specific)
14855 (member specific
14856 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14857 "TIMESTAMP" "TIMESTAMP_IA")))
14858 (catch 'match
14859 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14860 (setq key (if (match-end 1)
14861 (substring (org-match-string-no-properties 1)
14862 0 -1))
14863 string (if (equal key clockstr)
14864 (org-trim
14865 (buffer-substring-no-properties
14866 (match-beginning 3) (goto-char
14867 (point-at-eol))))
14868 (substring (org-match-string-no-properties 3)
14869 1 -1)))
14870 ;; Get the correct property name from the key. This is
14871 ;; necessary if the user has configured time keywords.
14872 (setq key1 (concat key ":"))
14873 (cond
14874 ((not key)
14875 (setq key
14876 (if (= (char-after (match-beginning 3)) ?\[)
14877 "TIMESTAMP_IA" "TIMESTAMP")))
14878 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14879 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14880 ((equal key1 org-closed-string) (setq key "CLOSED"))
14881 ((equal key1 org-clock-string) (setq key "CLOCK")))
14882 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14883 (progn
14884 (push (cons key string) props)
14885 ;; no need to search further if match is found
14886 (throw 'match t))
14887 (when (or (equal key "CLOCK") (not (assoc key props)))
14888 (push (cons key string) props)))))))
14890 (when (memq which '(all standard))
14891 ;; Get the standard properties, like :PROP: ...
14892 (setq range (org-get-property-block beg end))
14893 (when range
14894 (goto-char (car range))
14895 (while (re-search-forward
14896 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14897 (cdr range) t)
14898 (setq key (org-match-string-no-properties 1)
14899 value (org-trim (or (org-match-string-no-properties 2) "")))
14900 (unless (member key excluded)
14901 (push (cons key (or value "")) props)))))
14902 (if clocksum
14903 (push (cons "CLOCKSUM"
14904 (org-columns-number-to-string (/ (float clocksum) 60.)
14905 'add_times))
14906 props))
14907 (if clocksumt
14908 (push (cons "CLOCKSUM_T"
14909 (org-columns-number-to-string (/ (float clocksumt) 60.)
14910 'add_times))
14911 props))
14912 (unless (assoc "CATEGORY" props)
14913 (push (cons "CATEGORY" (org-get-category)) props))
14914 (append sum-props (nreverse props)))))))
14916 (defun org-entry-get (pom property &optional inherit literal-nil)
14917 "Get value of PROPERTY for entry or content at point-or-marker POM.
14918 If INHERIT is non-nil and the entry does not have the property,
14919 then also check higher levels of the hierarchy.
14920 If INHERIT is the symbol `selective', use inheritance only if the setting
14921 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14922 If the property is present but empty, the return value is the empty string.
14923 If the property is not present at all, nil is returned.
14925 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14926 do not interpret it as the list atom nil. This is used for inheritance
14927 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14928 (org-with-point-at pom
14929 (if (and inherit (if (eq inherit 'selective)
14930 (org-property-inherit-p property)
14932 (org-entry-get-with-inheritance property literal-nil)
14933 (if (member property org-special-properties)
14934 ;; We need a special property. Use `org-entry-properties' to
14935 ;; retrieve it, but specify the wanted property
14936 (cdr (assoc property (org-entry-properties nil 'special property)))
14937 (let ((range (org-get-property-block)))
14938 (when (and range (not (eq (car range) (cdr range))))
14939 (let* ((props (list (or (assoc property org-file-properties)
14940 (assoc property org-global-properties)
14941 (assoc property org-global-properties-fixed))))
14942 (ap (lambda (key)
14943 (when (re-search-forward
14944 (org-re-property key) (cdr range) t)
14945 (setq props
14946 (org-update-property-plist
14948 (if (match-end 1)
14949 (org-match-string-no-properties 1) "")
14950 props)))))
14951 val)
14952 (goto-char (car range))
14953 (funcall ap property)
14954 (goto-char (car range))
14955 (while (funcall ap (concat property "+")))
14956 (setq val (cdr (assoc property props)))
14957 (when val (if literal-nil val (org-not-nil val))))))))))
14959 (defun org-property-or-variable-value (var &optional inherit)
14960 "Check if there is a property fixing the value of VAR.
14961 If yes, return this value. If not, return the current value of the variable."
14962 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14963 (if (and prop (stringp prop) (string-match "\\S-" prop))
14964 (read prop)
14965 (symbol-value var))))
14967 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14968 "Delete the property PROPERTY from entry at point-or-marker POM.
14969 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14970 an empty drawer to delete."
14971 (org-with-point-at pom
14972 (if (member property org-special-properties)
14973 nil ; cannot delete these properties.
14974 (let ((range (org-get-property-block)))
14975 (if (and range
14976 (goto-char (car range))
14977 (re-search-forward
14978 (org-re-property property)
14979 (cdr range) t))
14980 (progn
14981 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14982 (and delete-empty-drawer
14983 (org-remove-empty-drawer-at
14984 delete-empty-drawer (car range)))
14986 nil)))))
14988 ;; Multi-values properties are properties that contain multiple values
14989 ;; These values are assumed to be single words, separated by whitespace.
14990 (defun org-entry-add-to-multivalued-property (pom property value)
14991 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14992 (let* ((old (org-entry-get pom property))
14993 (values (and old (org-split-string old "[ \t]"))))
14994 (setq value (org-entry-protect-space value))
14995 (unless (member value values)
14996 (setq values (cons value values))
14997 (org-entry-put pom property
14998 (mapconcat 'identity values " ")))))
15000 (defun org-entry-remove-from-multivalued-property (pom property value)
15001 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15002 (let* ((old (org-entry-get pom property))
15003 (values (and old (org-split-string old "[ \t]"))))
15004 (setq value (org-entry-protect-space value))
15005 (when (member value values)
15006 (setq values (delete value values))
15007 (org-entry-put pom property
15008 (mapconcat 'identity values " ")))))
15010 (defun org-entry-member-in-multivalued-property (pom property value)
15011 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15012 (let* ((old (org-entry-get pom property))
15013 (values (and old (org-split-string old "[ \t]"))))
15014 (setq value (org-entry-protect-space value))
15015 (member value values)))
15017 (defun org-entry-get-multivalued-property (pom property)
15018 "Return a list of values in a multivalued property."
15019 (let* ((value (org-entry-get pom property))
15020 (values (and value (org-split-string value "[ \t]"))))
15021 (mapcar 'org-entry-restore-space values)))
15023 (defun org-entry-put-multivalued-property (pom property &rest values)
15024 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15025 VALUES should be a list of strings. Spaces will be protected."
15026 (org-entry-put pom property
15027 (mapconcat 'org-entry-protect-space values " "))
15028 (let* ((value (org-entry-get pom property))
15029 (values (and value (org-split-string value "[ \t]"))))
15030 (mapcar 'org-entry-restore-space values)))
15032 (defun org-entry-protect-space (s)
15033 "Protect spaces and newline in string S."
15034 (while (string-match " " s)
15035 (setq s (replace-match "%20" t t s)))
15036 (while (string-match "\n" s)
15037 (setq s (replace-match "%0A" t t s)))
15040 (defun org-entry-restore-space (s)
15041 "Restore spaces and newline in string S."
15042 (while (string-match "%20" s)
15043 (setq s (replace-match " " t t s)))
15044 (while (string-match "%0A" s)
15045 (setq s (replace-match "\n" t t s)))
15048 (defvar org-entry-property-inherited-from (make-marker)
15049 "Marker pointing to the entry from where a property was inherited.
15050 Each call to `org-entry-get-with-inheritance' will set this marker to the
15051 location of the entry where the inheritance search matched. If there was
15052 no match, the marker will point nowhere.
15053 Note that also `org-entry-get' calls this function, if the INHERIT flag
15054 is set.")
15056 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15057 "Get PROPERTY of entry or content at point, search higher levels if needed.
15058 The search will stop at the first ancestor which has the property defined.
15059 If the value found is \"nil\", return nil to show that the property
15060 should be considered as undefined (this is the meaning of nil here).
15061 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15062 (move-marker org-entry-property-inherited-from nil)
15063 (let (tmp)
15064 (save-excursion
15065 (save-restriction
15066 (widen)
15067 (catch 'ex
15068 (while t
15069 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15070 (or (ignore-errors (org-back-to-heading t))
15071 (goto-char (point-min)))
15072 (move-marker org-entry-property-inherited-from (point))
15073 (throw 'ex tmp))
15074 (or (ignore-errors (org-up-heading-safe))
15075 (throw 'ex nil))))))
15076 (setq tmp (or tmp
15077 (cdr (assoc property org-file-properties))
15078 (cdr (assoc property org-global-properties))
15079 (cdr (assoc property org-global-properties-fixed))))
15080 (if literal-nil tmp (org-not-nil tmp))))
15082 (defvar org-property-changed-functions nil
15083 "Hook called when the value of a property has changed.
15084 Each hook function should accept two arguments, the name of the property
15085 and the new value.")
15087 (defun org-entry-put (pom property value)
15088 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15089 (org-with-point-at pom
15090 (org-back-to-heading t)
15091 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15092 range)
15093 (cond
15094 ((equal property "TODO")
15095 (when (and (stringp value) (string-match "\\S-" value)
15096 (not (member value org-todo-keywords-1)))
15097 (error "\"%s\" is not a valid TODO state" value))
15098 (if (or (not value)
15099 (not (string-match "\\S-" value)))
15100 (setq value 'none))
15101 (org-todo value)
15102 (org-set-tags nil 'align))
15103 ((equal property "PRIORITY")
15104 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15105 (string-to-char value) ?\ ))
15106 (org-set-tags nil 'align))
15107 ((equal property "CLOCKSUM")
15108 (if (not (re-search-forward
15109 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15110 (error "Cannot find a clock log")
15111 (goto-char (- (match-end 1) 2))
15112 (cond
15113 ((eq value 'earlier) (org-timestamp-down))
15114 ((eq value 'later) (org-timestamp-up)))
15115 (org-clock-sum-current-item)))
15116 ((equal property "SCHEDULED")
15117 (if (re-search-forward org-scheduled-time-regexp end t)
15118 (cond
15119 ((eq value 'earlier) (org-timestamp-change -1 'day))
15120 ((eq value 'later) (org-timestamp-change 1 'day))
15121 (t (call-interactively 'org-schedule)))
15122 (call-interactively 'org-schedule)))
15123 ((equal property "DEADLINE")
15124 (if (re-search-forward org-deadline-time-regexp end t)
15125 (cond
15126 ((eq value 'earlier) (org-timestamp-change -1 'day))
15127 ((eq value 'later) (org-timestamp-change 1 'day))
15128 (t (call-interactively 'org-deadline)))
15129 (call-interactively 'org-deadline)))
15130 ((member property org-special-properties)
15131 (error "The %s property can not yet be set with `org-entry-put'"
15132 property))
15133 (t ; a non-special property
15134 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15135 (setq range (org-get-property-block beg end 'force))
15136 (goto-char (car range))
15137 (if (re-search-forward
15138 (org-re-property-keyword property) (cdr range) t)
15139 (progn
15140 (delete-region (match-beginning 0) (match-end 0))
15141 (goto-char (match-beginning 0)))
15142 (goto-char (cdr range))
15143 (insert "\n")
15144 (backward-char 1)
15145 (org-indent-line))
15146 (insert ":" property ":")
15147 (and value (insert " " value))
15148 (org-indent-line)))))
15149 (run-hook-with-args 'org-property-changed-functions property value)))
15151 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15152 "Get all property keys in the current buffer.
15153 With INCLUDE-SPECIALS, also list the special properties that reflect things
15154 like tags and TODO state.
15155 With INCLUDE-DEFAULTS, also include properties that has special meaning
15156 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15157 and others.
15158 With INCLUDE-COLUMNS, also include property names given in COLUMN
15159 formats in the current buffer."
15160 (let (rtn range cfmt s p)
15161 (save-excursion
15162 (save-restriction
15163 (widen)
15164 (goto-char (point-min))
15165 (while (re-search-forward org-property-start-re nil t)
15166 (setq range (org-get-property-block))
15167 (goto-char (car range))
15168 (while (re-search-forward
15169 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15170 (cdr range) t)
15171 (add-to-list 'rtn (org-match-string-no-properties 1)))
15172 (outline-next-heading))))
15174 (when include-specials
15175 (setq rtn (append org-special-properties rtn)))
15177 (when include-defaults
15178 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15179 (add-to-list 'rtn org-effort-property))
15181 (when include-columns
15182 (save-excursion
15183 (save-restriction
15184 (widen)
15185 (goto-char (point-min))
15186 (while (re-search-forward
15187 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15188 nil t)
15189 (setq cfmt (match-string 2) s 0)
15190 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15191 cfmt s)
15192 (setq s (match-end 0)
15193 p (match-string 1 cfmt))
15194 (unless (or (equal p "ITEM")
15195 (member p org-special-properties))
15196 (add-to-list 'rtn (match-string 1 cfmt))))))))
15198 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15200 (defun org-property-values (key)
15201 "Return a list of all values of property KEY in the current buffer."
15202 (save-excursion
15203 (save-restriction
15204 (widen)
15205 (goto-char (point-min))
15206 (let ((re (org-re-property key))
15207 values)
15208 (while (re-search-forward re nil t)
15209 (add-to-list 'values (org-trim (match-string 1))))
15210 (delete "" values)))))
15212 (defun org-insert-property-drawer ()
15213 "Insert a property drawer into the current entry."
15214 (org-back-to-heading t)
15215 (looking-at org-outline-regexp)
15216 (let ((indent (if org-adapt-indentation
15217 (- (match-end 0) (match-beginning 0))
15219 (beg (point))
15220 (re (concat "^[ \t]*" org-keyword-time-regexp))
15221 end hiddenp)
15222 (outline-next-heading)
15223 (setq end (point))
15224 (goto-char beg)
15225 (while (re-search-forward re end t))
15226 (setq hiddenp (outline-invisible-p))
15227 (end-of-line 1)
15228 (and (equal (char-after) ?\n) (forward-char 1))
15229 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15230 (if (member (match-string 1) '("CLOCK:" ":END:"))
15231 ;; just skip this line
15232 (beginning-of-line 2)
15233 ;; Drawer start, find the end
15234 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15235 (beginning-of-line 1)))
15236 (org-skip-over-state-notes)
15237 (skip-chars-backward " \t\n\r")
15238 (if (eq (char-before) ?*) (forward-char 1))
15239 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15240 (beginning-of-line 0)
15241 (org-indent-to-column indent)
15242 (beginning-of-line 2)
15243 (org-indent-to-column indent)
15244 (beginning-of-line 0)
15245 (if hiddenp
15246 (save-excursion
15247 (org-back-to-heading t)
15248 (hide-entry))
15249 (org-flag-drawer t))))
15251 (defun org-insert-drawer (&optional arg drawer)
15252 "Insert a drawer at point.
15254 Optional argument DRAWER, when non-nil, is a string representing
15255 drawer's name. Otherwise, the user is prompted for a name.
15257 If a region is active, insert the drawer around that region
15258 instead.
15260 Point is left between drawer's boundaries."
15261 (interactive "P")
15262 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15263 "LOGBOOK"))
15264 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15265 ;; internally by Org. They are meant to be inserted
15266 ;; automatically.
15267 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15268 ;; Remove system drawers from list. Note: For some reason,
15269 ;; `org-completing-read' ignores the predicate while
15270 ;; `completing-read' handles it fine.
15271 (drawer (if arg "PROPERTIES"
15272 (or drawer
15273 (completing-read
15274 "Drawer: " org-drawers
15275 (lambda (d) (not (member d system-drawers))))))))
15276 (cond
15277 ;; With C-u, fall back on `org-insert-property-drawer'
15278 (arg (org-insert-property-drawer))
15279 ;; With an active region, insert a drawer at point.
15280 ((not (org-region-active-p))
15281 (progn
15282 (unless (bolp) (insert "\n"))
15283 (insert (format ":%s:\n\n:END:\n" drawer))
15284 (forward-line -2)))
15285 ;; Otherwise, insert the drawer at point
15287 (let ((rbeg (region-beginning))
15288 (rend (copy-marker (region-end))))
15289 (unwind-protect
15290 (progn
15291 (goto-char rbeg)
15292 (beginning-of-line)
15293 (when (save-excursion
15294 (re-search-forward org-outline-regexp-bol rend t))
15295 (error "Drawers cannot contain headlines"))
15296 ;; Position point at the beginning of the first
15297 ;; non-blank line in region. Insert drawer's opening
15298 ;; there, then indent it.
15299 (org-skip-whitespace)
15300 (beginning-of-line)
15301 (insert ":" drawer ":\n")
15302 (forward-line -1)
15303 (indent-for-tab-command)
15304 ;; Move point to the beginning of the first blank line
15305 ;; after the last non-blank line in region. Insert
15306 ;; drawer's closing, then indent it.
15307 (goto-char rend)
15308 (skip-chars-backward " \r\t\n")
15309 (insert "\n:END:")
15310 (deactivate-mark t)
15311 (indent-for-tab-command)
15312 (unless (eolp) (insert "\n")))
15313 ;; Clear marker, whatever the outcome of insertion is.
15314 (set-marker rend nil)))))))
15316 (defvar org-property-set-functions-alist nil
15317 "Property set function alist.
15318 Each entry should have the following format:
15320 (PROPERTY . READ-FUNCTION)
15322 The read function will be called with the same argument as
15323 `org-completing-read'.")
15325 (defun org-set-property-function (property)
15326 "Get the function that should be used to set PROPERTY.
15327 This is computed according to `org-property-set-functions-alist'."
15328 (or (cdr (assoc property org-property-set-functions-alist))
15329 'org-completing-read))
15331 (defun org-read-property-value (property)
15332 "Read PROPERTY value from user."
15333 (let* ((completion-ignore-case t)
15334 (allowed (org-property-get-allowed-values nil property 'table))
15335 (cur (org-entry-get nil property))
15336 (prompt (concat property " value"
15337 (if (and cur (string-match "\\S-" cur))
15338 (concat " [" cur "]") "") ": "))
15339 (set-function (org-set-property-function property))
15340 (val (if allowed
15341 (funcall set-function prompt allowed nil
15342 (not (get-text-property 0 'org-unrestricted
15343 (caar allowed))))
15344 (let (org-completion-use-ido org-completion-use-iswitchb)
15345 (funcall set-function prompt
15346 (mapcar 'list (org-property-values property))
15347 nil nil "" nil cur)))))
15348 (if (equal val "")
15350 val)))
15352 (defvar org-last-set-property nil)
15353 (defvar org-last-set-property-value nil)
15354 (defun org-read-property-name ()
15355 "Read a property name."
15356 (let* ((completion-ignore-case t)
15357 (keys (org-buffer-property-keys nil t t))
15358 (default-prop (or (save-excursion
15359 (save-match-data
15360 (beginning-of-line)
15361 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15362 (null (string= (match-string 1) "END"))
15363 (match-string 1))))
15364 org-last-set-property))
15365 (property (org-icompleting-read
15366 (concat "Property"
15367 (if default-prop (concat " [" default-prop "]") "")
15368 ": ")
15369 (mapcar 'list keys)
15370 nil nil nil nil
15371 default-prop)))
15372 (if (member property keys)
15373 property
15374 (or (cdr (assoc (downcase property)
15375 (mapcar (lambda (x) (cons (downcase x) x))
15376 keys)))
15377 property))))
15379 (defun org-set-property-and-value (use-last)
15380 "Allow to set [PROPERTY]: [value] direction from prompt.
15381 When use-default, don't even ask, just use the last
15382 \"[PROPERTY]: [value]\" string from the history."
15383 (interactive "P")
15384 (let* ((completion-ignore-case t)
15385 (pv (or (and use-last org-last-set-property-value)
15386 (org-completing-read
15387 "Enter a \"[Property]: [value]\" pair: "
15388 nil nil nil nil nil
15389 org-last-set-property-value)))
15390 prop val)
15391 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15392 (setq prop (match-string 1 pv)
15393 val (match-string 2 pv))
15394 (org-set-property prop val))))
15396 (defun org-set-property (property value)
15397 "In the current entry, set PROPERTY to VALUE.
15398 When called interactively, this will prompt for a property name, offering
15399 completion on existing and default properties. And then it will prompt
15400 for a value, offering completion either on allowed values (via an inherited
15401 xxx_ALL property) or on existing values in other instances of this property
15402 in the current file."
15403 (interactive (list nil nil))
15404 (let* ((property (or property (org-read-property-name)))
15405 (value (or value (org-read-property-value property)))
15406 (fn (cdr (assoc property org-properties-postprocess-alist))))
15407 (setq org-last-set-property property)
15408 (setq org-last-set-property-value (concat property ": " value))
15409 ;; Possibly postprocess the inserted value:
15410 (when fn (setq value (funcall fn value)))
15411 (unless (equal (org-entry-get nil property) value)
15412 (org-entry-put nil property value))))
15414 (defun org-delete-property (property &optional delete-empty-drawer)
15415 "In the current entry, delete PROPERTY.
15416 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15417 an empty drawer to delete."
15418 (interactive
15419 (let* ((completion-ignore-case t)
15420 (prop (org-icompleting-read "Property: "
15421 (org-entry-properties nil 'standard))))
15422 (list prop)))
15423 (message "Property %s %s" property
15424 (if (org-entry-delete nil property delete-empty-drawer)
15425 "deleted"
15426 "was not present in the entry")))
15428 (defun org-delete-property-globally (property)
15429 "Remove PROPERTY globally, from all entries."
15430 (interactive
15431 (let* ((completion-ignore-case t)
15432 (prop (org-icompleting-read
15433 "Globally remove property: "
15434 (mapcar 'list (org-buffer-property-keys)))))
15435 (list prop)))
15436 (save-excursion
15437 (save-restriction
15438 (widen)
15439 (goto-char (point-min))
15440 (let ((cnt 0))
15441 (while (re-search-forward
15442 (org-re-property property)
15443 nil t)
15444 (setq cnt (1+ cnt))
15445 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15446 (message "Property \"%s\" removed from %d entries" property cnt)))))
15448 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15450 (defun org-compute-property-at-point ()
15451 "Compute the property at point.
15452 This looks for an enclosing column format, extracts the operator and
15453 then applies it to the property in the column format's scope."
15454 (interactive)
15455 (unless (org-at-property-p)
15456 (error "Not at a property"))
15457 (let ((prop (org-match-string-no-properties 2)))
15458 (org-columns-get-format-and-top-level)
15459 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15460 (error "No operator defined for property %s" prop))
15461 (org-columns-compute prop)))
15463 (defvar org-property-allowed-value-functions nil
15464 "Hook for functions supplying allowed values for a specific property.
15465 The functions must take a single argument, the name of the property, and
15466 return a flat list of allowed values. If \":ETC\" is one of
15467 the values, this means that these values are intended as defaults for
15468 completion, but that other values should be allowed too.
15469 The functions must return nil if they are not responsible for this
15470 property.")
15472 (defun org-property-get-allowed-values (pom property &optional table)
15473 "Get allowed values for the property PROPERTY.
15474 When TABLE is non-nil, return an alist that can directly be used for
15475 completion."
15476 (let (vals)
15477 (cond
15478 ((equal property "TODO")
15479 (setq vals (org-with-point-at pom
15480 (append org-todo-keywords-1 '("")))))
15481 ((equal property "PRIORITY")
15482 (let ((n org-lowest-priority))
15483 (while (>= n org-highest-priority)
15484 (push (char-to-string n) vals)
15485 (setq n (1- n)))))
15486 ((member property org-special-properties))
15487 ((setq vals (run-hook-with-args-until-success
15488 'org-property-allowed-value-functions property)))
15490 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15491 (when (and vals (string-match "\\S-" vals))
15492 (setq vals (car (read-from-string (concat "(" vals ")"))))
15493 (setq vals (mapcar (lambda (x)
15494 (cond ((stringp x) x)
15495 ((numberp x) (number-to-string x))
15496 ((symbolp x) (symbol-name x))
15497 (t "???")))
15498 vals)))))
15499 (when (member ":ETC" vals)
15500 (setq vals (remove ":ETC" vals))
15501 (org-add-props (car vals) '(org-unrestricted t)))
15502 (if table (mapcar 'list vals) vals)))
15504 (defun org-property-previous-allowed-value (&optional previous)
15505 "Switch to the next allowed value for this property."
15506 (interactive)
15507 (org-property-next-allowed-value t))
15509 (defun org-property-next-allowed-value (&optional previous)
15510 "Switch to the next allowed value for this property."
15511 (interactive)
15512 (unless (org-at-property-p)
15513 (error "Not at a property"))
15514 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15515 (key (match-string 2))
15516 (value (match-string 3))
15517 (allowed (or (org-property-get-allowed-values (point) key)
15518 (and (member value '("[ ]" "[-]" "[X]"))
15519 '("[ ]" "[X]"))))
15520 (heading (save-match-data (nth 4 (org-heading-components))))
15521 nval)
15522 (unless allowed
15523 (error "Allowed values for this property have not been defined"))
15524 (if previous (setq allowed (reverse allowed)))
15525 (if (member value allowed)
15526 (setq nval (car (cdr (member value allowed)))))
15527 (setq nval (or nval (car allowed)))
15528 (if (equal nval value)
15529 (error "Only one allowed value for this property"))
15530 (org-at-property-p)
15531 (replace-match (concat " :" key ": " nval) t t)
15532 (org-indent-line)
15533 (beginning-of-line 1)
15534 (skip-chars-forward " \t")
15535 (when (equal prop org-effort-property)
15536 (save-excursion
15537 (org-back-to-heading t)
15538 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15539 (when (string= org-clock-current-task heading)
15540 (setq org-clock-effort nval)
15541 (org-clock-update-mode-line)))
15542 (run-hook-with-args 'org-property-changed-functions key nval)))
15544 (defun org-find-olp (path &optional this-buffer)
15545 "Return a marker pointing to the entry at outline path OLP.
15546 If anything goes wrong, throw an error.
15547 You can wrap this call to catch the error like this:
15549 (condition-case msg
15550 (org-mobile-locate-entry (match-string 4))
15551 (error (nth 1 msg)))
15553 The return value will then be either a string with the error message,
15554 or a marker if everything is OK.
15556 If THIS-BUFFER is set, the outline path does not contain a file,
15557 only headings."
15558 (let* ((file (if this-buffer buffer-file-name (pop path)))
15559 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15560 (level 1)
15561 (lmin 1)
15562 (lmax 1)
15563 limit re end found pos heading cnt flevel)
15564 (unless buffer (error "File not found :%s" file))
15565 (with-current-buffer buffer
15566 (save-excursion
15567 (save-restriction
15568 (widen)
15569 (setq limit (point-max))
15570 (goto-char (point-min))
15571 (while (setq heading (pop path))
15572 (setq re (format org-complex-heading-regexp-format
15573 (regexp-quote heading)))
15574 (setq cnt 0 pos (point))
15575 (while (re-search-forward re end t)
15576 (setq level (- (match-end 1) (match-beginning 1)))
15577 (if (and (>= level lmin) (<= level lmax))
15578 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15579 (when (= cnt 0) (error "Heading not found on level %d: %s"
15580 lmax heading))
15581 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15582 lmax heading))
15583 (goto-char found)
15584 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15585 (setq end (save-excursion (org-end-of-subtree t t))))
15586 (when (org-at-heading-p)
15587 (point-marker)))))))
15589 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15590 "Find node HEADING in BUFFER.
15591 Return a marker to the heading if it was found, or nil if not.
15592 If POS-ONLY is set, return just the position instead of a marker.
15594 The heading text must match exact, but it may have a TODO keyword,
15595 a priority cookie and tags in the standard locations."
15596 (with-current-buffer (or buffer (current-buffer))
15597 (save-excursion
15598 (save-restriction
15599 (widen)
15600 (goto-char (point-min))
15601 (let (case-fold-search)
15602 (if (re-search-forward
15603 (format org-complex-heading-regexp-format
15604 (regexp-quote heading)) nil t)
15605 (if pos-only
15606 (match-beginning 0)
15607 (move-marker (make-marker) (match-beginning 0)))))))))
15609 (defun org-find-exact-heading-in-directory (heading &optional dir)
15610 "Find Org node headline HEADING in all .org files in directory DIR.
15611 When the target headline is found, return a marker to this location."
15612 (let ((files (directory-files (or dir default-directory)
15613 nil "\\`[^.#].*\\.org\\'"))
15614 file visiting m buffer)
15615 (catch 'found
15616 (while (setq file (pop files))
15617 (message "trying %s" file)
15618 (setq visiting (org-find-base-buffer-visiting file))
15619 (setq buffer (or visiting (find-file-noselect file)))
15620 (setq m (org-find-exact-headline-in-buffer
15621 heading buffer))
15622 (when (and (not m) (not visiting)) (kill-buffer buffer))
15623 (and m (throw 'found m))))))
15625 (defun org-find-entry-with-id (ident)
15626 "Locate the entry that contains the ID property with exact value IDENT.
15627 IDENT can be a string, a symbol or a number, this function will search for
15628 the string representation of it.
15629 Return the position where this entry starts, or nil if there is no such entry."
15630 (interactive "sID: ")
15631 (let ((id (cond
15632 ((stringp ident) ident)
15633 ((symbol-name ident) (symbol-name ident))
15634 ((numberp ident) (number-to-string ident))
15635 (t (error "IDENT %s must be a string, symbol or number" ident))))
15636 (case-fold-search nil))
15637 (save-excursion
15638 (save-restriction
15639 (widen)
15640 (goto-char (point-min))
15641 (when (re-search-forward
15642 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15643 nil t)
15644 (org-back-to-heading t)
15645 (point))))))
15647 ;;;; Timestamps
15649 (defvar org-last-changed-timestamp nil)
15650 (defvar org-last-inserted-timestamp nil
15651 "The last time stamp inserted with `org-insert-time-stamp'.")
15652 (defvar org-time-was-given) ; dynamically scoped parameter
15653 (defvar org-end-time-was-given) ; dynamically scoped parameter
15654 (defvar org-ts-what) ; dynamically scoped parameter
15656 (defun org-time-stamp (arg &optional inactive)
15657 "Prompt for a date/time and insert a time stamp.
15658 If the user specifies a time like HH:MM or if this command is
15659 called with at least one prefix argument, the time stamp contains
15660 the date and the time. Otherwise, only the date is be included.
15662 All parts of a date not specified by the user is filled in from
15663 the current date/time. So if you just press return without
15664 typing anything, the time stamp will represent the current
15665 date/time.
15667 If there is already a timestamp at the cursor, it will be
15668 modified.
15670 With two universal prefix arguments, insert an active timestamp
15671 with the current time without prompting the user."
15672 (interactive "P")
15673 (let* ((ts nil)
15674 (default-time
15675 ;; Default time is either today, or, when entering a range,
15676 ;; the range start.
15677 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15678 (save-excursion
15679 (re-search-backward
15680 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15681 (- (point) 20) t)))
15682 (apply 'encode-time (org-parse-time-string (match-string 1)))
15683 (current-time)))
15684 (default-input (and ts (org-get-compact-tod ts)))
15685 (repeater (save-excursion
15686 (save-match-data
15687 (beginning-of-line)
15688 (when (re-search-forward
15689 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15690 (save-excursion (progn (end-of-line) (point))) t)
15691 (match-string 0)))))
15692 org-time-was-given org-end-time-was-given time)
15693 (cond
15694 ((and (org-at-timestamp-p t)
15695 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15696 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15697 (insert "--")
15698 (setq time (let ((this-command this-command))
15699 (org-read-date arg 'totime nil nil
15700 default-time default-input inactive)))
15701 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15702 ((org-at-timestamp-p t)
15703 (setq time (let ((this-command this-command))
15704 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15705 (when (org-at-timestamp-p t) ; just to get the match data
15706 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15707 (replace-match "")
15708 (setq org-last-changed-timestamp
15709 (org-insert-time-stamp
15710 time (or org-time-was-given arg)
15711 inactive nil nil (list org-end-time-was-given)))
15712 (when repeater (goto-char (1- (point))) (insert " " repeater)
15713 (setq org-last-changed-timestamp
15714 (concat (substring org-last-inserted-timestamp 0 -1)
15715 " " repeater ">"))))
15716 (message "Timestamp updated"))
15717 ((equal arg '(16))
15718 (org-insert-time-stamp (current-time) t))
15720 (setq time (let ((this-command this-command))
15721 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15722 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15723 nil nil (list org-end-time-was-given))))))
15725 ;; FIXME: can we use this for something else, like computing time differences?
15726 (defun org-get-compact-tod (s)
15727 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15728 (let* ((t1 (match-string 1 s))
15729 (h1 (string-to-number (match-string 2 s)))
15730 (m1 (string-to-number (match-string 3 s)))
15731 (t2 (and (match-end 4) (match-string 5 s)))
15732 (h2 (and t2 (string-to-number (match-string 6 s))))
15733 (m2 (and t2 (string-to-number (match-string 7 s))))
15734 dh dm)
15735 (if (not t2)
15737 (setq dh (- h2 h1) dm (- m2 m1))
15738 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15739 (concat t1 "+" (number-to-string dh)
15740 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15742 (defun org-time-stamp-inactive (&optional arg)
15743 "Insert an inactive time stamp.
15744 An inactive time stamp is enclosed in square brackets instead of angle
15745 brackets. It is inactive in the sense that it does not trigger agenda entries,
15746 does not link to the calendar and cannot be changed with the S-cursor keys.
15747 So these are more for recording a certain time/date."
15748 (interactive "P")
15749 (org-time-stamp arg 'inactive))
15751 (defvar org-date-ovl (make-overlay 1 1))
15752 (overlay-put org-date-ovl 'face 'org-date-selected)
15753 (org-detach-overlay org-date-ovl)
15755 (defvar org-ans1) ; dynamically scoped parameter
15756 (defvar org-ans2) ; dynamically scoped parameter
15758 (defvar org-plain-time-of-day-regexp) ; defined below
15760 (defvar org-overriding-default-time nil) ; dynamically scoped
15761 (defvar org-read-date-overlay nil)
15762 (defvar org-dcst nil) ; dynamically scoped
15763 (defvar org-read-date-history nil)
15764 (defvar org-read-date-final-answer nil)
15765 (defvar org-read-date-analyze-futurep nil)
15766 (defvar org-read-date-analyze-forced-year nil)
15767 (defvar org-read-date-inactive)
15769 (defvar org-read-date-minibuffer-local-map
15770 (let ((map (make-sparse-keymap)))
15771 (set-keymap-parent map minibuffer-local-map)
15772 (org-defkey map (kbd ".")
15773 (lambda () (interactive)
15774 (org-eval-in-calendar '(calendar-goto-today))))
15775 (org-defkey map [(meta shift left)]
15776 (lambda () (interactive)
15777 (org-eval-in-calendar '(calendar-backward-month 1))))
15778 (org-defkey map [(meta shift right)]
15779 (lambda () (interactive)
15780 (org-eval-in-calendar '(calendar-forward-month 1))))
15781 (org-defkey map [(meta shift up)]
15782 (lambda () (interactive)
15783 (org-eval-in-calendar '(calendar-backward-year 1))))
15784 (org-defkey map [(meta shift down)]
15785 (lambda () (interactive)
15786 (org-eval-in-calendar '(calendar-forward-year 1))))
15787 (org-defkey map [?\e (shift left)]
15788 (lambda () (interactive)
15789 (org-eval-in-calendar '(calendar-backward-month 1))))
15790 (org-defkey map [?\e (shift right)]
15791 (lambda () (interactive)
15792 (org-eval-in-calendar '(calendar-forward-month 1))))
15793 (org-defkey map [?\e (shift up)]
15794 (lambda () (interactive)
15795 (org-eval-in-calendar '(calendar-backward-year 1))))
15796 (org-defkey map [?\e (shift down)]
15797 (lambda () (interactive)
15798 (org-eval-in-calendar '(calendar-forward-year 1))))
15799 (org-defkey map [(shift up)]
15800 (lambda () (interactive)
15801 (org-eval-in-calendar '(calendar-backward-week 1))))
15802 (org-defkey map [(shift down)]
15803 (lambda () (interactive)
15804 (org-eval-in-calendar '(calendar-forward-week 1))))
15805 (org-defkey map [(shift left)]
15806 (lambda () (interactive)
15807 (org-eval-in-calendar '(calendar-backward-day 1))))
15808 (org-defkey map [(shift right)]
15809 (lambda () (interactive)
15810 (org-eval-in-calendar '(calendar-forward-day 1))))
15811 (org-defkey map "!"
15812 (lambda () (interactive)
15813 (org-eval-in-calendar '(diary-view-entries))
15814 (message "")))
15815 (org-defkey map ">"
15816 (lambda () (interactive)
15817 (org-eval-in-calendar '(scroll-calendar-left 1))))
15818 (org-defkey map "<"
15819 (lambda () (interactive)
15820 (org-eval-in-calendar '(scroll-calendar-right 1))))
15821 (org-defkey map "\C-v"
15822 (lambda () (interactive)
15823 (org-eval-in-calendar
15824 '(calendar-scroll-left-three-months 1))))
15825 (org-defkey map "\M-v"
15826 (lambda () (interactive)
15827 (org-eval-in-calendar
15828 '(calendar-scroll-right-three-months 1))))
15829 map)
15830 "Keymap for minibuffer commands when using `org-read-date'.")
15832 (defun org-read-date (&optional org-with-time to-time from-string prompt
15833 default-time default-input inactive)
15834 "Read a date, possibly a time, and make things smooth for the user.
15835 The prompt will suggest to enter an ISO date, but you can also enter anything
15836 which will at least partially be understood by `parse-time-string'.
15837 Unrecognized parts of the date will default to the current day, month, year,
15838 hour and minute. If this command is called to replace a timestamp at point,
15839 or to enter the second timestamp of a range, the default time is taken
15840 from the existing stamp. Furthermore, the command prefers the future,
15841 so if you are giving a date where the year is not given, and the day-month
15842 combination is already past in the current year, it will assume you
15843 mean next year. For details, see the manual. A few examples:
15845 3-2-5 --> 2003-02-05
15846 feb 15 --> currentyear-02-15
15847 2/15 --> currentyear-02-15
15848 sep 12 9 --> 2009-09-12
15849 12:45 --> today 12:45
15850 22 sept 0:34 --> currentyear-09-22 0:34
15851 12 --> currentyear-currentmonth-12
15852 Fri --> nearest Friday (today or later)
15853 etc.
15855 Furthermore you can specify a relative date by giving, as the *first* thing
15856 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15857 change in days weeks, months, years.
15858 With a single plus or minus, the date is relative to today. With a double
15859 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15860 +4d --> four days from today
15861 +4 --> same as above
15862 +2w --> two weeks from today
15863 ++5 --> five days from default date
15865 The function understands only English month and weekday abbreviations.
15867 While prompting, a calendar is popped up - you can also select the
15868 date with the mouse (button 1). The calendar shows a period of three
15869 months. To scroll it to other months, use the keys `>' and `<'.
15870 If you don't like the calendar, turn it off with
15871 \(setq org-read-date-popup-calendar nil)
15873 With optional argument TO-TIME, the date will immediately be converted
15874 to an internal time.
15875 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15876 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15877 still enter a time, and this function will inform the calling routine
15878 about this change. The calling routine may then choose to change the
15879 format used to insert the time stamp into the buffer to include the time.
15880 With optional argument FROM-STRING, read from this string instead from
15881 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15882 the time/date that is used for everything that is not specified by the
15883 user."
15884 (require 'parse-time)
15885 (let* ((org-time-stamp-rounding-minutes
15886 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15887 (org-dcst org-display-custom-times)
15888 (ct (org-current-time))
15889 (org-def (or org-overriding-default-time default-time ct))
15890 (org-defdecode (decode-time org-def))
15891 (dummy (progn
15892 (when (< (nth 2 org-defdecode) org-extend-today-until)
15893 (setcar (nthcdr 2 org-defdecode) -1)
15894 (setcar (nthcdr 1 org-defdecode) 59)
15895 (setq org-def (apply 'encode-time org-defdecode)
15896 org-defdecode (decode-time org-def)))))
15897 (mouse-autoselect-window nil) ; Don't let the mouse jump
15898 (calendar-frame-setup nil)
15899 (calendar-setup nil)
15900 (calendar-move-hook nil)
15901 (calendar-view-diary-initially-flag nil)
15902 (calendar-view-holidays-initially-flag nil)
15903 (timestr (format-time-string
15904 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15905 (prompt (concat (if prompt (concat prompt " ") "")
15906 (format "Date+time [%s]: " timestr)))
15907 ans (org-ans0 "") org-ans1 org-ans2 final)
15909 (cond
15910 (from-string (setq ans from-string))
15911 (org-read-date-popup-calendar
15912 (save-excursion
15913 (save-window-excursion
15914 (calendar)
15915 (org-eval-in-calendar '(setq cursor-type nil) t)
15916 (unwind-protect
15917 (progn
15918 (calendar-forward-day (- (time-to-days org-def)
15919 (calendar-absolute-from-gregorian
15920 (calendar-current-date))))
15921 (org-eval-in-calendar nil t)
15922 (let* ((old-map (current-local-map))
15923 (map (copy-keymap calendar-mode-map))
15924 (minibuffer-local-map
15925 (copy-keymap org-read-date-minibuffer-local-map)))
15926 (org-defkey map (kbd "RET") 'org-calendar-select)
15927 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15928 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15929 (unwind-protect
15930 (progn
15931 (use-local-map map)
15932 (setq org-read-date-inactive inactive)
15933 (add-hook 'post-command-hook 'org-read-date-display)
15934 (setq org-ans0 (read-string prompt default-input
15935 'org-read-date-history nil))
15936 ;; org-ans0: from prompt
15937 ;; org-ans1: from mouse click
15938 ;; org-ans2: from calendar motion
15939 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15940 (remove-hook 'post-command-hook 'org-read-date-display)
15941 (use-local-map old-map)
15942 (when org-read-date-overlay
15943 (delete-overlay org-read-date-overlay)
15944 (setq org-read-date-overlay nil)))))
15945 (bury-buffer "*Calendar*")))))
15947 (t ; Naked prompt only
15948 (unwind-protect
15949 (setq ans (read-string prompt default-input
15950 'org-read-date-history timestr))
15951 (when org-read-date-overlay
15952 (delete-overlay org-read-date-overlay)
15953 (setq org-read-date-overlay nil)))))
15955 (setq final (org-read-date-analyze ans org-def org-defdecode))
15957 (when org-read-date-analyze-forced-year
15958 (message "Year was forced into %s"
15959 (if org-read-date-force-compatible-dates
15960 "compatible range (1970-2037)"
15961 "range representable on this machine"))
15962 (ding))
15964 ;; One round trip to get rid of 34th of August and stuff like that....
15965 (setq final (decode-time (apply 'encode-time final)))
15967 (setq org-read-date-final-answer ans)
15969 (if to-time
15970 (apply 'encode-time final)
15971 (if (and (boundp 'org-time-was-given) org-time-was-given)
15972 (format "%04d-%02d-%02d %02d:%02d"
15973 (nth 5 final) (nth 4 final) (nth 3 final)
15974 (nth 2 final) (nth 1 final))
15975 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15977 (defvar org-def)
15978 (defvar org-defdecode)
15979 (defvar org-with-time)
15980 (defun org-read-date-display ()
15981 "Display the current date prompt interpretation in the minibuffer."
15982 (when org-read-date-display-live
15983 (when org-read-date-overlay
15984 (delete-overlay org-read-date-overlay))
15985 (when (minibufferp (current-buffer))
15986 (save-excursion
15987 (end-of-line 1)
15988 (while (not (equal (buffer-substring
15989 (max (point-min) (- (point) 4)) (point))
15990 " "))
15991 (insert " ")))
15992 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15993 " " (or org-ans1 org-ans2)))
15994 (org-end-time-was-given nil)
15995 (f (org-read-date-analyze ans org-def org-defdecode))
15996 (fmts (if org-dcst
15997 org-time-stamp-custom-formats
15998 org-time-stamp-formats))
15999 (fmt (if (or org-with-time
16000 (and (boundp 'org-time-was-given) org-time-was-given))
16001 (cdr fmts)
16002 (car fmts)))
16003 (txt (format-time-string fmt (apply 'encode-time f)))
16004 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16005 (txt (concat "=> " txt)))
16006 (when (and org-end-time-was-given
16007 (string-match org-plain-time-of-day-regexp txt))
16008 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16009 org-end-time-was-given
16010 (substring txt (match-end 0)))))
16011 (when org-read-date-analyze-futurep
16012 (setq txt (concat txt " (=>F)")))
16013 (setq org-read-date-overlay
16014 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16015 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16017 (defun org-read-date-analyze (ans org-def org-defdecode)
16018 "Analyze the combined answer of the date prompt."
16019 ;; FIXME: cleanup and comment
16020 (let ((nowdecode (decode-time (current-time)))
16021 delta deltan deltaw deltadef year month day
16022 hour minute second wday pm h2 m2 tl wday1
16023 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16024 (setq org-read-date-analyze-futurep nil
16025 org-read-date-analyze-forced-year nil)
16026 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16027 (setq ans "+0"))
16029 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16030 (setq ans (replace-match "" t t ans)
16031 deltan (car delta)
16032 deltaw (nth 1 delta)
16033 deltadef (nth 2 delta)))
16035 ;; Check if there is an iso week date in there. If yes, store the
16036 ;; info and postpone interpreting it until the rest of the parsing
16037 ;; is done.
16038 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16039 (setq iso-year (if (match-end 1)
16040 (org-small-year-to-year
16041 (string-to-number (match-string 1 ans))))
16042 iso-weekday (if (match-end 3)
16043 (string-to-number (match-string 3 ans)))
16044 iso-week (string-to-number (match-string 2 ans)))
16045 (setq ans (replace-match "" t t ans)))
16047 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16048 (when (string-match
16049 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16050 (setq year (if (match-end 2)
16051 (string-to-number (match-string 2 ans))
16052 (progn (setq kill-year t)
16053 (string-to-number (format-time-string "%Y"))))
16054 month (string-to-number (match-string 3 ans))
16055 day (string-to-number (match-string 4 ans)))
16056 (if (< year 100) (setq year (+ 2000 year)))
16057 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16058 t nil ans)))
16060 ;; Help matching dotted european dates
16061 (when (string-match
16062 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16063 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16064 (setq kill-year t)
16065 (string-to-number (format-time-string "%Y")))
16066 day (string-to-number (match-string 1 ans))
16067 month (string-to-number (match-string 2 ans))
16068 ans (replace-match (format "%04d-%02d-%02d" year month day)
16069 t nil ans)))
16071 ;; Help matching american dates, like 5/30 or 5/30/7
16072 (when (string-match
16073 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16074 (setq year (if (match-end 4)
16075 (string-to-number (match-string 4 ans))
16076 (progn (setq kill-year t)
16077 (string-to-number (format-time-string "%Y"))))
16078 month (string-to-number (match-string 1 ans))
16079 day (string-to-number (match-string 2 ans)))
16080 (if (< year 100) (setq year (+ 2000 year)))
16081 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16082 t nil ans)))
16083 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16084 ;; If there is a time with am/pm, and *no* time without it, we convert
16085 ;; so that matching will be successful.
16086 (loop for i from 1 to 2 do ; twice, for end time as well
16087 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16088 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16089 (setq hour (string-to-number (match-string 1 ans))
16090 minute (if (match-end 3)
16091 (string-to-number (match-string 3 ans))
16093 pm (equal ?p
16094 (string-to-char (downcase (match-string 4 ans)))))
16095 (if (and (= hour 12) (not pm))
16096 (setq hour 0)
16097 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16098 (setq ans (replace-match (format "%02d:%02d" hour minute)
16099 t t ans))))
16101 ;; Check if a time range is given as a duration
16102 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16103 (setq hour (string-to-number (match-string 1 ans))
16104 h2 (+ hour (string-to-number (match-string 3 ans)))
16105 minute (string-to-number (match-string 2 ans))
16106 m2 (+ minute (if (match-end 5) (string-to-number
16107 (match-string 5 ans))0)))
16108 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16109 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16110 t t ans)))
16112 ;; Check if there is a time range
16113 (when (boundp 'org-end-time-was-given)
16114 (setq org-time-was-given nil)
16115 (when (and (string-match org-plain-time-of-day-regexp ans)
16116 (match-end 8))
16117 (setq org-end-time-was-given (match-string 8 ans))
16118 (setq ans (concat (substring ans 0 (match-beginning 7))
16119 (substring ans (match-end 7))))))
16121 (setq tl (parse-time-string ans)
16122 day (or (nth 3 tl) (nth 3 org-defdecode))
16123 month (or (nth 4 tl)
16124 (if (and org-read-date-prefer-future
16125 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16126 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16127 (nth 4 org-defdecode)))
16128 year (or (and (not kill-year) (nth 5 tl))
16129 (if (and org-read-date-prefer-future
16130 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16131 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16132 (nth 5 org-defdecode)))
16133 hour (or (nth 2 tl) (nth 2 org-defdecode))
16134 minute (or (nth 1 tl) (nth 1 org-defdecode))
16135 second (or (nth 0 tl) 0)
16136 wday (nth 6 tl))
16138 (when (and (eq org-read-date-prefer-future 'time)
16139 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16140 (equal day (nth 3 nowdecode))
16141 (equal month (nth 4 nowdecode))
16142 (equal year (nth 5 nowdecode))
16143 (nth 2 tl)
16144 (or (< (nth 2 tl) (nth 2 nowdecode))
16145 (and (= (nth 2 tl) (nth 2 nowdecode))
16146 (nth 1 tl)
16147 (< (nth 1 tl) (nth 1 nowdecode)))))
16148 (setq day (1+ day)
16149 futurep t))
16151 ;; Special date definitions below
16152 (cond
16153 (iso-week
16154 ;; There was an iso week
16155 (require 'cal-iso)
16156 (setq futurep nil)
16157 (setq year (or iso-year year)
16158 day (or iso-weekday wday 1)
16159 wday nil ; to make sure that the trigger below does not match
16160 iso-date (calendar-gregorian-from-absolute
16161 (calendar-absolute-from-iso
16162 (list iso-week day year))))
16163 ; FIXME: Should we also push ISO weeks into the future?
16164 ; (when (and org-read-date-prefer-future
16165 ; (not iso-year)
16166 ; (< (calendar-absolute-from-gregorian iso-date)
16167 ; (time-to-days (current-time))))
16168 ; (setq year (1+ year)
16169 ; iso-date (calendar-gregorian-from-absolute
16170 ; (calendar-absolute-from-iso
16171 ; (list iso-week day year)))))
16172 (setq month (car iso-date)
16173 year (nth 2 iso-date)
16174 day (nth 1 iso-date)))
16175 (deltan
16176 (setq futurep nil)
16177 (unless deltadef
16178 (let ((now (decode-time (current-time))))
16179 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16180 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16181 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16182 ((equal deltaw "m") (setq month (+ month deltan)))
16183 ((equal deltaw "y") (setq year (+ year deltan)))))
16184 ((and wday (not (nth 3 tl)))
16185 ;; Weekday was given, but no day, so pick that day in the week
16186 ;; on or after the derived date.
16187 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16188 (unless (equal wday wday1)
16189 (setq day (+ day (% (- wday wday1 -7) 7))))))
16190 (if (and (boundp 'org-time-was-given)
16191 (nth 2 tl))
16192 (setq org-time-was-given t))
16193 (if (< year 100) (setq year (+ 2000 year)))
16194 ;; Check of the date is representable
16195 (if org-read-date-force-compatible-dates
16196 (progn
16197 (if (< year 1970)
16198 (setq year 1970 org-read-date-analyze-forced-year t))
16199 (if (> year 2037)
16200 (setq year 2037 org-read-date-analyze-forced-year t)))
16201 (condition-case nil
16202 (ignore (encode-time second minute hour day month year))
16203 (error
16204 (setq year (nth 5 org-defdecode))
16205 (setq org-read-date-analyze-forced-year t))))
16206 (setq org-read-date-analyze-futurep futurep)
16207 (list second minute hour day month year)))
16209 (defvar parse-time-weekdays)
16210 (defun org-read-date-get-relative (s today default)
16211 "Check string S for special relative date string.
16212 TODAY and DEFAULT are internal times, for today and for a default.
16213 Return shift list (N what def-flag)
16214 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16215 N is the number of WHATs to shift.
16216 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16217 the DEFAULT date rather than TODAY."
16218 (require 'parse-time)
16219 (when (and
16220 (string-match
16221 (concat
16222 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16223 "\\([0-9]+\\)?"
16224 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16225 "\\([ \t]\\|$\\)") s)
16226 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16227 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16228 (string-to-char (substring (match-string 1 s) -1))
16229 ?+))
16230 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16231 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16232 (what (if (match-end 3) (match-string 3 s) "d"))
16233 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16234 (date (if rel default today))
16235 (wday (nth 6 (decode-time date)))
16236 delta)
16237 (if wday1
16238 (progn
16239 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16240 (if (= dir ?-) (setq delta (- delta 7)))
16241 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16242 (list delta "d" rel))
16243 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16245 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16246 "Turn a user-specified date into the internal representation.
16247 The internal representation needed by the calendar is (month day year).
16248 This is a wrapper to handle the brain-dead convention in calendar that
16249 user function argument order change dependent on argument order."
16250 (if (boundp 'calendar-date-style)
16251 (cond
16252 ((eq calendar-date-style 'american)
16253 (list arg1 arg2 arg3))
16254 ((eq calendar-date-style 'european)
16255 (list arg2 arg1 arg3))
16256 ((eq calendar-date-style 'iso)
16257 (list arg2 arg3 arg1)))
16258 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16259 (if (org-bound-and-true-p european-calendar-style)
16260 (list arg2 arg1 arg3)
16261 (list arg1 arg2 arg3)))))
16263 (defun org-eval-in-calendar (form &optional keepdate)
16264 "Eval FORM in the calendar window and return to current window.
16265 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16266 otherwise stick to the current value of `org-ans2'."
16267 (let ((sf (selected-frame))
16268 (sw (selected-window)))
16269 (select-window (get-buffer-window "*Calendar*" t))
16270 (eval form)
16271 (when (and (not keepdate) (calendar-cursor-to-date))
16272 (let* ((date (calendar-cursor-to-date))
16273 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16274 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16275 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16276 (select-window sw)
16277 (org-select-frame-set-input-focus sf)))
16279 (defun org-calendar-select ()
16280 "Return to `org-read-date' with the date currently selected.
16281 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16282 (interactive)
16283 (when (calendar-cursor-to-date)
16284 (let* ((date (calendar-cursor-to-date))
16285 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16286 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16287 (if (active-minibuffer-window) (exit-minibuffer))))
16289 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16290 "Insert a date stamp for the date given by the internal TIME.
16291 WITH-HM means use the stamp format that includes the time of the day.
16292 INACTIVE means use square brackets instead of angular ones, so that the
16293 stamp will not contribute to the agenda.
16294 PRE and POST are optional strings to be inserted before and after the
16295 stamp.
16296 The command returns the inserted time stamp."
16297 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16298 stamp)
16299 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16300 (insert-before-markers (or pre ""))
16301 (when (listp extra)
16302 (setq extra (car extra))
16303 (if (and (stringp extra)
16304 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16305 (setq extra (format "-%02d:%02d"
16306 (string-to-number (match-string 1 extra))
16307 (string-to-number (match-string 2 extra))))
16308 (setq extra nil)))
16309 (when extra
16310 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16311 (insert-before-markers (setq stamp (format-time-string fmt time)))
16312 (insert-before-markers (or post ""))
16313 (setq org-last-inserted-timestamp stamp)))
16315 (defun org-toggle-time-stamp-overlays ()
16316 "Toggle the use of custom time stamp formats."
16317 (interactive)
16318 (setq org-display-custom-times (not org-display-custom-times))
16319 (unless org-display-custom-times
16320 (let ((p (point-min)) (bmp (buffer-modified-p)))
16321 (while (setq p (next-single-property-change p 'display))
16322 (if (and (get-text-property p 'display)
16323 (eq (get-text-property p 'face) 'org-date))
16324 (remove-text-properties
16325 p (setq p (next-single-property-change p 'display))
16326 '(display t))))
16327 (set-buffer-modified-p bmp)))
16328 (if (featurep 'xemacs)
16329 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16330 (org-restart-font-lock)
16331 (setq org-table-may-need-update t)
16332 (if org-display-custom-times
16333 (message "Time stamps are overlaid with custom format")
16334 (message "Time stamp overlays removed")))
16336 (defun org-display-custom-time (beg end)
16337 "Overlay modified time stamp format over timestamp between BEG and END."
16338 (let* ((ts (buffer-substring beg end))
16339 t1 w1 with-hm tf time str w2 (off 0))
16340 (save-match-data
16341 (setq t1 (org-parse-time-string ts t))
16342 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16343 (setq off (- (match-end 0) (match-beginning 0)))))
16344 (setq end (- end off))
16345 (setq w1 (- end beg)
16346 with-hm (and (nth 1 t1) (nth 2 t1))
16347 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16348 time (org-fix-decoded-time t1)
16349 str (org-add-props
16350 (format-time-string
16351 (substring tf 1 -1) (apply 'encode-time time))
16352 nil 'mouse-face 'highlight)
16353 w2 (length str))
16354 (if (not (= w2 w1))
16355 (add-text-properties (1+ beg) (+ 2 beg)
16356 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16357 (if (featurep 'xemacs)
16358 (progn
16359 (put-text-property beg end 'invisible t)
16360 (put-text-property beg end 'end-glyph (make-glyph str)))
16361 (put-text-property beg end 'display str))))
16363 (defun org-translate-time (string)
16364 "Translate all timestamps in STRING to custom format.
16365 But do this only if the variable `org-display-custom-times' is set."
16366 (when org-display-custom-times
16367 (save-match-data
16368 (let* ((start 0)
16369 (re org-ts-regexp-both)
16370 t1 with-hm inactive tf time str beg end)
16371 (while (setq start (string-match re string start))
16372 (setq beg (match-beginning 0)
16373 end (match-end 0)
16374 t1 (save-match-data
16375 (org-parse-time-string (substring string beg end) t))
16376 with-hm (and (nth 1 t1) (nth 2 t1))
16377 inactive (equal (substring string beg (1+ beg)) "[")
16378 tf (funcall (if with-hm 'cdr 'car)
16379 org-time-stamp-custom-formats)
16380 time (org-fix-decoded-time t1)
16381 str (format-time-string
16382 (concat
16383 (if inactive "[" "<") (substring tf 1 -1)
16384 (if inactive "]" ">"))
16385 (apply 'encode-time time))
16386 string (replace-match str t t string)
16387 start (+ start (length str)))))))
16388 string)
16390 (defun org-fix-decoded-time (time)
16391 "Set 0 instead of nil for the first 6 elements of time.
16392 Don't touch the rest."
16393 (let ((n 0))
16394 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16396 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16398 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16399 "Difference between TIMESTAMP-STRING and now in days.
16400 If SECONDS is non-nil, return the difference in seconds."
16401 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16402 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16403 (funcall fdiff (current-time)))))
16405 (defun org-deadline-close (timestamp-string &optional ndays)
16406 "Is the time in TIMESTAMP-STRING close to the current date?"
16407 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16408 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16409 (not (org-entry-is-done-p))))
16411 (defun org-get-wdays (ts &optional delay zero-delay)
16412 "Get the deadline lead time appropriate for timestring TS.
16413 When DELAY is non-nil, get the delay time for scheduled items
16414 instead of the deadline lead time. When ZERO-DELAY is non-nil
16415 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16416 don't try to find the delay cookie in the scheduled timestamp."
16417 (let ((tv (if delay org-scheduled-delay-days
16418 org-deadline-warning-days)))
16419 (cond
16420 ((or (and delay (< tv 0))
16421 (and delay zero-delay (<= tv 0))
16422 (and (not delay) (<= tv 0)))
16423 ;; Enforce this value no matter what
16424 (- tv))
16425 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16426 ;; lead time is specified.
16427 (floor (* (string-to-number (match-string 1 ts))
16428 (cdr (assoc (match-string 2 ts)
16429 '(("d" . 1) ("w" . 7)
16430 ("m" . 30.4) ("y" . 365.25)
16431 ("h" . 0.041667)))))))
16432 ;; go for the default.
16433 (t tv))))
16435 (defun org-calendar-select-mouse (ev)
16436 "Return to `org-read-date' with the date currently selected.
16437 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16438 (interactive "e")
16439 (mouse-set-point ev)
16440 (when (calendar-cursor-to-date)
16441 (let* ((date (calendar-cursor-to-date))
16442 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16443 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16444 (if (active-minibuffer-window) (exit-minibuffer))))
16446 (defun org-check-deadlines (ndays)
16447 "Check if there are any deadlines due or past due.
16448 A deadline is considered due if it happens within `org-deadline-warning-days'
16449 days from today's date. If the deadline appears in an entry marked DONE,
16450 it is not shown. The prefix arg NDAYS can be used to test that many
16451 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16452 (interactive "P")
16453 (let* ((org-warn-days
16454 (cond
16455 ((equal ndays '(4)) 100000)
16456 (ndays (prefix-numeric-value ndays))
16457 (t (abs org-deadline-warning-days))))
16458 (case-fold-search nil)
16459 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16460 (callback
16461 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16463 (message "%d deadlines past-due or due within %d days"
16464 (org-occur regexp nil callback)
16465 org-warn-days)))
16467 (defsubst org-re-timestamp (type)
16468 "Return a regexp for timestamp TYPE.
16469 Allowed values for TYPE are:
16471 all: all timestamps
16472 active: only active timestamps (<...>)
16473 inactive: only inactive timestamps ([...])
16474 scheduled: only scheduled timestamps
16475 deadline: only deadline timestamps
16477 When TYPE is nil, fall back on returning a regexp that matches
16478 both scheduled and deadline timestamps."
16479 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16480 ((eq type 'active) org-ts-regexp)
16481 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16482 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16483 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16484 ((eq type 'scheduled-or-deadline)
16485 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16487 (defun org-check-before-date (date)
16488 "Check if there are deadlines or scheduled entries before DATE."
16489 (interactive (list (org-read-date)))
16490 (let ((case-fold-search nil)
16491 (regexp (org-re-timestamp org-ts-type))
16492 (callback
16493 (lambda () (time-less-p
16494 (org-time-string-to-time (match-string 1))
16495 (org-time-string-to-time date)))))
16496 (message "%d entries before %s"
16497 (org-occur regexp nil callback) date)))
16499 (defun org-check-after-date (date)
16500 "Check if there are deadlines or scheduled entries after DATE."
16501 (interactive (list (org-read-date)))
16502 (let ((case-fold-search nil)
16503 (regexp (org-re-timestamp org-ts-type))
16504 (callback
16505 (lambda () (not
16506 (time-less-p
16507 (org-time-string-to-time (match-string 1))
16508 (org-time-string-to-time date))))))
16509 (message "%d entries after %s"
16510 (org-occur regexp nil callback) date)))
16512 (defun org-check-dates-range (start-date end-date)
16513 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16514 (interactive (list (org-read-date nil nil nil "Range starts")
16515 (org-read-date nil nil nil "Range end")))
16516 (let ((case-fold-search nil)
16517 (regexp (org-re-timestamp org-ts-type))
16518 (callback
16519 (lambda ()
16520 (let ((match (match-string 1)))
16521 (and
16522 (not (time-less-p
16523 (org-time-string-to-time match)
16524 (org-time-string-to-time start-date)))
16525 (time-less-p
16526 (org-time-string-to-time match)
16527 (org-time-string-to-time end-date)))))))
16528 (message "%d entries between %s and %s"
16529 (org-occur regexp nil callback) start-date end-date)))
16531 (defun org-evaluate-time-range (&optional to-buffer)
16532 "Evaluate a time range by computing the difference between start and end.
16533 Normally the result is just printed in the echo area, but with prefix arg
16534 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16535 If the time range is actually in a table, the result is inserted into the
16536 next column.
16537 For time difference computation, a year is assumed to be exactly 365
16538 days in order to avoid rounding problems."
16539 (interactive "P")
16541 (org-clock-update-time-maybe)
16542 (save-excursion
16543 (unless (org-at-date-range-p t)
16544 (goto-char (point-at-bol))
16545 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16546 (if (not (org-at-date-range-p t))
16547 (error "Not at a time-stamp range, and none found in current line")))
16548 (let* ((ts1 (match-string 1))
16549 (ts2 (match-string 2))
16550 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16551 (match-end (match-end 0))
16552 (time1 (org-time-string-to-time ts1))
16553 (time2 (org-time-string-to-time ts2))
16554 (t1 (org-float-time time1))
16555 (t2 (org-float-time time2))
16556 (diff (abs (- t2 t1)))
16557 (negative (< (- t2 t1) 0))
16558 ;; (ys (floor (* 365 24 60 60)))
16559 (ds (* 24 60 60))
16560 (hs (* 60 60))
16561 (fy "%dy %dd %02d:%02d")
16562 (fy1 "%dy %dd")
16563 (fd "%dd %02d:%02d")
16564 (fd1 "%dd")
16565 (fh "%02d:%02d")
16566 y d h m align)
16567 (if havetime
16568 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16570 d (floor (/ diff ds)) diff (mod diff ds)
16571 h (floor (/ diff hs)) diff (mod diff hs)
16572 m (floor (/ diff 60)))
16573 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16575 d (floor (+ (/ diff ds) 0.5))
16576 h 0 m 0))
16577 (if (not to-buffer)
16578 (message "%s" (org-make-tdiff-string y d h m))
16579 (if (org-at-table-p)
16580 (progn
16581 (goto-char match-end)
16582 (setq align t)
16583 (and (looking-at " *|") (goto-char (match-end 0))))
16584 (goto-char match-end))
16585 (if (looking-at
16586 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16587 (replace-match ""))
16588 (if negative (insert " -"))
16589 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16590 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16591 (insert " " (format fh h m))))
16592 (if align (org-table-align))
16593 (message "Time difference inserted")))))
16595 (defun org-make-tdiff-string (y d h m)
16596 (let ((fmt "")
16597 (l nil))
16598 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16599 l (push y l)))
16600 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16601 l (push d l)))
16602 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16603 l (push h l)))
16604 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16605 l (push m l)))
16606 (apply 'format fmt (nreverse l))))
16608 (defun org-time-string-to-time (s &optional buffer pos)
16609 "Convert a timestamp string into internal time."
16610 (condition-case errdata
16611 (apply 'encode-time (org-parse-time-string s))
16612 (error (error "Bad timestamp `%s'%s\nError was: %s"
16613 s (if (not (and buffer pos))
16615 (format " at %d in buffer `%s'" pos buffer))
16616 (cdr errdata)))))
16618 (defun org-time-string-to-seconds (s)
16619 "Convert a timestamp string to a number of seconds."
16620 (org-float-time (org-time-string-to-time s)))
16622 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16623 "Convert a time stamp to an absolute day number.
16624 If there is a specifier for a cyclic time stamp, get the closest
16625 date to DAYNR.
16626 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16627 The variable date is bound by the calendar when this is called."
16628 (cond
16629 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16630 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16631 daynr
16632 (+ daynr 1000)))
16633 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16634 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16635 (time-to-days (current-time))) (match-string 0 s)
16636 prefer show-all))
16637 (t (time-to-days
16638 (condition-case errdata
16639 (apply 'encode-time (org-parse-time-string s))
16640 (error (error "Bad timestamp `%s'%s\nError was: %s"
16641 s (if (not (and buffer pos))
16643 (format " at %d in buffer `%s'" pos buffer))
16644 (cdr errdata))))))))
16646 (defun org-days-to-iso-week (days)
16647 "Return the iso week number."
16648 (require 'cal-iso)
16649 (car (calendar-iso-from-absolute days)))
16651 (defun org-small-year-to-year (year)
16652 "Convert 2-digit years into 4-digit years.
16653 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16654 The year 2000 cannot be abbreviated. Any year larger than 99
16655 is returned unchanged."
16656 (if (< year 38)
16657 (setq year (+ 2000 year))
16658 (if (< year 100)
16659 (setq year (+ 1900 year))))
16660 year)
16662 (defun org-time-from-absolute (d)
16663 "Return the time corresponding to date D.
16664 D may be an absolute day number, or a calendar-type list (month day year)."
16665 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16666 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16668 (defun org-calendar-holiday ()
16669 "List of holidays, for Diary display in Org-mode."
16670 (require 'holidays)
16671 (let ((hl (funcall
16672 (if (fboundp 'calendar-check-holidays)
16673 'calendar-check-holidays 'check-calendar-holidays) date)))
16674 (if hl (mapconcat 'identity hl "; "))))
16676 (defun org-diary-sexp-entry (sexp entry date)
16677 "Process a SEXP diary ENTRY for DATE."
16678 (require 'diary-lib)
16679 (let ((result (if calendar-debug-sexp
16680 (let ((stack-trace-on-error t))
16681 (eval (car (read-from-string sexp))))
16682 (condition-case nil
16683 (eval (car (read-from-string sexp)))
16684 (error
16685 (beep)
16686 (message "Bad sexp at line %d in %s: %s"
16687 (org-current-line)
16688 (buffer-file-name) sexp)
16689 (sleep-for 2))))))
16690 (cond ((stringp result) (split-string result "; "))
16691 ((and (consp result)
16692 (not (consp (cdr result)))
16693 (stringp (cdr result))) (cdr result))
16694 ((and (consp result)
16695 (stringp (car result))) result)
16696 (result entry))))
16698 (defun org-diary-to-ical-string (frombuf)
16699 "Get iCalendar entries from diary entries in buffer FROMBUF.
16700 This uses the icalendar.el library."
16701 (let* ((tmpdir (if (featurep 'xemacs)
16702 (temp-directory)
16703 temporary-file-directory))
16704 (tmpfile (make-temp-name
16705 (expand-file-name "orgics" tmpdir)))
16706 buf rtn b e)
16707 (with-current-buffer frombuf
16708 (icalendar-export-region (point-min) (point-max) tmpfile)
16709 (setq buf (find-buffer-visiting tmpfile))
16710 (set-buffer buf)
16711 (goto-char (point-min))
16712 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16713 (setq b (match-beginning 0)))
16714 (goto-char (point-max))
16715 (if (re-search-backward "^END:VEVENT" nil t)
16716 (setq e (match-end 0)))
16717 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16718 (kill-buffer buf)
16719 (delete-file tmpfile)
16720 rtn))
16722 (defun org-closest-date (start current change prefer show-all)
16723 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16724 When PREFER is `past', return a date that is either CURRENT or past.
16725 When PREFER is `future', return a date that is either CURRENT or future.
16726 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16727 ;; Make the proper lists from the dates
16728 (catch 'exit
16729 (let ((a1 '(("h" . hour)
16730 ("d" . day)
16731 ("w" . week)
16732 ("m" . month)
16733 ("y" . year)))
16734 (shour (nth 2 (org-parse-time-string start)))
16735 dn dw sday cday n1 n2 n0
16736 d m y y1 y2 date1 date2 nmonths nm ny m2)
16738 (setq start (org-date-to-gregorian start)
16739 current (org-date-to-gregorian
16740 (if show-all
16741 current
16742 (time-to-days (current-time))))
16743 sday (calendar-absolute-from-gregorian start)
16744 cday (calendar-absolute-from-gregorian current))
16746 (if (<= cday sday) (throw 'exit sday))
16748 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16749 (setq dn (string-to-number (match-string 1 change))
16750 dw (cdr (assoc (match-string 2 change) a1)))
16751 (error "Invalid change specifier: %s" change))
16752 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16753 (cond
16754 ((eq dw 'hour)
16755 (let ((missing-hours
16756 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16757 dn)))
16758 (setq n1 (if (zerop missing-hours) cday
16759 (- cday (1+ (floor (/ missing-hours 24)))))
16760 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16761 ((eq dw 'day)
16762 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16763 n2 (+ n1 dn)))
16764 ((eq dw 'year)
16765 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16766 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16767 (setq date1 (list m d y1)
16768 n1 (calendar-absolute-from-gregorian date1)
16769 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16770 n2 (calendar-absolute-from-gregorian date2)))
16771 ((eq dw 'month)
16772 ;; approx number of month between the two dates
16773 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16774 ;; How often does dn fit in there?
16775 (setq d (nth 1 start) m (car start) y (nth 2 start)
16776 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16777 m (+ m nm)
16778 ny (floor (/ m 12))
16779 y (+ y ny)
16780 m (- m (* ny 12)))
16781 (while (> m 12) (setq m (- m 12) y (1+ y)))
16782 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16783 (setq m2 (+ m dn) y2 y)
16784 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16785 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16786 (while (<= n2 cday)
16787 (setq n1 n2 m m2 y y2)
16788 (setq m2 (+ m dn) y2 y)
16789 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16790 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16791 ;; Make sure n1 is the earlier date
16792 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16793 (if show-all
16794 (cond
16795 ((eq prefer 'past) (if (= cday n2) n2 n1))
16796 ((eq prefer 'future) (if (= cday n1) n1 n2))
16797 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16798 (cond
16799 ((eq prefer 'past) (if (= cday n2) n2 n1))
16800 ((eq prefer 'future) (if (= cday n1) n1 n2))
16801 (t (if (= cday n1) n1 n2)))))))
16803 (defun org-date-to-gregorian (date)
16804 "Turn any specification of DATE into a Gregorian date for the calendar."
16805 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16806 ((and (listp date) (= (length date) 3)) date)
16807 ((stringp date)
16808 (setq date (org-parse-time-string date))
16809 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16810 ((listp date)
16811 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16813 (defun org-parse-time-string (s &optional nodefault)
16814 "Parse the standard Org-mode time string.
16815 This should be a lot faster than the normal `parse-time-string'.
16816 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16817 hour and minute fields will be nil if not given."
16818 (cond ((string-match org-ts-regexp0 s)
16819 (list 0
16820 (if (or (match-beginning 8) (not nodefault))
16821 (string-to-number (or (match-string 8 s) "0")))
16822 (if (or (match-beginning 7) (not nodefault))
16823 (string-to-number (or (match-string 7 s) "0")))
16824 (string-to-number (match-string 4 s))
16825 (string-to-number (match-string 3 s))
16826 (string-to-number (match-string 2 s))
16827 nil nil nil))
16828 ((string-match "^<[^>]+>$" s)
16829 (decode-time (seconds-to-time (org-matcher-time s))))
16830 (t (error "Not a standard Org-mode time string: %s" s))))
16832 (defun org-timestamp-up (&optional arg)
16833 "Increase the date item at the cursor by one.
16834 If the cursor is on the year, change the year. If it is on the month,
16835 the day or the time, change that.
16836 With prefix ARG, change by that many units."
16837 (interactive "p")
16838 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16840 (defun org-timestamp-down (&optional arg)
16841 "Decrease the date item at the cursor by one.
16842 If the cursor is on the year, change the year. If it is on the month,
16843 the day or the time, change that.
16844 With prefix ARG, change by that many units."
16845 (interactive "p")
16846 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16848 (defun org-timestamp-up-day (&optional arg)
16849 "Increase the date in the time stamp by one day.
16850 With prefix ARG, change that many days."
16851 (interactive "p")
16852 (if (and (not (org-at-timestamp-p t))
16853 (org-at-heading-p))
16854 (org-todo 'up)
16855 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16857 (defun org-timestamp-down-day (&optional arg)
16858 "Decrease the date in the time stamp by one day.
16859 With prefix ARG, change that many days."
16860 (interactive "p")
16861 (if (and (not (org-at-timestamp-p t))
16862 (org-at-heading-p))
16863 (org-todo 'down)
16864 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16866 (defun org-at-timestamp-p (&optional inactive-ok)
16867 "Determine if the cursor is in or at a timestamp."
16868 (interactive)
16869 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16870 (pos (point))
16871 (ans (or (looking-at tsr)
16872 (save-excursion
16873 (skip-chars-backward "^[<\n\r\t")
16874 (if (> (point) (point-min)) (backward-char 1))
16875 (and (looking-at tsr)
16876 (> (- (match-end 0) pos) -1))))))
16877 (and ans
16878 (boundp 'org-ts-what)
16879 (setq org-ts-what
16880 (cond
16881 ((= pos (match-beginning 0)) 'bracket)
16882 ;; Point is considered to be "on the bracket" whether
16883 ;; it's really on it or right after it.
16884 ((= pos (1- (match-end 0))) 'bracket)
16885 ((= pos (match-end 0)) 'after)
16886 ((org-pos-in-match-range pos 2) 'year)
16887 ((org-pos-in-match-range pos 3) 'month)
16888 ((org-pos-in-match-range pos 7) 'hour)
16889 ((org-pos-in-match-range pos 8) 'minute)
16890 ((or (org-pos-in-match-range pos 4)
16891 (org-pos-in-match-range pos 5)) 'day)
16892 ((and (> pos (or (match-end 8) (match-end 5)))
16893 (< pos (match-end 0)))
16894 (- pos (or (match-end 8) (match-end 5))))
16895 (t 'day))))
16896 ans))
16898 (defun org-toggle-timestamp-type ()
16899 "Toggle the type (<active> or [inactive]) of a time stamp."
16900 (interactive)
16901 (when (org-at-timestamp-p t)
16902 (let ((beg (match-beginning 0)) (end (match-end 0))
16903 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16904 (save-excursion
16905 (goto-char beg)
16906 (while (re-search-forward "[][<>]" end t)
16907 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16908 t t)))
16909 (message "Timestamp is now %sactive"
16910 (if (equal (char-after beg) ?<) "" "in")))))
16912 (defun org-at-clock-log-p nil
16913 "Is the cursor on the clock log line?"
16914 (save-excursion
16915 (move-beginning-of-line 1)
16916 (looking-at "^[ \t]*CLOCK:")))
16918 (defvar org-clock-history) ; defined in org-clock.el
16919 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16920 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16921 "Change the date in the time stamp at point.
16922 The date will be changed by N times WHAT. WHAT can be `day', `month',
16923 `year', `minute', `second'. If WHAT is not given, the cursor position
16924 in the timestamp determines what will be changed.
16925 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16926 (let ((origin (point)) origin-cat
16927 with-hm inactive
16928 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16929 org-ts-what
16930 extra rem
16931 ts time time0 fixnext clrgx)
16932 (if (not (org-at-timestamp-p t))
16933 (error "Not at a timestamp"))
16934 (if (and (not what) (eq org-ts-what 'bracket))
16935 (org-toggle-timestamp-type)
16936 ;; Point isn't on brackets. Remember the part of the time-stamp
16937 ;; the point was in. Indeed, size of time-stamps may change,
16938 ;; but point must be kept in the same category nonetheless.
16939 (setq origin-cat org-ts-what)
16940 (if (and (not what) (not (eq org-ts-what 'day))
16941 org-display-custom-times
16942 (get-text-property (point) 'display)
16943 (not (get-text-property (1- (point)) 'display)))
16944 (setq org-ts-what 'day))
16945 (setq org-ts-what (or what org-ts-what)
16946 inactive (= (char-after (match-beginning 0)) ?\[)
16947 ts (match-string 0))
16948 (replace-match "")
16949 (when (string-match
16950 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16952 (setq extra (match-string 1 ts))
16953 (if suppress-tmp-delay
16954 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16955 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16956 (setq with-hm t))
16957 (setq time0 (org-parse-time-string ts))
16958 (when (and updown
16959 (eq org-ts-what 'minute)
16960 (not current-prefix-arg))
16961 ;; This looks like s-up and s-down. Change by one rounding step.
16962 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16963 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16964 (setcar (cdr time0) (+ (nth 1 time0)
16965 (if (> n 0) (- rem) (- dm rem))))))
16966 (setq time
16967 (encode-time (or (car time0) 0)
16968 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16969 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16970 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16971 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16972 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16973 (nthcdr 6 time0)))
16974 (when (and (member org-ts-what '(hour minute))
16975 extra
16976 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16977 (setq extra (org-modify-ts-extra
16978 extra
16979 (if (eq org-ts-what 'hour) 2 5)
16980 n dm)))
16981 (when (integerp org-ts-what)
16982 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16983 (if (eq what 'calendar)
16984 (let ((cal-date (org-get-date-from-calendar)))
16985 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16986 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16987 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16988 (setcar time0 (or (car time0) 0))
16989 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16990 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16991 (setq time (apply 'encode-time time0))))
16992 ;; Insert the new time-stamp, and ensure point stays in the same
16993 ;; category as before (i.e. not after the last position in that
16994 ;; category).
16995 (let ((pos (point)))
16996 ;; Stay before inserted string. `save-excursion' is of no use.
16997 (setq org-last-changed-timestamp
16998 (org-insert-time-stamp time with-hm inactive nil nil extra))
16999 (goto-char pos))
17000 (save-match-data
17001 (looking-at org-ts-regexp3)
17002 (goto-char (cond
17003 ;; `day' category ends before `hour' if any, or at
17004 ;; the end of the day name.
17005 ((eq origin-cat 'day)
17006 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17007 ((eq origin-cat 'hour) (min (match-end 7) origin))
17008 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17009 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17010 ;; `year' and `month' have both fixed size: point
17011 ;; couldn't have moved into another part.
17012 (t origin))))
17013 ;; Update clock if on a CLOCK line.
17014 (org-clock-update-time-maybe)
17015 ;; Maybe adjust the closest clock in `org-clock-history'
17016 (when org-clock-adjust-closest
17017 (if (not (and (org-at-clock-log-p)
17018 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17019 org-clock-history))))))
17020 (message "No clock to adjust")
17021 (cond ((save-excursion ; fix previous clock?
17022 (re-search-backward org-ts-regexp0 nil t)
17023 (org-looking-back (concat org-clock-string " \\[")))
17024 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17025 ((save-excursion ; fix next clock?
17026 (re-search-backward org-ts-regexp0 nil t)
17027 (looking-at (concat org-ts-regexp0 "\\] =>")))
17028 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17029 (save-window-excursion
17030 ;; Find closest clock to point, adjust the previous/next one in history
17031 (let* ((p (save-excursion (org-back-to-heading t)))
17032 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17033 (clfixnth
17034 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17035 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17036 (if (not clfixpos)
17037 (message "No clock to adjust")
17038 (save-excursion
17039 (org-goto-marker-or-bmk clfixpos)
17040 (org-show-subtree)
17041 (when (re-search-forward clrgx nil t)
17042 (goto-char (match-beginning 1))
17043 (let (org-clock-adjust-closest)
17044 (org-timestamp-change n org-ts-what updown))
17045 (message "Clock adjusted in %s for heading: %s"
17046 (file-name-nondirectory (buffer-file-name))
17047 (org-get-heading t t)))))))))
17048 ;; Try to recenter the calendar window, if any.
17049 (if (and org-calendar-follow-timestamp-change
17050 (get-buffer-window "*Calendar*" t)
17051 (memq org-ts-what '(day month year)))
17052 (org-recenter-calendar (time-to-days time))))))
17054 (defun org-modify-ts-extra (s pos n dm)
17055 "Change the different parts of the lead-time and repeat fields in timestamp."
17056 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17057 ng h m new rem)
17058 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17059 (cond
17060 ((or (org-pos-in-match-range pos 2)
17061 (org-pos-in-match-range pos 3))
17062 (setq m (string-to-number (match-string 3 s))
17063 h (string-to-number (match-string 2 s)))
17064 (if (org-pos-in-match-range pos 2)
17065 (setq h (+ h n))
17066 (setq n (* dm (org-no-warnings (signum n))))
17067 (when (not (= 0 (setq rem (% m dm))))
17068 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17069 (setq m (+ m n)))
17070 (if (< m 0) (setq m (+ m 60) h (1- h)))
17071 (if (> m 59) (setq m (- m 60) h (1+ h)))
17072 (setq h (min 24 (max 0 h)))
17073 (setq ng 1 new (format "-%02d:%02d" h m)))
17074 ((org-pos-in-match-range pos 6)
17075 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17076 ((org-pos-in-match-range pos 5)
17077 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17079 ((org-pos-in-match-range pos 9)
17080 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17081 ((org-pos-in-match-range pos 8)
17082 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17084 (when ng
17085 (setq s (concat
17086 (substring s 0 (match-beginning ng))
17088 (substring s (match-end ng))))))
17091 (defun org-recenter-calendar (date)
17092 "If the calendar is visible, recenter it to DATE."
17093 (let ((cwin (get-buffer-window "*Calendar*" t)))
17094 (when cwin
17095 (let ((calendar-move-hook nil))
17096 (with-selected-window cwin
17097 (calendar-goto-date (if (listp date) date
17098 (calendar-gregorian-from-absolute date))))))))
17100 (defun org-goto-calendar (&optional arg)
17101 "Go to the Emacs calendar at the current date.
17102 If there is a time stamp in the current line, go to that date.
17103 A prefix ARG can be used to force the current date."
17104 (interactive "P")
17105 (let ((tsr org-ts-regexp) diff
17106 (calendar-move-hook nil)
17107 (calendar-view-holidays-initially-flag nil)
17108 (calendar-view-diary-initially-flag nil))
17109 (if (or (org-at-timestamp-p)
17110 (save-excursion
17111 (beginning-of-line 1)
17112 (looking-at (concat ".*" tsr))))
17113 (let ((d1 (time-to-days (current-time)))
17114 (d2 (time-to-days
17115 (org-time-string-to-time (match-string 1)))))
17116 (setq diff (- d2 d1))))
17117 (calendar)
17118 (calendar-goto-today)
17119 (if (and diff (not arg)) (calendar-forward-day diff))))
17121 (defun org-get-date-from-calendar ()
17122 "Return a list (month day year) of date at point in calendar."
17123 (with-current-buffer "*Calendar*"
17124 (save-match-data
17125 (calendar-cursor-to-date))))
17127 (defun org-date-from-calendar ()
17128 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17129 If there is already a time stamp at the cursor position, update it."
17130 (interactive)
17131 (if (org-at-timestamp-p t)
17132 (org-timestamp-change 0 'calendar)
17133 (let ((cal-date (org-get-date-from-calendar)))
17134 (org-insert-time-stamp
17135 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17137 (defcustom org-effort-durations
17138 `(("h" . 60)
17139 ("d" . ,(* 60 8))
17140 ("w" . ,(* 60 8 5))
17141 ("m" . ,(* 60 8 5 4))
17142 ("y" . ,(* 60 8 5 40)))
17143 "Conversion factor to minutes for an effort modifier.
17145 Each entry has the form (MODIFIER . MINUTES).
17147 In an effort string, a number followed by MODIFIER is multiplied
17148 by the specified number of MINUTES to obtain an effort in
17149 minutes.
17151 For example, if the value of this variable is ((\"hours\" . 60)), then an
17152 effort string \"2hours\" is equivalent to 120 minutes."
17153 :group 'org-agenda
17154 :version "24.1"
17155 :type '(alist :key-type (string :tag "Modifier")
17156 :value-type (number :tag "Minutes")))
17158 (defun org-minutes-to-clocksum-string (m)
17159 "Format number of minutes as a clocksum string.
17160 The format is determined by `org-time-clocksum-format',
17161 `org-time-clocksum-use-fractional' and
17162 `org-time-clocksum-fractional-format' and
17163 `org-time-clocksum-use-effort-durations'."
17164 (let ((clocksum "") h d w mo y fmt n)
17165 (setq h (if org-time-clocksum-use-effort-durations
17166 (cdr (assoc "h" org-effort-durations)) 60)
17167 d (if org-time-clocksum-use-effort-durations
17168 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17169 w (if org-time-clocksum-use-effort-durations
17170 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17171 mo (if org-time-clocksum-use-effort-durations
17172 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17173 y (if org-time-clocksum-use-effort-durations
17174 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17175 ;; fractional format
17176 (if org-time-clocksum-use-fractional
17177 (cond
17178 ;; single format string
17179 ((stringp org-time-clocksum-fractional-format)
17180 (format org-time-clocksum-fractional-format (/ m (float h))))
17181 ;; choice of fractional formats for different time units
17182 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17183 (> (/ (truncate m) (* y d h)) 0))
17184 (format fmt (/ m (* y d (float h)))))
17185 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17186 (> (/ (truncate m) (* mo d h)) 0))
17187 (format fmt (/ m (* mo d (float h)))))
17188 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17189 (> (/ (truncate m) (* w d h)) 0))
17190 (format fmt (/ m (* w d (float h)))))
17191 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17192 (> (/ (truncate m) (* d h)) 0))
17193 (format fmt (/ m (* d (float h)))))
17194 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17195 (> (/ (truncate m) h) 0))
17196 (format fmt (/ m (float h))))
17197 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17198 (format fmt m))
17199 ;; fall back to smallest time unit with a format
17200 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17201 (format fmt (/ m (float h))))
17202 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17203 (format fmt (/ m (* d (float h)))))
17204 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17205 (format fmt (/ m (* w d (float h)))))
17206 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17207 (format fmt (/ m (* mo d (float h)))))
17208 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17209 (format fmt (/ m (* y d (float h))))))
17210 ;; standard (non-fractional) format, with single format string
17211 (if (stringp org-time-clocksum-format)
17212 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17213 ;; separate formats components
17214 (and (setq fmt (plist-get org-time-clocksum-format :years))
17215 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17216 (plist-get org-time-clocksum-format :require-years))
17217 (setq clocksum (concat clocksum (format fmt n))
17218 m (- m (* n y d h))))
17219 (and (setq fmt (plist-get org-time-clocksum-format :months))
17220 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17221 (plist-get org-time-clocksum-format :require-months))
17222 (setq clocksum (concat clocksum (format fmt n))
17223 m (- m (* n mo d h))))
17224 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17225 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17226 (plist-get org-time-clocksum-format :require-weeks))
17227 (setq clocksum (concat clocksum (format fmt n))
17228 m (- m (* n w d h))))
17229 (and (setq fmt (plist-get org-time-clocksum-format :days))
17230 (or (> (setq n (/ (truncate m) (* d h))) 0)
17231 (plist-get org-time-clocksum-format :require-days))
17232 (setq clocksum (concat clocksum (format fmt n))
17233 m (- m (* n d h))))
17234 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17235 (or (> (setq n (/ (truncate m) h)) 0)
17236 (plist-get org-time-clocksum-format :require-hours))
17237 (setq clocksum (concat clocksum (format fmt n))
17238 m (- m (* n h))))
17239 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17240 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17241 (setq clocksum (concat clocksum (format fmt m))))
17242 ;; return formatted time duration
17243 clocksum))))
17245 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17246 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17247 "Org mode version 8.0")
17249 (defun org-hours-to-clocksum-string (n)
17250 (org-minutes-to-clocksum-string (* n 60)))
17252 (defun org-hh:mm-string-to-minutes (s)
17253 "Convert a string H:MM to a number of minutes.
17254 If the string is just a number, interpret it as minutes.
17255 In fact, the first hh:mm or number in the string will be taken,
17256 there can be extra stuff in the string.
17257 If no number is found, the return value is 0."
17258 (cond
17259 ((integerp s) s)
17260 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17261 (+ (* (string-to-number (match-string 1 s)) 60)
17262 (string-to-number (match-string 2 s))))
17263 ((string-match "\\([0-9]+\\)" s)
17264 (string-to-number (match-string 1 s)))
17265 (t 0)))
17267 (defcustom org-image-actual-width t
17268 "Should we use the actual width of images when inlining them?
17270 When set to `t', always use the image width.
17272 When set to a number, use imagemagick (when available) to set
17273 the image's width to this value.
17275 When set to a number in a list, try to get the width from the
17276 #+ATTR.* keyword if it matches a width specification like
17277 width=\"[0-9]+\", and fall back on that number if none is found.
17279 When set to nil, try to get the width from an #+ATTR.* keyword
17280 and fall back on the original width if none is found.
17282 This requires Emacs >= 24.1, build with imagemagick support."
17283 :group 'org-appearance
17284 :version "24.4"
17285 :package-version '(Org . "8.0")
17286 :type '(choice
17287 (const :tag "Use the image width" t)
17288 (integer :tag "Use a number of pixels")
17289 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17290 (const :tag "Use #+ATTR* or don't resize" nil)))
17292 (defcustom org-agenda-inhibit-startup t
17293 "Inhibit startup when preparing agenda buffers.
17294 When this variable is `t' (the default), the initialization of
17295 the Org agenda buffers is inhibited: e.g. the visibility state
17296 is not set, the tables are not re-aligned, etc."
17297 :type 'boolean
17298 :version "24.3"
17299 :group 'org-agenda)
17301 (defun org-duration-string-to-minutes (s &optional output-to-string)
17302 "Convert a duration string S to minutes.
17304 A bare number is interpreted as minutes, modifiers can be set by
17305 customizing `org-effort-durations' (which see).
17307 Entries containing a colon are interpreted as H:MM by
17308 `org-hh:mm-string-to-minutes'."
17309 (let ((result 0)
17310 (re (concat "\\([0-9.]+\\) *\\("
17311 (regexp-opt (mapcar 'car org-effort-durations))
17312 "\\)")))
17313 (while (string-match re s)
17314 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17315 (string-to-number (match-string 1 s))))
17316 (setq s (replace-match "" nil t s)))
17317 (setq result (floor result))
17318 (incf result (org-hh:mm-string-to-minutes s))
17319 (if output-to-string (number-to-string result) result)))
17321 ;;;; Files
17323 (defun org-save-all-org-buffers ()
17324 "Save all Org-mode buffers without user confirmation."
17325 (interactive)
17326 (message "Saving all Org-mode buffers...")
17327 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17328 (when (featurep 'org-id) (org-id-locations-save))
17329 (message "Saving all Org-mode buffers... done"))
17331 (defun org-revert-all-org-buffers ()
17332 "Revert all Org-mode buffers.
17333 Prompt for confirmation when there are unsaved changes.
17334 Be sure you know what you are doing before letting this function
17335 overwrite your changes.
17337 This function is useful in a setup where one tracks org files
17338 with a version control system, to revert on one machine after pulling
17339 changes from another. I believe the procedure must be like this:
17341 1. M-x org-save-all-org-buffers
17342 2. Pull changes from the other machine, resolve conflicts
17343 3. M-x org-revert-all-org-buffers"
17344 (interactive)
17345 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17346 (error "Abort"))
17347 (save-excursion
17348 (save-window-excursion
17349 (mapc
17350 (lambda (b)
17351 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17352 (with-current-buffer b buffer-file-name))
17353 (org-pop-to-buffer-same-window b)
17354 (revert-buffer t 'no-confirm)))
17355 (buffer-list))
17356 (when (and (featurep 'org-id) org-id-track-globally)
17357 (org-id-locations-load)))))
17359 ;;;; Agenda files
17361 ;;;###autoload
17362 (defun org-switchb (&optional arg)
17363 "Switch between Org buffers.
17364 With one prefix argument, restrict available buffers to files.
17365 With two prefix arguments, restrict available buffers to agenda files.
17367 Defaults to `iswitchb' for buffer name completion.
17368 Set `org-completion-use-ido' to make it use ido instead."
17369 (interactive "P")
17370 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17371 ((equal arg '(16)) (org-buffer-list 'agenda))
17372 (t (org-buffer-list))))
17373 (org-completion-use-iswitchb org-completion-use-iswitchb)
17374 (org-completion-use-ido org-completion-use-ido))
17375 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17376 (setq org-completion-use-iswitchb t))
17377 (org-pop-to-buffer-same-window
17378 (org-icompleting-read "Org buffer: "
17379 (mapcar 'list (mapcar 'buffer-name blist))
17380 nil t))))
17382 ;;; Define some older names previously used for this functionality
17383 ;;;###autoload
17384 (defalias 'org-ido-switchb 'org-switchb)
17385 ;;;###autoload
17386 (defalias 'org-iswitchb 'org-switchb)
17388 (defun org-buffer-list (&optional predicate exclude-tmp)
17389 "Return a list of Org buffers.
17390 PREDICATE can be `export', `files' or `agenda'.
17392 export restrict the list to Export buffers.
17393 files restrict the list to buffers visiting Org files.
17394 agenda restrict the list to buffers visiting agenda files.
17396 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17397 (let* ((bfn nil)
17398 (agenda-files (and (eq predicate 'agenda)
17399 (mapcar 'file-truename (org-agenda-files t))))
17400 (filter
17401 (cond
17402 ((eq predicate 'files)
17403 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17404 ((eq predicate 'export)
17405 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17406 ((eq predicate 'agenda)
17407 (lambda (b)
17408 (with-current-buffer b
17409 (and (derived-mode-p 'org-mode)
17410 (setq bfn (buffer-file-name b))
17411 (member (file-truename bfn) agenda-files)))))
17412 (t (lambda (b) (with-current-buffer b
17413 (or (derived-mode-p 'org-mode)
17414 (string-match "\*Org .*Export"
17415 (buffer-name b)))))))))
17416 (delq nil
17417 (mapcar
17418 (lambda(b)
17419 (if (and (funcall filter b)
17420 (or (not exclude-tmp)
17421 (not (string-match "tmp" (buffer-name b)))))
17423 nil))
17424 (buffer-list)))))
17426 (defun org-agenda-files (&optional unrestricted archives)
17427 "Get the list of agenda files.
17428 Optional UNRESTRICTED means return the full list even if a restriction
17429 is currently in place.
17430 When ARCHIVES is t, include all archive files that are really being
17431 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17432 `org-agenda-archives-mode' is t."
17433 (let ((files
17434 (cond
17435 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17436 ((stringp org-agenda-files) (org-read-agenda-file-list))
17437 ((listp org-agenda-files) org-agenda-files)
17438 (t (error "Invalid value of `org-agenda-files'")))))
17439 (setq files (apply 'append
17440 (mapcar (lambda (f)
17441 (if (file-directory-p f)
17442 (directory-files
17443 f t org-agenda-file-regexp)
17444 (list f)))
17445 files)))
17446 (when org-agenda-skip-unavailable-files
17447 (setq files (delq nil
17448 (mapcar (function
17449 (lambda (file)
17450 (and (file-readable-p file) file)))
17451 files))))
17452 (when (or (eq archives t)
17453 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17454 (setq files (org-add-archive-files files)))
17455 files))
17457 (defun org-agenda-file-p (&optional file)
17458 "Return non-nil, if FILE is an agenda file.
17459 If FILE is omitted, use the file associated with the current
17460 buffer."
17461 (member (or file (buffer-file-name))
17462 (org-agenda-files t)))
17464 (defun org-edit-agenda-file-list ()
17465 "Edit the list of agenda files.
17466 Depending on setup, this either uses customize to edit the variable
17467 `org-agenda-files', or it visits the file that is holding the list. In the
17468 latter case, the buffer is set up in a way that saving it automatically kills
17469 the buffer and restores the previous window configuration."
17470 (interactive)
17471 (if (stringp org-agenda-files)
17472 (let ((cw (current-window-configuration)))
17473 (find-file org-agenda-files)
17474 (org-set-local 'org-window-configuration cw)
17475 (org-add-hook 'after-save-hook
17476 (lambda ()
17477 (set-window-configuration
17478 (prog1 org-window-configuration
17479 (kill-buffer (current-buffer))))
17480 (org-install-agenda-files-menu)
17481 (message "New agenda file list installed"))
17482 nil 'local)
17483 (message "%s" (substitute-command-keys
17484 "Edit list and finish with \\[save-buffer]")))
17485 (customize-variable 'org-agenda-files)))
17487 (defun org-store-new-agenda-file-list (list)
17488 "Set new value for the agenda file list and save it correctly."
17489 (if (stringp org-agenda-files)
17490 (let ((fe (org-read-agenda-file-list t)) b u)
17491 (while (setq b (find-buffer-visiting org-agenda-files))
17492 (kill-buffer b))
17493 (with-temp-file org-agenda-files
17494 (insert
17495 (mapconcat
17496 (lambda (f) ;; Keep un-expanded entries.
17497 (if (setq u (assoc f fe))
17498 (cdr u)
17500 list "\n")
17501 "\n")))
17502 (let ((org-mode-hook nil) (org-inhibit-startup t)
17503 (org-insert-mode-line-in-empty-file nil))
17504 (setq org-agenda-files list)
17505 (customize-save-variable 'org-agenda-files org-agenda-files))))
17507 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17508 "Read the list of agenda files from a file.
17509 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17510 filenames, used by `org-store-new-agenda-file-list' to write back
17511 un-expanded file names."
17512 (when (file-directory-p org-agenda-files)
17513 (error "`org-agenda-files' cannot be a single directory"))
17514 (when (stringp org-agenda-files)
17515 (with-temp-buffer
17516 (insert-file-contents org-agenda-files)
17517 (mapcar
17518 (lambda (f)
17519 (let ((e (expand-file-name (substitute-in-file-name f)
17520 org-directory)))
17521 (if pair-with-expansion
17522 (cons e f)
17523 e)))
17524 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17526 ;;;###autoload
17527 (defun org-cycle-agenda-files ()
17528 "Cycle through the files in `org-agenda-files'.
17529 If the current buffer visits an agenda file, find the next one in the list.
17530 If the current buffer does not, find the first agenda file."
17531 (interactive)
17532 (let* ((fs (org-agenda-files t))
17533 (files (append fs (list (car fs))))
17534 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17535 file)
17536 (unless files (error "No agenda files"))
17537 (catch 'exit
17538 (while (setq file (pop files))
17539 (if (equal (file-truename file) tcf)
17540 (when (car files)
17541 (find-file (car files))
17542 (throw 'exit t))))
17543 (find-file (car fs)))
17544 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17546 (defun org-agenda-file-to-front (&optional to-end)
17547 "Move/add the current file to the top of the agenda file list.
17548 If the file is not present in the list, it is added to the front. If it is
17549 present, it is moved there. With optional argument TO-END, add/move to the
17550 end of the list."
17551 (interactive "P")
17552 (let ((org-agenda-skip-unavailable-files nil)
17553 (file-alist (mapcar (lambda (x)
17554 (cons (file-truename x) x))
17555 (org-agenda-files t)))
17556 (ctf (file-truename
17557 (or buffer-file-name
17558 (error "Please save the current buffer to a file"))))
17559 x had)
17560 (setq x (assoc ctf file-alist) had x)
17562 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17563 (if to-end
17564 (setq file-alist (append (delq x file-alist) (list x)))
17565 (setq file-alist (cons x (delq x file-alist))))
17566 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17567 (org-install-agenda-files-menu)
17568 (message "File %s to %s of agenda file list"
17569 (if had "moved" "added") (if to-end "end" "front"))))
17571 (defun org-remove-file (&optional file)
17572 "Remove current file from the list of files in variable `org-agenda-files'.
17573 These are the files which are being checked for agenda entries.
17574 Optional argument FILE means use this file instead of the current."
17575 (interactive)
17576 (let* ((org-agenda-skip-unavailable-files nil)
17577 (file (or file buffer-file-name
17578 (error "Current buffer does not visit a file")))
17579 (true-file (file-truename file))
17580 (afile (abbreviate-file-name file))
17581 (files (delq nil (mapcar
17582 (lambda (x)
17583 (if (equal true-file
17584 (file-truename x))
17585 nil x))
17586 (org-agenda-files t)))))
17587 (if (not (= (length files) (length (org-agenda-files t))))
17588 (progn
17589 (org-store-new-agenda-file-list files)
17590 (org-install-agenda-files-menu)
17591 (message "Removed file: %s" afile))
17592 (message "File was not in list: %s (not removed)" afile))))
17594 (defun org-file-menu-entry (file)
17595 (vector file (list 'find-file file) t))
17597 (defun org-check-agenda-file (file)
17598 "Make sure FILE exists. If not, ask user what to do."
17599 (when (not (file-exists-p file))
17600 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17601 (abbreviate-file-name file))
17602 (let ((r (downcase (read-char-exclusive))))
17603 (cond
17604 ((equal r ?r)
17605 (org-remove-file file)
17606 (throw 'nextfile t))
17607 (t (error "Abort"))))))
17609 (defun org-get-agenda-file-buffer (file)
17610 "Get a buffer visiting FILE. If the buffer needs to be created, add
17611 it to the list of buffers which might be released later."
17612 (let ((buf (org-find-base-buffer-visiting file)))
17613 (if buf
17614 buf ; just return it
17615 ;; Make a new buffer and remember it
17616 (setq buf (find-file-noselect file))
17617 (if buf (push buf org-agenda-new-buffers))
17618 buf)))
17620 (defun org-release-buffers (blist)
17621 "Release all buffers in list, asking the user for confirmation when needed.
17622 When a buffer is unmodified, it is just killed. When modified, it is saved
17623 \(if the user agrees) and then killed."
17624 (let (buf file)
17625 (while (setq buf (pop blist))
17626 (setq file (buffer-file-name buf))
17627 (when (and (buffer-modified-p buf)
17628 file
17629 (y-or-n-p (format "Save file %s? " file)))
17630 (with-current-buffer buf (save-buffer)))
17631 (kill-buffer buf))))
17633 (defun org-agenda-prepare-buffers (files)
17634 "Create buffers for all agenda files, protect archived trees and comments."
17635 (interactive)
17636 (let ((pa '(:org-archived t))
17637 (pc '(:org-comment t))
17638 (pall '(:org-archived t :org-comment t))
17639 (inhibit-read-only t)
17640 (org-inhibit-startup org-agenda-inhibit-startup)
17641 (rea (concat ":" org-archive-tag ":"))
17642 file re)
17643 (save-excursion
17644 (save-restriction
17645 (while (setq file (pop files))
17646 (catch 'nextfile
17647 (if (bufferp file)
17648 (set-buffer file)
17649 (org-check-agenda-file file)
17650 (set-buffer (org-get-agenda-file-buffer file)))
17651 (widen)
17652 (org-refresh-category-properties)
17653 (org-refresh-properties org-effort-property 'org-effort)
17654 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17655 (setq org-todo-keywords-for-agenda
17656 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17657 (setq org-done-keywords-for-agenda
17658 (append org-done-keywords-for-agenda org-done-keywords))
17659 (setq org-todo-keyword-alist-for-agenda
17660 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17661 (setq org-drawers-for-agenda
17662 (append org-drawers-for-agenda org-drawers))
17663 (setq org-tag-alist-for-agenda
17664 (append org-tag-alist-for-agenda org-tag-alist))
17665 (org-with-silent-modifications
17666 (save-excursion
17667 (remove-text-properties (point-min) (point-max) pall)
17668 (when org-agenda-skip-archived-trees
17669 (goto-char (point-min))
17670 (while (re-search-forward rea nil t)
17671 (if (org-at-heading-p t)
17672 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17673 (goto-char (point-min))
17674 (setq re (format org-heading-keyword-regexp-format
17675 org-comment-string))
17676 (while (re-search-forward re nil t)
17677 (add-text-properties
17678 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17679 (setq org-todo-keywords-for-agenda
17680 (org-uniquify org-todo-keywords-for-agenda))
17681 (setq org-todo-keyword-alist-for-agenda
17682 (org-uniquify org-todo-keyword-alist-for-agenda)
17683 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17686 ;;;; CDLaTeX minor mode
17688 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17689 "Keymap for the minor `org-cdlatex-mode'.")
17691 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17692 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17693 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17694 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17695 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17697 (defvar org-cdlatex-texmathp-advice-is-done nil
17698 "Flag remembering if we have applied the advice to texmathp already.")
17700 (define-minor-mode org-cdlatex-mode
17701 "Toggle the minor `org-cdlatex-mode'.
17702 This mode supports entering LaTeX environment and math in LaTeX fragments
17703 in Org-mode.
17704 \\{org-cdlatex-mode-map}"
17705 nil " OCDL" nil
17706 (when org-cdlatex-mode
17707 (require 'cdlatex)
17708 (run-hooks 'cdlatex-mode-hook)
17709 (cdlatex-compute-tables))
17710 (unless org-cdlatex-texmathp-advice-is-done
17711 (setq org-cdlatex-texmathp-advice-is-done t)
17712 (defadvice texmathp (around org-math-always-on activate)
17713 "Always return t in org-mode buffers.
17714 This is because we want to insert math symbols without dollars even outside
17715 the LaTeX math segments. If Orgmode thinks that point is actually inside
17716 an embedded LaTeX fragment, let texmathp do its job.
17717 \\[org-cdlatex-mode-map]"
17718 (interactive)
17719 (let (p)
17720 (cond
17721 ((not (derived-mode-p 'org-mode)) ad-do-it)
17722 ((eq this-command 'cdlatex-math-symbol)
17723 (setq ad-return-value t
17724 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17726 (let ((p (org-inside-LaTeX-fragment-p)))
17727 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17728 (setq ad-return-value t
17729 texmathp-why '("Org-mode embedded math" . 0))
17730 (if p ad-do-it)))))))))
17732 (defun turn-on-org-cdlatex ()
17733 "Unconditionally turn on `org-cdlatex-mode'."
17734 (org-cdlatex-mode 1))
17736 (defun org-try-cdlatex-tab ()
17737 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17738 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17739 - inside a LaTeX fragment, or
17740 - after the first word in a line, where an abbreviation expansion could
17741 insert a LaTeX environment."
17742 (when org-cdlatex-mode
17743 (cond
17744 ;; Before any word on the line: No expansion possible.
17745 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17746 ;; Just after first word on the line: Expand it. Make sure it
17747 ;; cannot happen on headlines, though.
17748 ((save-excursion
17749 (skip-chars-backward "a-zA-Z0-9*")
17750 (skip-chars-backward " \t")
17751 (and (bolp) (not (org-at-heading-p))))
17752 (cdlatex-tab) t)
17753 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17755 (defun org-cdlatex-underscore-caret (&optional arg)
17756 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17757 Revert to the normal definition outside of these fragments."
17758 (interactive "P")
17759 (if (org-inside-LaTeX-fragment-p)
17760 (call-interactively 'cdlatex-sub-superscript)
17761 (let (org-cdlatex-mode)
17762 (call-interactively (key-binding (vector last-input-event))))))
17764 (defun org-cdlatex-math-modify (&optional arg)
17765 "Execute `cdlatex-math-modify' in LaTeX fragments.
17766 Revert to the normal definition outside of these fragments."
17767 (interactive "P")
17768 (if (org-inside-LaTeX-fragment-p)
17769 (call-interactively 'cdlatex-math-modify)
17770 (let (org-cdlatex-mode)
17771 (call-interactively (key-binding (vector last-input-event))))))
17775 ;;;; LaTeX fragments
17777 (defvar org-latex-regexps
17778 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17779 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17780 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17781 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17782 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17783 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17784 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17785 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17786 "Regular expressions for matching embedded LaTeX.")
17788 (defun org-inside-LaTeX-fragment-p ()
17789 "Test if point is inside a LaTeX fragment.
17790 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17791 sequence appearing also before point.
17792 Even though the matchers for math are configurable, this function assumes
17793 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17794 delimiters are skipped when they have been removed by customization.
17795 The return value is nil, or a cons cell with the delimiter and the
17796 position of this delimiter.
17798 This function does a reasonably good job, but can locally be fooled by
17799 for example currency specifications. For example it will assume being in
17800 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17801 fragments that are properly closed, but during editing, we have to live
17802 with the uncertainty caused by missing closing delimiters. This function
17803 looks only before point, not after."
17804 (catch 'exit
17805 (let ((pos (point))
17806 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17807 (lim (progn
17808 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17809 (point)))
17810 dd-on str (start 0) m re)
17811 (goto-char pos)
17812 (when dodollar
17813 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17814 re (nth 1 (assoc "$" org-latex-regexps)))
17815 (while (string-match re str start)
17816 (cond
17817 ((= (match-end 0) (length str))
17818 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17819 ((= (match-end 0) (- (length str) 5))
17820 (throw 'exit nil))
17821 (t (setq start (match-end 0))))))
17822 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17823 (goto-char pos)
17824 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17825 (and (match-beginning 2) (throw 'exit nil))
17826 ;; count $$
17827 (while (re-search-backward "\\$\\$" lim t)
17828 (setq dd-on (not dd-on)))
17829 (goto-char pos)
17830 (if dd-on (cons "$$" m))))))
17832 (defun org-inside-latex-macro-p ()
17833 "Is point inside a LaTeX macro or its arguments?"
17834 (save-match-data
17835 (org-in-regexp
17836 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17838 (defvar org-latex-fragment-image-overlays nil
17839 "List of overlays carrying the images of latex fragments.")
17840 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17842 (defun org-remove-latex-fragment-image-overlays ()
17843 "Remove all overlays with LaTeX fragment images in current buffer."
17844 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17845 (setq org-latex-fragment-image-overlays nil))
17847 (defun org-preview-latex-fragment (&optional subtree)
17848 "Preview the LaTeX fragment at point, or all locally or globally.
17849 If the cursor is in a LaTeX fragment, create the image and overlay
17850 it over the source code. If there is no fragment at point, display
17851 all fragments in the current text, from one headline to the next. With
17852 prefix SUBTREE, display all fragments in the current subtree. With a
17853 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17854 the cursor is before the first headline,
17855 display all fragments in the buffer.
17856 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17857 (interactive "P")
17858 (unless buffer-file-name
17859 (error "Can't preview LaTeX fragment in a non-file buffer"))
17860 (org-remove-latex-fragment-image-overlays)
17861 (save-excursion
17862 (save-restriction
17863 (let (beg end at msg)
17864 (cond
17865 ((or (equal subtree '(16))
17866 (not (save-excursion
17867 (re-search-backward org-outline-regexp-bol nil t))))
17868 (setq beg (point-min) end (point-max)
17869 msg "Creating images for buffer...%s"))
17870 ((equal subtree '(4))
17871 (org-back-to-heading)
17872 (setq beg (point) end (org-end-of-subtree t)
17873 msg "Creating images for subtree...%s"))
17875 (if (setq at (org-inside-LaTeX-fragment-p))
17876 (goto-char (max (point-min) (- (cdr at) 2)))
17877 (org-back-to-heading))
17878 (setq beg (point) end (progn (outline-next-heading) (point))
17879 msg (if at "Creating image...%s"
17880 "Creating images for entry...%s"))))
17881 (message msg "")
17882 (narrow-to-region beg end)
17883 (goto-char beg)
17884 (org-format-latex
17885 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17886 (file-name-nondirectory
17887 buffer-file-name)))
17888 default-directory 'overlays msg at 'forbuffer
17889 org-latex-create-formula-image-program)
17890 (message msg "done. Use `C-c C-c' to remove images.")))))
17892 (defun org-format-latex (prefix &optional dir overlays msg at
17893 forbuffer processing-type)
17894 "Replace LaTeX fragments with links to an image, and produce images.
17895 Some of the options can be changed using the variable
17896 `org-format-latex-options'."
17897 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17898 (let* ((prefixnodir (file-name-nondirectory prefix))
17899 (absprefix (expand-file-name prefix dir))
17900 (todir (file-name-directory absprefix))
17901 (opt org-format-latex-options)
17902 (optnew org-format-latex-options)
17903 (matchers (plist-get opt :matchers))
17904 (re-list org-latex-regexps)
17905 (cnt 0) txt hash link beg end re e checkdir
17906 string
17907 m n block-type block linkfile movefile ov)
17908 ;; Check the different regular expressions
17909 (while (setq e (pop re-list))
17910 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17911 block (if block-type "\n\n" ""))
17912 (when (member m matchers)
17913 (goto-char (point-min))
17914 (while (re-search-forward re nil t)
17915 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17916 (or (not overlays)
17917 (not (eq (get-char-property (match-beginning n)
17918 'org-overlay-type)
17919 'org-latex-overlay))))
17920 (cond
17921 ((eq processing-type 'verbatim))
17922 ((eq processing-type 'mathjax)
17923 ;; Prepare for MathJax processing.
17924 (setq string (match-string n))
17925 (when (member m '("$" "$1"))
17926 (save-excursion
17927 (delete-region (match-beginning n) (match-end n))
17928 (goto-char (match-beginning n))
17929 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17930 ((or (eq processing-type 'dvipng)
17931 (eq processing-type 'imagemagick))
17932 ;; Process to an image.
17933 (setq txt (match-string n)
17934 beg (match-beginning n) end (match-end n)
17935 cnt (1+ cnt))
17936 (let ((face (face-at-point))
17937 (fg (plist-get opt :foreground))
17938 (bg (plist-get opt :background))
17939 ;; Ensure full list is printed.
17940 print-length print-level)
17941 (when forbuffer
17942 ;; Get the colors from the face at point.
17943 (goto-char beg)
17944 (when (eq fg 'auto)
17945 (setq fg (face-attribute face :foreground nil 'default)))
17946 (when (eq bg 'auto)
17947 (setq bg (face-attribute face :background nil 'default)))
17948 (setq optnew (copy-sequence opt))
17949 (plist-put optnew :foreground fg)
17950 (plist-put optnew :background bg))
17951 (setq hash (sha1 (prin1-to-string
17952 (list org-format-latex-header
17953 org-latex-default-packages-alist
17954 org-latex-packages-alist
17955 org-format-latex-options
17956 forbuffer txt fg bg)))
17957 linkfile (format "%s_%s.png" prefix hash)
17958 movefile (format "%s_%s.png" absprefix hash)))
17959 (setq link (concat block "[[file:" linkfile "]]" block))
17960 (if msg (message msg cnt))
17961 (goto-char beg)
17962 (unless checkdir ; Ensure the directory exists.
17963 (setq checkdir t)
17964 (or (file-directory-p todir) (make-directory todir t)))
17965 (unless (file-exists-p movefile)
17966 (org-create-formula-image
17967 txt movefile optnew forbuffer processing-type))
17968 (if overlays
17969 (progn
17970 (mapc (lambda (o)
17971 (if (eq (overlay-get o 'org-overlay-type)
17972 'org-latex-overlay)
17973 (delete-overlay o)))
17974 (overlays-in beg end))
17975 (setq ov (make-overlay beg end))
17976 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17977 (if (featurep 'xemacs)
17978 (progn
17979 (overlay-put ov 'invisible t)
17980 (overlay-put
17981 ov 'end-glyph
17982 (make-glyph (vector 'png :file movefile))))
17983 (overlay-put
17984 ov 'display
17985 (list 'image :type 'png :file movefile :ascent 'center)))
17986 (push ov org-latex-fragment-image-overlays)
17987 (goto-char end))
17988 (delete-region beg end)
17989 (insert (org-add-props link
17990 (list 'org-latex-src
17991 (replace-regexp-in-string
17992 "\"" "" txt)
17993 'org-latex-src-embed-type
17994 (if block-type 'paragraph 'character))))))
17995 ((eq processing-type 'mathml)
17996 ;; Process to MathML
17997 (unless (save-match-data (org-format-latex-mathml-available-p))
17998 (error "LaTeX to MathML converter not configured"))
17999 (setq txt (match-string n)
18000 beg (match-beginning n) end (match-end n)
18001 cnt (1+ cnt))
18002 (if msg (message msg cnt))
18003 (goto-char beg)
18004 (delete-region beg end)
18005 (insert (org-format-latex-as-mathml
18006 txt block-type prefix dir)))
18008 (error "Unknown conversion type %s for latex fragments"
18009 processing-type)))))))))
18011 (defun org-create-math-formula (latex-frag &optional mathml-file)
18012 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18013 Use `org-latex-to-mathml-convert-command'. If the conversion is
18014 sucessful, return the portion between \"<math...> </math>\"
18015 elements otherwise return nil. When MATHML-FILE is specified,
18016 write the results in to that file. When invoked as an
18017 interactive command, prompt for LATEX-FRAG, with initial value
18018 set to the current active region and echo the results for user
18019 inspection."
18020 (interactive (list (let ((frag (when (org-region-active-p)
18021 (buffer-substring-no-properties
18022 (region-beginning) (region-end)))))
18023 (read-string "LaTeX Fragment: " frag nil frag))))
18024 (unless latex-frag (error "Invalid latex-frag"))
18025 (let* ((tmp-in-file (file-relative-name
18026 (make-temp-name (expand-file-name "ltxmathml-in"))))
18027 (ignore (write-region latex-frag nil tmp-in-file))
18028 (tmp-out-file (file-relative-name
18029 (make-temp-name (expand-file-name "ltxmathml-out"))))
18030 (cmd (format-spec
18031 org-latex-to-mathml-convert-command
18032 `((?j . ,(shell-quote-argument
18033 (expand-file-name org-latex-to-mathml-jar-file)))
18034 (?I . ,(shell-quote-argument tmp-in-file))
18035 (?o . ,(shell-quote-argument tmp-out-file)))))
18036 mathml shell-command-output)
18037 (when (org-called-interactively-p 'any)
18038 (unless (org-format-latex-mathml-available-p)
18039 (error "LaTeX to MathML converter not configured")))
18040 (message "Running %s" cmd)
18041 (setq shell-command-output (shell-command-to-string cmd))
18042 (setq mathml
18043 (when (file-readable-p tmp-out-file)
18044 (with-current-buffer (find-file-noselect tmp-out-file t)
18045 (goto-char (point-min))
18046 (when (re-search-forward
18047 (concat
18048 (regexp-quote
18049 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18050 "\\(.\\|\n\\)*"
18051 (regexp-quote "</math>")) nil t)
18052 (prog1 (match-string 0) (kill-buffer))))))
18053 (cond
18054 (mathml
18055 (setq mathml
18056 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18057 (when mathml-file
18058 (write-region mathml nil mathml-file))
18059 (when (org-called-interactively-p 'any)
18060 (message mathml)))
18061 ((message "LaTeX to MathML conversion failed")
18062 (message shell-command-output)))
18063 (delete-file tmp-in-file)
18064 (when (file-exists-p tmp-out-file)
18065 (delete-file tmp-out-file))
18066 mathml))
18068 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18069 prefix &optional dir)
18070 "Use `org-create-math-formula' but check local cache first."
18071 (let* ((absprefix (expand-file-name prefix dir))
18072 (print-length nil) (print-level nil)
18073 (formula-id (concat
18074 "formula-"
18075 (sha1
18076 (prin1-to-string
18077 (list latex-frag
18078 org-latex-to-mathml-convert-command)))))
18079 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18080 (formula-cache-dir (file-name-directory formula-cache)))
18082 (unless (file-directory-p formula-cache-dir)
18083 (make-directory formula-cache-dir t))
18085 (unless (file-exists-p formula-cache)
18086 (org-create-math-formula latex-frag formula-cache))
18088 (if (file-exists-p formula-cache)
18089 ;; Successful conversion. Return the link to MathML file.
18090 (org-add-props
18091 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18092 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18093 'org-latex-src-embed-type (if latex-frag-type
18094 'paragraph 'character)))
18095 ;; Failed conversion. Return the LaTeX fragment verbatim
18096 latex-frag)))
18098 (defun org-create-formula-image (string tofile options buffer &optional type)
18099 "Create an image from LaTeX source using dvipng or convert.
18100 This function calls either `org-create-formula-image-with-dvipng'
18101 or `org-create-formula-image-with-imagemagick' depending on the
18102 value of `org-latex-create-formula-image-program' or on the value
18103 of the optional TYPE variable.
18105 Note: ultimately these two function should be combined as they
18106 share a good deal of logic."
18107 (org-check-external-command
18108 "latex" "needed to convert LaTeX fragments to images")
18109 (funcall
18110 (case (or type org-latex-create-formula-image-program)
18111 ('dvipng
18112 (org-check-external-command
18113 "dvipng" "needed to convert LaTeX fragments to images")
18114 #'org-create-formula-image-with-dvipng)
18115 ('imagemagick
18116 (org-check-external-command
18117 "convert" "you need to install imagemagick")
18118 #'org-create-formula-image-with-imagemagick)
18119 (t (error
18120 "invalid value of `org-latex-create-formula-image-program'")))
18121 string tofile options buffer))
18123 (declare-function org-export--get-global-options "ox" (&optional backend))
18124 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18125 (defun org-create-formula--latex-header ()
18126 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18127 (org-latex-guess-inputenc
18128 (org-splice-latex-header
18129 org-format-latex-header
18130 org-latex-default-packages-alist
18131 org-latex-packages-alist t
18132 (plist-get
18133 (org-combine-plists
18134 (org-export--get-global-options 'latex)
18135 (org-export--get-inbuffer-options 'latex))
18136 :latex-header-extra))))
18138 ;; This function borrows from Ganesh Swami's latex2png.el
18139 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18140 "This calls dvipng."
18141 (require 'ox-latex)
18142 (let* ((tmpdir (if (featurep 'xemacs)
18143 (temp-directory)
18144 temporary-file-directory))
18145 (texfilebase (make-temp-name
18146 (expand-file-name "orgtex" tmpdir)))
18147 (texfile (concat texfilebase ".tex"))
18148 (dvifile (concat texfilebase ".dvi"))
18149 (pngfile (concat texfilebase ".png"))
18150 (fnh (if (featurep 'xemacs)
18151 (font-height (face-font 'default))
18152 (face-attribute 'default :height nil)))
18153 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18154 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18155 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18156 "Black"))
18157 (bg (or (plist-get options (if buffer :background :html-background))
18158 "Transparent")))
18159 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18160 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18161 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18162 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18163 (let ((latex-header (org-create-formula--latex-header)))
18164 (with-temp-file texfile
18165 (insert latex-header)
18166 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18167 (let ((dir default-directory))
18168 (condition-case nil
18169 (progn
18170 (cd tmpdir)
18171 (call-process "latex" nil nil nil texfile))
18172 (error nil))
18173 (cd dir))
18174 (if (not (file-exists-p dvifile))
18175 (progn (message "Failed to create dvi file from %s" texfile) nil)
18176 (condition-case nil
18177 (if (featurep 'xemacs)
18178 (call-process "dvipng" nil nil nil
18179 "-fg" fg "-bg" bg
18180 "-T" "tight"
18181 "-o" pngfile
18182 dvifile)
18183 (call-process "dvipng" nil nil nil
18184 "-fg" fg "-bg" bg
18185 "-D" dpi
18186 ;;"-x" scale "-y" scale
18187 "-T" "tight"
18188 "-o" pngfile
18189 dvifile))
18190 (error nil))
18191 (if (not (file-exists-p pngfile))
18192 (if org-format-latex-signal-error
18193 (error "Failed to create png file from %s" texfile)
18194 (message "Failed to create png file from %s" texfile)
18195 nil)
18196 ;; Use the requested file name and clean up
18197 (copy-file pngfile tofile 'replace)
18198 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18199 (if (file-exists-p (concat texfilebase e))
18200 (delete-file (concat texfilebase e))))
18201 pngfile))))
18203 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18204 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18205 "This calls convert, which is included into imagemagick."
18206 (require 'ox-latex)
18207 (let* ((tmpdir (if (featurep 'xemacs)
18208 (temp-directory)
18209 temporary-file-directory))
18210 (texfilebase (make-temp-name
18211 (expand-file-name "orgtex" tmpdir)))
18212 (texfile (concat texfilebase ".tex"))
18213 (pdffile (concat texfilebase ".pdf"))
18214 (pngfile (concat texfilebase ".png"))
18215 (fnh (if (featurep 'xemacs)
18216 (font-height (face-font 'default))
18217 (face-attribute 'default :height nil)))
18218 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18219 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18220 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18221 "black"))
18222 (bg (or (plist-get options (if buffer :background :html-background))
18223 "white")))
18224 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18225 (setq fg (org-latex-color-format fg)))
18226 (if (eq bg 'default) (setq bg (org-latex-color :background))
18227 (setq bg (org-latex-color-format
18228 (if (string= bg "Transparent") "white" bg))))
18229 (let ((latex-header (org-create-formula--latex-header)))
18230 (with-temp-file texfile
18231 (insert latex-header)
18232 (insert "\n\\begin{document}\n"
18233 "\\definecolor{fg}{rgb}{" fg "}\n"
18234 "\\definecolor{bg}{rgb}{" bg "}\n"
18235 "\n\\pagecolor{bg}\n"
18236 "\n{\\color{fg}\n"
18237 string
18238 "\n}\n"
18239 "\n\\end{document}\n")))
18240 (org-latex-compile texfile t)
18241 (if (not (file-exists-p pdffile))
18242 (progn (message "Failed to create pdf file from %s" texfile) nil)
18243 (condition-case nil
18244 (if (featurep 'xemacs)
18245 (call-process "convert" nil nil nil
18246 "-density" "96"
18247 "-trim"
18248 "-antialias"
18249 pdffile
18250 "-quality" "100"
18251 ;; "-sharpen" "0x1.0"
18252 pngfile)
18253 (call-process "convert" nil nil nil
18254 "-density" dpi
18255 "-trim"
18256 "-antialias"
18257 pdffile
18258 "-quality" "100"
18259 ;; "-sharpen" "0x1.0"
18260 pngfile))
18261 (error nil))
18262 (if (not (file-exists-p pngfile))
18263 (if org-format-latex-signal-error
18264 (error "Failed to create png file from %s" texfile)
18265 (message "Failed to create png file from %s" texfile)
18266 nil)
18267 ;; Use the requested file name and clean up
18268 (copy-file pngfile tofile 'replace)
18269 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18270 (if (file-exists-p (concat texfilebase e))
18271 (delete-file (concat texfilebase e))))
18272 pngfile))))
18274 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18275 "Fill a LaTeX header template TPL.
18276 In the template, the following place holders will be recognized:
18278 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18279 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18280 [PACKAGES] \\usepackage statements for PKG
18281 [NO-PACKAGES] do not include PKG
18282 [EXTRA] the string EXTRA
18283 [NO-EXTRA] do not include EXTRA
18285 For backward compatibility, if both the positive and the negative place
18286 holder is missing, the positive one (without the \"NO-\") will be
18287 assumed to be present at the end of the template.
18288 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18289 EXTRA is a string.
18290 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18291 (let (rpl (end ""))
18292 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18293 (setq rpl (if (or (match-end 1) (not def-pkg))
18294 "" (org-latex-packages-to-string def-pkg snippets-p t))
18295 tpl (replace-match rpl t t tpl))
18296 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18298 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18299 (setq rpl (if (or (match-end 1) (not pkg))
18300 "" (org-latex-packages-to-string pkg snippets-p t))
18301 tpl (replace-match rpl t t tpl))
18302 (if pkg (setq end
18303 (concat end "\n"
18304 (org-latex-packages-to-string pkg snippets-p)))))
18306 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18307 (setq rpl (if (or (match-end 1) (not extra))
18308 "" (concat extra "\n"))
18309 tpl (replace-match rpl t t tpl))
18310 (if (and extra (string-match "\\S-" extra))
18311 (setq end (concat end "\n" extra))))
18313 (if (string-match "\\S-" end)
18314 (concat tpl "\n" end)
18315 tpl)))
18317 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18318 "Turn an alist of packages into a string with the \\usepackage macros."
18319 (setq pkg (mapconcat (lambda(p)
18320 (cond
18321 ((stringp p) p)
18322 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18323 (format "%% Package %s omitted" (cadr p)))
18324 ((equal "" (car p))
18325 (format "\\usepackage{%s}" (cadr p)))
18327 (format "\\usepackage[%s]{%s}"
18328 (car p) (cadr p)))))
18330 "\n"))
18331 (if newline (concat pkg "\n") pkg))
18333 (defun org-dvipng-color (attr)
18334 "Return a RGB color specification for dvipng."
18335 (apply 'format "rgb %s %s %s"
18336 (mapcar 'org-normalize-color
18337 (if (featurep 'xemacs)
18338 (color-rgb-components
18339 (face-property 'default
18340 (cond ((eq attr :foreground) 'foreground)
18341 ((eq attr :background) 'background))))
18342 (color-values (face-attribute 'default attr nil))))))
18344 (defun org-dvipng-color-format (color-name)
18345 "Convert COLOR-NAME to a RGB color value for dvipng."
18346 (apply 'format "rgb %s %s %s"
18347 (mapcar 'org-normalize-color
18348 (color-values color-name))))
18350 (defun org-latex-color (attr)
18351 "Return a RGB color for the LaTeX color package."
18352 (apply 'format "%s,%s,%s"
18353 (mapcar 'org-normalize-color
18354 (if (featurep 'xemacs)
18355 (color-rgb-components
18356 (face-property 'default
18357 (cond ((eq attr :foreground) 'foreground)
18358 ((eq attr :background) 'background))))
18359 (color-values (face-attribute 'default attr nil))))))
18361 (defun org-latex-color-format (color-name)
18362 "Convert COLOR-NAME to a RGB color value."
18363 (apply 'format "%s,%s,%s"
18364 (mapcar 'org-normalize-color
18365 (color-values color-name))))
18367 (defun org-normalize-color (value)
18368 "Return string to be used as color value for an RGB component."
18369 (format "%g" (/ value 65535.0)))
18373 ;; Image display
18375 (defvar org-inline-image-overlays nil)
18376 (make-variable-buffer-local 'org-inline-image-overlays)
18378 (defun org-toggle-inline-images (&optional include-linked)
18379 "Toggle the display of inline images.
18380 INCLUDE-LINKED is passed to `org-display-inline-images'."
18381 (interactive "P")
18382 (if org-inline-image-overlays
18383 (progn
18384 (org-remove-inline-images)
18385 (message "Inline image display turned off"))
18386 (org-display-inline-images include-linked)
18387 (if (and (org-called-interactively-p)
18388 org-inline-image-overlays)
18389 (message "%d images displayed inline"
18390 (length org-inline-image-overlays))
18391 (message "No images to display inline"))))
18393 (defun org-redisplay-inline-images ()
18394 "Refresh the display of inline images."
18395 (interactive)
18396 (if (not org-inline-image-overlays)
18397 (org-toggle-inline-images)
18398 (org-toggle-inline-images)
18399 (org-toggle-inline-images)))
18401 (defun org-display-inline-images (&optional include-linked refresh beg end)
18402 "Display inline images.
18403 Normally only links without a description part are inlined, because this
18404 is how it will work for export. When INCLUDE-LINKED is set, also links
18405 with a description part will be inlined. This can be nice for a quick
18406 look at those images, but it does not reflect what exported files will look
18407 like.
18408 When REFRESH is set, refresh existing images between BEG and END.
18409 This will create new image displays only if necessary.
18410 BEG and END default to the buffer boundaries."
18411 (interactive "P")
18412 (unless refresh
18413 (org-remove-inline-images)
18414 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18415 (save-excursion
18416 (save-restriction
18417 (widen)
18418 (setq beg (or beg (point-min)) end (or end (point-max)))
18419 (goto-char beg)
18420 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18421 (substring (org-image-file-name-regexp) 0 -2)
18422 "\\)\\]" (if include-linked "" "\\]")))
18423 old file ov img type attrwidth width)
18424 (while (re-search-forward re end t)
18425 (setq old (get-char-property-and-overlay (match-beginning 1)
18426 'org-image-overlay)
18427 file (expand-file-name
18428 (concat (or (match-string 3) "") (match-string 4))))
18429 (when (image-type-available-p 'imagemagick)
18430 (setq attrwidth (if (or (listp org-image-actual-width)
18431 (null org-image-actual-width))
18432 (save-excursion
18433 (save-match-data
18434 (when (re-search-backward
18435 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18436 (save-excursion
18437 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18438 (string-to-number (match-string 1))))))
18439 width (cond ((eq org-image-actual-width t) nil)
18440 ((null org-image-actual-width) attrwidth)
18441 ((numberp org-image-actual-width)
18442 org-image-actual-width)
18443 ((listp org-image-actual-width)
18444 (or attrwidth (car org-image-actual-width))))
18445 type (if width 'imagemagick)))
18446 (when (file-exists-p file)
18447 (if (and (car-safe old) refresh)
18448 (image-refresh (overlay-get (cdr old) 'display))
18449 (setq img (save-match-data (create-image file type nil :width width)))
18450 (when img
18451 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18452 (overlay-put ov 'display img)
18453 (overlay-put ov 'face 'default)
18454 (overlay-put ov 'org-image-overlay t)
18455 (overlay-put ov 'modification-hooks
18456 (list 'org-display-inline-remove-overlay))
18457 (push ov org-inline-image-overlays)))))))))
18459 (define-obsolete-function-alias
18460 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18462 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18463 "Remove inline-display overlay if a corresponding region is modified."
18464 (let ((inhibit-modification-hooks t))
18465 (when (and ov after)
18466 (delete ov org-inline-image-overlays)
18467 (delete-overlay ov))))
18469 (defun org-remove-inline-images ()
18470 "Remove inline display of images."
18471 (interactive)
18472 (mapc 'delete-overlay org-inline-image-overlays)
18473 (setq org-inline-image-overlays nil))
18475 ;;;; Key bindings
18477 ;; Outline functions from `outline-mode-prefix-map'
18478 ;; that can be remapped in Org:
18479 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18480 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18481 (define-key org-mode-map [remap outline-forward-same-level]
18482 'org-forward-heading-same-level)
18483 (define-key org-mode-map [remap outline-backward-same-level]
18484 'org-backward-heading-same-level)
18485 (define-key org-mode-map [remap show-branches]
18486 'org-kill-note-or-show-branches)
18487 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18488 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18489 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18491 ;; Outline functions from `outline-mode-prefix-map' that can not
18492 ;; be remapped in Org:
18494 ;; - the column "key binding" shows whether the Outline function is still
18495 ;; available in Org mode on the same key that it has been bound to in
18496 ;; Outline mode:
18497 ;; - "overridden": key used for a different functionality in Org mode
18498 ;; - else: key still bound to the same Outline function in Org mode
18500 ;; | Outline function | key binding | Org replacement |
18501 ;; |------------------------------------+-------------+-----------------------|
18502 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18503 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18504 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18505 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18506 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18507 ;; | `show-entry' | overridden | no replacement |
18508 ;; | `show-children' | `C-c C-i' | visibility cycling |
18509 ;; | `show-branches' | `C-c C-k' | still same function |
18510 ;; | `show-subtree' | overridden | visibility cycling |
18511 ;; | `show-all' | overridden | no replacement |
18512 ;; | `hide-subtree' | overridden | visibility cycling |
18513 ;; | `hide-body' | overridden | no replacement |
18514 ;; | `hide-entry' | overridden | visibility cycling |
18515 ;; | `hide-leaves' | overridden | no replacement |
18516 ;; | `hide-sublevels' | overridden | no replacement |
18517 ;; | `hide-other' | overridden | no replacement |
18519 ;; Make `C-c C-x' a prefix key
18520 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18522 ;; TAB key with modifiers
18523 (org-defkey org-mode-map "\C-i" 'org-cycle)
18524 (org-defkey org-mode-map [(tab)] 'org-cycle)
18525 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18526 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18527 ;; The following line is necessary under Suse GNU/Linux
18528 (unless (featurep 'xemacs)
18529 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18530 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18531 (define-key org-mode-map [backtab] 'org-shifttab)
18533 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18534 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18535 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18537 ;; Cursor keys with modifiers
18538 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18539 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18540 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18541 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18543 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18544 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18545 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18546 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18548 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18549 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18550 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18551 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18553 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18554 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18555 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18556 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18558 ;; Babel keys
18559 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18560 (mapc (lambda (pair)
18561 (define-key org-babel-map (car pair) (cdr pair)))
18562 org-babel-key-bindings)
18564 ;;; Extra keys for tty access.
18565 ;; We only set them when really needed because otherwise the
18566 ;; menus don't show the simple keys
18568 (when (or org-use-extra-keys
18569 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18570 (not window-system))
18571 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18572 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18573 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18574 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18575 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18576 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18577 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18578 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18579 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18580 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18581 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18582 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18583 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18584 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18585 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18586 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18587 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18588 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18589 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18590 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18591 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18592 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18593 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18594 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18595 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18596 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18597 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18598 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18600 ;; All the other keys
18602 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18603 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18604 (if (boundp 'narrow-map)
18605 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18606 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18607 (if (boundp 'narrow-map)
18608 (org-defkey narrow-map "b" 'org-narrow-to-block)
18609 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18610 (if (boundp 'narrow-map)
18611 (org-defkey narrow-map "e" 'org-narrow-to-element)
18612 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18613 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18614 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18615 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18616 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18617 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18618 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18619 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18620 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18621 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18622 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18623 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18624 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18625 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18626 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18627 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18628 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18629 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18630 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18631 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18632 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18633 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18634 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18635 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18636 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18637 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18638 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18639 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18640 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18641 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18642 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18643 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18644 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18645 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18646 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18647 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18648 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18649 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18650 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18651 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18652 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18653 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18654 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18655 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18656 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18657 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18658 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18659 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18660 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18661 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18662 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18663 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18664 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18665 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18666 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18667 (org-defkey org-mode-map "\C-c^" 'org-sort)
18668 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18669 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18670 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18671 (org-defkey org-mode-map "\C-m" 'org-return)
18672 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18673 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18674 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18675 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18676 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18677 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18678 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18679 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18680 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18681 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18682 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18683 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18684 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18685 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18686 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18687 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18688 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18689 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18690 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18691 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18692 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18693 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18694 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18696 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18697 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18698 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18700 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18701 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18702 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18703 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18704 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18705 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18706 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18707 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18708 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18709 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18710 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18711 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18712 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18713 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18714 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18715 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18716 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18717 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18718 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18719 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18720 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18721 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18722 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18724 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18725 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18726 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18727 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18728 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18730 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18732 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18734 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18735 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18737 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18740 (when (featurep 'xemacs)
18741 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18744 (defconst org-speed-commands-default
18746 ("Outline Navigation")
18747 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18748 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18749 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18750 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18751 ("F" . org-next-block)
18752 ("B" . org-previous-block)
18753 ("u" . (org-speed-move-safe 'outline-up-heading))
18754 ("j" . org-goto)
18755 ("g" . (org-refile t))
18756 ("Outline Visibility")
18757 ("c" . org-cycle)
18758 ("C" . org-shifttab)
18759 (" " . org-display-outline-path)
18760 ("=" . org-columns)
18761 ("Outline Structure Editing")
18762 ("U" . org-shiftmetaup)
18763 ("D" . org-shiftmetadown)
18764 ("r" . org-metaright)
18765 ("l" . org-metaleft)
18766 ("R" . org-shiftmetaright)
18767 ("L" . org-shiftmetaleft)
18768 ("i" . (progn (forward-char 1) (call-interactively
18769 'org-insert-heading-respect-content)))
18770 ("^" . org-sort)
18771 ("w" . org-refile)
18772 ("a" . org-archive-subtree-default-with-confirmation)
18773 ("@" . org-mark-subtree)
18774 ("#" . org-toggle-comment)
18775 ("Clock Commands")
18776 ("I" . org-clock-in)
18777 ("O" . org-clock-out)
18778 ("Meta Data Editing")
18779 ("t" . org-todo)
18780 ("," . (org-priority))
18781 ("0" . (org-priority ?\ ))
18782 ("1" . (org-priority ?A))
18783 ("2" . (org-priority ?B))
18784 ("3" . (org-priority ?C))
18785 (":" . org-set-tags-command)
18786 ("e" . org-set-effort)
18787 ("E" . org-inc-effort)
18788 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18789 (org-entry-put (point) "APPT_WARNTIME" m)))
18790 ("Agenda Views etc")
18791 ("v" . org-agenda)
18792 ("/" . org-sparse-tree)
18793 ("Misc")
18794 ("o" . org-open-at-point)
18795 ("?" . org-speed-command-help)
18796 ("<" . (org-agenda-set-restriction-lock 'subtree))
18797 (">" . (org-agenda-remove-restriction-lock))
18799 "The default speed commands.")
18801 (defun org-print-speed-command (e)
18802 (if (> (length (car e)) 1)
18803 (progn
18804 (princ "\n")
18805 (princ (car e))
18806 (princ "\n")
18807 (princ (make-string (length (car e)) ?-))
18808 (princ "\n"))
18809 (princ (car e))
18810 (princ " ")
18811 (if (symbolp (cdr e))
18812 (princ (symbol-name (cdr e)))
18813 (prin1 (cdr e)))
18814 (princ "\n")))
18816 (defun org-speed-command-help ()
18817 "Show the available speed commands."
18818 (interactive)
18819 (if (not org-use-speed-commands)
18820 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18821 (with-output-to-temp-buffer "*Help*"
18822 (princ "User-defined Speed commands\n===========================\n")
18823 (mapc 'org-print-speed-command org-speed-commands-user)
18824 (princ "\n")
18825 (princ "Built-in Speed commands\n=======================\n")
18826 (mapc 'org-print-speed-command org-speed-commands-default))
18827 (with-current-buffer "*Help*"
18828 (setq truncate-lines t))))
18830 (defun org-speed-move-safe (cmd)
18831 "Execute CMD, but make sure that the cursor always ends up in a headline.
18832 If not, return to the original position and throw an error."
18833 (interactive)
18834 (let ((pos (point)))
18835 (call-interactively cmd)
18836 (unless (and (bolp) (org-at-heading-p))
18837 (goto-char pos)
18838 (error "Boundary reached while executing %s" cmd))))
18840 (defvar org-self-insert-command-undo-counter 0)
18842 (defvar org-table-auto-blank-field) ; defined in org-table.el
18843 (defvar org-speed-command nil)
18845 (define-obsolete-function-alias
18846 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18848 (defun org-speed-command-activate (keys)
18849 "Hook for activating single-letter speed commands.
18850 `org-speed-commands-default' specifies a minimal command set.
18851 Use `org-speed-commands-user' for further customization."
18852 (when (or (and (bolp) (looking-at org-outline-regexp))
18853 (and (functionp org-use-speed-commands)
18854 (funcall org-use-speed-commands)))
18855 (cdr (assoc keys (append org-speed-commands-user
18856 org-speed-commands-default)))))
18858 (define-obsolete-function-alias
18859 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18861 (defun org-babel-speed-command-activate (keys)
18862 "Hook for activating single-letter code block commands."
18863 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18864 (cdr (assoc keys org-babel-key-bindings))))
18866 (defcustom org-speed-command-hook
18867 '(org-speed-command-default-hook org-babel-speed-command-hook)
18868 "Hook for activating speed commands at strategic locations.
18869 Hook functions are called in sequence until a valid handler is
18870 found.
18872 Each hook takes a single argument, a user-pressed command key
18873 which is also a `self-insert-command' from the global map.
18875 Within the hook, examine the cursor position and the command key
18876 and return nil or a valid handler as appropriate. Handler could
18877 be one of an interactive command, a function, or a form.
18879 Set `org-use-speed-commands' to non-nil value to enable this
18880 hook. The default setting is `org-speed-command-activate'."
18881 :group 'org-structure
18882 :version "24.1"
18883 :type 'hook)
18885 (defun org-self-insert-command (N)
18886 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18887 If the cursor is in a table looking at whitespace, the whitespace is
18888 overwritten, and the table is not marked as requiring realignment."
18889 (interactive "p")
18890 (org-check-before-invisible-edit 'insert)
18891 (cond
18892 ((and org-use-speed-commands
18893 (setq org-speed-command
18894 (run-hook-with-args-until-success
18895 'org-speed-command-hook (this-command-keys))))
18896 (cond
18897 ((commandp org-speed-command)
18898 (setq this-command org-speed-command)
18899 (call-interactively org-speed-command))
18900 ((functionp org-speed-command)
18901 (funcall org-speed-command))
18902 ((and org-speed-command (listp org-speed-command))
18903 (eval org-speed-command))
18904 (t (let (org-use-speed-commands)
18905 (call-interactively 'org-self-insert-command)))))
18906 ((and
18907 (org-table-p)
18908 (progn
18909 ;; check if we blank the field, and if that triggers align
18910 (and (featurep 'org-table) org-table-auto-blank-field
18911 (member last-command
18912 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18913 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18914 ;; got extra space, this field does not determine column width
18915 (let (org-table-may-need-update) (org-table-blank-field))
18916 ;; no extra space, this field may determine column width
18917 (org-table-blank-field)))
18919 (eq N 1)
18920 (looking-at "[^|\n]* |"))
18921 (let (org-table-may-need-update)
18922 (goto-char (1- (match-end 0)))
18923 (backward-delete-char 1)
18924 (goto-char (match-beginning 0))
18925 (self-insert-command N)))
18927 (setq org-table-may-need-update t)
18928 (self-insert-command N)
18929 (org-fix-tags-on-the-fly)
18930 (if org-self-insert-cluster-for-undo
18931 (if (not (eq last-command 'org-self-insert-command))
18932 (setq org-self-insert-command-undo-counter 1)
18933 (if (>= org-self-insert-command-undo-counter 20)
18934 (setq org-self-insert-command-undo-counter 1)
18935 (and (> org-self-insert-command-undo-counter 0)
18936 buffer-undo-list (listp buffer-undo-list)
18937 (not (cadr buffer-undo-list)) ; remove nil entry
18938 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18939 (setq org-self-insert-command-undo-counter
18940 (1+ org-self-insert-command-undo-counter))))))))
18942 (defun org-check-before-invisible-edit (kind)
18943 "Check is editing if kind KIND would be dangerous with invisible text around.
18944 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18945 ;; First, try to get out of here as quickly as possible, to reduce overhead
18946 (if (and org-catch-invisible-edits
18947 (or (not (boundp 'visible-mode)) (not visible-mode))
18948 (or (get-char-property (point) 'invisible)
18949 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18950 ;; OK, we need to take a closer look
18951 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18952 (invisible-before-point (if (bobp) nil (get-char-property
18953 (1- (point)) 'invisible)))
18954 (border-and-ok-direction
18956 ;; Check if we are acting predictably before invisible text
18957 (and invisible-at-point (not invisible-before-point)
18958 (memq kind '(insert delete-backward)))
18959 ;; Check if we are acting predictably after invisible text
18960 ;; This works not well, and I have turned it off. It seems
18961 ;; better to always show and stop after invisible text.
18962 ;; (and (not invisible-at-point) invisible-before-point
18963 ;; (memq kind '(insert delete)))
18965 (when (or (memq invisible-at-point '(outline org-hide-block t))
18966 (memq invisible-before-point '(outline org-hide-block t)))
18967 (if (eq org-catch-invisible-edits 'error)
18968 (error "Editing in invisible areas is prohibited - make visible first"))
18969 (if (and org-custom-properties-overlays
18970 (y-or-n-p "Display invisible properties in this buffer? "))
18971 (org-toggle-custom-properties-visibility)
18972 ;; Make the area visible
18973 (save-excursion
18974 (if invisible-before-point
18975 (goto-char (previous-single-char-property-change
18976 (point) 'invisible)))
18977 (org-cycle))
18978 (cond
18979 ((eq org-catch-invisible-edits 'show)
18980 ;; That's it, we do the edit after showing
18981 (message
18982 "Unfolding invisible region around point before editing")
18983 (sit-for 1))
18984 ((and (eq org-catch-invisible-edits 'smart)
18985 border-and-ok-direction)
18986 (message "Unfolding invisible region around point before editing"))
18988 ;; Don't do the edit, make the user repeat it in full visibility
18989 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18991 (defun org-fix-tags-on-the-fly ()
18992 (when (and (equal (char-after (point-at-bol)) ?*)
18993 (org-at-heading-p))
18994 (org-align-tags-here org-tags-column)))
18996 (defun org-delete-backward-char (N)
18997 "Like `delete-backward-char', insert whitespace at field end in tables.
18998 When deleting backwards, in tables this function will insert whitespace in
18999 front of the next \"|\" separator, to keep the table aligned. The table will
19000 still be marked for re-alignment if the field did fill the entire column,
19001 because, in this case the deletion might narrow the column."
19002 (interactive "p")
19003 (save-match-data
19004 (org-check-before-invisible-edit 'delete-backward)
19005 (if (and (org-table-p)
19006 (eq N 1)
19007 (string-match "|" (buffer-substring (point-at-bol) (point)))
19008 (looking-at ".*?|"))
19009 (let ((pos (point))
19010 (noalign (looking-at "[^|\n\r]* |"))
19011 (c org-table-may-need-update))
19012 (backward-delete-char N)
19013 (if (not overwrite-mode)
19014 (progn
19015 (skip-chars-forward "^|")
19016 (insert " ")
19017 (goto-char (1- pos))))
19018 ;; noalign: if there were two spaces at the end, this field
19019 ;; does not determine the width of the column.
19020 (if noalign (setq org-table-may-need-update c)))
19021 (backward-delete-char N)
19022 (org-fix-tags-on-the-fly))))
19024 (defun org-delete-char (N)
19025 "Like `delete-char', but insert whitespace at field end in tables.
19026 When deleting characters, in tables this function will insert whitespace in
19027 front of the next \"|\" separator, to keep the table aligned. The table will
19028 still be marked for re-alignment if the field did fill the entire column,
19029 because, in this case the deletion might narrow the column."
19030 (interactive "p")
19031 (save-match-data
19032 (org-check-before-invisible-edit 'delete)
19033 (if (and (org-table-p)
19034 (not (bolp))
19035 (not (= (char-after) ?|))
19036 (eq N 1))
19037 (if (looking-at ".*?|")
19038 (let ((pos (point))
19039 (noalign (looking-at "[^|\n\r]* |"))
19040 (c org-table-may-need-update))
19041 (replace-match (concat
19042 (substring (match-string 0) 1 -1)
19043 " |"))
19044 (goto-char pos)
19045 ;; noalign: if there were two spaces at the end, this field
19046 ;; does not determine the width of the column.
19047 (if noalign (setq org-table-may-need-update c)))
19048 (delete-char N))
19049 (delete-char N)
19050 (org-fix-tags-on-the-fly))))
19052 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19053 (put 'org-self-insert-command 'delete-selection t)
19054 (put 'orgtbl-self-insert-command 'delete-selection t)
19055 (put 'org-delete-char 'delete-selection 'supersede)
19056 (put 'org-delete-backward-char 'delete-selection 'supersede)
19057 (put 'org-yank 'delete-selection 'yank)
19059 ;; Make `flyspell-mode' delay after some commands
19060 (put 'org-self-insert-command 'flyspell-delayed t)
19061 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19062 (put 'org-delete-char 'flyspell-delayed t)
19063 (put 'org-delete-backward-char 'flyspell-delayed t)
19065 ;; Make pabbrev-mode expand after org-mode commands
19066 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19067 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19069 ;; How to do this: Measure non-white length of current string
19070 ;; If equal to column width, we should realign.
19072 (defun org-remap (map &rest commands)
19073 "In MAP, remap the functions given in COMMANDS.
19074 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19075 (let (new old)
19076 (while commands
19077 (setq old (pop commands) new (pop commands))
19078 (if (fboundp 'command-remapping)
19079 (org-defkey map (vector 'remap old) new)
19080 (substitute-key-definition old new map global-map)))))
19082 (defun org-transpose-words ()
19083 "Transpose words for Org.
19084 This uses the `org-mode-transpose-word-syntax-table' syntax
19085 table, which interprets characters in `org-emphasis-alist' as
19086 word constituants."
19087 (interactive)
19088 (with-syntax-table org-mode-transpose-word-syntax-table
19089 (call-interactively 'transpose-words)))
19090 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19092 (when (eq org-enable-table-editor 'optimized)
19093 ;; If the user wants maximum table support, we need to hijack
19094 ;; some standard editing functions
19095 (org-remap org-mode-map
19096 'self-insert-command 'org-self-insert-command
19097 'delete-char 'org-delete-char
19098 'delete-backward-char 'org-delete-backward-char)
19099 (org-defkey org-mode-map "|" 'org-force-self-insert))
19101 (defvar org-ctrl-c-ctrl-c-hook nil
19102 "Hook for functions attaching themselves to `C-c C-c'.
19104 This can be used to add additional functionality to the C-c C-c
19105 key which executes context-dependent commands. This hook is run
19106 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19107 run after the last test.
19109 Each function will be called with no arguments. The function
19110 must check if the context is appropriate for it to act. If yes,
19111 it should do its thing and then return a non-nil value. If the
19112 context is wrong, just do nothing and return nil.")
19114 (defvar org-ctrl-c-ctrl-c-final-hook nil
19115 "Hook for functions attaching themselves to `C-c C-c'.
19117 This can be used to add additional functionality to the C-c C-c
19118 key which executes context-dependent commands. This hook is run
19119 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19120 before the first test.
19122 Each function will be called with no arguments. The function
19123 must check if the context is appropriate for it to act. If yes,
19124 it should do its thing and then return a non-nil value. If the
19125 context is wrong, just do nothing and return nil.")
19127 (defvar org-tab-first-hook nil
19128 "Hook for functions to attach themselves to TAB.
19129 See `org-ctrl-c-ctrl-c-hook' for more information.
19130 This hook runs as the first action when TAB is pressed, even before
19131 `org-cycle' messes around with the `outline-regexp' to cater for
19132 inline tasks and plain list item folding.
19133 If any function in this hook returns t, any other actions that
19134 would have been caused by TAB (such as table field motion or visibility
19135 cycling) will not occur.")
19137 (defvar org-tab-after-check-for-table-hook nil
19138 "Hook for functions to attach themselves to TAB.
19139 See `org-ctrl-c-ctrl-c-hook' for more information.
19140 This hook runs after it has been established that the cursor is not in a
19141 table, but before checking if the cursor is in a headline or if global cycling
19142 should be done.
19143 If any function in this hook returns t, not other actions like visibility
19144 cycling will be done.")
19146 (defvar org-tab-after-check-for-cycling-hook nil
19147 "Hook for functions to attach themselves to TAB.
19148 See `org-ctrl-c-ctrl-c-hook' for more information.
19149 This hook runs after it has been established that not table field motion and
19150 not visibility should be done because of current context. This is probably
19151 the place where a package like yasnippets can hook in.")
19153 (defvar org-tab-before-tab-emulation-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 every other options for TAB have been exhausted, but
19157 before indentation and \t insertion takes place.")
19159 (defvar org-metaleft-hook nil
19160 "Hook for functions attaching themselves to `M-left'.
19161 See `org-ctrl-c-ctrl-c-hook' for more information.")
19162 (defvar org-metaright-hook nil
19163 "Hook for functions attaching themselves to `M-right'.
19164 See `org-ctrl-c-ctrl-c-hook' for more information.")
19165 (defvar org-metaup-hook nil
19166 "Hook for functions attaching themselves to `M-up'.
19167 See `org-ctrl-c-ctrl-c-hook' for more information.")
19168 (defvar org-metadown-hook nil
19169 "Hook for functions attaching themselves to `M-down'.
19170 See `org-ctrl-c-ctrl-c-hook' for more information.")
19171 (defvar org-shiftmetaleft-hook nil
19172 "Hook for functions attaching themselves to `M-S-left'.
19173 See `org-ctrl-c-ctrl-c-hook' for more information.")
19174 (defvar org-shiftmetaright-hook nil
19175 "Hook for functions attaching themselves to `M-S-right'.
19176 See `org-ctrl-c-ctrl-c-hook' for more information.")
19177 (defvar org-shiftmetaup-hook nil
19178 "Hook for functions attaching themselves to `M-S-up'.
19179 See `org-ctrl-c-ctrl-c-hook' for more information.")
19180 (defvar org-shiftmetadown-hook nil
19181 "Hook for functions attaching themselves to `M-S-down'.
19182 See `org-ctrl-c-ctrl-c-hook' for more information.")
19183 (defvar org-metareturn-hook nil
19184 "Hook for functions attaching themselves to `M-RET'.
19185 See `org-ctrl-c-ctrl-c-hook' for more information.")
19186 (defvar org-shiftup-hook nil
19187 "Hook for functions attaching themselves to `S-up'.
19188 See `org-ctrl-c-ctrl-c-hook' for more information.")
19189 (defvar org-shiftup-final-hook nil
19190 "Hook for functions attaching themselves to `S-up'.
19191 This one runs after all other options except shift-select have been excluded.
19192 See `org-ctrl-c-ctrl-c-hook' for more information.")
19193 (defvar org-shiftdown-hook nil
19194 "Hook for functions attaching themselves to `S-down'.
19195 See `org-ctrl-c-ctrl-c-hook' for more information.")
19196 (defvar org-shiftdown-final-hook nil
19197 "Hook for functions attaching themselves to `S-down'.
19198 This one runs after all other options except shift-select have been excluded.
19199 See `org-ctrl-c-ctrl-c-hook' for more information.")
19200 (defvar org-shiftleft-hook nil
19201 "Hook for functions attaching themselves to `S-left'.
19202 See `org-ctrl-c-ctrl-c-hook' for more information.")
19203 (defvar org-shiftleft-final-hook nil
19204 "Hook for functions attaching themselves to `S-left'.
19205 This one runs after all other options except shift-select have been excluded.
19206 See `org-ctrl-c-ctrl-c-hook' for more information.")
19207 (defvar org-shiftright-hook nil
19208 "Hook for functions attaching themselves to `S-right'.
19209 See `org-ctrl-c-ctrl-c-hook' for more information.")
19210 (defvar org-shiftright-final-hook nil
19211 "Hook for functions attaching themselves to `S-right'.
19212 This one runs after all other options except shift-select have been excluded.
19213 See `org-ctrl-c-ctrl-c-hook' for more information.")
19215 (defun org-modifier-cursor-error ()
19216 "Throw an error, a modified cursor command was applied in wrong context."
19217 (error "This command is active in special context like tables, headlines or items"))
19219 (defun org-shiftselect-error ()
19220 "Throw an error because Shift-Cursor command was applied in wrong context."
19221 (if (and (boundp 'shift-select-mode) shift-select-mode)
19222 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19223 (error "This command works only in special context like headlines or timestamps")))
19225 (defun org-call-for-shift-select (cmd)
19226 (let ((this-command-keys-shift-translated t))
19227 (call-interactively cmd)))
19229 (defun org-shifttab (&optional arg)
19230 "Global visibility cycling or move to previous table field.
19231 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19232 on context.
19233 See the individual commands for more information."
19234 (interactive "P")
19235 (cond
19236 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19237 ((integerp arg)
19238 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19239 (message "Content view to level: %d" arg)
19240 (org-content (prefix-numeric-value arg2))
19241 (setq org-cycle-global-status 'overview)))
19242 (t (call-interactively 'org-global-cycle))))
19244 (defun org-shiftmetaleft ()
19245 "Promote subtree or delete table column.
19246 Calls `org-promote-subtree', `org-outdent-item-tree', or
19247 `org-table-delete-column', depending on context. See the
19248 individual commands for more information."
19249 (interactive)
19250 (cond
19251 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19252 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19253 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19254 ((if (not (org-region-active-p)) (org-at-item-p)
19255 (save-excursion (goto-char (region-beginning))
19256 (org-at-item-p)))
19257 (call-interactively 'org-outdent-item-tree))
19258 (t (org-modifier-cursor-error))))
19260 (defun org-shiftmetaright ()
19261 "Demote subtree or insert table column.
19262 Calls `org-demote-subtree', `org-indent-item-tree', or
19263 `org-table-insert-column', depending on context. See the
19264 individual commands for more information."
19265 (interactive)
19266 (cond
19267 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19268 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19269 ((org-at-heading-p) (call-interactively 'org-demote-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-indent-item-tree))
19274 (t (org-modifier-cursor-error))))
19276 (defun org-shiftmetaup (&optional arg)
19277 "Move subtree up or kill table row.
19278 Calls `org-move-subtree-up' or `org-table-kill-row' or
19279 `org-move-item-up' or `org-timestamp-up', depending on context.
19280 See the individual commands for more information."
19281 (interactive "P")
19282 (cond
19283 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19284 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19285 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19286 ((org-at-item-p) (call-interactively 'org-move-item-up))
19287 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19288 (call-interactively 'org-timestamp-up)))
19289 (t (call-interactively 'org-drag-line-backward))))
19291 (defun org-shiftmetadown (&optional arg)
19292 "Move subtree down or insert table row.
19293 Calls `org-move-subtree-down' or `org-table-insert-row' or
19294 `org-move-item-down' or `org-timestamp-up', depending on context.
19295 See the individual commands for more information."
19296 (interactive "P")
19297 (cond
19298 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19299 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19300 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19301 ((org-at-item-p) (call-interactively 'org-move-item-down))
19302 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19303 (call-interactively 'org-timestamp-down)))
19304 (t (call-interactively 'org-drag-line-forward))))
19306 (defsubst org-hidden-tree-error ()
19307 (error
19308 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19310 (defun org-metaleft (&optional arg)
19311 "Promote heading or move table column to left.
19312 Calls `org-do-promote' or `org-table-move-column', depending on context.
19313 With no specific context, calls the Emacs default `backward-word'.
19314 See the individual commands for more information."
19315 (interactive "P")
19316 (cond
19317 ((run-hook-with-args-until-success 'org-metaleft-hook))
19318 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19319 ((org-with-limited-levels
19320 (or (org-at-heading-p)
19321 (and (org-region-active-p)
19322 (save-excursion
19323 (goto-char (region-beginning))
19324 (org-at-heading-p)))))
19325 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19326 (call-interactively 'org-do-promote))
19327 ;; At an inline task.
19328 ((org-at-heading-p)
19329 (call-interactively 'org-inlinetask-promote))
19330 ((or (org-at-item-p)
19331 (and (org-region-active-p)
19332 (save-excursion
19333 (goto-char (region-beginning))
19334 (org-at-item-p))))
19335 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19336 (call-interactively 'org-outdent-item))
19337 (t (call-interactively 'backward-word))))
19339 (defun org-metaright (&optional arg)
19340 "Demote a subtree, a list item or move table column to right.
19341 In front of a drawer or a block keyword, indent it correctly.
19342 With no specific context, calls the Emacs default `forward-word'.
19343 See the individual commands for more information."
19344 (interactive "P")
19345 (cond
19346 ((run-hook-with-args-until-success 'org-metaright-hook))
19347 ((org-at-table-p) (call-interactively 'org-table-move-column))
19348 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19349 ((org-at-block-p) (call-interactively 'org-indent-block))
19350 ((org-with-limited-levels
19351 (or (org-at-heading-p)
19352 (and (org-region-active-p)
19353 (save-excursion
19354 (goto-char (region-beginning))
19355 (org-at-heading-p)))))
19356 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19357 (call-interactively 'org-do-demote))
19358 ;; At an inline task.
19359 ((org-at-heading-p)
19360 (call-interactively 'org-inlinetask-demote))
19361 ((or (org-at-item-p)
19362 (and (org-region-active-p)
19363 (save-excursion
19364 (goto-char (region-beginning))
19365 (org-at-item-p))))
19366 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19367 (call-interactively 'org-indent-item))
19368 (t (call-interactively 'forward-word))))
19370 (defun org-check-for-hidden (what)
19371 "Check if there are hidden headlines/items in the current visual line.
19372 WHAT can be either `headlines' or `items'. If the current line is
19373 an outline or item heading and it has a folded subtree below it,
19374 this function returns t, nil otherwise."
19375 (let ((re (cond
19376 ((eq what 'headlines) org-outline-regexp-bol)
19377 ((eq what 'items) (org-item-beginning-re))
19378 (t (error "This should not happen"))))
19379 beg end)
19380 (save-excursion
19381 (catch 'exit
19382 (unless (org-region-active-p)
19383 (setq beg (point-at-bol))
19384 (beginning-of-line 2)
19385 (while (and (not (eobp)) ;; this is like `next-line'
19386 (get-char-property (1- (point)) 'invisible))
19387 (beginning-of-line 2))
19388 (setq end (point))
19389 (goto-char beg)
19390 (goto-char (point-at-eol))
19391 (setq end (max end (point)))
19392 (while (re-search-forward re end t)
19393 (if (get-char-property (match-beginning 0) 'invisible)
19394 (throw 'exit t))))
19395 nil))))
19397 (defun org-metaup (&optional arg)
19398 "Move subtree up or move table row up.
19399 Calls `org-move-subtree-up' or `org-table-move-row' or
19400 `org-move-item-up', depending on context. See the individual commands
19401 for more information."
19402 (interactive "P")
19403 (cond
19404 ((run-hook-with-args-until-success 'org-metaup-hook))
19405 ((org-region-active-p)
19406 (let* ((a (min (region-beginning) (region-end)))
19407 (b (1- (max (region-beginning) (region-end))))
19408 (c (save-excursion (goto-char a)
19409 (move-beginning-of-line 0)))
19410 (d (save-excursion (goto-char a)
19411 (move-end-of-line 0) (point))))
19412 (transpose-regions a b c d)
19413 (goto-char c)))
19414 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19415 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19416 ((org-at-item-p) (call-interactively 'org-move-item-up))
19417 (t (org-drag-element-backward))))
19419 (defun org-metadown (&optional arg)
19420 "Move subtree down or move table row down.
19421 Calls `org-move-subtree-down' or `org-table-move-row' or
19422 `org-move-item-down', depending on context. See the individual
19423 commands for more information."
19424 (interactive "P")
19425 (cond
19426 ((run-hook-with-args-until-success 'org-metadown-hook))
19427 ((org-region-active-p)
19428 (let* ((a (min (region-beginning) (region-end)))
19429 (b (max (region-beginning) (region-end)))
19430 (c (save-excursion (goto-char b)
19431 (move-beginning-of-line 1)))
19432 (d (save-excursion (goto-char b)
19433 (move-end-of-line 1) (1+ (point)))))
19434 (transpose-regions a b c d)
19435 (goto-char d)))
19436 ((org-at-table-p) (call-interactively 'org-table-move-row))
19437 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19438 ((org-at-item-p) (call-interactively 'org-move-item-down))
19439 (t (org-drag-element-forward))))
19441 (defun org-shiftup (&optional arg)
19442 "Increase item in timestamp or increase priority of current headline.
19443 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19444 depending on context. See the individual commands for more information."
19445 (interactive "P")
19446 (cond
19447 ((run-hook-with-args-until-success 'org-shiftup-hook))
19448 ((and org-support-shift-select (org-region-active-p))
19449 (org-call-for-shift-select 'previous-line))
19450 ((org-at-timestamp-p t)
19451 (call-interactively (if org-edit-timestamp-down-means-later
19452 'org-timestamp-down 'org-timestamp-up)))
19453 ((and (not (eq org-support-shift-select 'always))
19454 org-enable-priority-commands
19455 (org-at-heading-p))
19456 (call-interactively 'org-priority-up))
19457 ((and (not org-support-shift-select) (org-at-item-p))
19458 (call-interactively 'org-previous-item))
19459 ((org-clocktable-try-shift 'up arg))
19460 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19461 (org-support-shift-select
19462 (org-call-for-shift-select 'previous-line))
19463 (t (org-shiftselect-error))))
19465 (defun org-shiftdown (&optional arg)
19466 "Decrease item in timestamp or decrease priority of current headline.
19467 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19468 depending on context. See the individual commands for more information."
19469 (interactive "P")
19470 (cond
19471 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19472 ((and org-support-shift-select (org-region-active-p))
19473 (org-call-for-shift-select 'next-line))
19474 ((org-at-timestamp-p t)
19475 (call-interactively (if org-edit-timestamp-down-means-later
19476 'org-timestamp-up 'org-timestamp-down)))
19477 ((and (not (eq org-support-shift-select 'always))
19478 org-enable-priority-commands
19479 (org-at-heading-p))
19480 (call-interactively 'org-priority-down))
19481 ((and (not org-support-shift-select) (org-at-item-p))
19482 (call-interactively 'org-next-item))
19483 ((org-clocktable-try-shift 'down arg))
19484 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19485 (org-support-shift-select
19486 (org-call-for-shift-select 'next-line))
19487 (t (org-shiftselect-error))))
19489 (defun org-shiftright (&optional arg)
19490 "Cycle the thing at point or in the current line, depending on context.
19491 Depending on context, this does one of the following:
19493 - switch a timestamp at point one day into the future
19494 - on a headline, switch to the next TODO keyword.
19495 - on an item, switch entire list to the next bullet type
19496 - on a property line, switch to the next allowed value
19497 - on a clocktable definition line, move time block into the future"
19498 (interactive "P")
19499 (cond
19500 ((run-hook-with-args-until-success 'org-shiftright-hook))
19501 ((and org-support-shift-select (org-region-active-p))
19502 (org-call-for-shift-select 'forward-char))
19503 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19504 ((and (not (eq org-support-shift-select 'always))
19505 (org-at-heading-p))
19506 (let ((org-inhibit-logging
19507 (not org-treat-S-cursor-todo-selection-as-state-change))
19508 (org-inhibit-blocking
19509 (not org-treat-S-cursor-todo-selection-as-state-change)))
19510 (org-call-with-arg 'org-todo 'right)))
19511 ((or (and org-support-shift-select
19512 (not (eq org-support-shift-select 'always))
19513 (org-at-item-bullet-p))
19514 (and (not org-support-shift-select) (org-at-item-p)))
19515 (org-call-with-arg 'org-cycle-list-bullet nil))
19516 ((and (not (eq org-support-shift-select 'always))
19517 (org-at-property-p))
19518 (call-interactively 'org-property-next-allowed-value))
19519 ((org-clocktable-try-shift 'right arg))
19520 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19521 (org-support-shift-select
19522 (org-call-for-shift-select 'forward-char))
19523 (t (org-shiftselect-error))))
19525 (defun org-shiftleft (&optional arg)
19526 "Cycle the thing at point or in the current line, depending on context.
19527 Depending on context, this does one of the following:
19529 - switch a timestamp at point one day into the past
19530 - on a headline, switch to the previous TODO keyword.
19531 - on an item, switch entire list to the previous bullet type
19532 - on a property line, switch to the previous allowed value
19533 - on a clocktable definition line, move time block into the past"
19534 (interactive "P")
19535 (cond
19536 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19537 ((and org-support-shift-select (org-region-active-p))
19538 (org-call-for-shift-select 'backward-char))
19539 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19540 ((and (not (eq org-support-shift-select 'always))
19541 (org-at-heading-p))
19542 (let ((org-inhibit-logging
19543 (not org-treat-S-cursor-todo-selection-as-state-change))
19544 (org-inhibit-blocking
19545 (not org-treat-S-cursor-todo-selection-as-state-change)))
19546 (org-call-with-arg 'org-todo 'left)))
19547 ((or (and org-support-shift-select
19548 (not (eq org-support-shift-select 'always))
19549 (org-at-item-bullet-p))
19550 (and (not org-support-shift-select) (org-at-item-p)))
19551 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19552 ((and (not (eq org-support-shift-select 'always))
19553 (org-at-property-p))
19554 (call-interactively 'org-property-previous-allowed-value))
19555 ((org-clocktable-try-shift 'left arg))
19556 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19557 (org-support-shift-select
19558 (org-call-for-shift-select 'backward-char))
19559 (t (org-shiftselect-error))))
19561 (defun org-shiftcontrolright ()
19562 "Switch to next TODO set."
19563 (interactive)
19564 (cond
19565 ((and org-support-shift-select (org-region-active-p))
19566 (org-call-for-shift-select 'forward-word))
19567 ((and (not (eq org-support-shift-select 'always))
19568 (org-at-heading-p))
19569 (org-call-with-arg 'org-todo 'nextset))
19570 (org-support-shift-select
19571 (org-call-for-shift-select 'forward-word))
19572 (t (org-shiftselect-error))))
19574 (defun org-shiftcontrolleft ()
19575 "Switch to previous TODO set."
19576 (interactive)
19577 (cond
19578 ((and org-support-shift-select (org-region-active-p))
19579 (org-call-for-shift-select 'backward-word))
19580 ((and (not (eq org-support-shift-select 'always))
19581 (org-at-heading-p))
19582 (org-call-with-arg 'org-todo 'previousset))
19583 (org-support-shift-select
19584 (org-call-for-shift-select 'backward-word))
19585 (t (org-shiftselect-error))))
19587 (defun org-shiftcontrolup (&optional n)
19588 "Change timestamps synchronously up in CLOCK log lines.
19589 Optional argument N tells to change by that many units."
19590 (interactive "P")
19591 (cond ((and (not org-support-shift-select)
19592 (org-at-clock-log-p)
19593 (org-at-timestamp-p t))
19594 (org-clock-timestamps-up n))
19595 (t (org-shiftselect-error))))
19597 (defun org-shiftcontroldown (&optional n)
19598 "Change timestamps synchronously down in CLOCK log lines.
19599 Optional argument N tells to change by that many units."
19600 (interactive "P")
19601 (cond ((and (not org-support-shift-select)
19602 (org-at-clock-log-p)
19603 (org-at-timestamp-p t))
19604 (org-clock-timestamps-down n))
19605 (t (org-shiftselect-error))))
19607 (defun org-ctrl-c-ret ()
19608 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19609 (interactive)
19610 (cond
19611 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19612 (t (call-interactively 'org-insert-heading))))
19614 (defun org-find-visible ()
19615 (let ((s (point)))
19616 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19617 (get-char-property s 'invisible)))
19619 (defun org-find-invisible ()
19620 (let ((s (point)))
19621 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19622 (not (get-char-property s 'invisible))))
19625 (defun org-copy-visible (beg end)
19626 "Copy the visible parts of the region."
19627 (interactive "r")
19628 (let (snippets s)
19629 (save-excursion
19630 (save-restriction
19631 (narrow-to-region beg end)
19632 (setq s (goto-char (point-min)))
19633 (while (not (= (point) (point-max)))
19634 (goto-char (org-find-invisible))
19635 (push (buffer-substring s (point)) snippets)
19636 (setq s (goto-char (org-find-visible))))))
19637 (kill-new (apply 'concat (nreverse snippets)))))
19639 (defun org-copy-special ()
19640 "Copy region in table or copy current subtree.
19641 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19642 See the individual commands for more information."
19643 (interactive)
19644 (call-interactively
19645 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19647 (defun org-cut-special ()
19648 "Cut region in table or cut current subtree.
19649 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19650 See the individual commands for more information."
19651 (interactive)
19652 (call-interactively
19653 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19655 (defun org-paste-special (arg)
19656 "Paste rectangular region into table, or past subtree relative to level.
19657 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19658 See the individual commands for more information."
19659 (interactive "P")
19660 (if (org-at-table-p)
19661 (org-table-paste-rectangle)
19662 (org-paste-subtree arg)))
19664 (defsubst org-in-fixed-width-region-p ()
19665 "Is point in a fixed-width region?"
19666 (save-match-data
19667 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19669 (defun org-edit-special (&optional arg)
19670 "Call a special editor for the element at point.
19671 When at a table, call the formula editor with `org-table-edit-formulas'.
19672 When in a source code block, call `org-edit-src-code'.
19673 When in a fixed-width region, call `org-edit-fixed-width-region'.
19674 When at an #+INCLUDE keyword, visit the included file.
19675 On a link, call `ffap' to visit the link at point.
19676 Otherwise, return a user error."
19677 (interactive)
19678 (let ((element (org-element-at-point)))
19679 (assert (not buffer-read-only) nil
19680 "Buffer is read-only: %s" (buffer-name))
19681 (case (org-element-type element)
19682 (src-block
19683 (if (not arg) (org-edit-src-code)
19684 (let* ((info (org-babel-get-src-block-info))
19685 (lang (nth 0 info))
19686 (params (nth 2 info))
19687 (session (cdr (assq :session params))))
19688 (if (not session) (org-edit-src-code)
19689 ;; At a src-block with a session and function called with
19690 ;; an ARG: switch to the buffer related to the inferior
19691 ;; process.
19692 (funcall (intern (concat "org-babel-prep-session:" lang))
19693 session params)))))
19694 (keyword
19695 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19696 (find-file
19697 (org-remove-double-quotes
19698 (car (org-split-string (org-element-property :value element)))))
19699 (user-error "No special environment to edit here")))
19700 (table
19701 (if (eq (org-element-property :type element) 'table.el)
19702 (org-edit-src-code)
19703 (call-interactively 'org-table-edit-formulas)))
19704 ;; Only Org tables contain `table-row' type elements.
19705 (table-row (call-interactively 'org-table-edit-formulas))
19706 ((example-block export-block) (org-edit-src-code))
19707 (fixed-width (org-edit-fixed-width-region))
19708 (otherwise
19709 ;; No notable element at point. Though, we may be at a link,
19710 ;; which is an object. Thus, scan deeper.
19711 (if (eq (org-element-type (org-element-context element)) 'link)
19712 (call-interactively 'ffap)
19713 (user-error "No special environment to edit here"))))))
19715 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19716 (defun org-ctrl-c-ctrl-c (&optional arg)
19717 "Set tags in headline, or update according to changed information at point.
19719 This command does many different things, depending on context:
19721 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19722 this is what we do.
19724 - If the cursor is on a statistics cookie, update it.
19726 - If the cursor is in a headline, prompt for tags and insert them
19727 into the current line, aligned to `org-tags-column'. When called
19728 with prefix arg, realign all tags in the current buffer.
19730 - If the cursor is in one of the special #+KEYWORD lines, this
19731 triggers scanning the buffer for these lines and updating the
19732 information.
19734 - If the cursor is inside a table, realign the table. This command
19735 works even if the automatic table editor has been turned off.
19737 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19738 the entire table.
19740 - If the cursor is at a footnote reference or definition, jump to
19741 the corresponding definition or references, respectively.
19743 - If the cursor is a the beginning of a dynamic block, update it.
19745 - If the current buffer is a capture buffer, close note and file it.
19747 - If the cursor is on a <<<target>>>, update radio targets and
19748 corresponding links in this buffer.
19750 - If the cursor is on a numbered item in a plain list, renumber the
19751 ordered list.
19753 - If the cursor is on a checkbox, toggle it.
19755 - If the cursor is on a code block, evaluate it. The variable
19756 `org-confirm-babel-evaluate' can be used to control prompting
19757 before code block evaluation, by default every code block
19758 evaluation requires confirmation. Code block evaluation can be
19759 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19760 (interactive "P")
19761 (cond
19762 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19763 org-occur-highlights
19764 org-latex-fragment-image-overlays)
19765 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19766 (org-remove-occur-highlights)
19767 (org-remove-latex-fragment-image-overlays)
19768 (message "Temporary highlights/overlays removed from current buffer"))
19769 ((and (local-variable-p 'org-finish-function (current-buffer))
19770 (fboundp org-finish-function))
19771 (funcall org-finish-function))
19772 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19774 (let* ((context (org-element-context)) (type (org-element-type context)))
19775 ;; Test if point is within a blank line.
19776 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19777 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19778 (user-error "C-c C-c can do nothing useful at this location"))
19779 ;; For convenience: at the first line of a paragraph on the
19780 ;; same line as an item, apply function on that item instead.
19781 (when (eq type 'paragraph)
19782 (let ((parent (org-element-property :parent context)))
19783 (when (and (eq (org-element-type parent) 'item)
19784 (= (point-at-bol) (org-element-property :begin parent)))
19785 (setq context parent type 'item))))
19786 ;; Act according to type of element or object at point.
19787 (case type
19788 (clock (org-clock-update-time-maybe))
19789 (dynamic-block
19790 (save-excursion
19791 (goto-char (org-element-property :post-affiliated context))
19792 (org-update-dblock)))
19793 (footnote-definition
19794 (goto-char (org-element-property :post-affiliated context))
19795 (call-interactively 'org-footnote-action))
19796 (footnote-reference (call-interactively 'org-footnote-action))
19797 ((headline inlinetask)
19798 (save-excursion (goto-char (org-element-property :begin context))
19799 (call-interactively 'org-set-tags)))
19800 (item
19801 ;; At an item: a double C-u set checkbox to "[-]"
19802 ;; unconditionally, whereas a single one will toggle its
19803 ;; presence. Without an universal argument, if the item
19804 ;; has a checkbox, toggle it. Otherwise repair the list.
19805 (let* ((box (org-element-property :checkbox context))
19806 (struct (org-element-property :structure context))
19807 (old-struct (copy-tree struct))
19808 (parents (org-list-parents-alist struct))
19809 (prevs (org-list-prevs-alist struct))
19810 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19811 (org-list-set-checkbox
19812 (org-element-property :begin context) struct
19813 (cond ((equal arg '(16)) "[-]")
19814 ((and (not box) (equal arg '(4))) "[ ]")
19815 ((or (not box) (equal arg '(4))) nil)
19816 ((eq box 'on) "[ ]")
19817 (t "[X]")))
19818 ;; Mimic `org-list-write-struct' but with grabbing
19819 ;; a return value from `org-list-struct-fix-box'.
19820 (org-list-struct-fix-ind struct parents 2)
19821 (org-list-struct-fix-item-end struct)
19822 (org-list-struct-fix-bul struct prevs)
19823 (org-list-struct-fix-ind struct parents)
19824 (let ((block-item
19825 (org-list-struct-fix-box struct parents prevs orderedp)))
19826 (if (and box (equal struct old-struct))
19827 (if (equal arg '(16))
19828 (message "Checkboxes already reset")
19829 (user-error "Cannot toggle this checkbox: %s"
19830 (if (eq box 'on)
19831 "all subitems checked"
19832 "unchecked subitems")))
19833 (org-list-struct-apply-struct struct old-struct)
19834 (org-update-checkbox-count-maybe))
19835 (when block-item
19836 (message "Checkboxes were removed due to empty box at line %d"
19837 (org-current-line block-item))))))
19838 (keyword
19839 (let ((org-inhibit-startup-visibility-stuff t)
19840 (org-startup-align-all-tables nil))
19841 (when (boundp 'org-table-coordinate-overlays)
19842 (mapc 'delete-overlay org-table-coordinate-overlays)
19843 (setq org-table-coordinate-overlays nil))
19844 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19845 (message "Local setup has been refreshed"))
19846 (plain-list
19847 ;; At a plain list, with a double C-u argument, set
19848 ;; checkboxes of each item to "[-]", whereas a single one
19849 ;; will toggle their presence according to the state of the
19850 ;; first item in the list. Without an argument, repair the
19851 ;; list.
19852 (let* ((begin (org-element-property :contents-begin context))
19853 (struct (org-element-property :structure context))
19854 (old-struct (copy-tree struct))
19855 (first-box (save-excursion
19856 (goto-char begin)
19857 (looking-at org-list-full-item-re)
19858 (match-string-no-properties 3)))
19859 (new-box (cond ((equal arg '(16)) "[-]")
19860 ((equal arg '(4)) (unless first-box "[ ]"))
19861 ((equal first-box "[X]") "[ ]")
19862 (t "[X]"))))
19863 (cond
19864 (arg
19865 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19866 (org-list-get-all-items
19867 begin struct (org-list-prevs-alist struct))))
19868 ((and first-box (eq (point) begin))
19869 ;; For convenience, when point is at bol on the first
19870 ;; item of the list and no argument is provided, simply
19871 ;; toggle checkbox of that item, if any.
19872 (org-list-set-checkbox begin struct new-box)))
19873 (org-list-write-struct
19874 struct (org-list-parents-alist struct) old-struct)
19875 (org-update-checkbox-count-maybe)
19876 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19877 ((property-drawer node-property)
19878 (call-interactively 'org-property-action))
19879 ((radio-target target)
19880 (call-interactively 'org-update-radio-target-regexp))
19881 (statistics-cookie
19882 (call-interactively 'org-update-statistics-cookies))
19883 ((table table-cell table-row)
19884 ;; At a table, recalculate every field and align it. Also
19885 ;; send the table if necessary. If the table has
19886 ;; a `table.el' type, just give up. At a table row or
19887 ;; cell, maybe recalculate line but always align table.
19888 (if (eq (org-element-property :type context) 'table.el)
19889 (message "Use C-c ' to edit table.el tables")
19890 (let ((org-enable-table-editor t))
19891 (if (or (eq type 'table)
19892 ;; Check if point is at a TBLFM line.
19893 (and (eq type 'table-row)
19894 (= (point) (org-element-property :end context))))
19895 (save-excursion
19896 (goto-char (org-element-property :contents-begin context))
19897 (org-call-with-arg 'org-table-recalculate (or arg t))
19898 (orgtbl-send-table 'maybe))
19899 (org-table-maybe-eval-formula)
19900 (cond (arg (call-interactively 'org-table-recalculate))
19901 ((org-table-maybe-recalculate-line))
19902 (t (org-table-align)))))))
19903 (timestamp (org-timestamp-change 0 'day))
19904 (otherwise
19905 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19906 (user-error
19907 "C-c C-c can do nothing useful at this location")))))))))
19909 (defun org-mode-restart ()
19910 "Restart Org-mode, to scan again for special lines.
19911 Also updates the keyword regular expressions."
19912 (interactive)
19913 (org-mode)
19914 (message "Org-mode restarted"))
19916 (defun org-kill-note-or-show-branches ()
19917 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19918 (interactive)
19919 (if (not org-finish-function)
19920 (progn
19921 (hide-subtree)
19922 (call-interactively 'show-branches))
19923 (let ((org-note-abort t))
19924 (funcall org-finish-function))))
19926 (defun org-return (&optional indent)
19927 "Goto next table row or insert a newline.
19928 Calls `org-table-next-row' or `newline', depending on context.
19929 See the individual commands for more information."
19930 (interactive)
19931 (let (org-ts-what)
19932 (cond
19933 ((or (bobp) (org-in-src-block-p))
19934 (if indent (newline-and-indent) (newline)))
19935 ((org-at-table-p)
19936 (org-table-justify-field-maybe)
19937 (call-interactively 'org-table-next-row))
19938 ;; when `newline-and-indent' is called within a list, make sure
19939 ;; text moved stays inside the item.
19940 ((and (org-in-item-p) indent)
19941 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19942 (progn
19943 (save-match-data (newline))
19944 (org-indent-line-to (length (match-string 0))))
19945 (let ((ind (org-get-indentation)))
19946 (newline)
19947 (if (org-looking-back org-list-end-re)
19948 (org-indent-line)
19949 (org-indent-line-to ind)))))
19950 ((and org-return-follows-link
19951 (org-at-timestamp-p t)
19952 (not (eq org-ts-what 'after)))
19953 (org-follow-timestamp-link))
19954 ((and org-return-follows-link
19955 (let ((tprop (get-text-property (point) 'face)))
19956 (or (eq tprop 'org-link)
19957 (and (listp tprop) (memq 'org-link tprop)))))
19958 (call-interactively 'org-open-at-point))
19959 ((and (org-at-heading-p)
19960 (looking-at
19961 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19962 (org-show-entry)
19963 (end-of-line 1)
19964 (newline))
19965 (t (if indent (newline-and-indent) (newline))))))
19967 (defun org-return-indent ()
19968 "Goto next table row or insert a newline and indent.
19969 Calls `org-table-next-row' or `newline-and-indent', depending on
19970 context. See the individual commands for more information."
19971 (interactive)
19972 (org-return t))
19974 (defun org-ctrl-c-star ()
19975 "Compute table, or change heading status of lines.
19976 Calls `org-table-recalculate' or `org-toggle-heading',
19977 depending on context."
19978 (interactive)
19979 (cond
19980 ((org-at-table-p)
19981 (call-interactively 'org-table-recalculate))
19983 ;; Convert all lines in region to list items
19984 (call-interactively 'org-toggle-heading))))
19986 (defun org-ctrl-c-minus ()
19987 "Insert separator line in table or modify bullet status of line.
19988 Also turns a plain line or a region of lines into list items.
19989 Calls `org-table-insert-hline', `org-toggle-item', or
19990 `org-cycle-list-bullet', depending on context."
19991 (interactive)
19992 (cond
19993 ((org-at-table-p)
19994 (call-interactively 'org-table-insert-hline))
19995 ((org-region-active-p)
19996 (call-interactively 'org-toggle-item))
19997 ((org-in-item-p)
19998 (call-interactively 'org-cycle-list-bullet))
20000 (call-interactively 'org-toggle-item))))
20002 (defun org-toggle-item (arg)
20003 "Convert headings or normal lines to items, items to normal lines.
20004 If there is no active region, only the current line is considered.
20006 If the first non blank line in the region is a headline, convert
20007 all headlines to items, shifting text accordingly.
20009 If it is an item, convert all items to normal lines.
20011 If it is normal text, change region into an item. With a prefix
20012 argument ARG, change each line in region into an item."
20013 (interactive "P")
20014 (let ((shift-text
20015 (function
20016 ;; Shift text in current section to IND, from point to END.
20017 ;; The function leaves point to END line.
20018 (lambda (ind end)
20019 (let ((min-i 1000) (end (copy-marker end)))
20020 ;; First determine the minimum indentation (MIN-I) of
20021 ;; the text.
20022 (save-excursion
20023 (catch 'exit
20024 (while (< (point) end)
20025 (let ((i (org-get-indentation)))
20026 (cond
20027 ;; Skip blank lines and inline tasks.
20028 ((looking-at "^[ \t]*$"))
20029 ((looking-at org-outline-regexp-bol))
20030 ;; We can't find less than 0 indentation.
20031 ((zerop i) (throw 'exit (setq min-i 0)))
20032 ((< i min-i) (setq min-i i))))
20033 (forward-line))))
20034 ;; Then indent each line so that a line indented to
20035 ;; MIN-I becomes indented to IND. Ignore blank lines
20036 ;; and inline tasks in the process.
20037 (let ((delta (- ind min-i)))
20038 (while (< (point) end)
20039 (unless (or (looking-at "^[ \t]*$")
20040 (looking-at org-outline-regexp-bol))
20041 (org-indent-line-to (+ (org-get-indentation) delta)))
20042 (forward-line)))))))
20043 (skip-blanks
20044 (function
20045 ;; Return beginning of first non-blank line, starting from
20046 ;; line at POS.
20047 (lambda (pos)
20048 (save-excursion
20049 (goto-char pos)
20050 (skip-chars-forward " \r\t\n")
20051 (point-at-bol)))))
20052 beg end)
20053 ;; Determine boundaries of changes.
20054 (if (org-region-active-p)
20055 (setq beg (funcall skip-blanks (region-beginning))
20056 end (copy-marker (region-end)))
20057 (setq beg (funcall skip-blanks (point-at-bol))
20058 end (copy-marker (point-at-eol))))
20059 ;; Depending on the starting line, choose an action on the text
20060 ;; between BEG and END.
20061 (org-with-limited-levels
20062 (save-excursion
20063 (goto-char beg)
20064 (cond
20065 ;; Case 1. Start at an item: de-itemize. Note that it only
20066 ;; happens when a region is active: `org-ctrl-c-minus'
20067 ;; would call `org-cycle-list-bullet' otherwise.
20068 ((org-at-item-p)
20069 (while (< (point) end)
20070 (when (org-at-item-p)
20071 (skip-chars-forward " \t")
20072 (delete-region (point) (match-end 0)))
20073 (forward-line)))
20074 ;; Case 2. Start at an heading: convert to items.
20075 ((org-at-heading-p)
20076 (let* ((bul (org-list-bullet-string "-"))
20077 (bul-len (length bul))
20078 ;; Indentation of the first heading. It should be
20079 ;; relative to the indentation of its parent, if any.
20080 (start-ind (save-excursion
20081 (cond
20082 ((not org-adapt-indentation) 0)
20083 ((not (outline-previous-heading)) 0)
20084 (t (length (match-string 0))))))
20085 ;; Level of first heading. Further headings will be
20086 ;; compared to it to determine hierarchy in the list.
20087 (ref-level (org-reduced-level (org-outline-level))))
20088 (while (< (point) end)
20089 (let* ((level (org-reduced-level (org-outline-level)))
20090 (delta (max 0 (- level ref-level))))
20091 ;; If current headline is less indented than the first
20092 ;; one, set it as reference, in order to preserve
20093 ;; subtrees.
20094 (when (< level ref-level) (setq ref-level level))
20095 (replace-match bul t t)
20096 (org-indent-line-to (+ start-ind (* delta bul-len)))
20097 ;; Ensure all text down to END (or SECTION-END) belongs
20098 ;; to the newly created item.
20099 (let ((section-end (save-excursion
20100 (or (outline-next-heading) (point)))))
20101 (forward-line)
20102 (funcall shift-text
20103 (+ start-ind (* (1+ delta) bul-len))
20104 (min end section-end)))))))
20105 ;; Case 3. Normal line with ARG: turn each non-item line into
20106 ;; an item.
20107 (arg
20108 (while (< (point) end)
20109 (unless (or (org-at-heading-p) (org-at-item-p))
20110 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20111 (replace-match
20112 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20113 (forward-line)))
20114 ;; Case 4. Normal line without ARG: make the first line of
20115 ;; region an item, and shift indentation of others
20116 ;; lines to set them as item's body.
20117 (t (let* ((bul (org-list-bullet-string "-"))
20118 (bul-len (length bul))
20119 (ref-ind (org-get-indentation)))
20120 (skip-chars-forward " \t")
20121 (insert bul)
20122 (forward-line)
20123 (while (< (point) end)
20124 ;; Ensure that lines less indented than first one
20125 ;; still get included in item body.
20126 (funcall shift-text
20127 (+ ref-ind bul-len)
20128 (min end (save-excursion (or (outline-next-heading)
20129 (point)))))
20130 (forward-line)))))))))
20132 (defun org-toggle-heading (&optional nstars)
20133 "Convert headings to normal text, or items or text to headings.
20134 If there is no active region, only the current line is considered.
20136 With a \\[universal-argument] prefix, convert the whole list at
20137 point into heading.
20139 In a region:
20141 - If the first non blank line is a headline, remove the stars
20142 from all headlines in the region.
20144 - If it is a normal line turn each and every normal line (i.e. not an
20145 heading or an item) in the region into a heading.
20147 - If it is a plain list item, turn all plain list items into headings.
20149 When converting a line into a heading, the number of stars is chosen
20150 such that the lines become children of the current entry. However,
20151 when a prefix argument is given, its value determines the number of
20152 stars to add."
20153 (interactive "P")
20154 (let ((skip-blanks
20155 (function
20156 ;; Return beginning of first non-blank line, starting from
20157 ;; line at POS.
20158 (lambda (pos)
20159 (save-excursion
20160 (goto-char pos)
20161 (while (org-at-comment-p) (forward-line))
20162 (skip-chars-forward " \r\t\n")
20163 (point-at-bol)))))
20164 beg end toggled)
20165 ;; Determine boundaries of changes. If a universal prefix has
20166 ;; been given, put the list in a region. If region ends at a bol,
20167 ;; do not consider the last line to be in the region.
20169 (when (and current-prefix-arg (org-at-item-p))
20170 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20171 (org-mark-element))
20173 (if (org-region-active-p)
20174 (setq beg (funcall skip-blanks (region-beginning))
20175 end (copy-marker (save-excursion
20176 (goto-char (region-end))
20177 (if (bolp) (point) (point-at-eol)))))
20178 (setq beg (funcall skip-blanks (point-at-bol))
20179 end (copy-marker (point-at-eol))))
20180 ;; Ensure inline tasks don't count as headings.
20181 (org-with-limited-levels
20182 (save-excursion
20183 (goto-char beg)
20184 (cond
20185 ;; Case 1. Started at an heading: de-star headings.
20186 ((org-at-heading-p)
20187 (while (< (point) end)
20188 (when (org-at-heading-p t)
20189 (looking-at org-outline-regexp) (replace-match "")
20190 (setq toggled t))
20191 (forward-line)))
20192 ;; Case 2. Started at an item: change items into headlines.
20193 ;; One star will be added by `org-list-to-subtree'.
20194 ((org-at-item-p)
20195 (let* ((stars (make-string
20196 (if nstars
20197 ;; subtract the star that will be added again by
20198 ;; `org-list-to-subtree'
20199 (1- (prefix-numeric-value current-prefix-arg))
20200 (or (org-current-level) 0))
20201 ?*))
20202 (add-stars
20203 (cond (nstars "") ; stars from prefix only
20204 ((equal stars "") "") ; before first heading
20205 (org-odd-levels-only "*") ; inside heading, odd
20206 (t "")))) ; inside heading, oddeven
20207 (while (< (point) end)
20208 (when (org-at-item-p)
20209 ;; Pay attention to cases when region ends before list.
20210 (let* ((struct (org-list-struct))
20211 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20212 (save-restriction
20213 (narrow-to-region (point) list-end)
20214 (insert
20215 (org-list-to-subtree
20216 (org-list-parse-list t)
20217 '(:istart (concat stars add-stars (funcall get-stars depth))
20218 :icount (concat stars add-stars (funcall get-stars depth)))))))
20219 (setq toggled t))
20220 (forward-line))))
20221 ;; Case 3. Started at normal text: make every line an heading,
20222 ;; skipping headlines and items.
20223 (t (let* ((stars (make-string
20224 (if nstars
20225 (prefix-numeric-value current-prefix-arg)
20226 (or (org-current-level) 0))
20227 ?*))
20228 (add-stars
20229 (cond (nstars "") ; stars from prefix only
20230 ((equal stars "") "*") ; before first heading
20231 (org-odd-levels-only "**") ; inside heading, odd
20232 (t "*"))) ; inside heading, oddeven
20233 (rpl (concat stars add-stars " ")))
20234 (while (< (point) end)
20235 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20236 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20237 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20238 (forward-line)))))))
20239 (unless toggled (message "Cannot toggle heading from here"))))
20241 (defun org-meta-return (&optional arg)
20242 "Insert a new heading or wrap a region in a table.
20243 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20244 See the individual commands for more information."
20245 (interactive "P")
20246 (cond
20247 ((run-hook-with-args-until-success 'org-metareturn-hook))
20248 ((or (org-at-drawer-p) (org-at-property-p))
20249 (newline-and-indent))
20250 ((org-at-table-p)
20251 (call-interactively 'org-table-wrap-region))
20252 (t (call-interactively 'org-insert-heading))))
20254 ;;; Menu entries
20256 (defsubst org-in-subtree-not-table-p ()
20257 "Are we in a subtree and not in a table?"
20258 (and (not (org-before-first-heading-p))
20259 (not (org-at-table-p))))
20261 ;; Define the Org-mode menus
20262 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20263 '("Tbl"
20264 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20265 ["Next Field" org-cycle (org-at-table-p)]
20266 ["Previous Field" org-shifttab (org-at-table-p)]
20267 ["Next Row" org-return (org-at-table-p)]
20268 "--"
20269 ["Blank Field" org-table-blank-field (org-at-table-p)]
20270 ["Edit Field" org-table-edit-field (org-at-table-p)]
20271 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20272 "--"
20273 ("Column"
20274 ["Move Column Left" org-metaleft (org-at-table-p)]
20275 ["Move Column Right" org-metaright (org-at-table-p)]
20276 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20277 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20278 ("Row"
20279 ["Move Row Up" org-metaup (org-at-table-p)]
20280 ["Move Row Down" org-metadown (org-at-table-p)]
20281 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20282 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20283 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20284 "--"
20285 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20286 ("Rectangle"
20287 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20288 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20289 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20290 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20291 "--"
20292 ("Calculate"
20293 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20294 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20295 ["Edit Formulas" org-edit-special (org-at-table-p)]
20296 "--"
20297 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20298 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20299 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20300 "--"
20301 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20302 "--"
20303 ["Sum Column/Rectangle" org-table-sum
20304 (or (org-at-table-p) (org-region-active-p))]
20305 ["Which Column?" org-table-current-column (org-at-table-p)])
20306 ["Debug Formulas"
20307 org-table-toggle-formula-debugger
20308 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20309 ["Show Col/Row Numbers"
20310 org-table-toggle-coordinate-overlays
20311 :style toggle
20312 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20313 "--"
20314 ["Create" org-table-create (and (not (org-at-table-p))
20315 org-enable-table-editor)]
20316 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20317 ["Import from File" org-table-import (not (org-at-table-p))]
20318 ["Export to File" org-table-export (org-at-table-p)]
20319 "--"
20320 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20322 (easy-menu-define org-org-menu org-mode-map "Org menu"
20323 '("Org"
20324 ("Show/Hide"
20325 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20326 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20327 ["Sparse Tree..." org-sparse-tree t]
20328 ["Reveal Context" org-reveal t]
20329 ["Show All" show-all t]
20330 "--"
20331 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20332 "--"
20333 ["New Heading" org-insert-heading t]
20334 ("Navigate Headings"
20335 ["Up" outline-up-heading t]
20336 ["Next" outline-next-visible-heading t]
20337 ["Previous" outline-previous-visible-heading t]
20338 ["Next Same Level" outline-forward-same-level t]
20339 ["Previous Same Level" outline-backward-same-level t]
20340 "--"
20341 ["Jump" org-goto t])
20342 ("Edit Structure"
20343 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20344 "--"
20345 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20346 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20347 "--"
20348 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20349 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20350 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20351 "--"
20352 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20353 "--"
20354 ["Copy visible text" org-copy-visible t]
20355 "--"
20356 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20357 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20358 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20359 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20360 "--"
20361 ["Sort Region/Children" org-sort t]
20362 "--"
20363 ["Convert to odd levels" org-convert-to-odd-levels t]
20364 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20365 ("Editing"
20366 ["Emphasis..." org-emphasize t]
20367 ["Edit Source Example" org-edit-special t]
20368 "--"
20369 ["Footnote new/jump" org-footnote-action t]
20370 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20371 ("Archive"
20372 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20373 "--"
20374 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20375 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20376 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20378 "--"
20379 ("Hyperlinks"
20380 ["Store Link (Global)" org-store-link t]
20381 ["Find existing link to here" org-occur-link-in-agenda-files t]
20382 ["Insert Link" org-insert-link t]
20383 ["Follow Link" org-open-at-point t]
20384 "--"
20385 ["Next link" org-next-link t]
20386 ["Previous link" org-previous-link t]
20387 "--"
20388 ["Descriptive Links"
20389 org-toggle-link-display
20390 :style radio
20391 :selected org-descriptive-links
20393 ["Literal Links"
20394 org-toggle-link-display
20395 :style radio
20396 :selected (not org-descriptive-links)])
20397 "--"
20398 ("TODO Lists"
20399 ["TODO/DONE/-" org-todo t]
20400 ("Select keyword"
20401 ["Next keyword" org-shiftright (org-at-heading-p)]
20402 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20403 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20404 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20405 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20406 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20407 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20408 "--"
20409 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20410 :selected org-enforce-todo-dependencies :style toggle :active t]
20411 "Settings for tree at point"
20412 ["Do Children sequentially" org-toggle-ordered-property :style radio
20413 :selected (org-entry-get nil "ORDERED")
20414 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20415 ["Do Children parallel" org-toggle-ordered-property :style radio
20416 :selected (not (org-entry-get nil "ORDERED"))
20417 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20418 "--"
20419 ["Set Priority" org-priority t]
20420 ["Priority Up" org-shiftup t]
20421 ["Priority Down" org-shiftdown t]
20422 "--"
20423 ["Get news from all feeds" org-feed-update-all t]
20424 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20425 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20426 ("TAGS and Properties"
20427 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20428 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20429 "--"
20430 ["Set property" org-set-property (not (org-before-first-heading-p))]
20431 ["Column view of properties" org-columns t]
20432 ["Insert Column View DBlock" org-insert-columns-dblock t])
20433 ("Dates and Scheduling"
20434 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20435 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20436 ("Change Date"
20437 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20438 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20439 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20440 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20441 ["Compute Time Range" org-evaluate-time-range t]
20442 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20443 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20444 "--"
20445 ["Custom time format" org-toggle-time-stamp-overlays
20446 :style radio :selected org-display-custom-times]
20447 "--"
20448 ["Goto Calendar" org-goto-calendar t]
20449 ["Date from Calendar" org-date-from-calendar t]
20450 "--"
20451 ["Start/Restart Timer" org-timer-start t]
20452 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20453 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20454 ["Insert Timer String" org-timer t]
20455 ["Insert Timer Item" org-timer-item t])
20456 ("Logging work"
20457 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20458 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20459 ["Clock out" org-clock-out t]
20460 ["Clock cancel" org-clock-cancel t]
20461 "--"
20462 ["Mark as default task" org-clock-mark-default-task t]
20463 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20464 ["Goto running clock" org-clock-goto t]
20465 "--"
20466 ["Display times" org-clock-display t]
20467 ["Create clock table" org-clock-report t]
20468 "--"
20469 ["Record DONE time"
20470 (progn (setq org-log-done (not org-log-done))
20471 (message "Switching to %s will %s record a timestamp"
20472 (car org-done-keywords)
20473 (if org-log-done "automatically" "not")))
20474 :style toggle :selected org-log-done])
20475 "--"
20476 ["Agenda Command..." org-agenda t]
20477 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20478 ("File List for Agenda")
20479 ("Special views current file"
20480 ["TODO Tree" org-show-todo-tree t]
20481 ["Check Deadlines" org-check-deadlines t]
20482 ["Timeline" org-timeline t]
20483 ["Tags/Property tree" org-match-sparse-tree t])
20484 "--"
20485 ["Export/Publish..." org-export-dispatch t]
20486 ("LaTeX"
20487 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20488 :selected org-cdlatex-mode]
20489 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20490 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20491 ["Modify math symbol" org-cdlatex-math-modify
20492 (org-inside-LaTeX-fragment-p)]
20493 ["Insert citation" org-reftex-citation t]
20494 "--"
20495 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20496 "--"
20497 ("MobileOrg"
20498 ["Push Files and Views" org-mobile-push t]
20499 ["Get Captured and Flagged" org-mobile-pull t]
20500 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20501 "--"
20502 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20503 "--"
20504 ("Documentation"
20505 ["Show Version" org-version t]
20506 ["Info Documentation" org-info t])
20507 ("Customize"
20508 ["Browse Org Group" org-customize t]
20509 "--"
20510 ["Expand This Menu" org-create-customize-menu
20511 (fboundp 'customize-menu-create)])
20512 ["Send bug report" org-submit-bug-report t]
20513 "--"
20514 ("Refresh/Reload"
20515 ["Refresh setup current buffer" org-mode-restart t]
20516 ["Reload Org (after update)" org-reload t]
20517 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20520 (defun org-info (&optional node)
20521 "Read documentation for Org-mode in the info system.
20522 With optional NODE, go directly to that node."
20523 (interactive)
20524 (info (format "(org)%s" (or node ""))))
20526 ;;;###autoload
20527 (defun org-submit-bug-report ()
20528 "Submit a bug report on Org-mode via mail.
20530 Don't hesitate to report any problems or inaccurate documentation.
20532 If you don't have setup sending mail from (X)Emacs, please copy the
20533 output buffer into your mail program, as it gives us important
20534 information about your Org-mode version and configuration."
20535 (interactive)
20536 (require 'reporter)
20537 (org-load-modules-maybe)
20538 (org-require-autoloaded-modules)
20539 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20540 (reporter-submit-bug-report
20541 "emacs-orgmode@gnu.org"
20542 (org-version nil 'full)
20543 (let (list)
20544 (save-window-excursion
20545 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20546 (delete-other-windows)
20547 (erase-buffer)
20548 (insert "You are about to submit a bug report to the Org-mode mailing list.
20550 We would like to add your full Org-mode and Outline configuration to the
20551 bug report. This greatly simplifies the work of the maintainer and
20552 other experts on the mailing list.
20554 HOWEVER, some variables you have customized may contain private
20555 information. The names of customers, colleagues, or friends, might
20556 appear in the form of file names, tags, todo states, or search strings.
20557 If you answer yes to the prompt, you might want to check and remove
20558 such private information before sending the email.")
20559 (add-text-properties (point-min) (point-max) '(face org-warning))
20560 (when (yes-or-no-p "Include your Org-mode configuration ")
20561 (mapatoms
20562 (lambda (v)
20563 (and (boundp v)
20564 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20565 (or (and (symbol-value v)
20566 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20567 (and
20568 (get v 'custom-type) (get v 'standard-value)
20569 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20570 (push v list)))))
20571 (kill-buffer (get-buffer "*Warn about privacy*"))
20572 list))
20573 nil nil
20574 "Remember to cover the basics, that is, what you expected to happen and
20575 what in fact did happen. You don't know how to make a good report? See
20577 http://orgmode.org/manual/Feedback.html#Feedback
20579 Your bug report will be posted to the Org-mode mailing list.
20580 ------------------------------------------------------------------------")
20581 (save-excursion
20582 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20583 (replace-match "\\1Bug: \\3 [\\2]")))))
20586 (defun org-install-agenda-files-menu ()
20587 (let ((bl (buffer-list)))
20588 (save-excursion
20589 (while bl
20590 (set-buffer (pop bl))
20591 (if (derived-mode-p 'org-mode) (setq bl nil)))
20592 (when (derived-mode-p 'org-mode)
20593 (easy-menu-change
20594 '("Org") "File List for Agenda"
20595 (append
20596 (list
20597 ["Edit File List" (org-edit-agenda-file-list) t]
20598 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20599 ["Remove Current File from List" org-remove-file t]
20600 ["Cycle through agenda files" org-cycle-agenda-files t]
20601 ["Occur in all agenda files" org-occur-in-agenda-files t]
20602 "--")
20603 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20605 ;;;; Documentation
20607 (defun org-require-autoloaded-modules ()
20608 (interactive)
20609 (mapc 'require
20610 '(org-agenda org-archive org-attach org-clock org-colview org-id
20611 org-remember org-table org-timer)))
20613 ;;;###autoload
20614 (defun org-reload (&optional uncompiled)
20615 "Reload all org lisp files.
20616 With prefix arg UNCOMPILED, load the uncompiled versions."
20617 (interactive "P")
20618 (require 'loadhist)
20619 (let* ((org-dir (org-find-library-dir "org"))
20620 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20621 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20622 (remove-re (mapconcat 'identity
20623 (mapcar (lambda (f) (concat "^" f "$"))
20624 (list (if (featurep 'xemacs)
20625 "org-colview"
20626 "org-colview-xemacs")
20627 "org" "org-loaddefs" "org-version"))
20628 "\\|"))
20629 (feats (delete-dups
20630 (mapcar 'file-name-sans-extension
20631 (mapcar 'file-name-nondirectory
20632 (delq nil
20633 (mapcar 'feature-file
20634 features))))))
20635 (lfeat (append
20636 (sort
20637 (setq feats
20638 (delq nil (mapcar
20639 (lambda (f)
20640 (if (and (string-match feature-re f)
20641 (not (string-match remove-re f)))
20642 f nil))
20643 feats)))
20644 'string-lessp)
20645 (list "org-version" "org")))
20646 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20647 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20648 load-uncore load-misses)
20649 (setq load-misses
20650 (delq 't
20651 (mapcar (lambda (f)
20652 (or (org-load-noerror-mustsuffix (concat org-dir f))
20653 (and (string= org-dir contrib-dir)
20654 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20655 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20656 (add-to-list 'load-uncore f 'append)
20659 lfeat)))
20660 (if load-uncore
20661 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20662 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20663 (if load-misses
20664 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20665 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20666 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20668 ;;;###autoload
20669 (defun org-customize ()
20670 "Call the customize function with org as argument."
20671 (interactive)
20672 (org-load-modules-maybe)
20673 (org-require-autoloaded-modules)
20674 (customize-browse 'org))
20676 (defun org-create-customize-menu ()
20677 "Create a full customization menu for Org-mode, insert it into the menu."
20678 (interactive)
20679 (org-load-modules-maybe)
20680 (org-require-autoloaded-modules)
20681 (if (fboundp 'customize-menu-create)
20682 (progn
20683 (easy-menu-change
20684 '("Org") "Customize"
20685 `(["Browse Org group" org-customize t]
20686 "--"
20687 ,(customize-menu-create 'org)
20688 ["Set" Custom-set t]
20689 ["Save" Custom-save t]
20690 ["Reset to Current" Custom-reset-current t]
20691 ["Reset to Saved" Custom-reset-saved t]
20692 ["Reset to Standard Settings" Custom-reset-standard t]))
20693 (message "\"Org\"-menu now contains full customization menu"))
20694 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20696 ;;;; Miscellaneous stuff
20698 ;;; Generally useful functions
20700 (defun org-get-at-bol (property)
20701 "Get text property PROPERTY at beginning of line."
20702 (get-text-property (point-at-bol) property))
20704 (defun org-find-text-property-in-string (prop s)
20705 "Return the first non-nil value of property PROP in string S."
20706 (or (get-text-property 0 prop s)
20707 (get-text-property (or (next-single-property-change 0 prop s) 0)
20708 prop s)))
20710 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20711 "Display the given MESSAGE as a warning."
20712 (if (fboundp 'display-warning)
20713 (display-warning 'org message
20714 (if (featurep 'xemacs) 'warning :warning))
20715 (let ((buf (get-buffer-create "*Org warnings*")))
20716 (with-current-buffer buf
20717 (goto-char (point-max))
20718 (insert "Warning (Org): " message)
20719 (unless (bolp)
20720 (newline)))
20721 (display-buffer buf)
20722 (sit-for 0))))
20724 (defun org-eval (form)
20725 "Eval FORM and return result."
20726 (condition-case error
20727 (eval form)
20728 (error (format "%%![Error: %s]" error))))
20730 (defun org-in-clocktable-p ()
20731 "Check if the cursor is in a clocktable."
20732 (let ((pos (point)) start)
20733 (save-excursion
20734 (end-of-line 1)
20735 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20736 (setq start (match-beginning 0))
20737 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20738 (>= (match-end 0) pos)
20739 start))))
20741 (defun org-in-commented-line ()
20742 "Is point in a line starting with `#'?"
20743 (equal (char-after (point-at-bol)) ?#))
20745 (defun org-in-indented-comment-line ()
20746 "Is point in a line starting with `#' after some white space?"
20747 (save-excursion
20748 (save-match-data
20749 (goto-char (point-at-bol))
20750 (looking-at "[ \t]*#"))))
20752 (defun org-in-verbatim-emphasis ()
20753 (save-match-data
20754 (and (org-in-regexp org-emph-re 2)
20755 (>= (point) (match-beginning 3))
20756 (<= (point) (match-end 4))
20757 (member (match-string 3) '("=" "~")))))
20759 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20760 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20761 (if (and marker (marker-buffer marker)
20762 (buffer-live-p (marker-buffer marker)))
20763 (progn
20764 (org-pop-to-buffer-same-window (marker-buffer marker))
20765 (if (or (> marker (point-max)) (< marker (point-min)))
20766 (widen))
20767 (goto-char marker)
20768 (org-show-context 'org-goto))
20769 (if bookmark
20770 (bookmark-jump bookmark)
20771 (error "Cannot find location"))))
20773 (defun org-quote-csv-field (s)
20774 "Quote field for inclusion in CSV material."
20775 (if (string-match "[\",]" s)
20776 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20779 (defun org-force-self-insert (N)
20780 "Needed to enforce self-insert under remapping."
20781 (interactive "p")
20782 (self-insert-command N))
20784 (defun org-string-width (s)
20785 "Compute width of string, ignoring invisible characters.
20786 This ignores character with invisibility property `org-link', and also
20787 characters with property `org-cwidth', because these will become invisible
20788 upon the next fontification round."
20789 (let (b l)
20790 (when (or (eq t buffer-invisibility-spec)
20791 (assq 'org-link buffer-invisibility-spec))
20792 (while (setq b (text-property-any 0 (length s)
20793 'invisible 'org-link s))
20794 (setq s (concat (substring s 0 b)
20795 (substring s (or (next-single-property-change
20796 b 'invisible s) (length s)))))))
20797 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20798 (setq s (concat (substring s 0 b)
20799 (substring s (or (next-single-property-change
20800 b 'org-cwidth s) (length s))))))
20801 (setq l (string-width s) b -1)
20802 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20803 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20806 (defun org-shorten-string (s maxlength)
20807 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20808 If the string is shorter or has length MAXLENGTH, just return the
20809 original string. If it is longer, the functions finds a space in the
20810 string, breaks this string off at that locations and adds three dots
20811 as ellipsis. Including the ellipsis, the string will not be longer
20812 than MAXLENGTH. If finding a good breaking point in the string does
20813 not work, the string is just chopped off in the middle of a word
20814 if necessary."
20815 (if (<= (length s) maxlength)
20817 (let* ((n (max (- maxlength 4) 1))
20818 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20819 (if (string-match re s)
20820 (concat (match-string 1 s) "...")
20821 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20823 (defun org-get-indentation (&optional line)
20824 "Get the indentation of the current line, interpreting tabs.
20825 When LINE is given, assume it represents a line and compute its indentation."
20826 (if line
20827 (if (string-match "^ *" (org-remove-tabs line))
20828 (match-end 0))
20829 (save-excursion
20830 (beginning-of-line 1)
20831 (skip-chars-forward " \t")
20832 (current-column))))
20834 (defun org-get-string-indentation (s)
20835 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20836 (let ((n -1) (i 0) (w tab-width) c)
20837 (catch 'exit
20838 (while (< (setq n (1+ n)) (length s))
20839 (setq c (aref s n))
20840 (cond ((= c ?\ ) (setq i (1+ i)))
20841 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20842 (t (throw 'exit t)))))
20845 (defun org-remove-tabs (s &optional width)
20846 "Replace tabulators in S with spaces.
20847 Assumes that s is a single line, starting in column 0."
20848 (setq width (or width tab-width))
20849 (while (string-match "\t" s)
20850 (setq s (replace-match
20851 (make-string
20852 (- (* width (/ (+ (match-beginning 0) width) width))
20853 (match-beginning 0)) ?\ )
20854 t t s)))
20857 (defun org-fix-indentation (line ind)
20858 "Fix indentation in LINE.
20859 IND is a cons cell with target and minimum indentation.
20860 If the current indentation in LINE is smaller than the minimum,
20861 leave it alone. If it is larger than ind, set it to the target."
20862 (let* ((l (org-remove-tabs line))
20863 (i (org-get-indentation l))
20864 (i1 (car ind)) (i2 (cdr ind)))
20865 (if (>= i i2) (setq l (substring line i2)))
20866 (if (> i1 0)
20867 (concat (make-string i1 ?\ ) l)
20868 l)))
20870 (defun org-remove-indentation (code &optional n)
20871 "Remove the maximum common indentation from the lines in CODE.
20872 N may optionally be the number of spaces to remove."
20873 (with-temp-buffer
20874 (insert code)
20875 (org-do-remove-indentation n)
20876 (buffer-string)))
20878 (defun org-do-remove-indentation (&optional n)
20879 "Remove the maximum common indentation from the buffer."
20880 (untabify (point-min) (point-max))
20881 (let ((min 10000) re)
20882 (if n
20883 (setq min n)
20884 (goto-char (point-min))
20885 (while (re-search-forward "^ *[^ \n]" nil t)
20886 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20887 (unless (or (= min 0) (= min 10000))
20888 (setq re (format "^ \\{%d\\}" min))
20889 (goto-char (point-min))
20890 (while (re-search-forward re nil t)
20891 (replace-match "")
20892 (end-of-line 1))
20893 min)))
20895 (defun org-fill-template (template alist)
20896 "Find each %key of ALIST in TEMPLATE and replace it."
20897 (let ((case-fold-search nil)
20898 entry key value)
20899 (setq alist (sort (copy-sequence alist)
20900 (lambda (a b) (< (length (car a)) (length (car b))))))
20901 (while (setq entry (pop alist))
20902 (setq template
20903 (replace-regexp-in-string
20904 (concat "%" (regexp-quote (car entry)))
20905 (or (cdr entry) "") template t t)))
20906 template))
20908 (defun org-base-buffer (buffer)
20909 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20910 (if (not buffer)
20911 buffer
20912 (or (buffer-base-buffer buffer)
20913 buffer)))
20915 (defun org-trim (s)
20916 "Remove whitespace at beginning and end of string."
20917 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20918 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20921 (defun org-wrap (string &optional width lines)
20922 "Wrap string to either a number of lines, or a width in characters.
20923 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20924 that costs. If there is a word longer than WIDTH, the text is actually
20925 wrapped to the length of that word.
20926 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20927 many lines, whatever width that takes.
20928 The return value is a list of lines, without newlines at the end."
20929 (let* ((words (org-split-string string "[ \t\n]+"))
20930 (maxword (apply 'max (mapcar 'org-string-width words)))
20931 w ll)
20932 (cond (width
20933 (org-do-wrap words (max maxword width)))
20934 (lines
20935 (setq w maxword)
20936 (setq ll (org-do-wrap words maxword))
20937 (if (<= (length ll) lines)
20939 (setq ll words)
20940 (while (> (length ll) lines)
20941 (setq w (1+ w))
20942 (setq ll (org-do-wrap words w)))
20943 ll))
20944 (t (error "Cannot wrap this")))))
20946 (defun org-do-wrap (words width)
20947 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20948 (let (lines line)
20949 (while words
20950 (setq line (pop words))
20951 (while (and words (< (+ (length line) (length (car words))) width))
20952 (setq line (concat line " " (pop words))))
20953 (setq lines (push line lines)))
20954 (nreverse lines)))
20956 (defun org-split-string (string &optional separators)
20957 "Splits STRING into substrings at SEPARATORS.
20958 No empty strings are returned if there are matches at the beginning
20959 and end of string."
20960 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20961 (start 0)
20962 notfirst
20963 (list nil))
20964 (while (and (string-match rexp string
20965 (if (and notfirst
20966 (= start (match-beginning 0))
20967 (< start (length string)))
20968 (1+ start) start))
20969 (< (match-beginning 0) (length string)))
20970 (setq notfirst t)
20971 (or (eq (match-beginning 0) 0)
20972 (and (eq (match-beginning 0) (match-end 0))
20973 (eq (match-beginning 0) start))
20974 (setq list
20975 (cons (substring string start (match-beginning 0))
20976 list)))
20977 (setq start (match-end 0)))
20978 (or (eq start (length string))
20979 (setq list
20980 (cons (substring string start)
20981 list)))
20982 (nreverse list)))
20984 (defun org-quote-vert (s)
20985 "Replace \"|\" with \"\\vert\"."
20986 (while (string-match "|" s)
20987 (setq s (replace-match "\\vert" t t s)))
20990 (defun org-uuidgen-p (s)
20991 "Is S an ID created by UUIDGEN?"
20992 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20994 (defun org-in-src-block-p (&optional inside)
20995 "Whether point is in a code source block.
20996 When INSIDE is non-nil, don't consider we are within a src block
20997 when point is at #+BEGIN_SRC or #+END_SRC."
20998 (let ((case-fold-search t) ov)
20999 (or (and (setq ov (overlays-at (point)))
21000 (memq 'org-block-background
21001 (overlay-properties (car ov))))
21002 (and (not inside)
21003 (save-match-data
21004 (save-excursion
21005 (beginning-of-line)
21006 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21008 (defun org-context ()
21009 "Return a list of contexts of the current cursor position.
21010 If several contexts apply, all are returned.
21011 Each context entry is a list with a symbol naming the context, and
21012 two positions indicating start and end of the context. Possible
21013 contexts are:
21015 :headline anywhere in a headline
21016 :headline-stars on the leading stars in a headline
21017 :todo-keyword on a TODO keyword (including DONE) in a headline
21018 :tags on the TAGS in a headline
21019 :priority on the priority cookie in a headline
21020 :item on the first line of a plain list item
21021 :item-bullet on the bullet/number of a plain list item
21022 :checkbox on the checkbox in a plain list item
21023 :table in an org-mode table
21024 :table-special on a special filed in a table
21025 :table-table in a table.el table
21026 :clocktable in a clocktable
21027 :src-block in a source block
21028 :link on a hyperlink
21029 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21030 :target on a <<target>>
21031 :radio-target on a <<<radio-target>>>
21032 :latex-fragment on a LaTeX fragment
21033 :latex-preview on a LaTeX fragment with overlaid preview image
21035 This function expects the position to be visible because it uses font-lock
21036 faces as a help to recognize the following contexts: :table-special, :link,
21037 and :keyword."
21038 (let* ((f (get-text-property (point) 'face))
21039 (faces (if (listp f) f (list f)))
21040 (case-fold-search t)
21041 (p (point)) clist o)
21042 ;; First the large context
21043 (cond
21044 ((org-at-heading-p t)
21045 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21046 (when (progn
21047 (beginning-of-line 1)
21048 (looking-at org-todo-line-tags-regexp))
21049 (push (org-point-in-group p 1 :headline-stars) clist)
21050 (push (org-point-in-group p 2 :todo-keyword) clist)
21051 (push (org-point-in-group p 4 :tags) clist))
21052 (goto-char p)
21053 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21054 (if (looking-at "\\[#[A-Z0-9]\\]")
21055 (push (org-point-in-group p 0 :priority) clist)))
21057 ((org-at-item-p)
21058 (push (org-point-in-group p 2 :item-bullet) clist)
21059 (push (list :item (point-at-bol)
21060 (save-excursion (org-end-of-item) (point)))
21061 clist)
21062 (and (org-at-item-checkbox-p)
21063 (push (org-point-in-group p 0 :checkbox) clist)))
21065 ((org-at-table-p)
21066 (push (list :table (org-table-begin) (org-table-end)) clist)
21067 (if (memq 'org-formula faces)
21068 (push (list :table-special
21069 (previous-single-property-change p 'face)
21070 (next-single-property-change p 'face)) clist)))
21071 ((org-at-table-p 'any)
21072 (push (list :table-table) clist)))
21073 (goto-char p)
21075 (let ((case-fold-search t))
21076 ;; New the "medium" contexts: clocktables, source blocks
21077 (cond ((org-in-clocktable-p)
21078 (push (list :clocktable
21079 (and (or (looking-at "#\\+BEGIN: clocktable")
21080 (search-backward "#+BEGIN: clocktable" nil t))
21081 (match-beginning 0))
21082 (and (re-search-forward "#\\+END:?" nil t)
21083 (match-end 0))) clist))
21084 ((org-in-src-block-p)
21085 (push (list :src-block
21086 (and (or (looking-at "#\\+BEGIN_SRC")
21087 (search-backward "#+BEGIN_SRC" nil t))
21088 (match-beginning 0))
21089 (and (search-forward "#+END_SRC" nil t)
21090 (match-beginning 0))) clist))))
21091 (goto-char p)
21093 ;; Now the small context
21094 (cond
21095 ((org-at-timestamp-p)
21096 (push (org-point-in-group p 0 :timestamp) clist))
21097 ((memq 'org-link faces)
21098 (push (list :link
21099 (previous-single-property-change p 'face)
21100 (next-single-property-change p 'face)) clist))
21101 ((memq 'org-special-keyword faces)
21102 (push (list :keyword
21103 (previous-single-property-change p 'face)
21104 (next-single-property-change p 'face)) clist))
21105 ((org-at-target-p)
21106 (push (org-point-in-group p 0 :target) clist)
21107 (goto-char (1- (match-beginning 0)))
21108 (if (looking-at org-radio-target-regexp)
21109 (push (org-point-in-group p 0 :radio-target) clist))
21110 (goto-char p))
21111 ((setq o (car (delq nil
21112 (mapcar
21113 (lambda (x)
21114 (if (memq x org-latex-fragment-image-overlays) x))
21115 (overlays-at (point))))))
21116 (push (list :latex-fragment
21117 (overlay-start o) (overlay-end o)) clist)
21118 (push (list :latex-preview
21119 (overlay-start o) (overlay-end o)) clist))
21120 ((org-inside-LaTeX-fragment-p)
21121 ;; FIXME: positions wrong.
21122 (push (list :latex-fragment (point) (point)) clist)))
21124 (setq clist (nreverse (delq nil clist)))
21125 clist))
21127 ;; FIXME: Compare with at-regexp-p Do we need both?
21128 (defun org-in-regexp (re &optional nlines visually)
21129 "Check if point is inside a match of regexp.
21130 Normally only the current line is checked, but you can include NLINES extra
21131 lines both before and after point into the search.
21132 If VISUALLY is set, require that the cursor is not after the match but
21133 really on, so that the block visually is on the match."
21134 (catch 'exit
21135 (let ((pos (point))
21136 (eol (point-at-eol (+ 1 (or nlines 0))))
21137 (inc (if visually 1 0)))
21138 (save-excursion
21139 (beginning-of-line (- 1 (or nlines 0)))
21140 (while (re-search-forward re eol t)
21141 (if (and (<= (match-beginning 0) pos)
21142 (>= (+ inc (match-end 0)) pos))
21143 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21145 (defun org-at-regexp-p (regexp)
21146 "Is point inside a match of REGEXP in the current line?"
21147 (catch 'exit
21148 (save-excursion
21149 (let ((pos (point)) (end (point-at-eol)))
21150 (beginning-of-line 1)
21151 (while (re-search-forward regexp end t)
21152 (if (and (<= (match-beginning 0) pos)
21153 (>= (match-end 0) pos))
21154 (throw 'exit t)))
21155 nil))))
21157 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21158 "Non-nil when point is between matches of START-RE and END-RE.
21160 Also return a non-nil value when point is on one of the matches.
21162 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21163 buffer positions. Default values are the positions of headlines
21164 surrounding the point.
21166 The functions returns a cons cell whose car (resp. cdr) is the
21167 position before START-RE (resp. after END-RE)."
21168 (save-match-data
21169 (let ((pos (point))
21170 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21171 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21172 beg end)
21173 (save-excursion
21174 ;; Point is on a block when on START-RE or if START-RE can be
21175 ;; found before it...
21176 (and (or (org-at-regexp-p start-re)
21177 (re-search-backward start-re limit-up t))
21178 (setq beg (match-beginning 0))
21179 ;; ... and END-RE after it...
21180 (goto-char (match-end 0))
21181 (re-search-forward end-re limit-down t)
21182 (> (setq end (match-end 0)) pos)
21183 ;; ... without another START-RE in-between.
21184 (goto-char (match-beginning 0))
21185 (not (re-search-backward start-re (1+ beg) t))
21186 ;; Return value.
21187 (cons beg end))))))
21189 (defun org-in-block-p (names)
21190 "Non-nil when point belongs to a block whose name belongs to NAMES.
21192 NAMES is a list of strings containing names of blocks.
21194 Return first block name matched, or nil. Beware that in case of
21195 nested blocks, the returned name may not belong to the closest
21196 block from point."
21197 (save-match-data
21198 (catch 'exit
21199 (let ((case-fold-search t)
21200 (lim-up (save-excursion (outline-previous-heading)))
21201 (lim-down (save-excursion (outline-next-heading))))
21202 (mapc (lambda (name)
21203 (let ((n (regexp-quote name)))
21204 (when (org-between-regexps-p
21205 (concat "^[ \t]*#\\+begin_" n)
21206 (concat "^[ \t]*#\\+end_" n)
21207 lim-up lim-down)
21208 (throw 'exit n))))
21209 names))
21210 nil)))
21212 (defun org-occur-in-agenda-files (regexp &optional nlines)
21213 "Call `multi-occur' with buffers for all agenda files."
21214 (interactive "sOrg-files matching: \np")
21215 (let* ((files (org-agenda-files))
21216 (tnames (mapcar 'file-truename files))
21217 (extra org-agenda-text-search-extra-files)
21219 (when (eq (car extra) 'agenda-archives)
21220 (setq extra (cdr extra))
21221 (setq files (org-add-archive-files files)))
21222 (while (setq f (pop extra))
21223 (unless (member (file-truename f) tnames)
21224 (add-to-list 'files f 'append)
21225 (add-to-list 'tnames (file-truename f) 'append)))
21226 (multi-occur
21227 (mapcar (lambda (x)
21228 (with-current-buffer
21229 (or (get-file-buffer x) (find-file-noselect x))
21230 (widen)
21231 (current-buffer)))
21232 files)
21233 regexp)))
21235 (if (boundp 'occur-mode-find-occurrence-hook)
21236 ;; Emacs 23
21237 (add-hook 'occur-mode-find-occurrence-hook
21238 (lambda ()
21239 (when (derived-mode-p 'org-mode)
21240 (org-reveal))))
21241 ;; Emacs 22
21242 (defadvice occur-mode-goto-occurrence
21243 (after org-occur-reveal activate)
21244 (and (derived-mode-p 'org-mode) (org-reveal)))
21245 (defadvice occur-mode-goto-occurrence-other-window
21246 (after org-occur-reveal activate)
21247 (and (derived-mode-p 'org-mode) (org-reveal)))
21248 (defadvice occur-mode-display-occurrence
21249 (after org-occur-reveal activate)
21250 (when (derived-mode-p 'org-mode)
21251 (let ((pos (occur-mode-find-occurrence)))
21252 (with-current-buffer (marker-buffer pos)
21253 (save-excursion
21254 (goto-char pos)
21255 (org-reveal)))))))
21257 (defun org-occur-link-in-agenda-files ()
21258 "Create a link and search for it in the agendas.
21259 The link is not stored in `org-stored-links', it is just created
21260 for the search purpose."
21261 (interactive)
21262 (let ((link (condition-case nil
21263 (org-store-link nil)
21264 (error "Unable to create a link to here"))))
21265 (org-occur-in-agenda-files (regexp-quote link))))
21267 (defun org-reverse-string (string)
21268 "Return the reverse of STRING."
21269 (apply 'string (reverse (string-to-list string))))
21271 (defun org-uniquify (list)
21272 "Remove duplicate elements from LIST."
21273 (let (res)
21274 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21275 res))
21277 (defun org-delete-all (elts list)
21278 "Remove all elements in ELTS from LIST."
21279 (while elts
21280 (setq list (delete (pop elts) list)))
21281 list)
21283 (defun org-count (cl-item cl-seq)
21284 "Count the number of occurrences of ITEM in SEQ.
21285 Taken from `count' in cl-seq.el with all keyword arguments removed."
21286 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21287 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21288 (while (< cl-start cl-end)
21289 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21290 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21291 (setq cl-start (1+ cl-start)))
21292 cl-count))
21294 (defun org-remove-if (predicate seq)
21295 "Remove everything from SEQ that fulfills PREDICATE."
21296 (let (res e)
21297 (while seq
21298 (setq e (pop seq))
21299 (if (not (funcall predicate e)) (push e res)))
21300 (nreverse res)))
21302 (defun org-remove-if-not (predicate seq)
21303 "Remove everything from SEQ that does not fulfill PREDICATE."
21304 (let (res e)
21305 (while seq
21306 (setq e (pop seq))
21307 (if (funcall predicate e) (push e res)))
21308 (nreverse res)))
21310 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21311 "Reduce two-argument FUNCTION across SEQ.
21312 Taken from `reduce' in cl-seq.el with all keyword arguments but
21313 \":initial-value\" removed."
21314 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21315 (cadr (memq :initial-value cl-keys)))
21316 (cl-seq (pop cl-seq))
21317 (t (funcall cl-func)))))
21318 (while cl-seq
21319 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21320 cl-accum))
21322 (defun org-back-over-empty-lines ()
21323 "Move backwards over whitespace, to the beginning of the first empty line.
21324 Returns the number of empty lines passed."
21325 (let ((pos (point)))
21326 (if (cdr (assoc 'heading org-blank-before-new-entry))
21327 (skip-chars-backward " \t\n\r")
21328 (unless (eobp)
21329 (forward-line -1)))
21330 (beginning-of-line 2)
21331 (goto-char (min (point) pos))
21332 (count-lines (point) pos)))
21334 (defun org-skip-whitespace ()
21335 (skip-chars-forward " \t\n\r"))
21337 (defun org-point-in-group (point group &optional context)
21338 "Check if POINT is in match-group GROUP.
21339 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21340 match. If the match group does not exist or point is not inside it,
21341 return nil."
21342 (and (match-beginning group)
21343 (>= point (match-beginning group))
21344 (<= point (match-end group))
21345 (if context
21346 (list context (match-beginning group) (match-end group))
21347 t)))
21349 (defun org-switch-to-buffer-other-window (&rest args)
21350 "Switch to buffer in a second window on the current frame.
21351 In particular, do not allow pop-up frames.
21352 Returns the newly created buffer."
21353 (org-no-popups
21354 (apply 'switch-to-buffer-other-window args)))
21356 (defun org-combine-plists (&rest plists)
21357 "Create a single property list from all plists in PLISTS.
21358 The process starts by copying the first list, and then setting properties
21359 from the other lists. Settings in the last list are the most significant
21360 ones and overrule settings in the other lists."
21361 (let ((rtn (copy-sequence (pop plists)))
21362 p v ls)
21363 (while plists
21364 (setq ls (pop plists))
21365 (while ls
21366 (setq p (pop ls) v (pop ls))
21367 (setq rtn (plist-put rtn p v))))
21368 rtn))
21370 (defun org-replace-escapes (string table)
21371 "Replace %-escapes in STRING with values in TABLE.
21372 TABLE is an association list with keys like \"%a\" and string values.
21373 The sequences in STRING may contain normal field width and padding information,
21374 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21375 so values can contain further %-escapes if they are define later in TABLE."
21376 (let ((tbl (copy-alist table))
21377 (case-fold-search nil)
21378 (pchg 0)
21379 e re rpl)
21380 (while (setq e (pop tbl))
21381 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21382 (when (and (cdr e) (string-match re (cdr e)))
21383 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21384 (safe "SREF"))
21385 (add-text-properties 0 3 (list 'sref sref) safe)
21386 (setcdr e (replace-match safe t t (cdr e)))))
21387 (while (string-match re string)
21388 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21389 (cdr e)))
21390 (setq string (replace-match rpl t t string))))
21391 (while (setq pchg (next-property-change pchg string))
21392 (let ((sref (get-text-property pchg 'sref string)))
21393 (when (and sref (string-match "SREF" string pchg))
21394 (setq string (replace-match sref t t string)))))
21395 string))
21397 (defun org-sublist (list start end)
21398 "Return a section of LIST, from START to END.
21399 Counting starts at 1."
21400 (let (rtn (c start))
21401 (setq list (nthcdr (1- start) list))
21402 (while (and list (<= c end))
21403 (push (pop list) rtn)
21404 (setq c (1+ c)))
21405 (nreverse rtn)))
21407 (defun org-find-base-buffer-visiting (file)
21408 "Like `find-buffer-visiting' but always return the base buffer and
21409 not an indirect buffer."
21410 (let ((buf (or (get-file-buffer file)
21411 (find-buffer-visiting file))))
21412 (if buf
21413 (or (buffer-base-buffer buf) buf)
21414 nil)))
21416 (defun org-image-file-name-regexp (&optional extensions)
21417 "Return regexp matching the file names of images.
21418 If EXTENSIONS is given, only match these."
21419 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21420 (image-file-name-regexp)
21421 (let ((image-file-name-extensions
21422 (or extensions
21423 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21424 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21425 (concat "\\."
21426 (regexp-opt (nconc (mapcar 'upcase
21427 image-file-name-extensions)
21428 image-file-name-extensions)
21430 "\\'"))))
21432 (defun org-file-image-p (file &optional extensions)
21433 "Return non-nil if FILE is an image."
21434 (save-match-data
21435 (string-match (org-image-file-name-regexp extensions) file)))
21437 (defun org-get-cursor-date (&optional with-time)
21438 "Return the date at cursor in as a time.
21439 This works in the calendar and in the agenda, anywhere else it just
21440 returns the current time.
21441 If WITH-TIME is non-nil, returns the time of the event at point (in
21442 the agenda) or the current time of the day."
21443 (let (date day defd tp tm hod mod)
21444 (when with-time
21445 (setq tp (get-text-property (point) 'time))
21446 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21447 (setq hod (string-to-number (match-string 1 tp))
21448 mod (string-to-number (match-string 2 tp))))
21449 (or tp (setq hod (nth 2 (decode-time (current-time)))
21450 mod (nth 1 (decode-time (current-time))))))
21451 (cond
21452 ((eq major-mode 'calendar-mode)
21453 (setq date (calendar-cursor-to-date)
21454 defd (encode-time 0 (or mod 0) (or hod 0)
21455 (nth 1 date) (nth 0 date) (nth 2 date))))
21456 ((eq major-mode 'org-agenda-mode)
21457 (setq day (get-text-property (point) 'day))
21458 (if day
21459 (setq date (calendar-gregorian-from-absolute day)
21460 defd (encode-time 0 (or mod 0) (or hod 0)
21461 (nth 1 date) (nth 0 date) (nth 2 date))))))
21462 (or defd (current-time))))
21464 (defun org-mark-subtree (&optional up)
21465 "Mark the current subtree.
21466 This puts point at the start of the current subtree, and mark at
21467 the end. If a numeric prefix UP is given, move up into the
21468 hierarchy of headlines by UP levels before marking the subtree."
21469 (interactive "P")
21470 (org-with-limited-levels
21471 (cond ((org-at-heading-p) (beginning-of-line))
21472 ((org-before-first-heading-p) (error "Not in a subtree"))
21473 (t (outline-previous-visible-heading 1))))
21474 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21475 (if (org-called-interactively-p 'any)
21476 (call-interactively 'org-mark-element)
21477 (org-mark-element)))
21480 ;;; Indentation
21482 (defun org-indent-line ()
21483 "Indent line depending on context."
21484 (interactive)
21485 (let* ((pos (point))
21486 (itemp (org-at-item-p))
21487 (case-fold-search t)
21488 (org-drawer-regexp (or org-drawer-regexp "\000"))
21489 (inline-task-p (and (featurep 'org-inlinetask)
21490 (org-inlinetask-in-task-p)))
21491 (inline-re (and inline-task-p
21492 (org-inlinetask-outline-regexp)))
21493 column)
21494 (if (and orgstruct-is-++ (eq pos (point)))
21495 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21496 (indent-according-to-mode))
21497 (beginning-of-line 1)
21498 (cond
21499 ;; Headings
21500 ((looking-at org-outline-regexp) (setq column 0))
21501 ;; Footnote definition
21502 ((looking-at org-footnote-definition-re) (setq column 0))
21503 ;; Literal examples
21504 ((looking-at "[ \t]*:\\( \\|$\\)")
21505 (setq column (org-get-indentation))) ; do nothing
21506 ;; Lists
21507 ((ignore-errors (goto-char (org-in-item-p)))
21508 (setq column (if itemp
21509 (org-get-indentation)
21510 (org-list-item-body-column (point))))
21511 (goto-char pos))
21512 ;; Drawers
21513 ((and (looking-at "[ \t]*:END:")
21514 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21515 (save-excursion
21516 (goto-char (1- (match-beginning 1)))
21517 (setq column (current-column))))
21518 ;; Special blocks
21519 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21520 (save-excursion
21521 (re-search-backward
21522 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21523 (setq column (org-get-indentation (match-string 0))))
21524 ((and (not (looking-at "[ \t]*#\\+begin_"))
21525 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21526 (save-excursion
21527 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21528 (setq column
21529 (cond ((equal (downcase (match-string 1)) "src")
21530 ;; src blocks: let `org-edit-src-exit' handle them
21531 (org-get-indentation))
21532 ((equal (downcase (match-string 1)) "example")
21533 (max (org-get-indentation)
21534 (org-get-indentation (match-string 0))))
21536 (org-get-indentation (match-string 0))))))
21537 ;; This line has nothing special, look at the previous relevant
21538 ;; line to compute indentation
21540 (beginning-of-line 0)
21541 (while (and (not (bobp))
21542 (not (looking-at org-table-line-regexp))
21543 (not (looking-at org-drawer-regexp))
21544 ;; When point started in an inline task, do not move
21545 ;; above task starting line.
21546 (not (and inline-task-p (looking-at inline-re)))
21547 ;; Skip drawers, blocks, empty lines, verbatim,
21548 ;; comments, tables, footnotes definitions, lists,
21549 ;; inline tasks.
21550 (or (and (looking-at "[ \t]*:END:")
21551 (re-search-backward org-drawer-regexp nil t))
21552 (and (looking-at "[ \t]*#\\+end_")
21553 (re-search-backward "[ \t]*#\\+begin_"nil t))
21554 (looking-at "[ \t]*[\n:#|]")
21555 (looking-at org-footnote-definition-re)
21556 (and (ignore-errors (goto-char (org-in-item-p)))
21557 (goto-char
21558 (org-list-get-top-point (org-list-struct))))
21559 (and (not inline-task-p)
21560 (featurep 'org-inlinetask)
21561 (org-inlinetask-in-task-p)
21562 (or (org-inlinetask-goto-beginning) t))))
21563 (beginning-of-line 0))
21564 (cond
21565 ;; There was an heading above.
21566 ((looking-at "\\*+[ \t]+")
21567 (if (not org-adapt-indentation)
21568 (setq column 0)
21569 (goto-char (match-end 0))
21570 (setq column (current-column))))
21571 ;; A drawer had started and is unfinished
21572 ((looking-at org-drawer-regexp)
21573 (goto-char (1- (match-beginning 1)))
21574 (setq column (current-column)))
21575 ;; Else, nothing noticeable found: get indentation and go on.
21576 (t (setq column (org-get-indentation))))))
21577 ;; Now apply indentation and move cursor accordingly
21578 (goto-char pos)
21579 (if (<= (current-column) (current-indentation))
21580 (org-indent-line-to column)
21581 (save-excursion (org-indent-line-to column)))
21582 ;; Special polishing for properties, see `org-property-format'
21583 (setq column (current-column))
21584 (beginning-of-line 1)
21585 (if (looking-at
21586 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21587 (replace-match (concat (match-string 1)
21588 (format org-property-format
21589 (match-string 2) (match-string 3)))
21590 t t))
21591 (org-move-to-column column))))
21593 (defun org-indent-drawer ()
21594 "Indent the drawer at point."
21595 (interactive)
21596 (let ((p (point))
21597 (e (and (save-excursion (re-search-forward ":END:" nil t))
21598 (match-end 0)))
21599 (folded
21600 (save-excursion
21601 (end-of-line)
21602 (when (overlays-at (point))
21603 (member 'invisible (overlay-properties
21604 (car (overlays-at (point)))))))))
21605 (when folded (org-cycle))
21606 (indent-for-tab-command)
21607 (while (and (move-beginning-of-line 2) (< (point) e))
21608 (indent-for-tab-command))
21609 (goto-char p)
21610 (when folded (org-cycle)))
21611 (message "Drawer at point indented"))
21613 (defun org-indent-block ()
21614 "Indent the block at point."
21615 (interactive)
21616 (let ((p (point))
21617 (case-fold-search t)
21618 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21619 (match-end 0)))
21620 (folded
21621 (save-excursion
21622 (end-of-line)
21623 (when (overlays-at (point))
21624 (member 'invisible (overlay-properties
21625 (car (overlays-at (point)))))))))
21626 (when folded (org-cycle))
21627 (indent-for-tab-command)
21628 (while (and (move-beginning-of-line 2) (< (point) e))
21629 (indent-for-tab-command))
21630 (goto-char p)
21631 (when folded (org-cycle)))
21632 (message "Block at point indented"))
21634 (defun org-indent-region (start end)
21635 "Indent region."
21636 (interactive "r")
21637 (save-excursion
21638 (let ((line-end (org-current-line end)))
21639 (goto-char start)
21640 (while (< (org-current-line) line-end)
21641 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21642 (t (call-interactively 'org-indent-line)))
21643 (move-beginning-of-line 2)))))
21646 ;;; Filling
21648 ;; We use our own fill-paragraph and auto-fill functions.
21650 ;; `org-fill-paragraph' relies on adaptive filling and context
21651 ;; checking. Appropriate `fill-prefix' is computed with
21652 ;; `org-adaptive-fill-function'.
21654 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21655 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21656 ;; `org-adaptive-fill-function' value. Internally,
21657 ;; `org-comment-line-break-function' breaks the line.
21659 ;; `org-setup-filling' installs filling and auto-filling related
21660 ;; variables during `org-mode' initialization.
21662 (defun org-setup-filling ()
21663 (interactive)
21664 ;; Prevent auto-fill from inserting unwanted new items.
21665 (when (boundp 'fill-nobreak-predicate)
21666 (org-set-local
21667 'fill-nobreak-predicate
21668 (org-uniquify
21669 (append fill-nobreak-predicate
21670 '(org-fill-paragraph-separate-nobreak-p
21671 org-fill-line-break-nobreak-p
21672 org-fill-paragraph-with-timestamp-nobreak-p)))))
21673 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21674 (org-set-local 'auto-fill-inhibit-regexp nil)
21675 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21676 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21677 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21679 (defvar org-element-paragraph-separate) ; org-element.el
21680 (defun org-fill-paragraph-separate-nobreak-p ()
21681 "Non-nil when a line break at point would insert a new item."
21682 (looking-at (substring org-element-paragraph-separate 1)))
21684 (defun org-fill-line-break-nobreak-p ()
21685 "Non-nil when a line break at point would create an Org line break."
21686 (save-excursion
21687 (skip-chars-backward "[ \t]")
21688 (skip-chars-backward "\\\\")
21689 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21691 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21692 "Non-nil when a line break at point would insert a new item."
21693 (and (org-at-timestamp-p t)
21694 (not (looking-at org-ts-regexp-both))))
21696 (declare-function message-in-body-p "message" ())
21697 (defvar orgtbl-line-start-regexp) ; From org-table.el
21698 (defun org-adaptive-fill-function ()
21699 "Compute a fill prefix for the current line.
21700 Return fill prefix, as a string, or nil if current line isn't
21701 meant to be filled."
21702 (let (prefix)
21703 (catch 'exit
21704 (when (derived-mode-p 'message-mode)
21705 (save-excursion
21706 (beginning-of-line)
21707 (cond ((or (not (message-in-body-p))
21708 (looking-at orgtbl-line-start-regexp))
21709 (throw 'exit nil))
21710 ((looking-at message-cite-prefix-regexp)
21711 (throw 'exit (match-string-no-properties 0)))
21712 ((looking-at org-outline-regexp)
21713 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21714 (org-with-wide-buffer
21715 (let* ((p (line-beginning-position))
21716 (element (save-excursion (beginning-of-line)
21717 (org-element-at-point)))
21718 (type (org-element-type element))
21719 (post-affiliated (org-element-property :post-affiliated element)))
21720 (unless (and post-affiliated (< p post-affiliated))
21721 (case type
21722 (comment (looking-at "[ \t]*# ?") (match-string 0))
21723 (footnote-definition "")
21724 ((item plain-list)
21725 (make-string (org-list-item-body-column
21726 (or post-affiliated
21727 (org-element-property :begin element)))
21728 ? ))
21729 (paragraph
21730 ;; Fill prefix is usually the same as the current line,
21731 ;; except if the paragraph is at the beginning of an item.
21732 (let ((parent (org-element-property :parent element)))
21733 (cond ((eq (org-element-type parent) 'item)
21734 (make-string (org-list-item-body-column
21735 (org-element-property :begin parent))
21736 ? ))
21737 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21738 (match-string 0))
21739 (t ""))))
21740 (comment-block
21741 ;; Only fill contents if P is within block boundaries.
21742 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21743 (forward-line)
21744 (point)))
21745 (cend (save-excursion
21746 (goto-char (org-element-property :end element))
21747 (skip-chars-backward " \r\t\n")
21748 (line-beginning-position))))
21749 (when (and (>= p cbeg) (< p cend))
21750 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21751 (match-string 0)
21752 "")))))))))))
21754 (declare-function message-goto-body "message" ())
21755 (defvar message-cite-prefix-regexp) ; From message.el
21756 (defvar org-element-all-successors) ; From org-element.el
21757 (defun org-fill-paragraph (&optional justify)
21758 "Fill element at point, when applicable.
21760 This function only applies to comment blocks, comments, example
21761 blocks and paragraphs. Also, as a special case, re-align table
21762 when point is at one.
21764 If JUSTIFY is non-nil (interactively, with prefix argument),
21765 justify as well. If `sentence-end-double-space' is non-nil, then
21766 period followed by one space does not end a sentence, so don't
21767 break a line there. The variable `fill-column' controls the
21768 width for filling.
21770 For convenience, when point is at a plain list, an item or
21771 a footnote definition, try to fill the first paragraph within."
21772 (interactive)
21773 (if (and (derived-mode-p 'message-mode)
21774 (or (not (message-in-body-p))
21775 (save-excursion (move-beginning-of-line 1)
21776 (looking-at message-cite-prefix-regexp))))
21777 ;; First ensure filling is correct in message-mode.
21778 (let ((fill-paragraph-function
21779 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21780 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21781 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21782 (paragraph-separate
21783 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21784 (fill-paragraph nil))
21785 (with-syntax-table org-mode-transpose-word-syntax-table
21786 ;; Move to end of line in order to get the first paragraph
21787 ;; within a plain list or a footnote definition.
21788 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21789 ;; First check if point is in a blank line at the beginning of
21790 ;; the buffer. In that case, ignore filling.
21791 (case (org-element-type element)
21792 ;; Use major mode filling function is src blocks.
21793 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21794 ;; Align Org tables, leave table.el tables as-is.
21795 (table-row (org-table-align) t)
21796 (table
21797 (when (eq (org-element-property :type element) 'org)
21798 (org-table-align))
21800 (paragraph
21801 ;; Paragraphs may contain `line-break' type objects.
21802 (let ((beg (max (point-min)
21803 (org-element-property :contents-begin element)))
21804 (end (min (point-max)
21805 (org-element-property :contents-end element))))
21806 ;; Do nothing if point is at an affiliated keyword.
21807 (if (< (line-end-position) beg) t
21808 (when (derived-mode-p 'message-mode)
21809 ;; In `message-mode', do not fill following citation
21810 ;; in current paragraph nor text before message body.
21811 (let ((body-start (save-excursion (message-goto-body))))
21812 (when body-start (setq beg (max body-start beg))))
21813 (when (save-excursion
21814 (re-search-forward
21815 (concat "^" message-cite-prefix-regexp) end t))
21816 (setq end (match-beginning 0))))
21817 ;; Fill paragraph, taking line breaks into account.
21818 ;; For that, slice the paragraph using line breaks as
21819 ;; separators, and fill the parts in reverse order to
21820 ;; avoid messing with markers.
21821 (save-excursion
21822 (goto-char end)
21823 (mapc
21824 (lambda (pos)
21825 (fill-region-as-paragraph pos (point) justify)
21826 (goto-char pos))
21827 ;; Find the list of ending positions for line breaks
21828 ;; in the current paragraph. Add paragraph
21829 ;; beginning to include first slice.
21830 (nreverse
21831 (cons beg
21832 (org-element-map
21833 (org-element--parse-objects
21834 beg end nil org-element-all-successors)
21835 'line-break
21836 (lambda (lb) (org-element-property :end lb)))))))
21837 t)))
21838 ;; Contents of `comment-block' type elements should be
21839 ;; filled as plain text, but only if point is within block
21840 ;; markers.
21841 (comment-block
21842 (let* ((case-fold-search t)
21843 (beg (save-excursion
21844 (goto-char (org-element-property :begin element))
21845 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21846 (forward-line)
21847 (point)))
21848 (end (save-excursion
21849 (goto-char (org-element-property :end element))
21850 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21851 (line-beginning-position))))
21852 (when (and (>= (point) beg) (< (point) end))
21853 (fill-region-as-paragraph
21854 (save-excursion
21855 (end-of-line)
21856 (re-search-backward "^[ \t]*$" beg 'move)
21857 (line-beginning-position))
21858 (save-excursion
21859 (beginning-of-line)
21860 (re-search-forward "^[ \t]*$" end 'move)
21861 (line-beginning-position))
21862 justify)))
21864 ;; Fill comments.
21865 (comment (fill-comment-paragraph justify))
21866 ;; Ignore every other element.
21867 (otherwise t))))))
21869 (defun org-auto-fill-function ()
21870 "Auto-fill function."
21871 ;; Check if auto-filling is meaningful.
21872 (let ((fc (current-fill-column)))
21873 (when (and fc (> (current-column) fc))
21874 (let* ((fill-prefix (org-adaptive-fill-function))
21875 ;; Enforce empty fill prefix, if required. Otherwise, it
21876 ;; will be computed again.
21877 (adaptive-fill-mode (not (equal fill-prefix ""))))
21878 (when fill-prefix (do-auto-fill))))))
21880 (defun org-comment-line-break-function (&optional soft)
21881 "Break line at point and indent, continuing comment if within one.
21882 The inserted newline is marked hard if variable
21883 `use-hard-newlines' is true, unless optional argument SOFT is
21884 non-nil."
21885 (if soft (insert-and-inherit ?\n) (newline 1))
21886 (save-excursion (forward-char -1) (delete-horizontal-space))
21887 (delete-horizontal-space)
21888 (indent-to-left-margin)
21889 (insert-before-markers-and-inherit fill-prefix))
21892 ;;; Comments
21894 ;; Org comments syntax is quite complex. It requires the entire line
21895 ;; to be just a comment. Also, even with the right syntax at the
21896 ;; beginning of line, some some elements (i.e. verse-block or
21897 ;; example-block) don't accept comments. Usual Emacs comment commands
21898 ;; cannot cope with those requirements. Therefore, Org replaces them.
21900 ;; Org still relies on `comment-dwim', but cannot trust
21901 ;; `comment-only-p'. So, `comment-region-function' and
21902 ;; `uncomment-region-function' both point
21903 ;; to`org-comment-or-uncomment-region'. Eventually,
21904 ;; `org-insert-comment' takes care of insertion of comments at the
21905 ;; beginning of line.
21907 ;; `org-setup-comments-handling' install comments related variables
21908 ;; during `org-mode' initialization.
21910 (defun org-setup-comments-handling ()
21911 (interactive)
21912 (org-set-local 'comment-use-syntax nil)
21913 (org-set-local 'comment-start "# ")
21914 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21915 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21916 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21917 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21919 (defun org-insert-comment ()
21920 "Insert an empty comment above current line.
21921 If the line is empty, insert comment at its beginning."
21922 (beginning-of-line)
21923 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21924 (org-indent-line)
21925 (insert "# "))
21927 (defvar comment-empty-lines) ; From newcomment.el.
21928 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21929 "Comment or uncomment each non-blank line in the region.
21930 Uncomment each non-blank line between BEG and END if it only
21931 contains commented lines. Otherwise, comment them."
21932 (save-restriction
21933 ;; Restrict region
21934 (narrow-to-region (save-excursion (goto-char beg)
21935 (skip-chars-forward " \r\t\n" end)
21936 (line-beginning-position))
21937 (save-excursion (goto-char end)
21938 (skip-chars-backward " \r\t\n" beg)
21939 (line-end-position)))
21940 (let ((uncommentp
21941 ;; UNCOMMENTP is non-nil when every non blank line between
21942 ;; BEG and END is a comment.
21943 (save-excursion
21944 (goto-char (point-min))
21945 (while (and (not (eobp))
21946 (let ((element (org-element-at-point)))
21947 (and (eq (org-element-type element) 'comment)
21948 (goto-char (min (point-max)
21949 (org-element-property
21950 :end element)))))))
21951 (eobp))))
21952 (if uncommentp
21953 ;; Only blank lines and comments in region: uncomment it.
21954 (save-excursion
21955 (goto-char (point-min))
21956 (while (not (eobp))
21957 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21958 (replace-match "" nil nil nil 1))
21959 (forward-line)))
21960 ;; Comment each line in region.
21961 (let ((min-indent (point-max)))
21962 ;; First find the minimum indentation across all lines.
21963 (save-excursion
21964 (goto-char (point-min))
21965 (while (and (not (eobp)) (not (zerop min-indent)))
21966 (unless (looking-at "[ \t]*$")
21967 (setq min-indent (min min-indent (current-indentation))))
21968 (forward-line)))
21969 ;; Then loop over all lines.
21970 (save-excursion
21971 (goto-char (point-min))
21972 (while (not (eobp))
21973 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21974 (org-move-to-column min-indent t)
21975 (insert comment-start))
21976 (forward-line))))))))
21979 ;;; Planning
21981 ;; This section contains tools to operate on timestamp objects, as
21982 ;; returned by, e.g. `org-element-context'.
21984 (defun org-timestamp-has-time-p (timestamp)
21985 "Non-nil when TIMESTAMP has a time specified."
21986 (org-element-property :hour-start timestamp))
21988 (defun org-timestamp-format (timestamp format &optional end utc)
21989 "Format a TIMESTAMP element into a string.
21991 FORMAT is a format specifier to be passed to
21992 `format-time-string'.
21994 When optional argument END is non-nil, use end of date-range or
21995 time-range, if possible.
21997 When optional argument UTC is non-nil, time will be expressed as
21998 Universal Time."
21999 (format-time-string
22000 format
22001 (apply 'encode-time
22002 (cons 0
22003 (mapcar
22004 (lambda (prop) (or (org-element-property prop timestamp) 0))
22005 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22006 '(:minute-start :hour-start :day-start :month-start
22007 :year-start)))))
22008 utc))
22010 (defun org-timestamp-split-range (timestamp &optional end)
22011 "Extract a timestamp object from a date or time range.
22013 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22014 the end of the range. Otherwise, extract its start.
22016 Return a new timestamp object sharing the same parent as
22017 TIMESTAMP."
22018 (let ((type (org-element-property :type timestamp)))
22019 (if (memq type '(active inactive diary)) timestamp
22020 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22021 ;; Set new type.
22022 (org-element-put-property
22023 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22024 ;; Copy start properties over end properties if END is
22025 ;; non-nil. Otherwise, copy end properties over `start' ones.
22026 (let ((p-alist '((:minute-start . :minute-end)
22027 (:hour-start . :hour-end)
22028 (:day-start . :day-end)
22029 (:month-start . :month-end)
22030 (:year-start . :year-end))))
22031 (dolist (p-cell p-alist)
22032 (org-element-put-property
22033 split-ts
22034 (funcall (if end 'car 'cdr) p-cell)
22035 (org-element-property
22036 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22037 ;; Eventually refresh `:raw-value'.
22038 (org-element-put-property split-ts :raw-value nil)
22039 (org-element-put-property
22040 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22042 (defun org-timestamp-translate (timestamp &optional boundary)
22043 "Apply `org-translate-time' on a TIMESTAMP object.
22044 When optional argument BOUNDARY is non-nil, it is either the
22045 symbol `start' or `end'. In this case, only translate the
22046 starting or ending part of TIMESTAMP if it is a date or time
22047 range. Otherwise, translate both parts."
22048 (if (and (not boundary)
22049 (memq (org-element-property :type timestamp)
22050 '(active-range inactive-range)))
22051 (concat
22052 (org-translate-time
22053 (org-element-property :raw-value
22054 (org-timestamp-split-range timestamp)))
22055 "--"
22056 (org-translate-time
22057 (org-element-property :raw-value
22058 (org-timestamp-split-range timestamp t))))
22059 (org-translate-time
22060 (org-element-property
22061 :raw-value
22062 (if (not boundary) timestamp
22063 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22067 ;;; Other stuff.
22069 (defun org-toggle-fixed-width-section (arg)
22070 "Toggle the fixed-width export.
22071 If there is no active region, the QUOTE keyword at the current headline is
22072 inserted or removed. When present, it causes the text between this headline
22073 and the next to be exported as fixed-width text, and unmodified.
22074 If there is an active region, this command adds or removes a colon as the
22075 first character of this line. If the first character of a line is a colon,
22076 this line is also exported in fixed-width font."
22077 (interactive "P")
22078 (let* ((cc 0)
22079 (regionp (org-region-active-p))
22080 (beg (if regionp (region-beginning) (point)))
22081 (end (if regionp (region-end)))
22082 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22083 (case-fold-search nil)
22084 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22085 off)
22086 (if regionp
22087 (save-excursion
22088 (goto-char beg)
22089 (setq cc (current-column))
22090 (beginning-of-line 1)
22091 (setq off (looking-at re))
22092 (while (> nlines 0)
22093 (setq nlines (1- nlines))
22094 (beginning-of-line 1)
22095 (cond
22096 (arg
22097 (org-move-to-column cc t)
22098 (insert ": \n")
22099 (forward-line -1))
22100 ((and off (looking-at re))
22101 (replace-match "" t t nil 1))
22102 ((not off) (org-move-to-column cc t) (insert ": ")))
22103 (forward-line 1)))
22104 (save-excursion
22105 (org-back-to-heading)
22106 (cond
22107 ((looking-at (format org-heading-keyword-regexp-format
22108 org-quote-string))
22109 (goto-char (match-end 1))
22110 (looking-at (concat " +" org-quote-string))
22111 (replace-match "" t t)
22112 (when (eolp) (insert " ")))
22113 ((looking-at org-outline-regexp)
22114 (goto-char (match-end 0))
22115 (insert org-quote-string " ")))))))
22117 (defun org-reftex-citation ()
22118 "Use reftex-citation to insert a citation into the buffer.
22119 This looks for a line like
22121 #+BIBLIOGRAPHY: foo plain option:-d
22123 and derives from it that foo.bib is the bibliography file relevant
22124 for this document. It then installs the necessary environment for RefTeX
22125 to work in this buffer and calls `reftex-citation' to insert a citation
22126 into the buffer.
22128 Export of such citations to both LaTeX and HTML is handled by the contributed
22129 package org-exp-bibtex by Taru Karttunen."
22130 (interactive)
22131 (let ((reftex-docstruct-symbol 'rds)
22132 (reftex-cite-format "\\cite{%l}")
22133 rds bib)
22134 (save-excursion
22135 (save-restriction
22136 (widen)
22137 (let ((case-fold-search t)
22138 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22139 (if (not (save-excursion
22140 (or (re-search-forward re nil t)
22141 (re-search-backward re nil t))))
22142 (error "No bibliography defined in file")
22143 (setq bib (concat (match-string 1) ".bib")
22144 rds (list (list 'bib bib)))))))
22145 (call-interactively 'reftex-citation)))
22147 ;;;; Functions extending outline functionality
22149 (defun org-beginning-of-line (&optional arg)
22150 "Go to the beginning of the current line. If that is invisible, continue
22151 to a visible line beginning. This makes the function of C-a more intuitive.
22152 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22153 first attempt, and only move to after the tags when the cursor is already
22154 beyond the end of the headline."
22155 (interactive "P")
22156 (let ((pos (point))
22157 (special (if (consp org-special-ctrl-a/e)
22158 (car org-special-ctrl-a/e)
22159 org-special-ctrl-a/e))
22160 refpos)
22161 (if (org-bound-and-true-p visual-line-mode)
22162 (beginning-of-visual-line 1)
22163 (beginning-of-line 1))
22164 (if (and arg (fboundp 'move-beginning-of-line))
22165 (call-interactively 'move-beginning-of-line)
22166 (if (bobp)
22168 (backward-char 1)
22169 (if (org-truely-invisible-p)
22170 (while (and (not (bobp)) (org-truely-invisible-p))
22171 (backward-char 1)
22172 (beginning-of-line 1))
22173 (forward-char 1))))
22174 (when special
22175 (cond
22176 ((and (looking-at org-complex-heading-regexp)
22177 (= (char-after (match-end 1)) ?\ ))
22178 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22179 (point-at-eol)))
22180 (goto-char
22181 (if (eq special t)
22182 (cond ((> pos refpos) refpos)
22183 ((= pos (point)) refpos)
22184 (t (point)))
22185 (cond ((> pos (point)) (point))
22186 ((not (eq last-command this-command)) (point))
22187 (t refpos)))))
22188 ((org-at-item-p)
22189 ;; Being at an item and not looking at an the item means point
22190 ;; was previously moved to beginning of a visual line, which
22191 ;; doesn't contain the item. Therefore, do nothing special,
22192 ;; just stay here.
22193 (when (looking-at org-list-full-item-re)
22194 ;; Set special position at first white space character after
22195 ;; bullet, and check-box, if any.
22196 (let ((after-bullet
22197 (let ((box (match-end 3)))
22198 (if (not box) (match-end 1)
22199 (let ((after (char-after box)))
22200 (if (and after (= after ? )) (1+ box) box))))))
22201 ;; Special case: Move point to special position when
22202 ;; currently after it or at beginning of line.
22203 (if (eq special t)
22204 (when (or (> pos after-bullet) (= (point) pos))
22205 (goto-char after-bullet))
22206 ;; Reversed case: Move point to special position when
22207 ;; point was already at beginning of line and command is
22208 ;; repeated.
22209 (when (and (= (point) pos) (eq last-command this-command))
22210 (goto-char after-bullet))))))))
22211 (org-no-warnings
22212 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22214 (defun org-end-of-line (&optional arg)
22215 "Go to the end of the line.
22216 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22217 tags on the first attempt, and only move to after the tags when
22218 the cursor is already beyond the end of the headline."
22219 (interactive "P")
22220 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22221 org-special-ctrl-a/e))
22222 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22223 'end-of-visual-line)
22224 ((fboundp 'move-end-of-line) 'move-end-of-line)
22225 (t 'end-of-line))))
22226 (if (or (not special) arg) (call-interactively move-fun)
22227 (let* ((element (save-excursion (beginning-of-line)
22228 (org-element-at-point)))
22229 (type (org-element-type element)))
22230 (cond
22231 ((memq type '(headline inlinetask))
22232 (let ((pos (point)))
22233 (beginning-of-line 1)
22234 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22235 (if (eq special t)
22236 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22237 (goto-char (match-beginning 1))
22238 (goto-char (match-end 0)))
22239 (if (or (< pos (match-end 0))
22240 (not (eq this-command last-command)))
22241 (goto-char (match-end 0))
22242 (goto-char (match-beginning 1))))
22243 (call-interactively move-fun))))
22244 ((org-element-property :hiddenp element)
22245 ;; If element is hidden, `move-end-of-line' would put point
22246 ;; after it. Use `end-of-line' to stay on current line.
22247 (call-interactively 'end-of-line))
22248 (t (call-interactively move-fun)))))
22249 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22251 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22252 (define-key org-mode-map "\C-e" 'org-end-of-line)
22254 (defun org-backward-sentence (&optional arg)
22255 "Go to beginning of sentence, or beginning of table field.
22256 This will call `backward-sentence' or `org-table-beginning-of-field',
22257 depending on context."
22258 (interactive "P")
22259 (cond
22260 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22261 (t (call-interactively 'backward-sentence))))
22263 (defun org-forward-sentence (&optional arg)
22264 "Go to end of sentence, or end of table field.
22265 This will call `forward-sentence' or `org-table-end-of-field',
22266 depending on context."
22267 (interactive "P")
22268 (cond
22269 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22270 (t (call-interactively 'forward-sentence))))
22272 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22273 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22275 (defun org-kill-line (&optional arg)
22276 "Kill line, to tags or end of line."
22277 (interactive "P")
22278 (cond
22279 ((or (not org-special-ctrl-k)
22280 (bolp)
22281 (not (org-at-heading-p)))
22282 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22283 org-ctrl-k-protect-subtree)
22284 (if (or (eq org-ctrl-k-protect-subtree 'error)
22285 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22286 (error "C-k aborted - would kill hidden subtree")))
22287 (call-interactively
22288 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22289 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22290 (kill-region (point) (match-beginning 1))
22291 (org-set-tags nil t))
22292 (t (kill-region (point) (point-at-eol)))))
22294 (define-key org-mode-map "\C-k" 'org-kill-line)
22296 (defun org-yank (&optional arg)
22297 "Yank. If the kill is a subtree, treat it specially.
22298 This command will look at the current kill and check if is a single
22299 subtree, or a series of subtrees[1]. If it passes the test, and if the
22300 cursor is at the beginning of a line or after the stars of a currently
22301 empty headline, then the yank is handled specially. How exactly depends
22302 on the value of the following variables, both set by default.
22304 org-yank-folded-subtrees
22305 When set, the subtree(s) will be folded after insertion, but only
22306 if doing so would now swallow text after the yanked text.
22308 org-yank-adjusted-subtrees
22309 When set, the subtree will be promoted or demoted in order to
22310 fit into the local outline tree structure, which means that the level
22311 will be adjusted so that it becomes the smaller one of the two
22312 *visible* surrounding headings.
22314 Any prefix to this command will cause `yank' to be called directly with
22315 no special treatment. In particular, a simple \\[universal-argument] prefix \
22316 will just
22317 plainly yank the text as it is.
22319 \[1] The test checks if the first non-white line is a heading
22320 and if there are no other headings with fewer stars."
22321 (interactive "P")
22322 (org-yank-generic 'yank arg))
22324 (defun org-yank-generic (command arg)
22325 "Perform some yank-like command.
22327 This function implements the behavior described in the `org-yank'
22328 documentation. However, it has been generalized to work for any
22329 interactive command with similar behavior."
22331 ;; pretend to be command COMMAND
22332 (setq this-command command)
22334 (if arg
22335 (call-interactively command)
22337 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22338 (and (org-kill-is-subtree-p)
22339 (or (bolp)
22340 (and (looking-at "[ \t]*$")
22341 (string-match
22342 "\\`\\*+\\'"
22343 (buffer-substring (point-at-bol) (point)))))))
22344 swallowp)
22345 (cond
22346 ((and subtreep org-yank-folded-subtrees)
22347 (let ((beg (point))
22348 end)
22349 (if (and subtreep org-yank-adjusted-subtrees)
22350 (org-paste-subtree nil nil 'for-yank)
22351 (call-interactively command))
22353 (setq end (point))
22354 (goto-char beg)
22355 (when (and (bolp) subtreep
22356 (not (setq swallowp
22357 (org-yank-folding-would-swallow-text beg end))))
22358 (org-with-limited-levels
22359 (or (looking-at org-outline-regexp)
22360 (re-search-forward org-outline-regexp-bol end t))
22361 (while (and (< (point) end) (looking-at org-outline-regexp))
22362 (hide-subtree)
22363 (org-cycle-show-empty-lines 'folded)
22364 (condition-case nil
22365 (outline-forward-same-level 1)
22366 (error (goto-char end))))))
22367 (when swallowp
22368 (message
22369 "Inserted text not folded because that would swallow text"))
22371 (goto-char end)
22372 (skip-chars-forward " \t\n\r")
22373 (beginning-of-line 1)
22374 (push-mark beg 'nomsg)))
22375 ((and subtreep org-yank-adjusted-subtrees)
22376 (let ((beg (point-at-bol)))
22377 (org-paste-subtree nil nil 'for-yank)
22378 (push-mark beg 'nomsg)))
22380 (call-interactively command))))))
22382 (defun org-yank-folding-would-swallow-text (beg end)
22383 "Would hide-subtree at BEG swallow any text after END?"
22384 (let (level)
22385 (org-with-limited-levels
22386 (save-excursion
22387 (goto-char beg)
22388 (when (or (looking-at org-outline-regexp)
22389 (re-search-forward org-outline-regexp-bol end t))
22390 (setq level (org-outline-level)))
22391 (goto-char end)
22392 (skip-chars-forward " \t\r\n\v\f")
22393 (if (or (eobp)
22394 (and (bolp) (looking-at org-outline-regexp)
22395 (<= (org-outline-level) level)))
22396 nil ; Nothing would be swallowed
22397 t))))) ; something would swallow
22399 (define-key org-mode-map "\C-y" 'org-yank)
22401 (defun org-truely-invisible-p ()
22402 "Check if point is at a character currently not visible.
22403 This version does not only check the character property, but also
22404 `visible-mode'."
22405 ;; Early versions of noutline don't have `outline-invisible-p'.
22406 (if (org-bound-and-true-p visible-mode)
22408 (outline-invisible-p)))
22410 (defun org-invisible-p2 ()
22411 "Check if point is at a character currently not visible."
22412 (save-excursion
22413 (if (and (eolp) (not (bobp))) (backward-char 1))
22414 ;; Early versions of noutline don't have `outline-invisible-p'.
22415 (outline-invisible-p)))
22417 (defun org-back-to-heading (&optional invisible-ok)
22418 "Call `outline-back-to-heading', but provide a better error message."
22419 (condition-case nil
22420 (outline-back-to-heading invisible-ok)
22421 (error (error "Before first headline at position %d in buffer %s"
22422 (point) (current-buffer)))))
22424 (defun org-before-first-heading-p ()
22425 "Before first heading?"
22426 (save-excursion
22427 (end-of-line)
22428 (null (re-search-backward org-outline-regexp-bol nil t))))
22430 (defun org-at-heading-p (&optional ignored)
22431 (outline-on-heading-p t))
22432 ;; Compatibility alias with Org versions < 7.8.03
22433 (defalias 'org-on-heading-p 'org-at-heading-p)
22435 (defun org-at-comment-p nil
22436 "Is cursor in a line starting with a # character?"
22437 (save-excursion
22438 (beginning-of-line)
22439 (looking-at "^#")))
22441 (defun org-at-drawer-p nil
22442 "Is cursor at a drawer keyword?"
22443 (save-excursion
22444 (move-beginning-of-line 1)
22445 (looking-at org-drawer-regexp)))
22447 (defun org-at-block-p nil
22448 "Is cursor at a block keyword?"
22449 (save-excursion
22450 (move-beginning-of-line 1)
22451 (looking-at org-block-regexp)))
22453 (defun org-point-at-end-of-empty-headline ()
22454 "If point is at the end of an empty headline, return t, else nil.
22455 If the heading only contains a TODO keyword, it is still still considered
22456 empty."
22457 (and (looking-at "[ \t]*$")
22458 (when org-todo-line-regexp
22459 (save-excursion
22460 (beginning-of-line 1)
22461 (let ((case-fold-search nil))
22462 (looking-at org-todo-line-regexp)
22463 (string= (match-string 3) ""))))))
22465 (defun org-at-heading-or-item-p ()
22466 (or (org-at-heading-p) (org-at-item-p)))
22468 (defun org-at-target-p ()
22469 (or (org-in-regexp org-radio-target-regexp)
22470 (org-in-regexp org-target-regexp)))
22471 ;; Compatibility alias with Org versions < 7.8.03
22472 (defalias 'org-on-target-p 'org-at-target-p)
22474 (defun org-up-heading-all (arg)
22475 "Move to the heading line of which the present line is a subheading.
22476 This function considers both visible and invisible heading lines.
22477 With argument, move up ARG levels."
22478 (if (fboundp 'outline-up-heading-all)
22479 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22480 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22482 (defun org-up-heading-safe ()
22483 "Move to the heading line of which the present line is a subheading.
22484 This version will not throw an error. It will return the level of the
22485 headline found, or nil if no higher level is found.
22487 Also, this function will be a lot faster than `outline-up-heading',
22488 because it relies on stars being the outline starters. This can really
22489 make a significant difference in outlines with very many siblings."
22490 (let (start-level re)
22491 (org-back-to-heading t)
22492 (setq start-level (funcall outline-level))
22493 (if (equal start-level 1)
22495 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22496 (if (re-search-backward re nil t)
22497 (funcall outline-level)))))
22499 (defun org-first-sibling-p ()
22500 "Is this heading the first child of its parents?"
22501 (interactive)
22502 (let ((re org-outline-regexp-bol)
22503 level l)
22504 (unless (org-at-heading-p t)
22505 (error "Not at a heading"))
22506 (setq level (funcall outline-level))
22507 (save-excursion
22508 (if (not (re-search-backward re nil t))
22510 (setq l (funcall outline-level))
22511 (< l level)))))
22513 (defun org-goto-sibling (&optional previous)
22514 "Goto the next sibling, even if it is invisible.
22515 When PREVIOUS is set, go to the previous sibling instead. Returns t
22516 when a sibling was found. When none is found, return nil and don't
22517 move point."
22518 (let ((fun (if previous 're-search-backward 're-search-forward))
22519 (pos (point))
22520 (re org-outline-regexp-bol)
22521 level l)
22522 (when (condition-case nil (org-back-to-heading t) (error nil))
22523 (setq level (funcall outline-level))
22524 (catch 'exit
22525 (or previous (forward-char 1))
22526 (while (funcall fun re nil t)
22527 (setq l (funcall outline-level))
22528 (when (< l level) (goto-char pos) (throw 'exit nil))
22529 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22530 (goto-char pos)
22531 nil))))
22533 (defun org-show-siblings ()
22534 "Show all siblings of the current headline."
22535 (save-excursion
22536 (while (org-goto-sibling) (org-flag-heading nil)))
22537 (save-excursion
22538 (while (org-goto-sibling 'previous)
22539 (org-flag-heading nil))))
22541 (defun org-goto-first-child ()
22542 "Goto the first child, even if it is invisible.
22543 Return t when a child was found. Otherwise don't move point and
22544 return nil."
22545 (let (level (pos (point)) (re org-outline-regexp-bol))
22546 (when (condition-case nil (org-back-to-heading t) (error nil))
22547 (setq level (outline-level))
22548 (forward-char 1)
22549 (if (and (re-search-forward re nil t) (> (outline-level) level))
22550 (progn (goto-char (match-beginning 0)) t)
22551 (goto-char pos) nil))))
22553 (defun org-show-hidden-entry ()
22554 "Show an entry where even the heading is hidden."
22555 (save-excursion
22556 (org-show-entry)))
22558 (defun org-flag-heading (flag &optional entry)
22559 "Flag the current heading. FLAG non-nil means make invisible.
22560 When ENTRY is non-nil, show the entire entry."
22561 (save-excursion
22562 (org-back-to-heading t)
22563 ;; Check if we should show the entire entry
22564 (if entry
22565 (progn
22566 (org-show-entry)
22567 (save-excursion
22568 (and (outline-next-heading)
22569 (org-flag-heading nil))))
22570 (outline-flag-region (max (point-min) (1- (point)))
22571 (save-excursion (outline-end-of-heading) (point))
22572 flag))))
22574 (defun org-get-next-sibling ()
22575 "Move to next heading of the same level, and return point.
22576 If there is no such heading, return nil.
22577 This is like outline-next-sibling, but invisible headings are ok."
22578 (let ((level (funcall outline-level)))
22579 (outline-next-heading)
22580 (while (and (not (eobp)) (> (funcall outline-level) level))
22581 (outline-next-heading))
22582 (if (or (eobp) (< (funcall outline-level) level))
22584 (point))))
22586 (defun org-get-last-sibling ()
22587 "Move to previous heading of the same level, and return point.
22588 If there is no such heading, return nil."
22589 (let ((opoint (point))
22590 (level (funcall outline-level)))
22591 (outline-previous-heading)
22592 (when (and (/= (point) opoint) (outline-on-heading-p t))
22593 (while (and (> (funcall outline-level) level)
22594 (not (bobp)))
22595 (outline-previous-heading))
22596 (if (< (funcall outline-level) level)
22598 (point)))))
22600 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22601 "Goto to the end of a subtree."
22602 ;; This contains an exact copy of the original function, but it uses
22603 ;; `org-back-to-heading', to make it work also in invisible
22604 ;; trees. And is uses an invisible-ok argument.
22605 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22606 ;; Furthermore, when used inside Org, finding the end of a large subtree
22607 ;; with many children and grandchildren etc, this can be much faster
22608 ;; than the outline version.
22609 (org-back-to-heading invisible-ok)
22610 (let ((first t)
22611 (level (funcall outline-level)))
22612 (if (and (derived-mode-p 'org-mode) (< level 1000))
22613 ;; A true heading (not a plain list item), in Org-mode
22614 ;; This means we can easily find the end by looking
22615 ;; only for the right number of stars. Using a regexp to do
22616 ;; this is so much faster than using a Lisp loop.
22617 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22618 (forward-char 1)
22619 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22620 ;; something else, do it the slow way
22621 (while (and (not (eobp))
22622 (or first (> (funcall outline-level) level)))
22623 (setq first nil)
22624 (outline-next-heading)))
22625 (unless to-heading
22626 (if (memq (preceding-char) '(?\n ?\^M))
22627 (progn
22628 ;; Go to end of line before heading
22629 (forward-char -1)
22630 (if (memq (preceding-char) '(?\n ?\^M))
22631 ;; leave blank line before heading
22632 (forward-char -1))))))
22633 (point))
22635 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22636 "Use Org version in org-mode, for dramatic speed-up."
22637 (if (derived-mode-p 'org-mode)
22638 (progn
22639 (org-end-of-subtree nil t)
22640 (unless (eobp) (backward-char 1)))
22641 ad-do-it))
22643 (defun org-end-of-meta-data-and-drawers ()
22644 "Jump to the first text after meta data and drawers in the current entry.
22645 This will move over empty lines, lines with planning time stamps,
22646 clocking lines, and drawers."
22647 (org-back-to-heading t)
22648 (let ((end (save-excursion (outline-next-heading) (point)))
22649 (re (concat "\\(" org-drawer-regexp "\\)"
22650 "\\|" "[ \t]*" org-keyword-time-regexp)))
22651 (forward-line 1)
22652 (while (re-search-forward re end t)
22653 (if (not (match-end 1))
22654 ;; empty or planning line
22655 (forward-line 1)
22656 ;; a drawer, find the end
22657 (re-search-forward "^[ \t]*:END:" end 'move)
22658 (forward-line 1)))
22659 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22660 (point)))
22662 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22663 "Move forward to the ARG'th subheading at same level as this one.
22664 Stop at the first and last subheadings of a superior heading.
22665 Normally this only looks at visible headings, but when INVISIBLE-OK is
22666 non-nil it will also look at invisible ones."
22667 (interactive "p")
22668 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22669 (if (and arg (< arg 0))
22670 (goto-char (point-min))
22671 (outline-next-heading))
22672 (org-at-heading-p)
22673 (let ((level (- (match-end 0) (match-beginning 0) 1))
22674 (f (if (and arg (< arg 0))
22675 're-search-backward
22676 're-search-forward))
22677 (count (if arg (abs arg) 1))
22678 (result (point)))
22679 (forward-char (if (and arg (< arg 0)) -1 1))
22680 (while (and (> count 0)
22681 (funcall f org-outline-regexp-bol nil 'move))
22682 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22683 (cond ((< l level) (setq count 0))
22684 ((and (= l level)
22685 (or invisible-ok
22686 (progn
22687 (goto-char (line-beginning-position))
22688 (not (outline-invisible-p)))))
22689 (setq count (1- count))
22690 (when (eq l level)
22691 (setq result (point)))))))
22692 (goto-char result))
22693 (beginning-of-line 1)))
22695 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22696 "Move backward to the ARG'th subheading at same level as this one.
22697 Stop at the first and last subheadings of a superior heading."
22698 (interactive "p")
22699 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22701 (defun org-next-block (arg &optional backward block-regexp)
22702 "Jump to the next block.
22703 With a prefix argument ARG, jump forward ARG many source blocks.
22704 When BACKWARD is non-nil, jump to the previous block.
22705 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22706 (interactive "p")
22707 (let ((re (or block-regexp org-block-regexp))
22708 (re-search-fn (or (and backward 're-search-backward)
22709 're-search-forward)))
22710 (if (looking-at re) (forward-char 1))
22711 (condition-case nil
22712 (funcall re-search-fn re nil nil arg)
22713 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22714 (goto-char (match-beginning 0)) (org-show-context)))
22716 (defun org-previous-block (arg &optional block-regexp)
22717 "Jump to the previous block.
22718 With a prefix argument ARG, jump backward ARG many source blocks.
22719 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22720 (interactive "p")
22721 (org-next-block arg t block-regexp))
22723 (defun org-forward-element ()
22724 "Move forward by one element.
22725 Move to the next element at the same level, when possible."
22726 (interactive)
22727 (cond ((eobp) (user-error "Cannot move further down"))
22728 ((org-with-limited-levels (org-at-heading-p))
22729 (let ((origin (point)))
22730 (goto-char (org-end-of-subtree nil t))
22731 (unless (org-with-limited-levels (org-at-heading-p))
22732 (goto-char origin)
22733 (user-error "Cannot move further down"))))
22735 (let* ((elem (org-element-at-point))
22736 (end (org-element-property :end elem))
22737 (parent (org-element-property :parent elem)))
22738 (if (and parent (= (org-element-property :contents-end parent) end))
22739 (goto-char (org-element-property :end parent))
22740 (goto-char end))))))
22742 (defun org-backward-element ()
22743 "Move backward by one element.
22744 Move to the previous element at the same level, when possible."
22745 (interactive)
22746 (cond ((bobp) (user-error "Cannot move further up"))
22747 ((org-with-limited-levels (org-at-heading-p))
22748 ;; At a headline, move to the previous one, if any, or stay
22749 ;; here.
22750 (let ((origin (point)))
22751 (org-with-limited-levels (org-backward-heading-same-level 1))
22752 ;; When current headline has no sibling above, move to its
22753 ;; parent.
22754 (when (= (point) origin)
22755 (or (org-with-limited-levels (org-up-heading-safe))
22756 (progn (goto-char origin)
22757 (user-error "Cannot move further up"))))))
22759 (let* ((trail (org-element-at-point 'keep-trail))
22760 (elem (car trail))
22761 (prev-elem (nth 1 trail))
22762 (beg (org-element-property :begin elem)))
22763 (cond
22764 ;; Move to beginning of current element if point isn't
22765 ;; there already.
22766 ((/= (point) beg) (goto-char beg))
22767 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22768 ((org-before-first-heading-p) (goto-char (point-min)))
22769 (t (org-back-to-heading)))))))
22771 (defun org-up-element ()
22772 "Move to upper element."
22773 (interactive)
22774 (if (org-with-limited-levels (org-at-heading-p))
22775 (unless (org-up-heading-safe) (error "No surrounding element"))
22776 (let* ((elem (org-element-at-point))
22777 (parent (org-element-property :parent elem)))
22778 (if parent (goto-char (org-element-property :begin parent))
22779 (if (org-with-limited-levels (org-before-first-heading-p))
22780 (error "No surrounding element")
22781 (org-with-limited-levels (org-back-to-heading)))))))
22783 (defvar org-element-greater-elements)
22784 (defun org-down-element ()
22785 "Move to inner element."
22786 (interactive)
22787 (let ((element (org-element-at-point)))
22788 (cond
22789 ((memq (org-element-type element) '(plain-list table))
22790 (goto-char (org-element-property :contents-begin element))
22791 (forward-char))
22792 ((memq (org-element-type element) org-element-greater-elements)
22793 ;; If contents are hidden, first disclose them.
22794 (when (org-element-property :hiddenp element) (org-cycle))
22795 (goto-char (or (org-element-property :contents-begin element)
22796 (error "No content for this element"))))
22797 (t (error "No inner element")))))
22799 (defun org-drag-element-backward ()
22800 "Move backward element at point."
22801 (interactive)
22802 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22803 (let* ((trail (org-element-at-point 'keep-trail))
22804 (elem (car trail))
22805 (prev-elem (nth 1 trail)))
22806 ;; Error out if no previous element or previous element is
22807 ;; a parent of the current one.
22808 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22809 (error "Cannot drag element backward")
22810 (let ((pos (point)))
22811 (org-element-swap-A-B prev-elem elem)
22812 (goto-char (+ (org-element-property :begin prev-elem)
22813 (- pos (org-element-property :begin elem)))))))))
22815 (defun org-drag-element-forward ()
22816 "Move forward element at point."
22817 (interactive)
22818 (let* ((pos (point))
22819 (elem (org-element-at-point)))
22820 (when (= (point-max) (org-element-property :end elem))
22821 (error "Cannot drag element forward"))
22822 (goto-char (org-element-property :end elem))
22823 (let ((next-elem (org-element-at-point)))
22824 (when (or (org-element-nested-p elem next-elem)
22825 (and (eq (org-element-type next-elem) 'headline)
22826 (not (eq (org-element-type elem) 'headline))))
22827 (goto-char pos)
22828 (error "Cannot drag element forward"))
22829 ;; Compute new position of point: it's shifted by NEXT-ELEM
22830 ;; body's length (without final blanks) and by the length of
22831 ;; blanks between ELEM and NEXT-ELEM.
22832 (let ((size-next (- (save-excursion
22833 (goto-char (org-element-property :end next-elem))
22834 (skip-chars-backward " \r\t\n")
22835 (forward-line)
22836 ;; Small correction if buffer doesn't end
22837 ;; with a newline character.
22838 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22839 (org-element-property :begin next-elem)))
22840 (size-blank (- (org-element-property :end elem)
22841 (save-excursion
22842 (goto-char (org-element-property :end elem))
22843 (skip-chars-backward " \r\t\n")
22844 (forward-line)
22845 (point)))))
22846 (org-element-swap-A-B elem next-elem)
22847 (goto-char (+ pos size-next size-blank))))))
22849 (defun org-drag-line-forward (arg)
22850 "Drag the line at point ARG lines forward."
22851 (interactive "p")
22852 (dotimes (n (abs arg))
22853 (let ((c (current-column)))
22854 (if (< 0 arg)
22855 (progn
22856 (beginning-of-line 2)
22857 (transpose-lines 1)
22858 (beginning-of-line 0))
22859 (transpose-lines 1)
22860 (beginning-of-line -1))
22861 (org-move-to-column c))))
22863 (defun org-drag-line-backward (arg)
22864 "Drag the line at point ARG lines backward."
22865 (interactive "p")
22866 (org-drag-line-forward (- arg)))
22868 (defun org-mark-element ()
22869 "Put point at beginning of this element, mark at end.
22871 Interactively, if this command is repeated or (in Transient Mark
22872 mode) if the mark is active, it marks the next element after the
22873 ones already marked."
22874 (interactive)
22875 (let (deactivate-mark)
22876 (if (and (org-called-interactively-p 'any)
22877 (or (and (eq last-command this-command) (mark t))
22878 (and transient-mark-mode mark-active)))
22879 (set-mark
22880 (save-excursion
22881 (goto-char (mark))
22882 (goto-char (org-element-property :end (org-element-at-point)))))
22883 (let ((element (org-element-at-point)))
22884 (end-of-line)
22885 (push-mark (org-element-property :end element) t t)
22886 (goto-char (org-element-property :begin element))))))
22888 (defun org-narrow-to-element ()
22889 "Narrow buffer to current element."
22890 (interactive)
22891 (let ((elem (org-element-at-point)))
22892 (cond
22893 ((eq (car elem) 'headline)
22894 (narrow-to-region
22895 (org-element-property :begin elem)
22896 (org-element-property :end elem)))
22897 ((memq (car elem) org-element-greater-elements)
22898 (narrow-to-region
22899 (org-element-property :contents-begin elem)
22900 (org-element-property :contents-end elem)))
22902 (narrow-to-region
22903 (org-element-property :begin elem)
22904 (org-element-property :end elem))))))
22906 (defun org-transpose-element ()
22907 "Transpose current and previous elements, keeping blank lines between.
22908 Point is moved after both elements."
22909 (interactive)
22910 (org-skip-whitespace)
22911 (let ((end (org-element-property :end (org-element-at-point))))
22912 (org-drag-element-backward)
22913 (goto-char end)))
22915 (defun org-unindent-buffer ()
22916 "Un-indent the visible part of the buffer.
22917 Relative indentation (between items, inside blocks, etc.) isn't
22918 modified."
22919 (interactive)
22920 (unless (eq major-mode 'org-mode)
22921 (error "Cannot un-indent a buffer not in Org mode"))
22922 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22923 unindent-tree ; For byte-compiler.
22924 (unindent-tree
22925 (function
22926 (lambda (contents)
22927 (mapc
22928 (lambda (element)
22929 (if (memq (org-element-type element) '(headline section))
22930 (funcall unindent-tree (org-element-contents element))
22931 (save-excursion
22932 (save-restriction
22933 (narrow-to-region
22934 (org-element-property :begin element)
22935 (org-element-property :end element))
22936 (org-do-remove-indentation)))))
22937 (reverse contents))))))
22938 (funcall unindent-tree (org-element-contents parse-tree))))
22940 (defun org-show-subtree ()
22941 "Show everything after this heading at deeper levels."
22942 (interactive)
22943 (outline-flag-region
22944 (point)
22945 (save-excursion
22946 (org-end-of-subtree t t))
22947 nil))
22949 (defun org-show-entry ()
22950 "Show the body directly following this heading.
22951 Show the heading too, if it is currently invisible."
22952 (interactive)
22953 (save-excursion
22954 (condition-case nil
22955 (progn
22956 (org-back-to-heading t)
22957 (outline-flag-region
22958 (max (point-min) (1- (point)))
22959 (save-excursion
22960 (if (re-search-forward
22961 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22962 (match-beginning 1)
22963 (point-max)))
22964 nil)
22965 (org-cycle-hide-drawers 'children))
22966 (error nil))))
22968 (defun org-make-options-regexp (kwds &optional extra)
22969 "Make a regular expression for keyword lines."
22970 (concat
22971 "^#\\+\\("
22972 (mapconcat 'regexp-quote kwds "\\|")
22973 (if extra (concat "\\|" extra))
22974 "\\):[ \t]*\\(.*\\)"))
22976 ;; Make isearch reveal the necessary context
22977 (defun org-isearch-end ()
22978 "Reveal context after isearch exits."
22979 (when isearch-success ; only if search was successful
22980 (if (featurep 'xemacs)
22981 ;; Under XEmacs, the hook is run in the correct place,
22982 ;; we directly show the context.
22983 (org-show-context 'isearch)
22984 ;; In Emacs the hook runs *before* restoring the overlays.
22985 ;; So we have to use a one-time post-command-hook to do this.
22986 ;; (Emacs 22 has a special variable, see function `org-mode')
22987 (unless (and (boundp 'isearch-mode-end-hook-quit)
22988 isearch-mode-end-hook-quit)
22989 ;; Only when the isearch was not quitted.
22990 (org-add-hook 'post-command-hook 'org-isearch-post-command
22991 'append 'local)))
22992 (org-fix-ellipsis-at-bol)))
22994 (defun org-isearch-post-command ()
22995 "Remove self from hook, and show context."
22996 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22997 (org-show-context 'isearch))
23000 ;;;; Integration with and fixes for other packages
23002 ;;; Imenu support
23004 (defvar org-imenu-markers nil
23005 "All markers currently used by Imenu.")
23006 (make-variable-buffer-local 'org-imenu-markers)
23008 (defun org-imenu-new-marker (&optional pos)
23009 "Return a new marker for use by Imenu, and remember the marker."
23010 (let ((m (make-marker)))
23011 (move-marker m (or pos (point)))
23012 (push m org-imenu-markers)
23015 (defun org-imenu-get-tree ()
23016 "Produce the index for Imenu."
23017 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23018 (setq org-imenu-markers nil)
23019 (let* ((n org-imenu-depth)
23020 (re (concat "^" (org-get-limited-outline-regexp)))
23021 (subs (make-vector (1+ n) nil))
23022 (last-level 0)
23023 m level head0 head)
23024 (save-excursion
23025 (save-restriction
23026 (widen)
23027 (goto-char (point-max))
23028 (while (re-search-backward re nil t)
23029 (setq level (org-reduced-level (funcall outline-level)))
23030 (when (and (<= level n)
23031 (looking-at org-complex-heading-regexp)
23032 (setq head0 (org-match-string-no-properties 4)))
23033 (setq head (org-link-display-format head0)
23034 m (org-imenu-new-marker))
23035 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23036 (if (>= level last-level)
23037 (push (cons head m) (aref subs level))
23038 (push (cons head (aref subs (1+ level))) (aref subs level))
23039 (loop for i from (1+ level) to n do (aset subs i nil)))
23040 (setq last-level level)))))
23041 (aref subs 1)))
23043 (eval-after-load "imenu"
23044 '(progn
23045 (add-hook 'imenu-after-jump-hook
23046 (lambda ()
23047 (if (derived-mode-p 'org-mode)
23048 (org-show-context 'org-goto))))))
23050 (defun org-link-display-format (link)
23051 "Replace a link with either the description, or the link target
23052 if no description is present"
23053 (save-match-data
23054 (if (string-match org-bracket-link-analytic-regexp link)
23055 (replace-match (if (match-end 5)
23056 (match-string 5 link)
23057 (concat (match-string 1 link)
23058 (match-string 3 link)))
23059 nil t link)
23060 link)))
23062 (defun org-toggle-link-display ()
23063 "Toggle the literal or descriptive display of links."
23064 (interactive)
23065 (if org-descriptive-links
23066 (progn (org-remove-from-invisibility-spec '(org-link))
23067 (org-restart-font-lock)
23068 (setq org-descriptive-links nil))
23069 (progn (add-to-invisibility-spec '(org-link))
23070 (org-restart-font-lock)
23071 (setq org-descriptive-links t))))
23073 ;; Speedbar support
23075 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23076 "Overlay marking the agenda restriction line in speedbar.")
23077 (overlay-put org-speedbar-restriction-lock-overlay
23078 'face 'org-agenda-restriction-lock)
23079 (overlay-put org-speedbar-restriction-lock-overlay
23080 'help-echo "Agendas are currently limited to this item.")
23081 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23083 (defun org-speedbar-set-agenda-restriction ()
23084 "Restrict future agenda commands to the location at point in speedbar.
23085 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23086 (interactive)
23087 (require 'org-agenda)
23088 (let (p m tp np dir txt)
23089 (cond
23090 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23091 'org-imenu t))
23092 (setq m (get-text-property p 'org-imenu-marker))
23093 (with-current-buffer (marker-buffer m)
23094 (goto-char m)
23095 (org-agenda-set-restriction-lock 'subtree)))
23096 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23097 'speedbar-function 'speedbar-find-file))
23098 (setq tp (previous-single-property-change
23099 (1+ p) 'speedbar-function)
23100 np (next-single-property-change
23101 tp 'speedbar-function)
23102 dir (speedbar-line-directory)
23103 txt (buffer-substring-no-properties (or tp (point-min))
23104 (or np (point-max))))
23105 (with-current-buffer (find-file-noselect
23106 (let ((default-directory dir))
23107 (expand-file-name txt)))
23108 (unless (derived-mode-p 'org-mode)
23109 (error "Cannot restrict to non-Org-mode file"))
23110 (org-agenda-set-restriction-lock 'file)))
23111 (t (error "Don't know how to restrict Org-mode's agenda")))
23112 (move-overlay org-speedbar-restriction-lock-overlay
23113 (point-at-bol) (point-at-eol))
23114 (setq current-prefix-arg nil)
23115 (org-agenda-maybe-redo)))
23117 (eval-after-load "speedbar"
23118 '(progn
23119 (speedbar-add-supported-extension ".org")
23120 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23121 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23122 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23123 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23124 (add-hook 'speedbar-visiting-tag-hook
23125 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23127 ;;; Fixes and Hacks for problems with other packages
23129 ;; Make flyspell not check words in links, to not mess up our keymap
23130 (defvar org-element-affiliated-keywords) ; From org-element.el
23131 (defvar org-element-block-name-alist) ; From org-element.el
23132 (defun org-mode-flyspell-verify ()
23133 "Don't let flyspell put overlays at active buttons, or on
23134 {todo,all-time,additional-option-like}-keywords."
23135 (let ((pos (max (1- (point)) (point-min)))
23136 (word (thing-at-point 'word)))
23137 (and (not (get-text-property pos 'keymap))
23138 (not (get-text-property pos 'org-no-flyspell))
23139 (not (member word org-todo-keywords-1))
23140 (not (member word org-all-time-keywords))
23141 (not (member word org-options-keywords))
23142 (not (member word (mapcar 'car org-startup-options)))
23143 (not (member-ignore-case word org-element-affiliated-keywords))
23144 (not (member-ignore-case word (org-get-export-keywords)))
23145 (not (member-ignore-case
23146 word (mapcar 'car org-element-block-name-alist)))
23147 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23149 (defun org-remove-flyspell-overlays-in (beg end)
23150 "Remove flyspell overlays in region."
23151 (and (org-bound-and-true-p flyspell-mode)
23152 (fboundp 'flyspell-delete-region-overlays)
23153 (flyspell-delete-region-overlays beg end))
23154 (add-text-properties beg end '(org-no-flyspell t)))
23156 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23157 (eval-after-load "bookmark"
23158 '(if (boundp 'bookmark-after-jump-hook)
23159 ;; We can use the hook
23160 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23161 ;; Hook not available, use advice
23162 (defadvice bookmark-jump (after org-make-visible activate)
23163 "Make the position visible."
23164 (org-bookmark-jump-unhide))))
23166 ;; Make sure saveplace shows the location if it was hidden
23167 (eval-after-load "saveplace"
23168 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23169 "Make the position visible."
23170 (org-bookmark-jump-unhide)))
23172 ;; Make sure ecb shows the location if it was hidden
23173 (eval-after-load "ecb"
23174 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23175 "Make hierarchy visible when jumping into location from ECB tree buffer."
23176 (if (derived-mode-p 'org-mode)
23177 (org-show-context))))
23179 (defun org-bookmark-jump-unhide ()
23180 "Unhide the current position, to show the bookmark location."
23181 (and (derived-mode-p 'org-mode)
23182 (or (outline-invisible-p)
23183 (save-excursion (goto-char (max (point-min) (1- (point))))
23184 (outline-invisible-p)))
23185 (org-show-context 'bookmark-jump)))
23187 ;; Make session.el ignore our circular variable
23188 (eval-after-load "session"
23189 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23191 ;;;; Experimental code
23193 (defun org-closed-in-range ()
23194 "Sparse tree of items closed in a certain time range.
23195 Still experimental, may disappear in the future."
23196 (interactive)
23197 ;; Get the time interval from the user.
23198 (let* ((time1 (org-float-time
23199 (org-read-date nil 'to-time nil "Starting date: ")))
23200 (time2 (org-float-time
23201 (org-read-date nil 'to-time nil "End date:")))
23202 ;; callback function
23203 (callback (lambda ()
23204 (let ((time
23205 (org-float-time
23206 (apply 'encode-time
23207 (org-parse-time-string
23208 (match-string 1))))))
23209 ;; check if time in interval
23210 (and (>= time time1) (<= time time2))))))
23211 ;; make tree, check each match with the callback
23212 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23214 ;;;; Finish up
23216 (provide 'org)
23218 (run-hooks 'org-load-hook)
23220 ;;; org.el ends here